在T-SQL中手动引发错误以跳转到开始CATCH块
是否可以在存储过程中手动引发错误以停止执行并跳转到开始CATCH块?C中的一些模拟抛出新异常 这是我的存储过程的主体:在T-SQL中手动引发错误以跳转到开始CATCH块,sql,sql-server,tsql,exception-handling,try-catch,Sql,Sql Server,Tsql,Exception Handling,Try Catch,是否可以在存储过程中手动引发错误以停止执行并跳转到开始CATCH块?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 @@tra
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
我知道一种方法:选择1/0,但这太糟糕了 您可以使用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子句。是您要查找的详细信息。
从MSDN:
生成错误消息并
启动服务器的错误处理
一场错误可以是
引用用户定义的消息
存储在sys.messages目录中
动态查看或生成消息。
该消息作为服务器返回
发送给调用方的错误消息
应用程序或关联的捕获
TRY…CATCH构造的块
CodeProject有一个详细说明,它还详细描述了如何工作以及如何使用它。SQL有一个错误引发机制
RAISERROR ( { msg_id | msg_str | @local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]
只要在网上查一下书就行了。但是您必须生成相应严重性的错误,严重性为0到10的错误不会导致您跳转到catch块。您可以使用SQL Server 2012+中提供的THROW:
THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>
引发异常并将执行转移到SQL Server 2017中TRY…CATCH构造的CATCH块
请参考下面的链接
不能在函数中使用“THROW”。悲哀的