如何使用THROW结合TRY CATCH中的测试值?

时间:2015-02-12 08:12:21

标签: sql-server sql-server-2012

我编码了这个:

BEGIN TRY

SELECT @TestUserId = UserId,
       @TestCreatedBy = CreatedBy
FROM   UserTest
WHERE  UserTestId = @UserTestId

IF ( @TestUserId != @UserId & @TestCreatedBy != @UserID)
BEGIN
   THROW 50000,'THROW TEST',1
END

END TRY
BEGIN CATCH
   SET @RC = 1
   SET @ErrorMessage = ERROR_MESSAGE()
   RETURN
END CATCH

我遇到以IF开头的行的问题。它给出了一个错误说:

! - Incorrect syntax

此外,THROW行显示错误

有人可以告诉我如何正确地进行此抛出和错误以及如何捕获它。我可以捕获特定于50000代码的块吗?

2 个答案:

答案 0 :(得分:1)

我希望@UserId在某处定义。问题出在&上 - 将其替换为AND

答案 1 :(得分:1)

试试这个

BEGIN TRY

SELECT @TestUserId = UserId,
       @TestCreatedBy = CreatedBy
FROM   UserTest
WHERE  UserTestId = @UserTestId

IF ( @TestUserId != @UserId AND @TestCreatedBy != @UserID)
BEGIN
   raiserror('THROW TEST',16,1)
END

END TRY
BEGIN CATCH
   SET @RC = 1
   SET @ErrorMessage = ERROR_MESSAGE()
   RETURN
END CATCH