我使用IF
条件,我得到了长脚本。
所以我想使用CASE
WHEN
缩短脚本。
如何更改以下内容以使用CASE
WHEN
代替IF
:
DECLARE @SDATE1 DATE='2015-01-01'
DECLARE @EDATE1 DATE='2016-01-01'
DECLARE @ASOF VARCHAR(10)='YES'
IF @ASOF='YES'
select * from customer
ELSE
select * from customer WHERE
CAST(CUSTDATE AS DATE)END
BETWEEN @SDATE1 AND @EDATE1
答案 0 :(得分:1)
DECLARE @SDATE1 DATE='2015-01-01'
DECLARE @EDATE1 DATE='2016-01-01'
DECLARE @ASOF VARCHAR(10)='YES'
SELECT *
FROM customer
WHERE (CAST(CUSTDATE AS DATE) >= @SDATE1 AND CAST(CUSTDATE AS DATE) <= @EDATE1 AND @ASOF <> 'YES')
OR @ASOF='YES'
我还删除了语法上不正确的END
,并将between
替换为>= <=
。有关between
的一些潜在问题,请参阅here。
答案 1 :(得分:0)
那么如何编写更复杂的条件
SELECT *
FROM customer WHERE
(@ASOF != 'YES'
AND CAST(CUSTDATE AS DATE) BETWEEN @SDATE1 AND @EDATE1)
OR @ASOF = 'YES'