我有两个表,TableA
和TableB
这样的表和UPDATE的外键:INSERT到另一个表(SQL Server 2008中)
TableA
-------------------------------------------
| id | some_data | new_FK_column_on_B |
| ---- | ----------- | ------------------ |
| 1 | ... | null |
| ... | ... | null |
| 999 | ... | null |
-------------------------------------------
TableB
----------------------
| id | some_data |
| ---- | ----------- |
| | |
----------------------
目前,TableB
是空的,而在TableA
FK列所有行均为null
。我需要编写一次性初始化scrit以填充TableB
并通过插入TableB
的行中的标识符为TableA
初始化某些行(标准,非全部)的FK列。
我知道两种方法可以做到这一点:
使用while
和
scope_identity()
,插入新行
TableB
,并在每次迭代更新
TableA
,而存在于
TableA
行,应更新
1)
while (exists (select 1 from TableA where [condition]))
begin
insert into TableB (some_data) values ('some_data')
update TableA set new_FK_column_on_B
where id = (select top 1 id from TableA where [condition])
end
2)在TableB
中创建临时列,在TableA
中存储行id
,为其插入,然后使用join
更新TableA
alter table TableB add temp int
go
insert into TableB (some_data, temp) select 'some_data', id from TableA where [condition]
update TableA
set new_FK_column_on_B = b.id
from TableB as b
join TableA as a on a.id = b.temp
alter table TableB drop column temp
此外,我试图从insert
这样莫名其妙output
使用,但它的语法不正确:
update TableA
set new_FK_column_on_B =
(
select insertedId from
(
insert into TableB (some_data)
output inserter.id as insertedId
values ('some_data')
)
)
where [condition]
有没有更简单的方式来做到使用while
或对矫正任何表这个内部消除?
这不是一种情况,因为'table_'和'tableB'的'some_data'不一样。它可能是各种各样的列,不同类型,并且它不是唯一的表,它可以重复。 – user2123532
我认为这不是@ user2123532所说的完整答案。 – roll