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?
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?
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
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
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
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
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
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
PS this way you can get rid of the trigger as well? Or do you need that for another reason?
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
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!
If you need help on specifics, just say.
Andy