primary key

M

Matt Mercer

Hi all,

Hope I am not posting too many questions...cannot find the answer
anywhere, though. I need to know when I insert a record into my
database table what the primary key is for that record. It is
generated by SQL automatically, but I need to associate data in other
tables with it.

I can pull the highest primary key # from the table but if someone
else submits info before this happens I may get the wrong number. Is
there a way to find out what they primary key assigned is as I do the
insert? Thanks again.
 
H

Hermit Dave

if you primary key field is identity field then all you do is start a

strat trans myinsert

insert statement here

declare @myprimarykey int
select @myprimarykey == @@identity

commit trans myinsert

--

Regards,

Hermit Dave
(http://hdave.blogspot.com)
 
L

Lucas Tam

(e-mail address removed) (Matt Mercer) wrote in
Is
there a way to find out what they primary key assigned is as I do the
insert? Thanks again.

INSERT INTO MyTable Values (1,2,3,4,5); SELECT @@IDENTITY;

Just use the statement above with a ADO.NET Command ExecuteScalar Method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top