Sql server选择条件的情况

时间:2017-06-09 08:34:31

标签: sql sql-server

我使用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

2 个答案:

答案 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'