0

我需要根据某些条件在 Sybase ASE 数据服务器上执行密码重置:

if validations_here
begin
    exec sp_password 'sso_passw', 'new_passw', @userid
end

sp_password可能会引发一些错误,例如10316 - "New password provided is the same as the previous password"。虽然我找不到任何文档,但我认为它们不应该是致命错误,应该可以用raiserror.

由于调用者以这种方式处理它会更容易,我想获取错误代码并将其作为结果集的一部分返回,所以我考虑选择@@error。我的代码如下(我只转录了我认为与问题相关的部分):

create procedure sp_desbloc_blanqueo_usr    
    @userid sysname,        
    @sso_pass varchar(20),  
    @new_pass varchar(20)   
as
begin
    declare @ret_code int
    declare @ret_msg varchar(100)
    declare @myerror int

    select @ret_code = 0, @ret_msg = 'OK'

    exec sp_password @sso_pass, @new_pass, @userid
    set @myerror = @@error 
    if @myerror <> 0
    begin
        select @ret_code = @myerror, @ret_msg = 'Error occurred changing password' 
        -- It would be nice to have the actual error message as well
        goto fin
    end

    fin:
    select @ret_code as ret_code, @ret_msg as ret_msg
end

但是,每当我执行存储过程时,我都会得到 0 asret_code和 OK as ret_msg(即使参数sp_password错误)。

如何sp_password从存储过程中“捕获”错误代码?

4

1 回答 1

1

当出现问题时,许多“sp_”存储过程设置一个非零返回码。通常处理这个返回码比试图捕捉存储过程中引发的错误要好。IIRC,Transact-SQL 无法实现这种捕获;需要第三代语言,例如 C。

要将 myproc 存储过程的返回码放入变量 @myvar,语法为

exec @myvar = myproc [arguments] 

sp_password 的一个简单示例:

declare @spreturn int  
exec @spreturn = sp_password 'notmyoldpw', 'notmynewpw'  
print "Return from sp_password is %1!", @spreturn  
go

Server Message:  Number  10315, Severity  14  
Server 'SDSTRHA01_SY01', Procedure 'sp_password', Line 148:  
Invalid caller's password specified, password left unchanged.  
Server Message:  Number  17720, Severity  16  
Server 'SDSTRHA01_SY01', Procedure 'sp_password', Line 158:  
Error:  Unable to set the Password.  
(1 row affected)  
Return from sp_password is 1  
(return status = 1)  

第一行定义的 int 变量@spreturn 得到 sp_password 返回码,其值为 1,如最后消息行中的 (return status = 1) 所示。它不为零的原因很清楚:sp_password 中有两个错误,10315 和 17720。重点是关注这个非零返回代码并忽略 10315 和 17720。在您的存储过程中,应该检查 @spreturn 是否为零. 如果为零,则运行正常,否则失败。

于 2015-10-26T20:10:34.097 回答