我對數據庫做了一些修改,我需要將舊數據遷移到新表中。爲此,我需要填寫一張表格(ReportOptions)從原始表格(Practice)中獲取數據,並填寫第二個中間表格(PracticeReportOption)。是否可以讓SQL Output子句返回未插入的列?
ReportOption (ReportOptionId int PK, field1, field2...)
Practice (PracticeId int PK, field1, field2...)
PracticeReportOption (PracticeReportOptionId int PK, PracticeId int FK, ReportOptionId int FK, field1, field2...)
我做了一個查詢來獲取所有我需要從實踐移到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子句的目標表上,那會很棒(我認爲我不能,但我不知道)。關於如何滿足我的需求的任何想法?
在此先感謝。
您可以在OUTPUT子句中返回插入行的表中的任何列。因此,即使您沒有在INSERT語句中爲給定列提供值,仍然可以在OUTPUT子句中指定該列。但是,您不能從其他表中返回SQL變量或列。 –
@marc_s謝謝你的回覆,但我沒有在目的地表中需要的字段(我需要的是PracticeId,它不在ReportOption上) –