最佳答案
我已经对数据库做了一些修改,需要将旧数据迁移到新表中。为此,我需要从原始表(Practice
)获取数据填充一个表(ReportOptions
) ,并填充第二个中间表(PracticeReportOption
)。
ReportOption (
ReportOptionId int PK,
field1, field2...
)
Practice (
PracticeId int PK,
field1, field2...
)
PracticeReportOption (
PracticeReportOptionId int PK,
PracticeId int FK,
ReportOptionId int FK,
field1, field2...
)
我进行了一个查询,以获得从 Practice
移动到 ReportOptions
所需的所有数据,但是在填充中间表时遇到了麻烦。
--Auxiliary tables
DECLARE @ReportOption TABLE (
PracticeId int, -- This field is not on the actual ReportOption table
field1, field2...
)
DECLARE @PracticeReportOption TABLE (
PracticeId int,
ReportOptionId int,
field1, field2
)
--First I get all the data I need to move
INSERT INTO @ReportOption
SELECT P.practiceId, field1, field2...
FROM Practice P
--I insert it into the new table,
--but somehow I need to have the repation PracticeId / ReportOptionId
INSERT INTO ReportOption (field1, field2...)
OUTPUT @ReportOption.PracticeId, --> this is the field I don't know how to get
inserted.ReportOptionId
INTO @PracticeReportOption (PracticeId, ReportOptionId)
SELECT field1, field2
FROM @ReportOption
-- This would insert the relationship, If I knew how to get it!
INSERT INTO @PracticeReportOption (PracticeId, ReportOptionId)
SELECT PracticeId, ReportOptionId
FROM @ReportOption
如果我能在 OUTPUT
子句中引用一个不来自目标表的字段,那就太好了(我想我不能,但我不确定)。有什么办法可以满足我的需求吗?