存储过程以查找过去n个月中雇用的员工数量

时间:2014-07-23 23:07:27

标签: sql-server stored-procedures

我正在尝试创建一个存储过程,该过程返回Northwind数据库中最近n个月雇佣的员工数。这就是我得到的:

CREATE PROC spGetEmployeeCountByDateHire
@num1 int 
,@num2 int 
,@EmployeeCount int output
 WITH Encryption 
AS 
BEGIN 
select @EmployeeCount = COUNT(*),
DATEDIFF(DAY, HireDate, getdate()) AS Diff 
FROM  Employees where DATEDIFF(DAY, HireDate, getdate()) between @num1 and @num2 
ORDER BY HireDate Desc END

我得到了这个错误:消息141,级别15,状态1,过程spGetEmployeeCountByDateHire,第8行为变量赋值的SELECT语句不能与数据检索操作结合使用。

有人可以帮我理解我做错了吗?

1 个答案:

答案 0 :(得分:0)

错误正是告诉您不能将count(*)分配给变量并同时选择datediff操作的原因。通过从选择列表

中删除DATEDIFF(DAY, HireDate, getdate()) AS Diff部分,更改您的选择语句,如下所示
select @EmployeeCount = COUNT(*)
FROM  Employees 
where DATEDIFF(DAY, HireDate, getdate()) between @num1 and @num2