Return Insert语句生成的所有Id

Return all Ids generated by Insert statement

我正在将一个 table 值参数传递给 SP,然后它将数据插入两个 table。第二个 table 需要第一个 table 的 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)
)

现在,我想将数据插入 table 1 as

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

并进入table 2 as

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 可以实现单条记录插入。但是我如何针对这个特定案例实现类似的功能?

尝试:

-- 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