用于获取记录的条件WHERE子句

时间:2014-03-06 05:46:51

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我正在使用SQL Server 2008 R2。

我有一个SQL块,如下所示:

DECLARE @Day INT = 5
DECLARE @Month INT = NULL
DECLARE @year INT = NULL
DECLARE @dtnow DATETIME

SET @dtnow = GETDATE()

IF @Month IS NULL
    SELECT @Month = MONTH(DATEADD(MONTH,-1, @dtnow ))

IF @Year IS NULL
    SELECT @year = YEAR(DATEADD(MONTH,-1, @dtnow ))


SELECT * 
FROM TblSalesRecords 
WHERE 
    CASE WHEN @Day IS NULL THEN -- Condition One
        BEGIN 
            ISNULL(@Month, MONTH(TblSalesRecords.CreatedDate)) = MONTH(TblSalesRecords.CreatedDate) 
            AND (@year, YEAR(TblSalesRecords.CreatedDate)) = YEAR(TblSalesRecords.CreatedDate)
        END 
    ELSE                        -- Condition two
        BEGIN 
            TblSalesRecords.CreatedDate BETWEEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(DATEADD(MONTH,-1, @dtnow ))) + '-' + CONVERT(VARCHAR,month(DATEADD(MONTH,-1,@dtnow))) + '-' + CONVERT(VARCHAR, DAY(DATEADD(MONTH,-1,@dtnow))) +' 00:00:00.000') 
            AND CONVERT (DATETIME, CONVERT(VARCHAR,YEAR(DATEADD(DAY,-1,@dtnow ))) + '-' + CONVERT(VARCHAR,MONTH(DATEADD(DAY,-1,@dtnow))) + '-' + CONVERT(VARCHAR, DAY(DATEADD(DAY,-1,@dtnow))) +' 23:59:59.998')
        END
    END 
    AND TblSalesRecords.IsDeleted=0

我想要实现的是,

如果@Day设置为NULL,那么它应该执行CASE..WHEN语句 - 的条件一 - 条件二< / em>的。

但我在"="语句中的CASE..WHEN附近收到语法错误。

任何人都可以告诉我如何实现这一目标吗?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT * 
FROM TblSalesRecords 
WHERE (@Day IS NULL 
            AND ISNULL(@Month, MONTH(TblSalesRecords.CreatedDate)) = MONTH(TblSalesRecords.CreatedDate) 
            AND (@year, YEAR(TblSalesRecords.CreatedDate)) = YEAR(TblSalesRecords.CreatedDate)
       )
    OR (@Day IS NOT NULL                      -- Condition two
            AND TblSalesRecords.CreatedDate BETWEEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(DATEADD(MONTH,-1, @dtnow ))) + '-' + CONVERT(VARCHAR,month(DATEADD(MONTH,-1,@dtnow))) + '-' + CONVERT(VARCHAR, DAY(DATEADD(MONTH,-1,@dtnow))) +' 00:00:00.000') 
            AND CONVERT (DATETIME, CONVERT(VARCHAR,YEAR(DATEADD(DAY,-1,@dtnow ))) + '-' + CONVERT(VARCHAR,MONTH(DATEADD(DAY,-1,@dtnow))) + '-' + CONVERT(VARCHAR, DAY(DATEADD(DAY,-1,@dtnow))) +' 23:59:59.998')
        )
    AND TblSalesRecords.IsDeleted=0

(@year, YEAR(TblSalesRecords.CreatedDate)) = YEAR(TblSalesRecords.CreatedDate)中还有另一种语法错误,但我不确定应该是什么,所以我保持原样。