我正在尝试编写一个更改用户密码的程序,但我在完成它时遇到了一些困难,我有一般的要点,但有一些语法错误。这是我的程序;
CREATE PROC ChangePassword
@User_Name NVARCHAR(50),
@OldPassword NVARCHAR(50),
@NewPassword NVARCHAR(50),
@ResponseMessage NVARCHAR(250)='' OUTPUT
AS
BEGIN
SET NOCOUNT ON
IF ((
SELECT PasswordHash
FROM dbo.Users
WHERE dbo.Users.user_name=@User_Name)=HASHBYTES('SHA2_512',@OldPassword + (
SELECT CAST(Salt AS NVARCHAR(50))
FROM dbo.Users
WHERE dbo.Users.user_name = @User_Name)))
THEN
UPDATE dbo.Users SET PasswordHash = HASHBYTES('SHA2_512',@NewPassword + (
SELECT CAST(Salt AS NVARCHAR(50))
FROM dbo.Users
WHERE dbo.Users.user_name = @User_Name))
SET @ResponseMessage = 'Password Changed Successfully'
ELSE
SET @ResponseMessage = 'Old Password did not match'
END
它基本上检查他们输入的旧密码的散列是否与实际旧密码的散列匹配,如果是,则用新密码的散列更新它,但我对{{1}有点困难}}语句因为IF
和THEN
分别在ELSE
和incorrect syntax near 'THEN'
下面有编译错误,有人可以提供一些指导来解决这个问题吗?
答案 0 :(得分:1)
为了便于阅读和维护,您可以执行以下操作:
CREATE PROC ChangePassword
@User_Name NVARCHAR(50),
@OldPassword NVARCHAR(50),
@NewPassword NVARCHAR(50),
@ResponseMessage NVARCHAR(250) = '' OUTPUT
AS
BEGIN
-- To keep track of the old password hash in the User table
DECLARE @oldPasswordHash VARBINARY(8000) = (SELECT PasswordHash FROM dbo.Users WHERE User_Name = @User_Name);
-- To obtain the salt used with the HASHBYTES function and passwords
DECLARE @salt NVARCHAR(50) = (SELECT Salt FROM dbo.Users WHERE User_Name = @User_Name);
-- To check if the old password hash in the User table matches the the @OldPassword passed by the user
DECLARE @computedOldPasswordHash VARBINARY(8000) = HASHBYTES('SHA2_512', @OldPassword + @salt);
-- Check if old password hash equals the computed old password hash
IF (@oldPasswordHash = @computedOldPasswordHash)
BEGIN
-- new password hash
DECLARE @newPasswordHash VARBINARY(8000) = HASHBYTES('SHA2_512', @NewPassword + @salt);
UPDATE dbo.Users
SET PasswordHash = @newPasswordHash
WHERE User_Name = @User_Name
SET @ResponseMessage = 'Password Changed Successfully'
END
ELSE
BEGIN
SET @ResponseMessage = 'Old Password did not match'
END
END
答案 1 :(得分:0)
在SQL语言中,则不用于IF语句。 然后它在案例结构中使用,好吗? 改变你的开始
保持这种状态
CREATE PROC ChangePassword
@User_Name NVARCHAR(50),
@OldPassword NVARCHAR(50),
@NewPassword NVARCHAR(50),
@ResponseMessage NVARCHAR(250)='' OUTPUT
AS
BEGIN
SET NOCOUNT ON
IF ((
SELECT PasswordHash
FROM dbo.Users
WHERE dbo.Users.user_name=@User_Name)=HASHBYTES('SHA2_512',@OldPassword + (
SELECT CAST(Salt AS NVARCHAR(50))
FROM dbo.Users
WHERE dbo.Users.user_name = @User_Name)))
BEGIN
UPDATE dbo.Users SET PasswordHash = HASHBYTES('SHA2_512',@NewPassword + (
SELECT CAST(Salt AS NVARCHAR(50))
FROM dbo.Users
WHERE dbo.Users.user_name = @User_Name))
SET @ResponseMessage = 'Password Changed Successfully'
END
ELSE
BEGIN
SET @ResponseMessage = 'Old Password did not match'
END --END ELSE
END --end proc