SQL Server:为新添加的行选择主键编号
我当前正在
SELECT MAX(CustomerID)...
选择 CustomerID
,它是表的主键,新添加的行的编号,因为我需要将此编号用于另一个使用它作为外键的表。通过 INSERT
添加一行,并按顺序执行一个 SELECT
查询。
在 SQL Server Management Studio 的列属性下,我看到 Identity Increment
设置为 1
。使用 MAX(CustomerID)
获取我需要的内容是否存在不安全的原因?对于此过程,代码将始终是“一行 INSERT 和一个 SELECT 查询”。如果有更好的方法,那会是什么?也许,在某个地方,“给我新添加的行的 CustomerID
”?
I'm currently using
SELECT MAX(CustomerID)...
to select the CustomerID
, which is the primary key of the table, number of a newly added row because I need to use this number for another table that uses it as a foreign key. One row is added via INSERT
, and one SELECT
query is performed sequentially.
Under column property in SQL Server Management Studio, I see the Identity Increment
is set to 1
. Is there an unsafe reason to use MAX(CustomerID)
to get what I need? The code will always be "one row INSERT and one SELECT queries" for this procedure. If there is a better way, what would that be? Perhaps, somewhere along the line, "get me the CustomerID
of the newly added row"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在并发条件下(并且当表为空时)
使用
SELECT SCOPE_IDENTITY()
或OUTPUT
, 您建议的MAX(CustomerID)
方法将失败> 条款。以下两者的示例Your suggested approach with
MAX(CustomerID)
will fail under conditions of concurrency (and when the table is empty)use
SELECT SCOPE_IDENTITY()
or theOUTPUT
clause. Examples of both below