你不能做你試圖做什麼。該語言不會允許你。要設置的階段,我創建了以下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