Link to home
Create AccountLog in
Avatar of tunhien
tunhien

asked on

Get the key of recently inserted record!

I use SQL Server for store database.
And use Trigger to generate the primary key for new records.

I have problem when I write a programme on Winform:
   When I insert a record into database, I wanna know what the key SQL gennerate for it is so that I can use it for the future.

Show is any good way to do that?
Avatar of AGBrown
AGBrown
Flag of United Kingdom of Great Britain and Northern Ireland image

The SQL function SCOPE_IDENTITY will return the identity used for the last record inserted. You can use a stored procedure to do your insert, and return the value of SCOPE_IDENTITY as an OUTPUT parameter from the stored procedure.

If you need help on specifics, just say.

Andy
Avatar of tunhien
tunhien

ASKER

If I use store procedure then no need to use trigger! and SCOPE_IDENTITY because I can return the key I generated. :d

Show is there any way to do that with C# code not SQL Sever?
Thanks
I don't think I mentioned triggers. Also, if you use a stored procedure, the most efficient way to get the identity you have just inserted _is_ to use SCOPE_IDENTITY. Otherwise, how would you do it? You could do a SELECT Id From... using your inserted values, but that is very messy.

So the only way to do it with C#, if you don't want to do it with a stored procedure and SCOPE_IDENTITY is to execute a second statement after your insert which does just that ... selects the id based on a WHERE clause that finds your inserted values.

So how would you do it with a stored procedure? I'm intrigued.

Andy
Avatar of tunhien

ASKER

It's sound good way!

But please show me more about the store procedure! How can U generate code automatically?

If I've got a table like this:

create table test
(
         code       int,     -- Need to auto increase
         primary key (code)
)


Please write the SP to do that when Insert and return is the key has just been inserted!
Thanks

ASKER CERTIFIED SOLUTION
Avatar of AGBrown
AGBrown
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
PS this way you can get rid of the trigger as well? Or do you need that for another reason?
Avatar of tunhien

ASKER

uupppp!

Thanks for your suggestion! I now I knew the IDENTITY in SQL server. :"> :d
I will try with the new way instead of trigger. :d
good luck!