简体   繁体   中英

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'

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 select s 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM