0

我正在使用SQL Server 2008 R2。如果@Day設置爲NULL那麼就應該執行的CASE..WHEN聲明有條件的WHERE子句用於獲取記錄

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 

我想實現的是,

- 條件一:

我有如下的SQL塊其他- 條件二

但是我在CASE..WHEN聲明中得到"="附近的語法錯誤。

任何人都可以讓我知道如何做到這一點?

回答

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)另一個語法錯誤,但我不知道什麼應該在那裏,所以我離開它,因爲它是。

+0

謝謝Syzmon。我來檢查一下。 – Dev

+0

不工作。在這種情況下,條件1和條件2都是取回記錄。 – Dev

+0

在這種情況下@Day是否爲null?沒有看到數據就很難給出明確的答案。 – Szymon