Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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...
SQL
--@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 


...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!
Posted

No, it is not.

SCOPE_IDENTITY[^]


(But I never use identity columns. They cause too much trouble.)
 
Share this answer
 
v2
Comments
Homero Rivera 4-Oct-13 17:09pm    
Looks like the best option. I'll take as answer as soon as I can test it, please be patient.
SELECT id FROM table ORDER BY id DESC LIMIT 1

or

SELECT LAST_INSERT_ID()
 
Share this answer
 
Comments
Homero Rivera 4-Oct-13 17:10pm    
Looks good, only this works for MySQL not for MS SQL Server. Could you improve your answer stating this is for MySQL; I'll be glad to accept as solution as soon as that is stated.
Ranesh M Raj 5-Oct-13 0:24am    
SElECT IDENT_CURRENT('tablename') in Ms Sql

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900