有时候会有某种需求:需要对比两个表的表结构是否一致,有时候甚至是整个数据库所有表的表结构对比......。表结构对比无非就是字段名、字段类型、字段数据类型、以及字段的顺序的对比。如果需要对比表结构,可以通过下面简单的脚本实现:
SELECT M.OWNER
,M.TABLE_NAME
,M.COLUMN_ID
,M.COLUMN_NAME
,M.DATA_TYPE
,M.DATA_LENGTH
,N.OWNER
,N.TABLE_NAME
,N.COLUMN_ID
,N.COLUMN_NAME
,N.DATA_TYPE
,N.DATA_LENGTH
FROM
(
SELECT OWNER
,TABLE_NAME
,COLUMN_ID
,COLUMN_NAME
,DATA_TYPE
,DATA_LENGTH
FROM DBA_TAB_COLUMNS
WHERE OWNER=&OWNER_A
AND TABLE_NAME=&TABLE_NAME_A
) M LEFT JOIN
(
SELECT OWNER
,TABLE_NAME
,COLUMN_ID
,COLUMN_NAME
,DATA_TYPE
,DATA_LENGTH
FROM DBA_TAB_COLUMNS
WHERE OWNER=&OWNER_B
AND TABLE_NAME=&TABLE_NAME_B
) N ON M.COLUMN_ID =N.COLUMN_ID
AND M.COLUMN_NAME = N.COLUMN_NAME
AND M.DATA_TYPE = N.DATA_TYPE
AND M.DATA_LENGTH= N.DATA_LENGTH
ORDER BY M.TABLE_NAME, M.COLUMN_ID;
但是如果A表与B表前面的字段一致,然而B表有一些额外的字段,那么上面的SQL(左连接)就会查不出两者之间结构的不同。此时需要使用右连接才能对比出真正的表结构。所以如果需要对比两者的表结构是否一致,最好左连接查一次,右连接查一次。才能真正的确认两者的表结构的异同。
SELECT M.OWNER
,M.TABLE_NAME
,M.COLUMN_ID
,M.COLUMN_NAME
,M.DATA_TYPE
,M.DATA_LENGTH
,N.OWNER
,N.TABLE_NAME
,N.COLUMN_ID
,N.COLUMN_NAME
,N.DATA_TYPE
,N.DATA_LENGTH
FROM
(
SELECT OWNER
,TABLE_NAME
,COLUMN_ID
,COLUMN_NAME
,DATA_TYPE
,DATA_LENGTH
FROM DBA_TAB_COLUMNS
WHERE OWNER=&OWNER_A
AND TABLE_NAME=&TABLE_NAME_A
) M RIGHT JOIN
(
SELECT OWNER
,TABLE_NAME
,COLUMN_ID
,COLUMN_NAME
,DATA_TYPE
,DATA_LENGTH
FROM DBA_TAB_COLUMNS
WHERE OWNER=&OWNER_B
AND TABLE_NAME=&TABLE_NAME_B
) N ON M.COLUMN_ID =N.COLUMN_ID
AND M.COLUMN_NAME = N.COLUMN_NAME
AND M.DATA_TYPE = N.DATA_TYPE
AND M.DATA_LENGTH= N.DATA_LENGTH
ORDER BY M.TABLE_NAME, M.COLUMN_ID;
时间: 2024-10-11 07:13:16