Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT query inside TRY CATCH returns empty result set even when error occurs

If you try run following query in MS SQL Server, you will see two result sets as output. I would like to know the reason why SELECT statement still returns result set even when error occurs and how I can remove it when error happens.Because as you may see, I am trying to return another result set with error message.

BEGIN TRY
    SET NOCOUNT ON;

    --invoke divide by zero error
    SELECT 1 / 0 AS DIVZEROERROR

END TRY

BEGIN CATCH
    SELECT ERROR_MESSAGE() AS ERRRORMESSAGE;
END CATCH
like image 335
Pyae Phyo Aung Avatar asked May 30 '26 23:05

Pyae Phyo Aung


1 Answers

SQL Server streams results to the client. Imagine a 1 billion row query. The results are not buffered but streamed as they become available.

SQL Server started streaming and only then noticed the error because the error happened as part of executing the query plan.

Insert the query results to a temp table and only if no error is caught select the contents of that temp table.

like image 79
usr Avatar answered Jun 02 '26 16:06

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!