tsqlt - 如何避免 tSQLt 在 raiserror 之后中止调用的过程?
问题描述
在我们的存储过程中,我们喜欢在使用 raiserror() 引发和出错后“返回”一个特定的返回值
为此,我们使用低严重级别(例如 12),然后是返回值,例如:
create or alter proc dbo.usp_test
as
begin
print '**start of proc'
raiserror( 'error on purpose',12,1);
print '**after the error'
return -3
end
这在运行该过程时完美运行:
declare @RC int
exec @RC = dbo.usp_test
print concat('The return code is ', @RC)
/* output:
**start of proc
Msg 50000, Level 12, State 1, Procedure usp_test, Line 6 [Batch Start Line 12]
error on purpose
**after the error
The return code is -3
*/
但是,当从单元测试中调用该 proc 时,行为是不同的,在 raiserror 之后突然停止执行:
create schema T_usp_test authorization dbo;
GO
EXECUTE sp_addextendedproperty @name = 'tSQLt.TestClass', @value = 1, @level0type = 'SCHEMA', @level0name = 'T_usp_test'
GO
create or alter proc T_usp_test.[test mytest]
as
begin
exec tSQLt.ExpectException;
declare @RC int;
exec @RC = dbo.usp_test;
print concat('The return code is ', @RC)
end
GO
exec tSQLt.Run 'T_usp_test.[test mytest]'
/* output:
(1 row affected)
**start of proc
+----------------------+
|Test Execution Summary|
+----------------------+
|No|Test Case Name |Dur(ms)|Result |
+--+--------------------------+-------+-------+
|1 |[T_usp_test].[test mytest]| 7|Success|
-----------------------------------------------------------------------------
Test Case Summary: 1 test case(s) executed, 1 succeeded, 0 failed, 0 errored.
-----------------------------------------------------------------------------
*/
所以问题:
1)为什么行为不同,proc现在突然停止执行raiserror()
?
2)我怎样才能克服这个?
解决方案
运行测试的核心过程是 tSQLt.Private_RunTest,它在 TRY...CATCH 块中运行测试。来自https://docs.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-2017的文档:
A TRY...CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection.
看起来您已将严重性设置为 12。考虑降低 RAISERROR 调用的严重性,看看是否会改变行为。您也可以尝试将您的 RAISERROR 调用包装在它自己的 TRY...CATCH 块中。
推荐阅读
- sql - 如何用 0 填充 null 并使用 spark `pivot` 累积`count`?
- java - 如何使用 volley 将 FCM 通知从一台设备发送到多台设备(订阅主题)
- android - MotionLayout 中的浮动操作按钮(FAB),.show() 不起作用,.hide() 工作不正确
- css - 是否可以在 Vue.js 的不同“页面”上设置不同的菜单样式?
- matlab - 您如何交叉关联音频文件以查看样本是否与原始文件匹配?
- sql-server - VB Net - SQL - 比较文本框的值和 SQL 值
- mysql - 列的页面溢出(InnoDB)如何在 MySQL 中工作?
- laravel - Laravel belongsTo() 为结果中的第一个关系返回 null
- hyperlink - MS Edge PDF 查看器是否会去除适用于 Windows 10 版本 1909 的 IE 中的 PDF 链接?
- java - 自 Andriod 11 以来应用程序活动上方的黑色死区