TRY CATCH in SQL Server

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

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

But I get 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 someone tell me how to do try catch in SQL Server?

+5
source share
4 answers

This is a fully valid statement for SQL Server 2005 and above, so I would look at 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 he will return 80 or lower, it seems that he does not know BEGIN TRY, only BEGIN. BEGIN TRYIt was added in SQL Server 2005.

+8
source

, , SQL Server 2008.

+2

If you still have this error, the question arises: did you insert the BEGIN CATCH ... END CATCH section. If not, you will get this error. If you have a BEGIN TRY ... END TRY section without a T-SQL code in it, then it will also result in an error.

I don’t think that useful people tell you that you are using SQL Server 2000. Most likely, the problem is with T-SQL encoding, since you usually know which server you are running on.

+2
source
Begin try
  Begin transaction
    --------
    --------
  Commit transaction
End try
Begin catch
  Rollback transaction
End catch

http://intquesans.blogspot.com/2011/05/how-we-can-use-try-catch-in-sql.html

+2
source

All Articles