开发者

Compare two records and show only the difference

I'd like a Oracle Pipelined Function which compares two records from a query result and shows o开发者_C百科nly the column which have changed between the query result?


Here is a blunt instrument approach to the problem.

create or replace function col_diff
    ( p_empno_1 in emp.empno%type
      , p_empno_2 in emp.empno%type )
    return col_nt pipelined
is
    out_val col_t := new col_t(null, null, null);
    emp_rec1 emp%rowtype;
    emp_rec2 emp%rowtype;
begin
    select *
    into emp_rec1
    from emp
    where empno = p_empno_1;
    select *
    into emp_rec2
    from emp
    where empno = p_empno_2;

    if emp_rec1.ename != emp_rec2.ename
    then
        out_val.col_name := 'ENAME';
        out_val.old_val := emp_rec1.ename;
        out_val.new_val := emp_rec2.ename;
        pipe row (out_val); 
    end if;
    if emp_rec1.hiredate != emp_rec2.hiredate
    then
        out_val.col_name := 'HIREDATE';
        out_val.old_val := to_char(emp_rec1.hiredate, 'DD-MON-YYYY');
        out_val.new_val := to_char(emp_rec2.hiredate, 'DD-MON-YYYY');
        pipe row (out_val); 
    end if;
    return;
end;
/

So, given this test data...

SQL> select empno, ename, hiredate
  2  from emp
  3  where empno > 8100
  4  /

     EMPNO ENAME      HIREDATE
---------- ---------- ---------
      8101 PSMITH     03-DEC-10
      8102 PSMITH     02-JAN-11

SQL>

... we get this output:

SQL> select * from table (col_diff(8101,8102))
  2  /

COL_NAME
------------------------------
OLD_VAL
-------------------------------------------------------------------
NEW_VAL
-------------------------------------------------------------------
HIREDATE
03-DEC-2010
02-JAN-2011


SQL>

Now, doubtlessly you would like something which is less verbose. I think it may be possible to do something using the enhanced Method 4 dynamic SQL which was introduced in 11g. Alas, you say you are using 10g.


Its not quite what you want, but Kevin Meade's blog on OracleFAQ has a solution which works for me:

http://www.orafaq.com/node/1826

http://www.orafaq.com/files/column_diffs.txt

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜