如何在同一查询中使用ISNULL和HASHBYTES?

时间:2019-04-06 13:31:47

标签: sql sql-server

我正在SQL Server ISNULL过程中使用UPDATE命令,并且正在使用密码哈希字节

ALTER PROCEDURE [dbo].[Update_Users]
    (@Id INT,
     @StaffName NVARCHAR(50) NULL,
     @Email NVARCHAR(100) NULL,
     @UserName VARCHAR(40),
     @Password VARCHAR(50),
     @Phoneno NVARCHAR(50) NULL,
     @Admin CHAR(3) NULL)
AS
BEGIN
    UPDATE Users 
    SET StaffName = ISNULL(StaffName, @StaffName),
        Email = ISNULL(Email, @Email),
        UserName = ISNULL(UserName, @UserName),
        PasswordHash = HASHBYTES('SHA2_512', @Password),
        Phoneno = ISNULL(Phoneno, @Phoneno),
        [IsAdmin] = ISNULL(IsAdmin, @Admin)
    WHERE Id = @Id
END

如何使用hashbytes列上的isnullpasswordhash

2 个答案:

答案 0 :(得分:0)

不确定我是否猜对了,但是从您的UPDATE模式来看,您可能想要

...
passwordhash = isnull(password, hashbytes('SHA2_512', @Password)),
...

即如果passwordhash为空,则将其替换为@password变量中密码的哈希值。

答案 1 :(得分:0)

转换为varbinary

 isnull( HASHBYTES('SHA2_512', @Password),convert (varbinary,'') )

尝试一下

 alter procedure [dbo].[Update_Users]
(
@Id int ,
@StaffName nvarchar(50)   ,
@Email nvarchar(100)  ,
@UserName varchar(40),
@Password varchar(50),
@Phoneno nvarchar(50)  ,
@Admin char(3)   
)
as
 begin
 Update Users 
 Set StaffName=ISnull(StaffName,@StaffName),
  Email=ISnull(Email,@Email),
  UserName=Isnull(UserName,@UserName),
  PasswordHash =  isnull( HASHBYTES('SHA2_512', @Password),convert (varbinary,'') ),
  Phoneno=Isnull(Phoneno,@Phoneno),
  [IsAdmin]=Isnull(IsAdmin,@Admin)
  where Id=@Id
end