Reputation: 59
In T-SQL, the following are true:
Given these facts, will any unusual behavior result from the following code?
IF EXISTS (
SELECT someValue FROM someTable WHERE someValue = 1
)
BEGIN TRY
-- do something
END TRY
BEGIN CATCH
PRINT @@ERROR
END CATCH
Will the PRINT @@ERROR line execute if the IF statement evaluates to false? My hunch is that the code within the Catch block will not be executed if control never reaches the Try block, but I cannot find any documentation to addresses this specific issue.
I could skip over this entire issue by wrapping the entire Try/Catch block in a BEGIN statement, but I'd like to avoid that if possible (just for aesthetics).
Upvotes: 3
Views: 5692
Reputation: 77876
Will the PRINT @@ERROR line execute if the IF statement evaluates to false?
Simple answer NO. You can try and see for yourself. Only if the IF ..
block evaluates to TRUE
then it will. See a sample code below
alter procedure testsp
as
begin
declare @var int;
IF EXISTS (
SELECT Name FROM student WHERE Marks < 90
)
BEGIN TRY
set @var = 20/0;
END TRY
BEGIN CATCH
PRINT @@ERROR
END CATCH
end
Upvotes: 3