存储过程帮助:将年份作为参数传递以获得结果

时间:2013-07-15 05:51:22

标签: sql-server sql-server-2008-r2 stored-procedures parameters datetime

我试图基本输入一年(不是整个日期)来取回一组结果,这些结果将告诉我今年销售的东西数量。不过我不知道怎么做。下面是我的一个例子。

ALTER PROC OrderYear
(@OrderYear datetime)
AS

SELECT Orderdate as [Year],COUNT(SalesOrderID) as Count
FROM Sales.SalesOrderHeader
WHERE @OrderYear=YEAR(OrderDate)
GROUP BY OrderDate

BEGIN
SET NOCOUNT ON
END

EXEC OrderYear '2005'

2 个答案:

答案 0 :(得分:7)

您希望将查询谓词表示为范围,因为范围是可搜索的:

SELECT Orderdate as [Year],COUNT(SalesOrderID) as Count
FROM Sales.SalesOrderHeader
WHERE OrderDate >= @firstDayOfYear AND OrderDate <= @lastDayOfYear
GROUP BY OrderDate;

所以诀窍就是计算某一年的@firstDayOfYear@lastDayOfYear。我会将此作为练习留给读者。

答案 1 :(得分:-1)

程序正常,更改输入参数的类型:

ALTER PROC OrderYear
(@OrderYear int) 
AS
SELECT Orderdate as [Year],COUNT(SalesOrderID) as Count
FROM Sales.SalesOrderHeader
WHERE @OrderYear=YEAR(OrderDate)
GROUP BY OrderDate