返回Insert语句生成的所有ID

时间:2015-06-09 17:25:51

标签: sql-server stored-procedures

我将表值参数传递给SP,然后将数据插入到两个表中。第二个表需要第一个表的Id(主键)。结构如下所示:

Table_1
(
  Id BIGINT NOT NULL , --Primary Key
  FirstName NVARCHAR(50),
  LastName NVARCHAR(50),
  Category NVARCHAR(10),
  UniqueIdentifier NVARCHAR(100)
)

Table_2
(
  Id BIGINT NOT NULL, --Primary Key
  UserId BIGINT REFERENCES Table_1(Id) NOT NULL,
  Role NVARCHAR(20)
)

现在,我希望将数据作为

插入表1中
INSERT INTO Table_1
(FirstName, LastName, Category, UniqueIdentifier)
SELECT tmp.FN, tmp.LN, tmp.Cat, tmp.UniqueIdentifier
FROM #TempTable tmp;

和表2中的

INSERT INTO Table_2
(UserId, Role)
SELECT out.Id, tmp.Role
FROM #TempTable2 tmp
JOIN OUTPUT out
ON tmp.UniqueIdentifier = out.UniqueIdentifier

这里我希望从第一个插入的结果中将OUTPUT填充为Id和UniqueIdentifier。我知道使用OUTPUT.Id和OUTPUT.UniqueIdentifier可以实现单个记录插入。但是,我如何为这种特殊情况实现类似的功能呢?

1 个答案:

答案 0 :(得分:2)

尝试:

-- create temp table to hold the id and unique ids
CREATE TABLE #table1_ids(id bigint not null, 
                         [UniqueIdentifier] NVARCHAR(100));

-- insert data into 1st table and obtain the ids into above temp ids table 
INSERT INTO Table_1(FirstName, LastName, Category, [UniqueIdentifier])
OUTPUT inserted.ID, inserted.[UniqueIdentifier] INTO #table1_ids 
SELECT tmp.FN, tmp.LN, tmp.Cat, tmp.UniqueIdentifier
FROM #TempTable tmp;

-- insert data into 2nd table using the above temp ids table
INSERT INTO Table_2(UserId, Role)
SELECT tids.Id, tmp.Role
FROM #TempTable2 tmp
INNER JOIN #table1_ids tids ON 
     tmp.UniqueIdentifier = tids.UniqueIdentifier