当前位置:  开发笔记 > 编程语言 > 正文

必须为存储过程声明标量变量错误

如何解决《必须为存储过程声明标量变量错误》经验,为你挑选了1个好方法。

我有以下存储过程:

CREATE procedure validateLogin    
(    
 @password varchar(200),    
 @username varchar(100),  
 @IpAddress   varchar(100)  
)    
AS    
BEGIN    
   Declare @qry varchar(max), @LockedIp varchar(max), @LockedTime DateTime, @TimeDifference int;    

   set @qry = 'select IdUser, UserName, FirstName, LastName, idOrg, Users.idRole, Roles.Title as [Role], Allowed_IP from Users, Roles where Users.idRole = Roles.idRole    
 and lower(UserName) = @username and [password] = @password' ;    

   select 
       @LockedIp = isnull(Allowed_IP,''),
       @LockedTime = isnull(LockedTime, getDate()) 
   from Users 
   where UserName = ISNULL(@username,'');    

   SELECT 
       @TimeDifference = DATEDIFF(MINUTE, @LockedTime, GETDATE())    

   IF exists(select * from Users where UserName = @username AND Password = @password AND Active = 1)    
   BEGIN     
       IF exists(select * from Users where UserName = @username AND isnull(IsLocked, 0) = 1)    
       BEGIN -- BE1    
          IF(@LockedIp = @IpAddress)     
          BEGIN --BE2    
             IF (@TimeDifference >5)    
             BEGIN --BE5    
                 UPDATE Users 
                 SET IsLocked = 0, LockedTime = null 
                 WHERE UserName = ISNULL(@username,'')  

                 exec(@qry);    
             END --BE5    
          ELSE     
          BEGIN    
             select 'Your Account has been Locked.Try after some time' as Error    
          END    
       END --BE2    
    Else IF(@LockedIp!=@IpAddress)     
     BEGIN --BE4    

        UPDATE Users 
        SET IsLocked = 0, LockedTime = null 
        WHERE UserName = isnull(@username,'')  

        exec(@qry);    
     END --BE4    
    END -- BE1    
   Else    
    BEGIN --BE3    
       exec(@qry);    
    END -- BE3    
 END      
END 
Go

当我执行此操作时:

exec validateLogin '|161|217|4|51','admin','127.0.0.1' 

我收到以下错误:

消息137,级别15,状态2,行3
必须声明标量变量"@username".

我在参数列表中声明了这个变量,然后也出现了错误.

请帮我.

我该如何解决这个问题?



1> GarethD..:

EXEC()将在不同的范围内执行,因此找不到您的参数.你应该使用sp_executesql和添加你的参数:

DECLARE @qry NVARCHAR(MAX);

SET @qry = N'select IdUser,UserName,FirstName,LastName,idOrg,Users.idRole,Roles.Title as [Role],Allowed_IP 
            from Users,Roles 
            where Users.idRole=Roles.idRole    
            and lower(UserName)=@username 
            and [password]=@password' ;   


EXECUTE sp_executesql @qry, 
                    N'@username varchar(100), @password varchar(200)', 
                    @Username, 
                    @Password;

推荐阅读
郑小蒜9299_941611_G
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有