我使用SQL Server 2005,並希望打造一批地址記錄,更新聯繫人記錄與新標識的:如何在更新父項時插入一組子記錄?
看看下面的表格
create table contact(id int primary key identity, home_address_id int, work_address_id int)
create table address(id int primary key identity, street varchar(25), number int)
鍵和外鍵:
ALTER TABLE dbo.contact ADD CONSTRAINT FK_contact_address1 FOREIGN KEY (home_address_id) REFERENCES dbo.address(id)
ALTER TABLE dbo.contact ADD CONSTRAINT FK_contact_address2 FOREIGN KEY (work_address_id) REFERENCES dbo.address(id)
一些虛擬數據
insert into contact default values
insert into contact default values
insert into contact default values
如何我可以爲所有沒有家庭地址的聯繫人插入默認空地址記錄,並一次性更新home_address_id?
第一部分是簡單的:
insert into address(street) select null from contact where home_address_id is null
我甚至可以得到新創建的地址的ID:
declare @addressTable table(id int)
insert into address(street)
OUTPUT INSERTED.Id INTO @addressTable
select null from contact where home_address_id is null
這裏是新的ID的
select * from @addressTable
但如何更新與這些新的Id的聯繫表?