简体   繁体   English

如果使用多个insert语句,有没有办法使用SCOPE_IDENTITY?

[英]Is there any way to use SCOPE_IDENTITY if using a multiple insert statement?

I will import many data rows from a csv file into a SQL Server database (through a web application). 我将许多数据行从csv文件导入SQL Server数据库(通过Web应用程序)。 I need the auto generated id value back for the client. 我需要为客户端返回自动生成的id值。

If I do this in a loop, the performance is very bad (but I can use SCOPE_IDENTITY() without any problems). 如果我在循环中执行此操作,性能非常差(但我可以使用SCOPE_IDENTITY()而没有任何问题)。

A more performant solution would be a way like this: 更高效的解决方案是这样的:

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

Is there any way to get all generated IDs and not only the last generated id? 有没有办法获得所有生成的ID,而不仅仅是最后生成的ID?

Thanks for your help! 谢谢你的帮助!

Best regards, Thorsten 最好的问候,托尔斯滕

No, SCOPE_IDENTITY() only gives you the one, latest inserted IDENTITY value. 不, SCOPE_IDENTITY()仅为您提供一个最新插入的IDENTITY值。 But you could check out the OUTPUT clause of SQL Server .... 但是你可以查看SQL Server的OUTPUT子句 ....

DECLARE @IdentityTable TABLE (SomeKeyValue INT, NewIdentity INT)

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

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. 运行INSERT语句后,表变量将保留“某个键值”(为此,标识行)以及插入的每行的新插入的ID值。 Now go crazy with this! 现在对此疯狂! :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM