oracle insert into returning,Oracle RETURNING INTO 用法示例

The RETURNING INTO clause allows us to return column values for rows affected by DML statements. The following test table is used to demonstrate this clause.

DROP TABLE t1;

DROP SEQUENCE t1_seq;

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');

COMMIT;

When we insert data using a sequence to generate our primary key value, we can return the primary key value as follows.

SET SERVEROUTPUT ON

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

PL/SQL procedure successfully completed.

SQL>

The syntax is also available for update and delete statements.

SET SERVEROUTPUT ON

DECLARE

l_id t1.id%TYPE;

BEGIN

UPDATE t1

SET description = description

WHERE description = 'FOUR'

RETURNING id INTO l_id;

DBMS_OUTPUT.put_line('UPDATE ID=' || l_id);

DELETE from t1

WHERE description = 'FOUR'

RETURNING id INTO l_id;

DBMS_OUTPUT.put_line('DELETE ID=' || l_id);

COMMIT;

END;

/

UPDATE ID=4

DELETE ID=4

PL/SQL procedure successfully completed.

SQL>

When DML affects multiple rows we can still use the RETURNING INTO, but now we must return the values into a collection using the BULK COLLECT clause.

SET SERVEROUTPUT ON

DECLARE

TYPE t_tab IS TABLE OF t1.id%TYPE;

l_tab t_tab;

BEGIN

UPDATE t1

SET description = description

RETURNING id BULK COLLECT INTO l_tab;

FOR i IN l_tab.first .. l_tab.last LOOP

DBMS_OUTPUT.put_line('UPDATE ID=' || l_tab(i));

END LOOP;

COMMIT;

END;

/

UPDATE ID=1

UPDATE ID=2

UPDATE ID=3

PL/SQL procedure successfully completed.

SQL>

We can also use the RETURNING INTO clause in combination with bulk binds.

SET SERVEROUTPUT ON

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值