2011-03-02 44 views
0

我有一張關於客戶(客戶(姓名,地址))的數據表,其中包含諸如「John Doe」,「Some Street 123」之類的行。對於表中的每一行,我想在Person(id,name)表中插入一行,在Address(id,person_id,address)表中也插入一行。從屬插入語句

我可以通過在客戶運行的每一行兩個INSERT語句做到這一點:

insert into Person(name) values (@name); 
insert into Address(person_id, address) values (scope_identity(), @address); 

但是,這是低效的。我想要做的插入批處理,有點像這樣:

-- This works, the problem is with the Address table... 
insert into Person(name) 
select name from Customer 

-- This looks good but does not work because name is not unique. 
insert into Address(person_id, address) 
select p.person_id, c.address 
from Customer c join Person p on c.name = p.name 

回答

1

由於您丟失了第一次插入的每行的scope_identity()值,因此您沒有辦法做到這一點。

一個解決可能會增加客戶主鍵字段以人表,然後使用此領域第二插件的加入:

插入之前,人

alter table Person add customerID int null; 

然後批量插入創建客戶ID字段:

-- inserting customerID 
insert into Person(name, customerID) 
select name, customerID from Customer 

-- joining on customerID. 
insert into Address(person_id, address) 
select p.person_id, c.address 
    from Customer c 
    join Person p on c.customerID = p.customerID 

後,你可以從Person表中刪除客戶ID字段:

alter table Person drop column customerID 
0

,你在這兩個表中創建獨特類型的某些領域涉及them.otherwise你想加入,你不要有獨特的領域這是更好條件