我正在尝试从不同的表中复制数据,同时保持彼此之间的不同链接。
我桌子的简化结构:
timetable (pk INT PRIMARY KEY IDENTITY(1,1), name VARCHAR(50))
timetable_group (pk INT PRIMARY KEY IDENTITY(1,1), timetable_fk INT, name VARCHAR(50))
timetable_class (pk INT PRIMARY KEY IDENTITY(1,1), timetable_fk INT, timetable_group_fk INT, name VARCHAR(50))
我的目标是能够在timetable_group和timetable_class中复制时间表条目及其所有相关条目。
获得@new_timetable_fk
INSERT
和@@IDENTITY
之后,我遇到了问题:
如何从timetable_group
复制并取回插入的pK,以便在复制timetable_class
时能够使用它们?
我试过用这个:
-- This is a parameter to my code
DECLARE @timetable_fk INT
SET @timetable_fk = 1
-- start of my Stored Procedure
-- this will hold my new timetable_fk
DECLARE @new_timetable_fk INT
-- this will hold the old and new pks of timetable_group
-- so we can join on it
DECLARE @timetable_group_link_pks TABLE (new_pk INT, old_pk INT)
-- copy the timetable entry
INSERT INTO timetable (name)
SELECT LEFT(name + ' copy', 50)
FROM timetable
WHERE pk = @timetable_fk
-- get the pk of the newly inserted value
SET @new_timetable_fk = @@IDENTITY
-- copy timetable_group
INSERT INTO timetable_group (timetable_fk, name)
-- This return the error `The multi-part identifier "g.pk" could not be bound`
OUTPUT inserted.pk, g.pk
INTO @timetable_group_link_pks
SELECT @new_timetable_fk, g.name
FROM timetable_group g
WHERE g.timetable_fk = @timetable_fk
-- copy timetable class
INSERT INTO timetable_class (timetable_fk, timetable_group_fk, name)
SELECT @new_timetable_fk, gl.new_pk, c.name
FROM timetable_class c
JOIN @timetable_group_link_pks gl ON c.timetable_group_fk = gl.old_pk
WHERE c.timetable_fk = @timetable_fk
但它不起作用,因为我不能在OUTPUT子句中使用g.pk。
MSDN告诉我们OUTPUT子句应该按我的意愿工作,但TSQL不接受它。
知道如何解决这个问题吗?
答案 0 :(得分:2)
你应该使用Merge语句和Output子句而不是直接插入, 请参阅Link
答案 1 :(得分:0)
“输出”中不存在g.pk,因为“插入”和选择查询不会自动连接。
你可以跳过@timetable_group_link_pks表和OUTPUT的东西,你不需要它。
这应该有效:
-- copy timetable_group
INSERT INTO timetable_group (timetable_fk, name)
SELECT @new_timetable_fk, g.name
FROM timetable_group g
WHERE g.timetable_fk = @timetable_fk
-- copy timetable_class
INSERT INTO timetable_class (timetable_fk, timetable_group_fk, name)
SELECT @new_timetable_fk, c.timetable_group_fk, c.name
FROM timetable_class c
join timetable_group g on g.timetable_fk = c.timetable_fk
WHERE c.timetable_fk = @timetable_fk and g.pk = @timetable_fk