【问题标题】:SQL Server 2012 Insert a Set and Get all PK Values?SQL Server 2012 插入一组并获取所有 PK 值?
【发布时间】:2014-05-28 03:18:38
【问题描述】:

我有一个接受 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 但我对其他基于集合的建议持开放态度...... .

谢谢。

【问题讨论】:

  • 为什么不对每一行使用一个触发器?
  • @Rahul,你是说临时表上的触发器吗?在真正的桌子上?这将如何将方法从基于行转变为基于集合?
  • 您实际上是在对真实表进行批量插入,并为每个插入更新临时表。所以我想,insert into real_table select from TVP -> 为每一行定义一个插入后触发器,相应地更新临时表。至少我看到你走的是粗略的方法。
  • 您需要临时表中的主键,您可以使用与输出合并来创建将 PK 从临时表映射到生成的标识的表。见Using merge..output to get mapping between source.id and target.id

标签: sql-server sql-insert table-valued-parameters rbar


【解决方案1】:

我建议您使用OUTPUT 子句将您的结果从 TVP 批量插入到您的表中。

这是一个例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多