是否可以在存储过程中手动引发错误以停止执行并跳转到BEGIN CATCH块?throw new Exception()in的一些类似物C#。
BEGIN CATCH
throw new Exception()
C#
这是我的存储过程的主体:
BEGIN TRY BEGIN TRAN -- do something IF @foobar IS NULL -- here i want to raise an error to rollback transaction -- do something next COMMIT TRAN END TRY BEGIN CATCH IF @@trancount > 0 ROLLBACK TRAN END CATCH
我知道一种方法:SELECT 1/0但是太糟糕了!
SELECT 1/0
您可以使用raiserror。在此处阅读更多详细信息
raiserror
-来自MSDN
BEGIN TRY -- RAISERROR with severity 11-19 will cause execution to -- jump to the CATCH block. RAISERROR ('Error raised in TRY block.', -- Message text. 16, -- Severity. 1 -- State. ); END TRY BEGIN CATCH 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;
编辑 如果您使用的是SQL Server 2012+,则可以使用throw子句。这是详细信息。
throw