Reputation: 15617
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?
Upvotes: 9
Views: 15528
Reputation:
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
Upvotes: 2
Reputation: 21
If you still have this error, the question becomes, have you put a BEGIN CATCH...END CATCH section in. If not, you get this error. If you have a BEGIN TRY...END TRY section with no T-SQL code in it, then it will also produce the error.
I don't think it's helpful people tell you that you're using SQL Server 2000. It is more likely a T-SQL coding issue as you tend to know what server you are running.
Upvotes: 2
Reputation: 103697
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.
Upvotes: 9