应用场景:数据库里有两个数据结构一样的表,在其中一个主表中设计了一个触发器,当删除该表中的一条数据时,同时把这条记录插入另一个表,有时候会突然报错,一直提示表结构不一样不能删除,这个时候就需要比较这两个表的结构。
1、创建测试表
create table TA(
id VARCHAR2(36) not null,
name VARCHAR2(100),
age NUMBER,
sex VARCHAR2(2)
);
insert into TA (id, name, age, sex)
values (\'1\', \'1\', 1, \'1\');
insert into TA (id, name, age, sex)
values (\'2\', \'2\', 2, \'2\');
insert into TA (id, name, age, sex)
values (\'3\', \'3\', 3, \'3\');
commit;
create table TB(
id VARCHAR2(36) not null,
name VARCHAR2(10), --字段类型和TA不同
age NUMBER,
clazz VARCHAR2(36) --字段名称和类型都和TA不同
);
insert into TB (id, name, age, clazz)
values (\'1\', \'1\', 1, \'1\');
insert into TB (id, name, age, clazz)
values (\'2\', \'2\', 1, \'3\'); --第四个值和TA不同
insert into TB (id, name, age, clazz)
values (\'3\', \'3\', 3, \'3\');
commit;
2、sql方式比较
select \'TA\' table_name,* from (
select column_name,data_type||\'(\'||data_length||\')\' data_type from user_tab_columns where table_name = \'TA\'
minus select column_name,data_type||\'(\'||data_length||\')\' data_type from user_tab_columns where table_name = \'TB\'
)
union
select \'TB\' table_name,* from (
select column_name,data_type||\'(\'||data_length||\')\' data_type from user_tab_columns where table_name = \'TB\'
minus
select column_name,data_type||\'(\'||data_length||\')\' data_type from user_tab_columns where table_name = \'TA\'
)
3、存储过程方式比较
CREATE or replace PROCEDURE proc_check_table(table1 varchar(100) , table2 varchar(100)) AS
TYPE Rd IS RECORD(column_name VARCHAR(128), data_type VARCHAR(128));
v_row1 Rd;
v_row2 Rd;
cur cursor;
BEGIN
open cur for
select column_name,data_type||\'(\'||data_length||\')\' data_type from user_tab_columns where table_name = table1 minus
select column_name,data_type||\'(\'||data_length||\')\' data_type from user_tab_columns where table_name = table2;
LOOP
FETCH cur INTO v_row1;
EXIT WHEN cur%NOTFOUND;
print table1||\'--\'||v_row1.column_name ||\'--\'||v_row1.data_type;
END LOOP;
CLOSE cur;
open cur for
select column_name,data_type||\'(\'||data_length||\')\' data_type from user_tab_columns where table_name = table2 minus
select column_name,data_type||\'(\'||data_length||\')\' data_type from user_tab_columns where table_name = table1;
LOOP
FETCH cur INTO v_row2;
EXIT WHEN cur%NOTFOUND;
print table2||\'--\'||v_row2.column_name ||\'--\'||v_row2.data_type;
END LOOP;
CLOSE cur;
END;
/
call proc_check_table(\'TA\',\'TB\');
1、 比较两个表中的数据是否相同,并找出差异数据。
(
select * from TA
minus
select * from TB
)
union
(
select * from TB
minus
select * from TA
)
更多资讯请上达梦技术社区了解: https://eco.dameng.com