|
-
December 4th, 2008, 12:44 PM
#1
Return id from stored procedure
Hi!
I have a stored procedure (SQL 2000) in which i make an insert in a table. Some of the columns in the table are:
ID (int)
FileName (varchar)
[Time] (datetime)
The problem is that "ID" is the primary key, and configured as "Identity". Whenever I make an insert, the value of this field is automatically generated. I want to return the number that is generated at insert, but I don't know how to!? I hope someone can help me! Great forum btw...
/M
-
December 5th, 2008, 04:52 AM
#2
Re: Return id from stored procedure
There is a scope_identity() function which will get you what you want
see http://msdn.microsoft.com/en-us/library/ms190315.aspx
gl
Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. - Rich Cook
0100 1101 0110 1001 0110 0011 0110 1000 0110 0001 0110 0101 0110 1100 0010 0000 0100 0101 0110 1100 0110 1100 0110 0101 0111 0010
-
December 11th, 2008, 10:15 PM
#3
Re: Return id from stored procedure
or u can used RETURN @@IDENTITY but it's for all ur scope based on the documentation
-
January 6th, 2009, 12:08 AM
#4
Re: Return id from stored procedure
Never use "RETURN @@IDENTITY" - it is just asking for trouble!

Use only "RETURN SCOPE_IDENTITY()" instead.
Why?
Let us see:
Code:
INSERT INTO table1 (a) VALUES ('a')
RETURN @@IDENTITY
Its seams to work OK.
And than U decided to have a trigger defined on table1 which do this:
Code:
INSERT INTO table2 (a) select [id] from inserted
And it is also working good.... But ... hmmm ... why [id]s returned from SP are now wrong?
Because U returned global value of identity, not identity which U generated in the scope of your SP. That’s why!
Use "SCOPE_IDENTITY()" always (it was introduced by Microsoft in MsSQL2000 to fix problem with triggers, and Microsoft is keeping @@IDENTITY IMHO only for backward compatibility)
Best regards,
Krzemo.
Last edited by Krzemo; January 6th, 2009 at 12:11 AM.
Reason: removing blank CODE tags
-
January 11th, 2009, 11:02 PM
#5
Re: Return id from stored procedure
aargh..thanks for that info Krzemo
i never used trigger in my DB, so never run into any trouble ..will change it to SCOPE_IDENTITY() ASAP
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|