有没有什么办法,如果使用多个insert语句使用SCOPE_IDENTITY? [英] Is there any way to use SCOPE_IDENTITY if using a multiple insert statement?

查看:197
本文介绍了有没有什么办法,如果使用多个insert语句使用SCOPE_IDENTITY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将导入很多数据行从一个CSV文件导入到SQL Server数据库(通过一个Web应用程序)。我需要自动生成的值id回客户端。

I will import many data rows from a csv file into a SQL Server database (through a web application). I need the auto generated id value back for the client.

如果我这样做,在一个循环中,表现非常糟糕(但我可以用 SCOPE_IDENTITY()没有任何问题)。

If I do this in a loop, the performance is very bad (but I can use SCOPE_IDENTITY() without any problems).

一个更高性能的解决方案会是这样一种方式:

A more performant solution would be a way like this:

INSERT INTO [MyTable]
VALUES ('1'), ('2'), ('3')
SELECT SCOPE_IDENTITY()

有没有办法让所有生成的ID,而不是只有最后生成的ID?

Is there any way to get all generated IDs and not only the last generated id?

感谢您的帮助!

最好的问候, 托尔斯滕

Best regards, Thorsten

推荐答案

没有, SCOPE_IDENTITY()只给你在一,最新的插入身份值。但是你可以检查出的SQL Server 输出条款 ....

No, SCOPE_IDENTITY() only gives you the one, latest inserted IDENTITY value. But you could check out the OUTPUT clause of SQL Server ....

DECLARE @IdentityTable TABLE (SomeKeyValue INT, NewIdentity INT)

INSERT INTO [MyTable]
OUTPUT Inserted.Keyvalue, Inserted.ID INTO @IdentityTable(SomeKeyValue, NewIdentity)
VALUES ('1'), ('2'), ('3')

一旦你运行你的插入语句,表变量将举行一些关键值(为你,标识行)和新插入的 ID 值插入的每一行。现在疯狂地使用这个! : - )

Once you've run your INSERT statement, the table variable will hold "some key value" (for you, to identify the row) and the newly inserted ID values for each row inserted. Now go crazy with this! :-)

这篇关于有没有什么办法,如果使用多个insert语句使用SCOPE_IDENTITY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆