时间:2023-03-04 10:50:49 | 栏目:Oracle | 点击:次
ORACLE的DML语句中可以指定RETURNING语句。使用起来也很简单,和SELECT INTO语句没有多大区别。RETURNING语句的使用在很多情况下可以简化PL/SQL编程。
INSERT INTO SELECT和MERGE语句不支持RETURNING语句。RETURNING和return通用。
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;
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;
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;
DECLARE TYPE t_desc_tab IS TABLE OF t1.description%TYPE; TYPE t_tab IS TABLE OF t1%ROWTYPE; l_desc_tab t_desc_tab := t_desc_tab('FIVE', 'SIX', 'SEVEN'); l_tab t_tab; BEGIN FORALL i IN l_desc_tab.first .. l_desc_tab.last INSERT INTO t1 VALUES (t1_seq.nextval, l_desc_tab(i)) RETURNING id, description BULK COLLECT INTO l_tab; FOR i IN l_tab.first .. l_tab.last LOOP DBMS_OUTPUT.put_line('INSERT ID=' || l_tab(i).id || ' DESC=' || l_tab(i).description); END LOOP; COMMIT; END;
DECLARE TYPE t_tab IS TABLE OF t1.id%TYPE; l_tab t_tab; BEGIN EXECUTE IMMEDIATE 'UPDATE t1 SET description = description RETURNING id INTO :l_tab' using 7369 RETURNING 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;
注意:
returning into在动态sql内部和外面都要写,且外面的returning后面不加字段直接into。
using在returning前面
动态sql内部into后面变量名不固定,注意冒号(:),可以是命名规则下的任意字符。
returning bulk collect into要写在外面,且后面不能是record。
using (OracleCommand cmd = Globals.Db.Connection.CreateCommand()) { cmd.CommandText = "INSERT INTO table (Col1, Col2) VALUES (:ParamCol1, :ParamCol2) RETURNING ROWIDTOCHAR(ROWID) INTO :OutputROWID"; cmd.Parameters.Add(paramCol1, data["Col1"]); cmd.Parameters.Add(paramCol2, data["Col2"]); OracleParameter outputRowId = new OracleParameter(":OutputROWID", OracleDbType.Varchar2, 30) { Direction = ParameterDirection.ReturnValue };//一定要有Size参数。 cmd.Parameters.Add(outputRowId); cmd.BindByName = true; cmd.ExecuteNonQuery(); string rtnValue = outputRowId.Value.ToString(); }