有个需求,创建一张表,这张表的列包含其余几张表的列,创建好后怎么进行校验对比。
1、创建一个函数,接受列名和目标表名作为参数,并返回一个布尔值,表示该列名是否存在于目标表中。
CREATE OR REPLACE FUNCTION column_exists_in_target(
p_column_name VARCHAR2,
p_target_table VARCHAR2
) RETURN BOOLEAN AS
v_exists NUMBER(1);
BEGIN
SELECT CASE WHEN EXISTS (
SELECT 1 FROM user_tab_columns WHERE table_name = p_target_table AND column_name = p_column_name
) THEN 1 ELSE 0 END INTO v_exists FROM DUAL;
RETURN v_exists = 1;
END;
2、创建一个存储过程,遍历其他表的列名,并调用函数来检查列名是否存在于目标表中。将结果插入到临时表中。
CREATE OR REPLACE PROCEDURE compare_columns AS
v_table_name VARCHAR2(100);
v_column_name VARCHAR2(100);
v_is_matched NUMBER(1);
CURSOR cur_tables IS
SELECT table_name FROM user_tables WHERE table_name IN ('TABLE1', 'TABLE2', 'TABLE3', 'TABLE4', 'TABLE5', 'TABLE6', 'TABLE7');
BEGIN
FOR table_rec IN cur_tables LOOP
v_table_name := table_rec.table_name;
-- 查询当前表的列名
FOR column_rec IN (SELECT column_name FROM user_tab_columns WHERE table_name = v_table_name) LOOP
v_column_name := column_rec.column_name;
-- 检查列名是否在目标表中
v_is_matched := column_exists_in_target(v_column_name, 'TARGET_TABLE');
-- 插入对比结果到临时表
INSERT INTO temp_column_comparison (column_name, source_table, is_matched)
VALUES (v_column_name, v_table_name, v_is_matched);
END LOOP;
END LOOP;
END;
执行测试
EXECUTE compare_columns;
SELECT * FROM temp_column_comparison;