Search code examples
c#sqlraiserrorexecutereader

Combining SQL `raiserror` with `select` in C#


I want to know if there is a way of using both SQL raiserror and retrieving the selected result in C#. ExecuteReader() in C# will throw an exception when raiserror occurs, but I still want to use the reader to capture any data returned.

Below is a simplified example. If this is not possible I will use raiserror for general cases and select for specific cases.

if (some-error)
begin
    select  @Message = 'ERROR: script made a booboo',
            @State = 'State Info'
    raiserror (@Messsage, 16, 1)
    goto exit_sp
end

exit_sp:
    select  @Message 'Message', @State 'State'

Solution

  • If you lower the severity to 10 or below (from memory) it will not raise an exception, but will be available via the InfoMessage event on the connection. Note, however, that because of how TDS works, you should ensure that you Read() etc to the end of all results; for example, if you have multiple selects and then a raiserror, and you only read the first select before dropping the data-reader, there is a chance you won't see the message (the TDS will be killed).