T-SQL Store Prodecure执行问题一输入参数(默认值)和一个输出参数

时间:2018-02-22 13:29:59

标签: tsql

我使用带有默认值和输出参数的输入参数创建了一个存储过程,但是如果没有收到错误消息,我就无法执行它:

  

Msg 8162,Level 16,State 2,Procedure spGetEmployeeCountDefault,Line 21   形式参数“@Gender”未声明为OUTPUT参数,而是在请求的输出中传递的实际参数。

商店程序的定义以及我如何执行它:

CREATE PROCEDURE spGetEmployeeCountDefault
(
 @Gender nchar(1) = 'F', -- Supply Gender Value e.g. 'M' or 'F'
 @EmployeeCount int Output  -- Return an Integer Value for Employee Count
)
AS

BEGIN
    -- Main SP Code to retrieve the count 
    SELECT @EmployeeCount = COUNT([BusinessEntityID]) 
    FROM  [HumanResources].[Employee]
    WHERE Gender = @Gender
END

-- Execute store procedure and select result
DECLARE @EmployeeCount int
EXEC spGetEmployeeCountDefault @EmployeeCount out 
SELECT @EmployeeCount [Total of Employes]

定义是否正确,是否可以这样使用商店程序,谢谢?

1 个答案:

答案 0 :(得分:2)

如果您没有明确命名参数,即

EXECUTE spGetEmployeeCountDefault @EmployeeCount = @EmployeeCount OUT;

然后SQL Server将按照它们在create procedure语句中声明的顺序分配它们,所以你真正拥有的是相当于:

DECLARE @EmployeeCount int

EXECUTE spGetEmployeeCountDefault @Gender = @EmployeeCount OUT;

导致问题的原因是什么。因此,您需要如上所述明确命名参数,或传递@Gender的值:

DECLARE @EmployeeCount int

EXECUTE spGetEmployeeCountDefault NULL, @EmployeeCount OUT;