在T-SQL中手动引发错误以跳转到BEGIN CATCH块

aba*_*hev 36 sql t-sql sql-server exception-handling try-catch

是否可以手动引发存储过程中的错误以停止执行并跳转到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
Run Code Online (Sandbox Code Playgroud)

我知道一种方式:SELECT 1/0但它太可怕了!

The*_*iot 67

你可以使用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;
Run Code Online (Sandbox Code Playgroud)

编辑 如果您使用的是SQL Server 2012+,则可以使用throw子句.是详细信息.


Jim*_*Aho 13

您可以使用THROW(在SQL Server 2012+中可用):

THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>
Run Code Online (Sandbox Code Playgroud)

MSDN THROW(Transact-SQL)

Sql Server中RAISERROR和THROW之间的差异

  • 无法在函数内使用“ THROW”。伤心。 (2认同)