T-SQL,在子查询中使用 MAX()+1 插入不会增加,替代方案吗?
我有一个查询,需要将行“批量”插入到具有不带标识的主键的表中。
--TableA
--PK int (Primary key, no-identity)
--CustNo int
INSERT INTO TableA (PK,CustNo)
SELECT (SELECT MAX(PK)+1 AS PK FROM TableA), CustNo
FROM Customers
(简化示例 - 请不要评论可能的并发问题:-))
问题是它不会增加“每个”已处理行的 PK,并且我遇到了主键冲突。
我知道如何使用游标/while 循环来做到这一点,但我想避免这种情况,并以基于集合的方式解决它,如果可能的话?
(运行 SQL Server 2008 标准版)
I have a query where I need to "batch" insert rows into a table with a primary key without identity.
--TableA
--PK int (Primary key, no-identity)
--CustNo int
INSERT INTO TableA (PK,CustNo)
SELECT (SELECT MAX(PK)+1 AS PK FROM TableA), CustNo
FROM Customers
(simplified example - please don't comment about possible concurrency issues :-))
The problem is that it doesn't increment the PK "for each" processed row, and I get a primary key violation.
I know how to do it with a cursor/while loop, but I would like to avoid that, and solve it in a set-based kind of manner, if that's even possible ?
(running SQL Server 2008 Standard)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
+1 Michael Buen,但我有一个建议:
表“tablea”可以为空,所以我们应该这样写:
这将防止在尝试使用此代码时出现空错误。
+1 to Michael Buen, but I have one suggestion:
The table "tablea" can be empty, so we should write:
This will prevent a null error when trying to use this code.
正如您所看到的问题是它们都获得相同的行号,每行的 max(PK) +1 都是相同的。
尝试将其转换为
Max(PK) + Row_number()
我正在研究为什么你知道这是一个坏主意等,并且为了获得一个目的而简化了你的问题答案,而不是您希望如何解决问题。
The problem as you have seen is that they all get the same row number, the max(PK) +1 is the same for every row.
Try convert it to be
Max(PK) + Row_number()
I'm working on the basis as to why you know this is a bad idea etc, and your question is simplified for the purpose of getting an answer, and not how you would wish to solve the problem.
你可以;
You can;
我给你一个建议,伙计,一个更好的 SQL 实践是使用 SEQUENCE,你猜怎么着,这很容易做到,只需复制并粘贴我的:
并像这样使用:
希望这个技巧能够帮助你!
I have a suggestion for you buddy, a better practice on SQL says to use SEQUENCE, and guess what, it´s VERY easy to do it man, just copy and paste mine:
and use like this:
Hope this tip able to help ya!