开发者

Return count in Stored Procedure

开发者 https://www.devze.com 2023-02-13 18:15 出处:网络
I wrote a stored procedure to return a count. But I got a null value. Can anybody tell me where is the problem in my stored procedure.

I wrote a stored procedure to return a count. But I got a null value. Can anybody tell me where is the problem in my stored procedure.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[ValidateUser]
@UserName varchar(50),
@Password varchar(50),
@Num_of_User int output

AS 
BEGIN
  SET NOCOUNT ON;

  SELECT 开发者_StackOverflow社区@Num_of_user =COUNT(*) 
    FROM login
   WHERE username = @UserName 
     AND pw = @Password

  RETURN

END


you are setting the value into the variable @num_of_user. add select @num_of_user after the query

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER PROCEDURE [dbo].[ValidateUser]
    @UserName varchar(50),
    @Password varchar(50),
    @Num_of_User int output

AS
BEGIN
    SET NOCOUNT ON;
     SELECT @Num_of_user =COUNT(*) 
         FROM login
         WHERE username=@UserName AND pw=@Password

     SELECT @Num_of_user
return
END


It doesn't actually return the count, it's an output parameter.

Either change your sproc to return @num_of_user or check the output parameter instead of the return value.


Procedures and functions in SQL server are a bit confusing to me, since a procedure can also return a value. However, you can achieve what you wish by removing the output parameter @Num_of_user and replacing

SELECT @Num_of_user =COUNT(*) 
    FROM login
   WHERE username = @UserName 
     AND pw = @Password

with

SELECT COUNT(*) 
    FROM login
   WHERE username = @UserName 
     AND pw = @Password

The last select statement is always returned from a PROCEDURE in SQL server.


You do not need the isnull. Select count(*) always return a non-null value. You can even issue a

select count(*) from anytable where 1=2 

and you'll get a 0, not a null. I think that your problem arrives when you exec the sp. You may be lacking the 'output' keyword next to the @Num_of_User. Your call should be something like

declare @outNum int 
exec ValidateUser 'some', 'wrong', @outNum output
print @outNum

Notice the 'output' keyword to the right of the parameter


Just another method but outside the Stored Procedure a simple SELECT @@ROWCOUNT can work to get the number of rows.


Had the same issue when it returned null; try to use parenthesis:

SELECT @Num_of_user = ( COUNT(*) 
    FROM login
   WHERE username = @UserName 
     AND pw = @Password )
0

精彩评论

暂无评论...
验证码 换一张
取 消