1

我正在将一个表中的数据插入到其他几个表中。第一次插入将创建一个新的用户 ID。此新用户 ID 将用于后续插入。我还将继续将源表中的用户名插入到其他表中。下面的插入链适用于一位用户。可能会涉及 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
4

1 回答 1

1

您可以使用 Insert 语句的输出子句批量捕获生成的 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

于 2013-01-03T00:16:30.003 回答