tags:

views:

2896

answers:

5

Here's a very simple question. I have an SP that inserts a row into a table and at the end there's the statement RETURN @@IDENTITY. What I can't seem to find is a way to retrieve this value in C#. I'm using the Enterprise library and using the method:

db.ExecuteNonQuery(cmd);

I've tried cmd.Parameters[0].Value to get the value but that returns 0 all the time. Any ideas?

+3  A: 
Dim c as new sqlcommand("...")

Dim d As New SqlParameter()
d.Direction = ParameterDirection.ReturnValue
c.parameters.add(d)

c.executeNonQuery

(@@IDENTITY) = d.value

It is more or less like this...either this or just return the value from a stored procedure as an output parameter.

Craig Norton
You need to add the parameter to the command, but almost there.
Ady
Thats what this line does - c.parameters.add(d) ... though I might have put that in whilst editing whilst you were writing this comment.
Craig Norton
Thanks man. This works.
Daud
Yea, that was the case. Not sure if the parameter name needs to be defined so I posted my own response as well.
Ady
+3  A: 

BTW, in most circumstances, you should use SCOPE_IDENTITY() rather than @@IDENTITY. Ref.

Mitch Wheat
I agree, but in this context it probably doesn't matter.
Ady
There isn't enough information given to determine that. You should only ever use @@IDENTITY when you actually require it.
Mitch Wheat
+1  A: 

One point to mention. You should really use SCOPE_IDENTITY to return the identity value after INSERT. There is potential for @@IDENTITY to return the wrong value. Especially if TRIGGERS are in use, writing value to other tables after INSERT.

See the Books Online page for more detail.

Neil Albrock
A: 

Sounds to me like you want to execute with a scalar value

SqlCommand.ExecuteScalar()

as others have mentioned I think using SCOPE_IDENTITY() is more secure than the @@IDENTITY variable

thmsn
the SP would need to end : select @@IDENTITY rather than return for this to work.
Ady
+1  A: 

Someone says use

IDENT_CURRENT('TableName')

http://www.velocityreviews.com/forums/t303448-return-identity-after-sql-insert.html

-Zubair http://zubairdotnet.blogspot.com