Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Stored procedures sql sp年或年和月_Stored Procedures_Dry - Fatal编程技术网

Stored procedures sql sp年或年和月

Stored procedures sql sp年或年和月,stored-procedures,dry,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 )

我有一些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
当然,逻辑比求和(col)更复杂

我的问题是,如何编写此SP以使逻辑不会在两个SP之间重复,即使这意味着在我指的是全年的情况下,目标月通过0?

SELECT sum(col)
SELECT sum(col) 
FROM [yourtable]
WHERE year(dateTime) = @TargetYear 
    AND (@targetMonth < 0 OR month(dateTime) = @targetMonth)
从[你的桌子] 其中年份(日期时间)=@TargetYear 和(@targetMonth<0或month(dateTime)=@targetMonth)
我喜欢乔尔的答案,只是如果你把零作为一个月,他的答案就行不通了。您需要@targetMonth=0,例如:

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

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

Create PROCEDURE Report( @targetYear int, @targetMonth int = null )
可以使用参数调用,也可以不使用参数调用:

exec Report 2009
exec Report 2009, 2 
然后在逻辑中检查空值:

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)