CREATE TABLE t1 (id NUMBER(10),description VARCHAR2(50),CONSTRAINT t1_pk PRIMARY KEY (id));
CREATE SEQUENCE t1_seq;
INSERT INTO t1 VALUES (t1_seq.nextval, 'ONE');
INSERT INTO t1 VALUES (t1_seq.nextval, 'TWO');
INSERT INTO t1 VALUES (t1_seq.nextval, 'THREE');
returning into語句的主要做用是:
delete操做:returning返回的是delete以前的結果
insert操做:returning返回的是insert以後的結果
update操做:returning語句是返回update以後的結果
注意:returning into語句不支持insert into select 語句和merge語句
下面演示該語句的具體用法
(1)獲取添加的值
declare
l_id t1.id%type;
begin
insert into t1 values(t1_seq.nextval,'four')
returning id into l_id;
commit;
dbms_output.put_line('id='||l_id);
end
運行結果 id=4
(2)更新和刪除
1 DECLARE l_id t1.id%TYPE;
2 BEGIN
3 UPDATE t1
4 SET description = 'two2'
5 WHERE ID=2
6 RETURNING id INTO l_id;
7 DBMS_OUTPUT.put_line('UPDATE ID=' || l_id);
8 DELETE FROM t1 WHERE description = 'THREE'
9 RETURNING id INTO l_id;
10 DBMS_OUTPUT.put_line('DELETE ID=' || l_id);
11 COMMIT;
12* END;
SQL> /
UPDATE ID=2
DELETE ID=3
(3)若是更新dml操做影響多條記錄能夠經過bulk collect into 來提取
1 declare
2 type t_tab is table of t1.id%type;
3 l_tab t_tab;
4 begin
5 update t1
6 set description=description
7 returning id bulk collect into l_tab;
8 for i in l_tab.first..l_tab.last loop
9 dbms_output.put_line('update id='||l_tab(i));
10 end loop;
11* end;
SQL> /
update id=21
update id=22
update id=23
(4)若是插入操做影響多行也能夠獲取
declare
type description_table_type is table of t1.description%type;
type t1_table_type is table of t1%rowtype;
description_table description_table_type:=description_table_type('FIVE', 'SIX', 'SEVEN');
t1_table t1_table_type;
begin
forall i in description_table.first..description_table.last
insert into t1 values(t1_seq.nextval,description_table(i))
returning id ,description bulk collect into t1_table;
for i in t1_table.first..t1_table.last loop
DBMS_OUTPUT.put_line('INSERT ID=' || t1_table(i).id ||'DESC='|| t1_table(i).description);
end loop;
end;
/
執行結果
INSERT ID=27DESC=FIVE
INSERT ID=28DESC=SIX
INSERT ID=29DESC=SEVEN
PL/SQL procedure successfully completed.
forall指的是同時插入,若是使用for循環也能夠插入三條記錄,但默認returing只顯示最後一條
http://blog.csdn.net/whhitgen/article/details/12511505oop