Skip to content
Advertisement

how to get the ID of the record that is update in C#

I am able to get a sql query that can return the ID of a record that is update in the Database; that ID is needed to update other records.

but I don’t know how to get that updated ID value in C#.

Advertisement

Answer

I think you’re really asking how do you retrieve the resultset returned by an INSERT or UPDATE with an OUTPUT clause. You use ExecuteReader instead of ExecuteNonQuery

Here’s simplified example:

Create a test table

C# code

Update where Val is 'ABC' returning the rows updated and print them (excuse the suspect error handling etc)

Prints

And SELECT * FROM Test now shows

Hope this helps. You should be aware that this approach can have issues with triggers and raising/handling of SQL errors.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement