Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert into a table and get back the primary key value?

I have a primary key set up to auto increment.

I am doing multiple queries and I need to retrieve that primary key value to use as a foreign key in another table (IsIdentity = TRUE).

Is there any elegant way to get back the primary key value when I do an insert query? Right now I am requerying and getting the highest value in that column which seems really hacky.

Any suggestions?

like image 754
leora Avatar asked Sep 01 '09 03:09

leora


People also ask

How do you undo a primary key?

In Object Explorer, right-click the table with the primary key, and select Design. In the table grid, right-click the row with the primary key and choose Remove Primary Key to toggle the setting from on to off. To undo this action, close the table without saving the changes.

How do I find the primary key in a table?

Primary Keys. The primary key of a table is the column whose values are different in every row. Because they are different, they make each row unique. If no one such column exists, the primary key is a composite of two or more columns whose values, taken together, are different in every row.


2 Answers

If you are using SQL Server 2005 or later, you can use the OUTPUT clause.

create table T(   pk int identity primary key,   dat varchar(20) ); go  insert into T output inserted.pk values ('new item'); go  drop table T; 

The output can be directed to a table as well as to the client. For example:

create table T(   pk int identity primary key,   dat varchar(20) );  create table U(   i int identity(1001,1) primary key,   T_pk int not null,   d datetime ); go   insert into T output inserted.pk, getdate() into U(T_pk,d) values ('new item'), ('newer item'); go  select * from T; select * from U; go  drop table T, U; 

Beginning with SQL Server 2008, you can use "composable DML" for more possibilities.

like image 146
Steve Kass Avatar answered Oct 23 '22 13:10

Steve Kass


insert into YourTable values (...)

get the new PK with scope_identity()

select scope_identity()
like image 38
roman m Avatar answered Oct 23 '22 12:10

roman m