我有以下SQL Server存储过程验证密码。
ALTER PROC [dbo].[spValidatePassword]
@UserId uniqueidentifier,
@Password NVARCHAR(255)
AS
BEGIN
DECLARE @PasswordHash NVARCHAR(255) = HASHBYTES('SHA2_512', (SELECT @Password + CAST((SELECT p.PasswordSalt FROM Passwords p WHERE p.UserId = @UserId) AS NVARCHAR(255))))
SELECT COUNT(*)
from Passwords
WHERE UserId = @UserId
AND [Password] = @PasswordHash
--return 1 if valid password
--return 0 if not valid
END
如果计数大于零,如何从存储过程返回1,否则为零?
答案 0 :(得分:3)
尝试此查询,如果有结果将返回1
,否则0
SELECT (CASE WHEN COUNT(*) > 1 THEN 1 ELSE 0 END)
FROM Passwords
WHERE UserId = @UserId
AND [Password] = @PasswordHash
答案 1 :(得分:2)
ALTER PROC [dbo].[spValidatePassword]
@UserId uniqueidentifier,
@Password NVARCHAR(255)
AS
BEGIN
DECLARE @PasswordHash NVARCHAR(255) = HASHBYTES('SHA2_512', (SELECT @Password + CAST((SELECT p.PasswordSalt FROM Passwords p WHERE p.UserId = @UserId) AS NVARCHAR(255))))
SELECT
CASE WHEN EXISTS (
SELECT *
from Passwords
WHERE UserId = @UserId
AND [Password] = @PasswordHash
)
THEN 1
ELSE 0
END
--return 1 if valid password
--return 0 if not valid
END
但是考虑使用其他身份验证模型,如OAuth或Office 365登录,而不是重新发明轮子
答案 2 :(得分:0)
IF (SELECT COUNT(UserId) from Passwords WHERE UserId = @UserId AND [Password] = @PasswordHash) > 0
begin
return 1;
End
ELse
begin
return 0;
end
此查询将返回所需的结果
答案 3 :(得分:0)
IF EXISTS (
SELECT *
from Passwords
WHERE UserId = @UserId
AND [Password] = @PasswordHash
)
RETURN 1;
ELSE
RETURN 0;
答案 4 :(得分:0)
您还可以使用OUTPUT Type存储过程将标量(在您的情况下为1或0)结果为:
ALTER PROC [dbo].[spValidatePassword]
@UserId uniqueidentifier,
@Password NVARCHAR(255),
@result TINYINT OUTPUT
AS
BEGIN
DECLARE @PasswordHash NVARCHAR(255) = HASHBYTES('SHA2_512', (SELECT @Password + CAST((SELECT p.PasswordSalt FROM Passwords p WHERE p.UserId = @UserId) AS NVARCHAR(255))))
SELECT @result = COUNT(*)
from Passwords
WHERE UserId = @UserId
AND [Password] = @PasswordHash
END
您可以执行此proc作为:
DECLARE @output TINYINT
EXEC [dbo].[spValidatePassword] @UserId= 'any user id',@Password = 'any password',@result = @output OUTPUT
PRINT @output