获取错误为“消息137,级别15,状态2,行4”必须声明标量变量" @TotalCount"。'

时间:2017-02-13 19:08:58

标签: sql-server

Create procedure spgetaveragesalaryAndCount
    @Gender nvarchar,
    @DepartmentId int,
    @AverageSalary int out,
    @TotalCount int out
As
Begin
    select 
        @AverageSalary = AVG(salary), 
        @TotalCount = COUNT(Id)
    from 
        tblemployee 
    where 
        Gender = @Gender 
        and DepartmentId = @DepartmentId 
    group by 
        gender, departmentid
End

declare @AvgSalary int 
declare @HeadCount int

exec spgetaveragesalaryAndCount 
           @Gender = 'Male',
           @DepartmentId = '1', 
           @AverageSalary = @AvgSalary out,
           @HeadCount = @TotalCount out

Print @AvgSalary, @totalcount

每当我调用此存储过程时,我都会收到错误:

  

必须声明标量变量" @TotalCount"

2 个答案:

答案 0 :(得分:2)

您希望在exec中撤消分配,并在打印

中使用@HeadCount
declare @AvgSalary int
declare @HeadCount int

exec spgetaveragesalaryAndCount @Gender = 'Male',
    @DepartmentId = '1',
    @AverageSalary = @AvgSalary out,
    @TotalCount = @HeadCount  out     -- here and 

print @AvgSalary,
    @HeadCount        -- here

另外,正如注释中@marc_s所述,使用带有varchar / nvarchar声明的长度。没有它,默认长度将是一个字符。

Create procedure spgetaveragesalaryAndCount
    @Gender nvarchar(20),
    . . . 

答案 1 :(得分:0)

你缺少@TotalCount int中的declare语句,请参阅下面的代码,

Create procedure spgetaveragesalaryAndCount
    @Gender nvarchar,
    @DepartmentId int,
    @AverageSalary int out,
    @TotalCount int out
    As
    Begin
    select @AverageSalary=AVG(salary), @TotalCount=COUNT(Id)
     from tblemployee where Gender=@Gender and DepartmentId=@DepartmentId group by gender,departmentid
    End

    declare @AvgSalary int 
    declare @HeadCount int
    DECLARE @TotalCount int
    exec spgetaveragesalaryAndCount @Gender='Male',@DepartmentId='1', @AverageSalary=@AvgSalary out,
     @HeadCount=@TotalCount out
    Print @AvgSalary ,@totalcount