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”?
Your suggested approach with
MAX(CustomerID)will fail under conditions of concurrency (and when the table is empty)use
SELECT SCOPE_IDENTITY()or theOUTPUTclause. Examples of both below