我有兩個表,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