-10

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?

J. Steen
  • 15,260
  • 15
  • 59
  • 62
shiroi
  • 1
  • 5

3 Answers3

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,032
  • 10
  • 15
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.

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
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Phoenix
  • 1
  • 1
  • 1
    This 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