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?
You can achieve it this way:
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.