需要从表中删除的存储过程,然后比较传入的值

时间:2016-12-15 16:35:58

标签: sql-server stored-procedures

我对如何继续我的存储过程感到困惑。此SP的想法是获取这些传入值,将它们与我的User_Passwords表进行比较。根据公司政策查看该表是否过长。删除旧的以将表缩小到正确的大小。然后将传入的密码与之前的密码进行比较,在我的VB.Net代码上抛出一个错误,说明他们需要选择不同的密码,因为之前使用过它。我已经对我陷入困境的地方做了评论。

DECLARE @UserNumberOfPasswords INT
DECLARE @ua_pk uniqueidentifier = GUID
DECLARE @ResetDaysAmount INT = 30
DECLARE @AllowedNumberOfPasswords INT = 10
DECLARE @CurrentPasswordDate DATE = GetDate()
DECLARE @CurrentPassword varchar(25) = 'Password'
DECLARE @PreviousPassword BIT = 0

SELECT *
FROM User_Passwords
WHERE ua_fk = @ua_pk
ORDER BY up_PasswordDate ASC

SELECT @UserNumberOfPasswords = COUNT(*)    
FROM User_Passwords AS up
WHERE ua_fk = GUID

IF @UserNumberOfPasswords > @AllowedNumberOfPasswords
BEGIN
    WITH T
    AS (SELECT TOP (@UserNumberOfPasswords - (@AllowedNumberOfPasswords - 1)) *
        FROM   User_Passwords
        WHERE  ua_fk = @ua_pk
        ORDER BY up_PasswordDate ASC)
    DELETE FROM T; 
END

IF @UserNumberOfPasswords = @AllowedNumberOfPasswords
BEGIN
    WITH T
    AS (SELECT TOP 1 *
        FROM User_Passwords
        WHERE ua_fk = @ua_pk
        ORDER BY up_PasswordDate ASC)
    DELETE FROM T;
END

--Where I'm stumped.  I have tried to use 'up_Password' but it's throwing an error
--"the multi-part identifier "User_Passwords.up_Password" could not be bound".
--The column's type is varchar(25), just like @CurrentPassword

IF @CurrentPassword = User_Passwords.up_Password
BEGIN
    WITH T
    AS (SELECT *
        FROM User_Passwords
        WHERE ua_fk = @ua_pk
        ORDER BY up_PasswordDate ASC)
        --I know this isn't completed but I want to change the BadPassword =1

稍后在SP中,如果密码是新密码,我将添加到表中。

1 个答案:

答案 0 :(得分:3)

@SeanLange提出了非常好的观点。我建议你这样做。

IF @CurrentPassword = User_Passwords.up_Password不是有效的声明。 Exists允许您检查查询是否返回任何结果。

以下是一个例子:

IF EXISTS (SELECT 1 FROM User_Passwords WHERE up_Password = @CurrentPassword)
    BEGIN

        PRINT 'We got one'
    END
ELSE
    BEGIN

        PRINT 'No match'
    END