sql sp年或年和月

时间:2009-02-12 19:50:16

标签: stored-procedures dry

我有一些年份和月份的SP:

Create PROCEDURE Report(
    @targetYear int,
    @targetMonth int
)

用以下方式查询:

select sum(col) where year(dateTime) = @targetYear and month(dateTime) = @targetMonth

然后我一年只有同样的事情

Create PROCEDURE Report(
    @targetYear int
)

并查询它:

select sum(col) where year(dateTime) = @targetYear

当然,逻辑比sum(col)

更复杂

我的问题是,我怎么能写这个SP所以不会在两个SP上重复逻辑,即使它意味着在我指的是全年时将0传递给目标月份?

3 个答案:

答案 0 :(得分:1)

我喜欢乔尔的回答,但是如果你在月份中输入零,他将无法工作。你需要@ targetMonth = 0例如:

SELECT sum(col) 
WHERE year(dateTime) = @TargetYear AND 
(@targetMonth = 0 OR month(dateTime) = @targetMonth)

答案 1 :(得分:0)

SELECT sum(col) 
FROM [yourtable]
WHERE year(dateTime) = @TargetYear 
    AND (@targetMonth < 0 OR month(dateTime) = @targetMonth)

答案 2 :(得分:0)

存储过程可以有一个可选参数:

Create PROCEDURE Report( @targetYear int, @targetMonth int = null )

可以使用参数调用它:

exec Report 2009
exec Report 2009, 2 

然后在逻辑中检查null:

SELECT sum(col) 
FROM [yourtable]
WHERE (year(dateTime) = @TargetYear and @targetMonth = null)
  OR (year(dateTime) = @TargetYear AND @targetMonth = month(dateTime))

SELECT sum(col) 
FROM [yourtable]
WHERE year(dateTime) = @TargetYear 
  AND (@targetMonth = null OR year(dateTime) = @TargetYear)