开发者

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 ne开发者_运维技巧ar '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?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜