在SQL Server存储过程中执行DECRYPTBYKEY时获取空输出

时间:2014-03-15 19:16:41

标签: sql-server stored-procedures

我是存储过程的新手。我已成功将用户密码加密到表中。但是当我写一个解密SP时,我得到一个空输出。请检查SP并指出我的错误

ALTER PROCEDURE [dbo].[temp]
    @EmployeeUserName varchar(20),
    @EmployeePassword varchar(20),
    @Flag varchar(10),
    @Error VARCHAR(10) OUT
AS
BEGIN
    if (@Flag = 'login')
    BEGIN
        DECLARE @EncryptedPasswordfromDatabase varbinary(256)
        DECLARE @DecryptedPassword varchar(20)

        select @EncryptedPasswordfromDatabase = EmployeePassword from employeelogin where EmployeeUserName=@EmployeeUserName

        OPEN SYMMETRIC KEY EmployeeLoginKey DECRYPTION BY CERTIFICATE EncryptPasswordCert
        SET @Error = convert(varbinary(20),DECRYPTBYKEY(@EncryptedPasswordfromDatabase))
        RETURN @Error
        CLOSE SYMMETRIC KEY EmployeeLoginKey
    END
END

提前致谢

1 个答案:

答案 0 :(得分:0)

当你将@Error参数作为OUTPUT传递时,你不需要返回关键字。

程序定义

USE [Practice]
GO
ALTER PROCEDURE [dbo].[temp]
    @EmployeeUserName varchar(20),
    @EmployeePassword varchar(20),
    @Flag varchar(10),
    @Error VARCHAR(10) OUT
AS
BEGIN
    if (@Flag = 'login')
    BEGIN
        DECLARE @EncryptedPasswordfromDatabase varbinary(256)
        DECLARE @DecryptedPassword varchar(20)

        select @EncryptedPasswordfromDatabase = EmployeePassword from employeelogin where EmployeeUserName=@EmployeeUserName

        OPEN SYMMETRIC KEY EmployeeLoginKey DECRYPTION BY CERTIFICATE EncryptPasswordCert
        SET @Error = convert(varbinary(20),DECRYPTBYKEY(@EncryptedPasswordfromDatabase));
-- No Return required
        CLOSE SYMMETRIC KEY EmployeeLoginKey    
    END
END

EXECUTE PROC

DECLARE @Error_OUT VARCHAR(10); 

EXECUTE [dbo].[temp]
              @EmployeeUserName = 'Emp Name'
             ,@EmployeePassword = 'Password'
             ,@Flag             = 'some flag'
             ,@Error            =  @Error_OUT OUTPUT --<-- Use the OUTPUT word here
                                                        -- when passing params

<强> RETURN

在您的程序RETURN中的任意位置使用stops the execution of code there关键字并退出。因此,在代码中,一旦代码进入IF块,SYMMETRIC KEY将永远不会关闭。

RETURN关键字也只能用于return INT datatype。您的@Error是VARCHAR数据类型。即使您在程序中的正确位置使用它,它也无法使用RETURN关键字。