1

我有以下查询

DECLARE @onlymonth bit
SET @onlymonth = 0

DECLARE @month int
SET @month = 5

SELECT 
SUM(amount) amount
FROM accounting ac
WHERE
DATEPART(mm,ac.date) <= @month

我想要的是取决于 @onlymonth 参数删除次要符号所以......例如

...WHERE DATEPART(mm,ac.date) = CASE WHEN @onlymonth = 0 THEN = @month ELSE <= @month END...

类似的东西..有什么线索吗?

提前致谢。

4

3 回答 3

2

尝试这个:

SELECT 
    SUM(amount) amount
FROM
    accounting ac
WHERE
    (DATEPART(mm,ac.date) = @month and @onlymonth = 0)
OR
    (DATEPART(mm,ac.date) <= @month and @onlymonth = 1)
于 2013-07-30T22:14:00.720 回答
0

替代方法:

declare @month int, @bSingleMonth bit
set @month = 7
set @bSingleMonth = 1

SELECT SUM(amount) amount
FROM accounting ac
WHERE DATEPART(mm, ac.date)
     between 1 + IsNull(@bSingleMonth, 0) * (@month - 1) and @month

这使得它什么between @month and @month时候@bSingleMonth设置,between 1 and @month什么时候不设置。

于 2013-07-30T22:27:32.733 回答
0

这可以满足您的需求。

DECLARE @onlymonth bit
SET @onlymonth = 0

DECLARE @month int
SET @month = 5

if (@onlymonth = 0)
begin
    SELECT 
    SUM(amount) amount
    FROM accounting ac
    WHERE
    DATEPART(mm,ac.date) <= @month
end
else 
begin
    SELECT 
    SUM(amount) amount
    FROM accounting ac
    WHERE
    DATEPART(mm,ac.date) = @month
end
于 2013-07-30T22:13:29.320 回答