当执行返回表中“resident”计数的存储过程时,期望为4,但是为零

时间:2016-10-03 07:05:14

标签: sql sql-server stored-procedures

我的tblResident表中有四行,其中ID列是主键,当我执行以下代码时,我希望得到4,但是我取而代之的是0。为什么会这样?

create procedure spGetTotalResidentCount2
as
begin
    return select count(ID) from tblResident
end

declare @TotalResident int 
execute @TotalResident =  spGetTotalResidentCount2
select @TotalResident

5 个答案:

答案 0 :(得分:2)

这应该这样做

create procedure spGetTotalResidentCount2 as
begin
    set nocount on
    select count(ID) from tblResident
end

execute spGetTotalResidentCount2

或者您可以创建一个功能:

create function dbo.fnGetTotalResidentCount2 returns int as
begin
     declare @count int
     select @count = count(ID) from tblResident
     return @count
end

并像这样使用

declare @count int
select @count = dbo.fnGetTotalResidentCount2

答案 1 :(得分:2)

您需要使用 OUTPUT 值才能将值分配给@TotalResident字段。

create procedure spGetTotalResidentCount2
(
    @countResident int out
)
as
begin
    set @countResident = 4
end

declare @TotalResident int = 0
execute spGetTotalResidentCount2  @TotalResident out
select @TotalResident

或者您也可以使用 RETURN 来执行此操作。检查以下代码:

alter procedure spGetTotalResidentCount2
as
begin
    return 4
end

declare @TotalResident int = 0
execute @TotalResident = spGetTotalResidentCount2  
select @TotalResident

答案 2 :(得分:2)

使用OUTPUT子句

create procedure spGetTotalResidentCount2
@count int OUTPUT
as
    select @count = count(ID) from tblResident

return
GO

declare @TotalResident int 
execute @TotalResident =  spGetTotalResidentCount2 output
select @TotalResident

答案 3 :(得分:1)

这是因为您要返回值而不是仅选择它们。将您的程序正文更改为SELECT COUNT(ID) FROM tblResident

答案 4 :(得分:1)

试试这个:

CREATE PROC spGetTotalResidentCount2
AS
BEGIN
  DECLARE @count INT;
  SELECT @count = count(ID) FROM tblResident;
  RETURN @count;
END