Skip to Main Content
  • Questions
  • How to print row value involved in merge statement

Breadcrumb

Question and Answer

Maria Colgan

Thanks for the question, Amiya Ranjan.

Asked: February 10, 2017 - 3:48 pm UTC

Last updated: February 13, 2017 - 6:04 pm UTC

Version: 12.1.0.2.0

Viewed 1000+ times

You Asked

Hi,

By using dbms_output.put_line( sql%rowcount) we can get the number of rows affected by merge statement.
Is it possible to print value of those rows during merge using PL/sql?

thanks,
Amiya.

and we said...

See https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:9528727800346317168

If you really need those rows, you would need to break the merge into separate UPDATE and INSERT statements, and then use RETURNING BULK COLLECT, eg

SQL> create table t1 ( x1 int, y1 int );

Table created.

SQL> create table t2 ( x2 int, y2 int );

Table created.

SQL>
SQL> insert into t1 values (1,1);

1 row created.

SQL> insert into t1 values (2,2);

1 row created.

SQL> insert into t1 values (3,3);

1 row created.

SQL>
SQL> insert into t2 values (2,5);

1 row created.

SQL> insert into t2 values (3,6);

1 row created.

SQL> insert into t2 values (4,7);

1 row created.

SQL>
SQL> set serverout on
SQL> DECLARE
  2    type numlist is table of number index by pls_integer;
  3    ret_x numlist;
  4    ret_y numlist;
  5  BEGIN
  6    update t1
  7    set y1 = ( select y2 from t2 where t2.x2 = t1.x1 )
  8    where x1 in ( select x2 from t2 )
  9    RETURNING x1,y1
 10    BULK COLLECT INTO ret_x, ret_y;
 11
 12    DBMS_OUTPUT.PUT_LINE ('updated ' || SQL%ROWCOUNT || ' rows:');
 13    FOR i IN ret_x.FIRST .. ret_x.LAST
 14    LOOP
 15      DBMS_OUTPUT.PUT_LINE (ret_x(i)||','||ret_y(i));
 16    END LOOP;
 17  END;
 18  /
updated 2 rows:
2,5
3,6

PL/SQL procedure successfully completed.

SQL>
SQL>



Is this answer out of date? If it is, please let us know via a Comment

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library