Getting the Id of MS SQL Server Last Entered Record
In MS SQL Server, the following procedure is followed to get the Id of the last record entered into the system.
--INSERT COMMAND SELECT SCOPE_IDENTITY()Id means the "primary key" column of the table, which may not be of "int" data type. Therefore, it is more accurate to obtain this record with the SCOPE_IDENTITY() method instead of reaching the last record with the "Max()" function.
The SCOPE_IDENTITY() method is often used in a "stored procedure". The purpose of use is generally the request to perform another operation with that record immediately after INSERT a record into the system. Therefore, the "primary key" is obtained using the relevant method.
Let's examine the example below..
INSERT INTO Table1 (Column1, Column2, Column3) VALUES ('Value1', 'Value2', 'Value3') DECLARE @LAST_ID AS INT SET @LAST_ID = (SELECT SCOPE_IDENTITY()) UPDATE Table2 SET Column1 = 'Value1', Column2 = 'Value2' WHERE Table1_Id = @LASTIn the example, after a record is inserted into the table, the variable @LAST is created and the "primary key" of this record is assigned to the created variable with the SCOPE_IDENTITY method. This variable is then used in the second operation, the UPDATE query.