我将给出我当前方法的伪代码示例,如果有人知道一种不能一次只处理一行的方法,我将非常感激。我正在使用 MS SQL Server 2008。
define cursor for the data to be inserted (about 3 million records)
loop
(
insert record into table 1
use scope_identity() to get key
insert record into table 2 that references table 1
)
我宁愿同时对两个表进行某种插入,因为游标和循环很慢。
在有人提示我为什么要向两个具有一对一关系的单独表中插入某些内容之前,这是因为第一个表无法修改,并且我需要第二个(临时)表中的信息作为数据转换的引用稍后进行操作。
不,我无法添加临时列来保存无法修改的表中的引用数据,因为它无法修改。这是一个实时系统,我无权更改该表。
<小时/>其他信息:
例如
Source:
1 a big monkey
2 a tall elephant
3 a big giraffe
4 a tiny cow
5 a tall cow
Dest:
Table 1 Table 2
monkey 1 big
elephant 2 tall
giraffe 3 big
cow 4 tiny
cow 5 tall
最佳答案
您可以使用merge在 Table1
和 output 上进入表2
。
merge Table1
using SourceTable
on 0 = 1
when not matched then
insert (Animal) values (SourceTable.Animal)
output inserted.ID, SourceTable.Size into Table2(ID, Size);
注意:如果 Table2
具有针对 Table1
定义的外键,则无法直接输出到 Table2
.在这种情况下,您可以使用临时表作为输出目标,并从临时表插入到 Table2
中。
关于sql-server - 有没有一种方法可以从一个到另一个使用 FK 批量插入到两个表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3249073/