I inserted values into an SQL table that has an auto increment primary key and I want to get the Pk value that the last insert has it. How do I do that?
Asked
Active
Viewed 1,777 times
3 Answers
0
try this
@LastInsertedId=SCOPE_IDENTITY()
you should use this after insert query
insert into table(ColumnName)values("name")
@LastInsertedId=SCOPE_IDENTITY()

ali zarei
- 1,212
- 11
- 17
0
if you want to get the PK when you insert values you can use this code:
INSERT INTO table_name (column2,column3,column4)
OUTPUT Inserterd.column1
VALUES (value1,value2,value3)
in above code column1
is the PK that is auto increment you want to get.

mohamadkamal
- 43
- 6
0
I think it would be easier if you first add a column in your named Updatedate (datetime), then you can just write the query like below :
Select top 1 *
From TableName
Order By Updatedate desc
-
1This is **NOT** going to work in a system with even just medium load of concurrent users - by the time your code gets to the point to select the `TOP 1` row, one or several **more** rows could have been inserted by other users of the system. This is **NOT RELIABLE** and thus **NOT RECOMMENDED!** – marc_s Jan 01 '18 at 12:20