如何避免tSQLt在rarrrror后中止调用的proc?

时间:2019-03-28 17:21:29

标签: tsqlt

在我们的存储过程中,我们喜欢在使用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时,其行为是不同的,突然在提高筹码器之后停止执行:

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)我该如何克服?

1 个答案:

答案 0 :(得分:0)

运行测试的核心proc是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块中。