比较2表之间的数据

时间:2013-09-02 06:53:24

标签: sql oracle function plsql

嘿,我需要比较两个结构相同的表。

Table1
EmpNO - Pkey
EmpName
DeptName
FatherName
IssueDate
ValidDate

我需要传递EMPNO作为参数,我需要比较任何一列是否有变化?并返回YES或NO value。

我可以使用PL / SQL功能吗?我正在考虑使用CONCAT in-build函数来做到这一点。

我正在尝试以下

Table1Concat = Select CONCAT(Column1.....6) from tbale1 where emp_no= in_empno;
Table2Concat = Select CONCAT(Column1.....6) from tbale2 where emp_no= in_empno;

IF(Table1Concat<>Table2Concat  ) THEN return data_changed :='YES';
  else data_changed :='NO';
END;

1 个答案:

答案 0 :(得分:1)

如果您只想检测是否有任何值,那么......

select count(*)
from (select * from table1 where emp_no = my_emp_no
      union 
      select * from table2 where emp_no = my_emp_no
      )

如果它返回1,那么行是相同的,如果它返回2,则存在差异。

列必须按照相同的顺序才能使用,或者您必须按照匹配顺序列出所有列名称。

如果你想要批量执行大量行,那么你很可能会使用不同的解决方案,不会遍历为每个运行此代码的每个emp_no。

对于两个表中都存在所有emp_id的批量数据,请使用以下格式的查询:

select table1.emp_no,
       case when table1.column1 = table2.column1 and 
                 table2.column2 = table2.column2 and
                 table2.column3 = table2.column3 and
                 ...
            then 'Yes'
            else 'No
       end columns_match
from   table1
join   table2 on table1.emp_no = table2.emp_no

您可以将此结果直接插入日志记录表。

尽管照顾空值。 “any_value = null”永远不会成立,并且“any_value!= Null”也永远不会成立,因此您可能需要添加逻辑来处理其中一个或两个值为空的情况。

相关问题