从表中获取最后一个自动编号的最佳方法 [英] Best way to get the last autonumber from a table

查看:54
本文介绍了从表中获取最后一个自动编号的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1。假设我在MS SQL Server数据库中有一个具有自动编号列(标识列)的表。我们称之为'Sales'和标识列'SaleID'。



2.然后我有一个StoredProcedure插入总销售额,触发SaleID生成(原因) SaleID是标识)并将生成的SaleID返回给应用程序,以便可以进一步使用。



3.最后,假设这是一个Web应用程序(ASP) .Net)很多用户同时可以触发销售。





如果我的存储过程代码是......

1. Suppose I have a table in MS SQL Server database that has an autonumber column (identity column). Let's call the table 'Sales' and identity column 'SaleID'.

2. Then I have a StoredProcedure which inserts the total sale amount, triggering SaleID to generate (cause SaleID is identity) and returns the SaleID generated to the app so it can be used further ahead.

3. Finally, suppose this is all for a web application (ASP.Net) where a lot of users simultaneously can trigger a sale.


If my Stored Procedure code is...

--@HypotheticalSalesTotal comes from the SP's parameters

declare @SaleID INT

INSERT INTO dbo.Sales (SaleDate, Total) VALUES (GETDATE(), @HypotheticalSalesTotal)

SELECT @SaleID = MAX(SaleID)
FROM dbo.Sales 





...这是一种安全获取与此次销售相对应的SaleID的方法吗?

鉴于网络应用程序上的同时购买者数量,SaleID可以交叉吗?



或者MS SQL Server是否安全地在队列中逐个运行StoredProcedures?







非常感谢!



...Is this a way to safely obtain the SaleID that corresponds to this sale?
Given the amount of simultaneous buyers at the web app, is there any chance the SaleIDs could cross?

Or does MS SQL Server safely runs StoredProcedures one by one in queue?



Thank you very much!

推荐答案

不,不是。



SCOPE_IDENTITY [ ^ ]





(但我从不使用标识列。它们会造成太多麻烦。)
No, it is not.

SCOPE_IDENTITY[^]


(But I never use identity columns. They cause too much trouble.)


SELECT id FROM table ORDER BY id DESC LIMIT 1







SELECT LAST_INSERT_ID()
SELECT id FROM table ORDER BY id DESC LIMIT 1

or

SELECT LAST_INSERT_ID()


这篇关于从表中获取最后一个自动编号的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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