查找一个表中存在的列,而不是另一个表中的列。请阅读说明

时间:2019-04-23 06:20:10

标签: sql oracle11g

我有两个版本的数据库V5和V9。 V9是最新版本。 我必须在V9的表中而不是V5的表名中找到相似的列。 例如,表名称:V9中的ashish_table具有5列A,B,C,D和E。                       V5中的同一表ashish_table具有3列A,B和C。

因此,在V9的表ashish_table中存在两列D和E,而在V5的ashish_table中没有。

我已经在这两个数据库之间建立了连接。我还搜索并找到了下面的脚本,该脚本基于“ data_type,data_length,data_scale,data_precision”比较表;但是它仅匹配具有相同名称的列。 例如。它将根据data_type,data_length,data_scale,data_precision匹配A,B和C列;如果假设列A的数据类型已从char更改为varchar,而其他两列的详细信息相同,则仅返回列A。 它不提供V5的ashish_table中不存在的D和E。

set verify  off 
set heading off
column data_type format a20

accept table1 prompt 'Table 1: '
accept table2 prompt 'Table 2: '

prompt
prompt The table &table1 and &table2 have columns with the same name but differ:
prompt -------------------------------------------------------------------------

select 
       column_name,data_type, data_length, data_scale, data_precision
from  
       user_tab_columns
where 
       table_name = upper('&table1')
minus
select 
       column_name,data_type, data_length, data_scale, data_precision
from 
       user_tab_columns
where 
       table_name = upper('&table2');

感谢您阅读大问题。 有没有可以比较两个表并给出缺失列的脚本。

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容查找是否还有其他列:

select c2.table_name,c2.COLUMN_NAME
from all_tab_cols c2
where table_name='&table1'
and c2.COLUMN_NAME not in (select column_name 
    from all_tab_cols 
    where table_name='&table2');

这未经测试,但是可以做到:

select 
       column_name,data_type, data_length, data_scale, data_precision
from  
       user_tab_columns
where 
       table_name = upper('&table1')
minus
select 
       column_name,data_type, data_length, data_scale, data_precision
from 
       user_tab_columns
where 
       table_name = upper('&table2');
union
select c2.COLUMN_NAME, c2.data_type, c2.data_length, c2.data_scale, c2.data_precision
from all_tab_cols c2
where table_name='&table1'
and c2.COLUMN_NAME not in (select column_name 
    from all_tab_cols 
    where table_name='&table2');