Sql server SQL中where子句中的Acheive If语句
我试图检查where子句中的一个条件Sql server SQL中where子句中的Acheive If语句,sql-server,Sql Server,我试图检查where子句中的一个条件 Select * from [Sale Master] where IF (@IsTime='1') BEGIN convert(char(19),Sale_Date,20) between'2016-05-18 10:45:00' and '2016-05-18 10:55:00' END ELSE BEGIN convert(char(10),Sale_Date,20) between'2016-05-18' and '2016-05-18' END
Select * from [Sale Master] where
IF (@IsTime='1')
BEGIN
convert(char(19),Sale_Date,20) between'2016-05-18 10:45:00' and '2016-05-18 10:55:00'
END
ELSE
BEGIN
convert(char(10),Sale_Date,20) between'2016-05-18' and '2016-05-18'
END
我实际上想做的是根据@IsTime
位变量搜索记录。如果是真的,它应该考虑日期和时间,否则它只考虑日期。我知道If条件不应该在Where子句中使用,但我不知道如何使用CASE。尝试以下方法:
Select *
from [Sale Master]
where
(
(@IsTime=1)
and
convert(char(19),Sale_Date,20) between '2016-05-18 10:45:00' and '2016-05-18 10:55:00'
)
or
(
(@IsTime=0)
and
convert(char(10),Sale_Date,20) between '2016-05-18' and '2016-05-18'
)
试试这个:
Select *
from [Sale Master]
where
(
(@IsTime=1)
and
convert(char(19),Sale_Date,20) between '2016-05-18 10:45:00' and '2016-05-18 10:55:00'
)
or
(
(@IsTime=0)
and
convert(char(10),Sale_Date,20) between '2016-05-18' and '2016-05-18'
)
您不需要if()
——也不需要案例。但更重要的是:没有理由将日期转换为字符串进行比较。因此:
Select *
from [Sale Master]
where (@IsTime = '1' and sale_date between '2016-05-18 10:45:00' and '2016-05-18 10:55:00') or
(@IsTime <> '1' and Sale_Date between '2016-05-18' and '2016-05-18');
Aaron Bertrand解释了在日期/时间中使用between
的问题。您不需要if()
--也不需要案例。但更重要的是:没有理由将日期转换为字符串进行比较。因此:
Select *
from [Sale Master]
where (@IsTime = '1' and sale_date between '2016-05-18 10:45:00' and '2016-05-18 10:55:00') or
(@IsTime <> '1' and Sale_Date between '2016-05-18' and '2016-05-18');
Aaron Bertrand解释了在日期/时间中使用between
的问题。尝试这样做,这有点类似于Gordon Linoff post,但我删除了一个条件
SELECT *
FROM [Sale Master]
WHERE (
@IsTime = '1'
AND sale_date BETWEEN '2016-05-18 10:45:00'
AND '2016-05-18 10:55:00'
)
OR (
Sale_Date BETWEEN '2016-05-18'
AND '2016-05-18'
);
试着这样做,这有点类似于Gordon Linoff的帖子,但我删除了一个条件
SELECT *
FROM [Sale Master]
WHERE (
@IsTime = '1'
AND sale_date BETWEEN '2016-05-18 10:45:00'
AND '2016-05-18 10:55:00'
)
OR (
Sale_Date BETWEEN '2016-05-18'
AND '2016-05-18'
);
您不需要在位
值周围加引号。您不需要在位
值周围加引号。@Tanner:请解释原因,以便我理解。首先,第二个子句将被计算,而不管@IsTime
的值是多少。其次,带有日期检查的子句具有相同的值,因此不存在中间值。也许可以对它进行测试,看看你的代码对伪数据做了什么。@Tanner:解释一下为什么,这样我就可以理解了。首先,第二个子句将被计算,而不管@IsTime
的值是多少。其次,带有日期检查的子句具有相同的值,因此不存在中间值。也许可以测试它,看看您的代码对虚拟数据做了什么。