你不能做你试图做什么。该语言不会允许你。要设置的阶段,我创建了以下3个表
SET NOCOUNT ON;
CREATE TABLE dbo.Final
(
ID int IDENTITY(1,1) NOT NULL
, text1 varchar(50) NOT NULL
, text2 varchar(50) NOT NULL
, text3 varchar(50) NOT NULL
);
CREATE TABLE dbo.Chain
(
ID int NOT NULL
);
CREATE TABLE dbo.Chained
(
ID int NOT NULL
, Foo int NOT NULL
);
只是为了演示,其中OUTPUT
条款推移,我们将插入4行,看到好的漂亮的插入的虚拟表和相关的ID值。
-- Works
INSERT INTO
dbo.Final
(
text1
, text2
, text3
)
OUTPUT
INSERTED.*
SELECT
D.t1
, D.t2
, D.t3
FROM
(
VALUES
('A', 'B', 'C')
, ('D', 'B', 'C')
, ('G', 'B', 'C')
, ('J', 'B', 'C')
) D (t1,t2,t3);
现在,如果我执行以下语句,它将正常工作。但是,如果我忽略INSERT只是目测检查我想放到桌子上,SQL Server将引发以下错误
A nested INSERT, UPDATE, DELETE, or MERGE statement is not allowed in a SELECT statement that is not the immediate source of rows for an INSERT statement.
-- Comment out the insert portion to generate
-- A nested INSERT, UPDATE, DELETE, or MERGE statement is not allowed in a SELECT statement that is not the immediate source of rows for an INSERT statement.
INSERT INTO
dbo.Chain
(
ID
)
SELECT
X.ID
FROM
(
INSERT INTO
dbo.Final
(
text1
, text2
, text3
)
OUTPUT
INSERTED.*
SELECT
D.t1
, D.t2
, D.t3
FROM
(
VALUES
('A', 'B', 'C')
, ('D', 'B', 'C')
, ('G', 'B', 'C')
, ('J', 'B', 'C')
) D (t1,t2,t3)
) x
但是,你要多走一英里和适用,或将虚拟表格的结果与其他内容联系起来,那样就不会飞。
A nested INSERT, UPDATE, DELETE, or MERGE statement is not allowed on either side of a JOIN or APPLY operator.
我想这只是一个复杂程度太多。
-- Now, try the same bit except we use the derived table as a JOIN/APPLY
-- Can't fix what's not supported
-- A nested INSERT, UPDATE, DELETE, or MERGE statement is not allowed on either side of a JOIN or APPLY operator.
INSERT INTO
dbo.Chained
(
ID
, Foo
)
SELECT
X.ID
, D.foo
FROM
(
VALUES
(1)
) D(Foo)
CROSS APPLY
(
INSERT INTO
dbo.Final
(
text1
, text2
, text3
)
OUTPUT
INSERTED.*
SELECT
D.t1
, D.t2
, D.t3
FROM
(
VALUES
('A', 'B', 'C')
, ('D', 'B', 'C')
, ('G', 'B', 'C')
, ('J', 'B', 'C')
) D (t1,t2,t3)
) x;
如果你确实需要类似的东西,那么你将不得不把它分解成单独的语句。
的你为什么要做这样的插入?你究竟想要完成什么? – LittleBobbyTables 2014-09-24 17:43:07
类似于T1表中的每个ID,将TEX1,2和3插入到FINAL表中。 – 2014-09-24 18:01:47
你只是试图做一个插入,或做一个插入,然后得到结果?该语法只是令人困惑,而且您的解释与您写的代码不完全同步 – LittleBobbyTables 2014-09-24 18:04:06