I am unable to use THROW SQL Server 2008 R2

送分小仙女□ 提交于 2019-11-30 21:45:12

问题


SQL Server 2008 R2 Management Studio does not recognized my throw in the below example, it says

incorrect syntax near Throw

I am trying to throw an error here, so I can handled it in my website when someone insert the same value twice.

Begin Try
 insert into BusinessID (BusinessID) values (@ID)
 insert into BusinessID (BusinessID) values (@ID)

End Try

Begin Catch

Print 'PK already exist'
THROW
End Catch

回答1:


THROW Statement is introduced in SQL Server 2012

http://msdn.microsoft.com/en-us/library/ee677615.aspx

You can use RAISERROR instead.

http://msdn.microsoft.com/en-us/library/483588bd-021b-4eae-b4ee-216268003e79(v=sql.105)

BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;



回答2:


Use RAISERROR instead of Throw in your sql block.

Begin Try
 insert into BusinessID (BusinessID) values (@ID)
 insert into BusinessID (BusinessID) values (@ID)

End Try

Begin Catch

Print 'PK already exist'
  DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

SELECT 
    @ErrorMessage = ERROR_MESSAGE(),
    @ErrorSeverity = ERROR_SEVERITY(),
    @ErrorState = ERROR_STATE();

-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
           @ErrorSeverity, -- Severity.
           @ErrorState -- State.
           );
End Catch


来源:https://stackoverflow.com/questions/16670985/i-am-unable-to-use-throw-sql-server-2008-r2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!