Haider Ali Wajihi Haider Ali Wajihi - 1 year ago 94
SQL Question

How can I get an error message that happens when using ExecuteNonQuery()?

I am executing a command in this way :

var Command = new SqlCommand(cmdText, Connection, tr);


In the command there is an error, however .NET does not throw any error message. How could I know that the command did not executed properly, and how to get the exception?

Answer Source

You'll only get an exception in C# if your error's severity is 16 or above. If you are using a PRINT, you won't get an exception in .NET.

If you can edit the raise error code, this would cause a SqlException in C#:

RAISERROR('Some error message', 16, 1)

You can then get to each individual error in the SqlException.Errors collection.

Just a side-note - SQL Server will continue to run commands after the RAISERROR if you don't RETURN directly afterwards. If you don't return, you can get multiple errors back.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download