2013-01-02 22 views
0

我將數據從一個表格插入到其他幾個表格中。第一個插入將創建一個新的用戶標識。這個新用戶標識將用於後續插入。我也將繼續從源表中插入用戶名到其他表中。下面的插入鏈是針對一個用戶的。可能會涉及2000個用戶。如何分組幾個插入?

我很熟悉如何使用遊標完成此操作。有沒有其他的方式來做這個沒有光標的插入鏈?

insert into table 1 using @username and @firstname from source table 

insert into table 2 using userid generated from table 1 (userid1) 

insert into table 3 using @username and userid1 

insert into table 4 using userid1 
+1

可以使用輸出條款(http://msdn.microsoft.com/en-gb/library/ms177564(v=sql.100)。 aspx)可以批量捕獲ID,如果你可以按照時尚的方式安排你的插入。 – Laurence

+0

我熟悉輸出子句。你有沒有一個你喜歡時尚的例子? – 4thSpace

+1

http://sqlfiddle.com/#!3/89ab3/1 – Laurence

回答

1

您可以使用Insert語句的Output Clause來批量捕獲生成的ID。

例如:

Create Table dbo.Source (
    FirstName nvarchar(100), 
    LastName nvarchar(100) 
); 

Create Table dbo.Attrs (
    Id int Identity Not Null Primary Key, 
    Name nvarchar(100) Not Null, 
    DefaultVal nvarchar(100) 
); 

Create Table dbo.Table1 (
    Id Int Identity Not Null Primary Key, 
    FirstName nvarchar(100), 
    LastName nvarchar(100) 
); 

Create Table dbo.Table2 (
    Id int Identity Not Null Primary Key, 
    Table1ID int Not Null Foreign Key References dbo.Table1 (Id), 
    AttrId int Not Null Foreign Key References dbo.Attrs (Id) 
); 

Insert Into dbo.Source Values 
    (N'Mickey', N'Mouse'), 
    (N'Donald', N'Duck'), 
    (N'Goofy', Null); 

Insert Into dbo.Attrs Values 
    ('Size', 'Small'), 
    ('Wings', 'No'); 

Declare @Temp1 Table (Id Int, FirstName nvarchar(100), LastName nvarchar(100)) 
Declare @Temp2 Table (Id int, Table1ID int, AttrId int) 

Insert Into dbo.Table1 
    (FirstName, LastName) 
Output 
    inserted.Id, inserted.FirstName, inserted.LastName 
Into 
    @Temp1 
Select 
    FirstName, LastName 
From 
    dbo.Source 


Insert Into dbo.Table2 
    (Table1ID, AttrId) 
Output 
    inserted.Id, Inserted.Table1ID, Inserted.AttrID 
Into 
    @Temp2 
Select 
    t.Id, 
    a.Id 
From 
    @Temp1 t 
    Cross Join 
    dbo.Attrs a 

Select * From @Temp2 

http://sqlfiddle.com/#!3/31110/3

+0

謝謝。跟進問題,如果你有興趣:http://stackoverflow.com/questions/14143750/how-to-supply-values-to-sproc-from-table。 – 4thSpace