Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TRY CATCH in SQL Server

I am using SQL Server 2008. I have tried to execute the following:

BEGIN TRY
    SELECT 1/0;
END TRY
BEGIN CATCH
    PRINT 'ERROR'
END CATCH;

But I am getting the following error:

>Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near 'TRY'.
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'END'.

Can any one tell me how execute try catch in SQL Server?

like image 205
ANP Avatar asked Oct 26 '10 13:10

ANP


1 Answers

That is a completely valid statement for SQL Server 2005 and up, so I'd check your compatibility level using sp_dbcmptlevel (Transact-SQL):

exec sp_dbcmptlevel 'YourDatabaseName'

80 = SQL Server 2000
90 = SQL Server 2005
100 = SQL Server 2008

I think it will return 80 or lower, it seems that it doesn't know BEGIN TRY, only BEGIN. The BEGIN TRY was added in SQL Server 2005.

like image 76
KM. Avatar answered Oct 19 '22 19:10

KM.