returning 自己通常结合dml 语句使用。(insert update delete)
使用方法:
update table_name set expr1 returning column_name into xxx
insert: 返回的是添加后的值
update:返回时更新后的值
delete:返回删除前的值
returning 可以再sqlplus 和plsql中使用
如果是plsql就如上面的代码,xxx为声明的变量名
如果是sqlplus,xxx 可以为变量,即
variable var_name varchar2(10) update table_name set expr1 returning column_name into :var_name;
这里的 :var_name 使用的是绑定变量
另外,returning 貌似可以与 return通用
insert into values 支持 returning
insert into select、 和merge 语句 不支持 returning
例子1:
建表语句:
create table test111( a1 varchar(10), a2 varchar(20) ); create sequence test111_s1 start with 1 increment by 1 cache 20 maxvalue 999999999999999999999999999 cycle;
declare seq number; begin insert into test111 values(test111_s1.nextval,'aaa2') returning a1 into seq; dbms_output.put_line(seq); end; declare seq number; begin insert into test111 values(test111_s1.nextval,'aaa3'); select test111_s1.currval into seq from dual; commit; dbms_output.put_line(seq); end;
例子2:
再另外,returning 可以与bulk collect 结合(批量绑定, 另外一个是 forall)
declare type table_type is table of column_name%type; v_tab table_type; begin update table_name set expr1 returning column_name bulk collect into v_tab; for i in v_tab.first .. v_tab.last loop dbms_output.put_line( l_tab(i)); end loop; commit; end;
ora-06547:insert,update或delete语句必须使用returning子句
产生这个错误的原因:
returning into子句作用于insert,update,delete,上而select则不行,应该用into。
报错的存储如下:
create or replace procedure p_stu_info(s_id number, s_name varchar2) is v_name varchar2(10); v_age number; v_errmsg varchar2(200); begin execute immediate 'select name,age from student_test where id=:1 and name=:2' using s_id, s_name returning into v_name, v_age; dbms_output.put_line(v_name || '的年龄为:' || to_char(v_age)); exception when others then v_errmsg := substrb(sqlerrm, 1, 200); dbms_output.put_line('找不到相应学生'); end p_stu_info;
改成下面这样就ok了:
create or replace procedure p_stu_info(s_id number, s_name varchar2) is v_name varchar2(10); v_age number; v_errmsg varchar2(200); begin execute immediate 'select name,age from student_test where id=:1 and name=:2' into v_name, v_age using s_id, s_name; dbms_output.put_line(v_name || '的年龄为:' || to_char(v_age)); exception when others then v_errmsg := substrb(sqlerrm, 1, 200); dbms_output.put_line('找不到相应学生,错误原因:'||v_errmsg); end p_stu_info;