我正在使用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
附近收到语法错误。
任何人都可以告诉我如何实现这一目标吗?
答案 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)
中还有另一种语法错误,但我不确定应该是什么,所以我保持原样。