gpt4 book ai didi

sql - PLSQL Insert into with 子查询和返回子句

转载 作者:行者123 更新时间:2023-12-02 18:13:31 27 4
gpt4 key购买 nike

我无法找出以下伪 SQL 的正确语法:

INSERT INTO some_table
(column1,
column2)
SELECT col1_value,
col2_value
FROM other_table
WHERE ...
RETURNING id
INTO local_var;

我想插入带有子查询值的内容。插入后我需要新生成的 id。

这是 Oracle 文档所说的:

Insert Statement

Returning Into

好吧,我认为仅使用值子句是不可能的......有替代方案吗?

最佳答案

您不能使用 INSERT 中的 RETURNING BULK COLLECT。但是,此方法可以用于更新和删除:

create table test2(aa number)
/
insert into test2(aa)
select level
from dual
connect by level<100
/

set serveroutput on
declare
TYPE t_Numbers IS TABLE OF test2.aa%TYPE
INDEX BY BINARY_INTEGER;
v_Numbers t_Numbers;
v_count number;
begin


update test2
set aa = aa+1
returning aa bulk collect into v_Numbers;

for v_count in 1..v_Numbers.count loop
dbms_output.put_line('v_Numbers := ' || v_Numbers(v_count));
end loop;

end;

您可以通过一些额外的步骤让它工作(使用 TREAT 进行 FORALL INSERT)如本文所述:

returning with insert..select

T

利用他们创建的示例并将其应用到 test2 测试表

 CREATE or replace TYPE ot AS OBJECT
( aa number);
/


CREATE TYPE ntt AS TABLE OF ot;
/

set serveroutput on
DECLARE

nt_passed_in ntt;
nt_to_return ntt;

FUNCTION pretend_parameter RETURN ntt IS
nt ntt;
BEGIN
SELECT ot(level) BULK COLLECT INTO nt
FROM dual
CONNECT BY level <= 5;
RETURN nt;
END pretend_parameter;

BEGIN

nt_passed_in := pretend_parameter();

FORALL i IN 1 .. nt_passed_in.COUNT
INSERT INTO test2(aa)
VALUES
( TREAT(nt_passed_in(i) AS ot).aa
)
RETURNING ot(aa)
BULK COLLECT INTO nt_to_return;

FOR i IN 1 .. nt_to_return.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(
'Sequence value = [' || TO_CHAR(nt_to_return(i).aa) || ']'
);
END LOOP;

END;
/

关于sql - PLSQL Insert into with 子查询和返回子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5325033/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com