zoukankan      html  css  js  c++  java
  • 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)更新和删除

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

  • 相关阅读:
    python系列之
    php正则:匹配(),{},[]小括号,大括号,中括号里面的内容
    TCP、UDP以及HTTP的简单讲解
    Python Async/Await入门指南
    asyncio并发编程
    python中socket模块详解
    TCP和UDP的优缺点及区别
    网络通信 --> IO多路复用之select、poll、epoll详解
    异步IO和协程
    Python--多任务(多进程,多线程,协程)
  • 原文地址:https://www.cnblogs.com/zcy_soft/p/2269551.html
Copyright © 2011-2022 走看看