2010-07-29 97 views
2

我使用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的聯繫表?

回答

1

我會從你得到一個新接觸的那一刻,正是如此做:

[receive contact information] 
//prior to inserting contact 
declare @homeAddress int, @workAddress int 

[insert home address here (real or default based on input)] 
set @homeAddress = @@Identity 

[insert work address here (real or default)] 
set @workAddress = @@Identity 

[insert contact here referencing @homeAddress & @workAddress] 

對於你的表已經是東西,你將有你所有的空值ID關聯到聯繫人ID。或者,你可以清空你的空值地址,然後以某種方式修改上述語句的更新(大腦現在不工作,所以我想要的只是一個遊標,而遊標是邪惡的)。

2

如果可能的話,我會建議通過增加Contact_Addresses表規範化數據庫:

CREATE TABLE Contact_Addresses 
(
    contact_id INT NOT NULL, 
    address_id INT NOT NULL, 
    address_type VARCHAR(10) NOT NULL, 
    CONSTRAINT PK_Contact_Addresses PRIMARY KEY CLUSTERED (contact_id, address_id, address_type), 
    CONSTRAINT FK_ContactAddresses_Contacts (contact_id) REFERENCES Contacts (id), 
    CONSTRAINT FK_ContactAddresses_Addresses (address_id) REFERENCES Addresses (id), 
    CONSTRAINT CK_ContactAddresses_address_type CHECK address_type IN ('HOME', 'WORK') 
) 

接下來,我會建議在您的數據庫不把「虛擬」的記載。這將最終導致頭痛。數據庫應該包含系統中數據的準確記錄。如果您希望在系統中沒有地址存在聯繫人時默認顯示某個值,請在您的UI中處理該值。

如果你真的必須雖然,然後將下面的代碼應該做的伎倆:

;WITH C_CTE AS 
(
    SELECT 
     id, 
     home_address_id, 
     ROW_NUMBER() OVER(ORDER BY id) AS seq 
    FROM 
     Contacts 
), 
(
    SELECT 
     id, 
     ROW_NUMBER() OVER(ORDER BY id) AS seq 
    FROM 
     Addresses 
) 
UPDATE 
    C_CTE 
SET 
    home_address_id = A.id 
FROM 
    C_CTE C 
INNER JOIN A_CTE A ON A.seq = C.seq 
相關問題