[英]Migrating a header-detail pair of tables on sql server
How would you migrate SOME records from a header-detail pair of tables (with IDENTITY ID's) to a new pair of tables in another DB? 您如何将某些记录从表头详细信息对表(具有IDENTITY ID)迁移到另一个数据库中的新表对?
For example, yo need to migrate record numbered 4,6,9 and 10 from the header table and all their details. 例如,您需要从头表及其所有详细信息中迁移编号为4,6,9和10的记录。
When you INSERT the header records on the new table, their ID's will be 1,2,3 and 4. When inserting the details, the child record from 4 will need to point to 1, 6 to 2 and so on. 当您在新表上插入标头记录时,它们的ID将分别为1,2,3和4。插入详细信息时,从4开始的子记录将需要指向1、6到2,依此类推。
Is there a way to use the OUTPUT clause to include a field that is not inserted in the table, as a way to pair "old" ID' to "new" ones? 有没有一种方法可以使用OUTPUT子句包含未插入表中的字段,以将“旧” ID'与“新” ID配对?
The OUTPUT
clause of an INSERT
statement will only allow you to select values that are actually inserted into the target table. INSERT
语句的OUTPUT
子句仅允许您选择实际插入到目标表中的值。 You can work around this by using a MERGE
instead, as the OUTPUT
clause of a MERGE
statement will allow you to select values from the source data as well. 您可以改用
MERGE
来解决此问题,因为MERGE
语句的OUTPUT
子句也允许您从源数据中选择值。 Here's an example: 这是一个例子:
declare @src table (id bigint, data char);
declare @dest table (id bigint identity(1,1), data char);
insert @src values (4, 'A'), (6, 'B'), (9, 'C'), (10, 'D');
insert @dest (data)
output inserted.id, S.id -- ERROR
select data from @src S;
merge @dest D
using @src S on 1 = 0
when not matched then
insert (data) values (S.data)
output inserted.id as [New ID], S.id as [Old ID]; -- LEGAL
Results of the MERGE
statement: MERGE
语句的结果:
New ID Old ID
1 4
2 6
3 9
4 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.