Copy data from SQL Server Staging to Live tables

时间:2017-08-04 13:11:17

标签: sql-server database

I have a SQL Server database with staging tables where a user entered data gets saved until they finally submit the application form at which point the data gets copied to live tables.

So I have a table called ApplicationStaging with columns:

ApplicationID        1
UserID               2
CustomerName         'Joe Bloggs'
//More columns removed for brevity

Then I have a table called ItemStaging with columns:

ItemID               1
ApplicationID (FK)   1
ItemName             'Car'
//More columns removed for brevity

Then I have my live Application table and live Item table which at the minute contain exactly the same column names as the staging tables. I have around 20 tables like this and there are FK relationships between some different tables. what is the best way to use a stored procedure to copy the data from the staging tables to the live tables while recreating the FK relationships (noting that the IDs from staging to submitted may be different depending on when an end user submits the application versus when it was saved).

I was thinking one of the things I will need to do on the live tables is add a StagingID column and set that so I will be able to have a link back to what data was copied into the live table from the staging table

1 个答案:

答案 0 :(得分:1)

两种解决方案:

使用Sequences为生产和登台表生成ID,然后您不必担心ID映射。

如果序列为no,则使用OUTPUT子句提取ID映射:

INSERT INTO Parent
OUTPUT INSERTED.ID, StagingParent.ID INTO @ParentIDMapping( PID, SPID )
SELECT *
FROM StagingParent

INSERT INTO Child
OUTPUT INSERTED.ID, Child.ID INTO @ChildIDMapping
SELECT PID AS FK, * 
FROM StagingChild AS SC
    INNER JOIN @ParentIDMapping AS PID ON SC.FK = SPID 

请参阅此MSDN文档底部的示例,了解如何使用OUTPUT

更新:由于INSERT不允许您输出实际未插入的列,因此您需要使用MERGE。请参阅:Is it possible to for SQL Output clause to return a column not being inserted?