I’m reading that using the OUTPUT clause is probably the best way to retrieve the Identity of a newly inserted record. I’m pretty sure I could write a stored procedure and call that but my business objects use dynamically generated sql so having to use a stored procedure would be problematic. Can anyone show me how to use ado.net to execute a single input statement with the output clause and get the returned Identity value? It looks like it might not be possible to do it exactly this way but I thought I’d ask…
EDIT: Okay so it was easier than I thought… I thought I had to output to a table variable at first. But the way I am doing it now isn’t working quite right as it is returning the Identity ‘before’ inserting the new record. Here is the statement I was just testing with:
INSERT Test (F1)
OUTPUT SCOPE_IDENTITY()
VALUES ('Testing')
Every time I do this it gives me back a result one number lower than what the value of the last inserted record’s Identity actually is. I would just add 1 to the result, but of course that won’t work when I’m going between tables and the last result was from a different table.
I’m wondering if I should use IDENT_CURRENT(‘Test’) and add 1 to that since it will be handled as a single transaction and I shouldn’t have to worry about concurrency issues.
Any thoughts on how to get the correct result returned though?
If your identity field name is Id, then use like this:
Value returned by
SCOPE_IDENTITY()will change AFTER theinsertand obviouslyOUTPUTfinishOr keep it simple:
and you shouldn’t even know what is the identity field.