0

我有一个需要 TVP 的存储过程,输入有 6,000 行。当前代码将 TVP 复制到临时表中,在临时表上迭代 RBAR 以在真实表上插入一行,从插入中获取 Identity/PK 值,使用 PK 更新临时表(稍后在存储过程中使用),然后重复。

有没有一种很酷和/或快速的方法来插入整个临时表,然后用 PK 值更新它?没有什么直截了当的想法浮现在脑海中,所有想法都受到赞赏。

我想我可以在临时表中添加一个附加列并在其上放置一个序列号,以便行都是唯一的并遵循这个想法: http ://www.sqlteam.com/article/using-the-output-clause- to-capture-identity-values-on-multi-row-inserts但我对其他基于集合的建议持开放态度....

谢谢。

4

1 回答 1

0

我建议您从 TVP 批量插入到表中,使用该OUTPUT子句用您的结果填充临时表。

这是一个例子:

-- Setup
-- Create the data type
CREATE TYPE dbo.TVPtest AS TABLE 

(

    c1 int NOT NULL, 
    c2 int NULL 
)
GO
CREATE TABLE tableA
(
    id int primary key identity,
    c1 int not null,
    c2 int null
)

-- This is the example
declare @t TVPTest
declare @i int = 1000

-- get a TVP with 1000 rows
WHILE @i >= 0
BEGIN
    INSERT INTO @t
        VALUES (@i, ABS(CHECKSUM(NewId())) % 99)
    SET @i= @i -1
END

-- logic from here is what you would put in your stored procedure
CREATE TABLE #new
(
    id int,
    c1 int not null,
    c2 int null
)

INSERT INTO tableA (c1, c2)
OUTPUT inserted.id, inserted.c1, inserted.c2 into #new
SELECT c1, c2
FROM @t

SELECT *
FROM #new
于 2014-05-28T08:23:39.693 回答