We are handling Exceptions in our stored procedures using Try/Catch block. In a stored procedure I have intentionally made an error to check how the exceptions being handled. I wrote a stored procedure like as below,
CREATE PROCEDURE TEST
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRAN
;WITH CTE
AS
(SELECT TOP 10 *
FROM student)
SELECT * FROM CTE
SELECT * INTO #VAL
FROM CTE
IF @@ERROR = 0
BEGIN
COMMIT TRAN;
END
END TRY
BEGIN CATCH
SELECT @@ERROR AS ERROR, ERROR_LINE() AS [Error Line], ERROR_MESSAGE() AS [Error Message]
ROLLBACK TRAN;
END CATCH
SET NOCOUNT OFF;
END
In the Above Stored procedure I have used a CTE multiple Times. I expected that SQL-SERVER will handle the exception but it didn't. While Executing the Above stored Procedure I got below error
Msg 208, Level 16, State 1, Procedure TEST, Line 16
Invalid object name 'CTE'.
Msg 266, Level 16, State 2, Procedure TEST, Line 16
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 2.
Why the Exception is not handled ? Could someone give idea on this?
Thanks for the help.