为什么在OUTPUT / INSERTED行中无法识别INSERT表别名?
编辑:链接表需要填充新的@Data_Table.Id(INSERTED.id,works)和@ NewData_Table.ObjectId(错误)。因此,可以创建一个'链接表',以及从@Data_Table到@Tmp_Link_Table的外键关系。
编辑:
--Expected Output
--ObjectId DataId
--11 3
--12 4
--13 5
--14 6
DECLARE @NewData_Table TABLE
( [Data] VARCHAR(50) NOT NULL,
ObjectId INT NOT NULL)
DECLARE @Tmp_Link_Table TABLE
( ObjectId INT NOT NULL,
DataId INT NOT NULL)
DECLARE @Data_Table TABLE
( Id INT NOT NULL Identity(1,1),
Data VARCHAR(50) NOT NULL)
-- create new objects
INSERT INTO @NewData_Table (ObjectId, Data) VALUES (11,'Data 1')
INSERT INTO @NewData_Table (ObjectId, Data) VALUES (12,'Data 2')
INSERT INTO @NewData_Table (ObjectId, Data) VALUES (13,'Data 3')
INSERT INTO @NewData_Table (ObjectId, Data) VALUES (14,'Data 4')
SELECT * FROM @NewData_Table
-- create some data
INSERT INTO @Data_Table (Data) VALUES ('Data One')
INSERT INTO @Data_Table (Data) VALUES ('Data Two')
--@Data_Table BEFORE
SELECT * FROM @Data_Table
- Q !:为什么“Msg 4104,Level 16,State 1,Line 27多部分标识符”d.ObjectId“无法绑定。”
INSERT INTO @Data_Table (Data) OUTPUT d.ObjectId, INSERTED.Id INTO @Tmp_Link_Table (ObjectId, DataId)
SELECT d.Data
FROM @NewData_Table AS d
--@Data_Table AFTER
SELECT * FROM @Data_Table
--Linked table from INSERT
SELECT * FROM @Tmp_Link_Table
答案 0 :(得分:3)
不幸的是,对于INSERT
语句,您无法输出不是插入列之一的列(尽管我似乎无法在解释此内容的文档中找到引用)。
通过使用合并声明,可以解决这个问题。
例如,更改此部分:
INSERT INTO @Data_Table (Data) OUTPUT d.ObjectId, INSERTED.Id INTO @Tmp_Link_Table (ObjectId, DataId)
SELECT d.Data
FROM @NewData_Table AS d
对此:
MERGE @Data_Table AS DT
USING @NewData_Table AS NDT
ON 1 = 2 -- This never matches...
WHEN NOT MATCHED THEN -- So this is always true...
INSERT (Data)
VALUES (NDT.Data)
OUTPUT NDT.ObjectId, INSERTED.id
INTO @Tmp_Link_Table (ObjectId, DataId);
答案 1 :(得分:0)
您必须更新您的表架构和查询,如下所示:
DECLARE @NewData_Table TABLE
( [Data] VARCHAR(50) NOT NULL,
ObjectId INT NOT NULL
)
DECLARE @Tmp_Link_Table TABLE
( ObjectId INT NOT NULL,
DataId INT NOT NULL
)
DECLARE @Data_Table TABLE
( Id INT NOT NULL Identity(1,1),
Data INT
)
-- create new objects
INSERT INTO @NewData_Table (ObjectId, Data) VALUES (11,66)
INSERT INTO @NewData_Table (ObjectId, Data) VALUES (12,88)
INSERT INTO @NewData_Table (ObjectId, Data) VALUES (13,99)
INSERT INTO @NewData_Table (ObjectId, Data) VALUES (14,44)
SELECT * FROM @NewData_Table
-- create some data
INSERT INTO @Data_Table (Data) VALUES (44)
INSERT INTO @Data_Table (Data) VALUES (55)
--@Data_Table BEFORE
SELECT * FROM @Data_Table
INSERT INTO @Data_Table (Data) OUTPUT INSERTED.Data, INSERTED.Id INTO @Tmp_Link_Table (ObjectId, DataId)
SELECT d.Data
FROM @NewData_Table AS d
--@Data_Table AFTER
SELECT * FROM @Data_Table
--Linked table from INSERT
SELECT * FROM @Tmp_Link_Table
输出(@Tmp_Link_Table):