oracle into 循环,学习oracle中return into的用法

oracle中return into语句的用法。

创建基础数据:

复制代码 代码示例:

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,更新和删除

复制代码 代码示例:

DECLARE l_id t1.id%TYPE;

BEGIN

UPDATE t1

SET description = 'two2'

WHERE ID=2

RETURNING id INTO l_id;

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

DELETE FROM t1 WHERE description = 'THREE'

RETURNING id INTO l_id;

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

COMMIT;

* END;

SQL> /

UPDATE ID=2

DELETE ID=3

3,如果更新dml操作影响多条记录可以通过bulk collect into 来提取

复制代码 代码示例:

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;

* 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只显示最后一条。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值