批量插入返回无序标识字段
我有(tableA)带有一个标识字段(ID),我需要通过一次插入操作一次插入多行,所以我使用表结构作为我的存储过程的传递参数
我需要插入的id和插入顺序,所以我正在我的 SP 中运行以下查询 (tableB 与 tableA 具有相同的结构):
CREATE PROCEDURE ssp_Test
(
tableA tableAType
)
AS
BEGIN
INSERT INTO tableB(field1, field2, ...)
OUTPUT INSERTED.ID
SELECT field1, field2, ... from tableA
END
如果我使用 100 条记录运行上述过程,它将返回新的标识字段及其插入到 tableB 的顺序,但是当我使用 500 条记录运行它时,所有插入的 id 都会返回,但没有合理的顺序为什么会发生这种情况?
我不需要另一个临时表将其放在那里并对其进行排序并返回,我只是想知道为什么会发生这种情况,并且是否有任何解决方案而不使用额外的临时表进行排序?
I have (tableA) with one identity field (ID), I need to insert multiple rows at once with one insertion operation, so I use table structure as a passing parameter to my stored procedure
I need the inserted id with the order of insertion so i'm running the following query in my SP
(tableB has the same structure as tableA):
CREATE PROCEDURE ssp_Test
(
tableA tableAType
)
AS
BEGIN
INSERT INTO tableB(field1, field2, ...)
OUTPUT INSERTED.ID
SELECT field1, field2, ... from tableA
END
If I run the above procedure with 100 records it returns the newly identity field with the order it inserted to the tableB, but when I run it with 500 records all of the inserted id returns with no reasonable order why this happens?
I don't need another temp table to put it there and sort that and return, i just want to know why its happening and is there any solution without using extra temp table for sorting ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想要订购某些东西,则必须使用 ORDER BY 子句。尝试依赖物理顺序是没有价值的(即使您认为您知道存在一个物理顺序(即因为聚集索引)
If you want something ordered you'll have to use an ORDER BY clause. There's not value in trying to rely on a physical order (even if you think you know one exists (ie because of a clustered index)
看这篇文章:
http://technet.microsoft.com/en-us/library/ms177564.aspx
它指出:
“无法保证将更改应用于表的顺序与将行插入输出表或表变量的顺序相对应。”
我建议在插入后使用 select 来检索 ID。
Look at this article:
http://technet.microsoft.com/en-us/library/ms177564.aspx
It states:
"There is no guarantee that the order in which the changes are applied to the table and the order in which the rows are inserted into the output table or table variable will correspond."
I suggest using a select after your insert to retrieve the ID's.
要使用数字序列填充列,请使用 ROW_NUMBER()(或 SQL Server 2012 中的序列)。不要尝试依赖 IDENTITY 列,因为它的行为并不总是可控的。
To populate a column with a numerical sequence use ROW_NUMBER() (or a sequence in SQL Server 2012). Don't try to rely on the IDENTITY column because its behaviour can't always be controlled.