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?
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.
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.
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.
insert into YourTable values (...)
get the new PK with scope_identity()
select scope_identity()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With