Conditional WHERE clause for fetching records

2019-08-18 02:36发布

I am using SQL Server 2008 R2.

I am having an SQL block as below :

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

What I want to achieve is,

If @Day is set to NULL then it should execute the CASE..WHEN Statement of -- Condition One else of -- Condition two.

But I am getting Syntax error near "=" in CASE..WHEN Statement.

Can anyone let me know how to achieve this?

1条回答
老娘就宠你
2楼-- · 2019-08-18 03:19

You can achieve it this way:

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

There's another syntax error in (@year, YEAR(TblSalesRecords.CreatedDate)) = YEAR(TblSalesRecords.CreatedDate) but I'm not sure what should be there so I left it as it is.

查看更多
登录 后发表回答