Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在WHERE子句中使用带BETWEEN的大小写_Sql_Sql Server_Tsql - Fatal编程技术网

Sql 在WHERE子句中使用带BETWEEN的大小写

Sql 在WHERE子句中使用带BETWEEN的大小写,sql,sql-server,tsql,Sql,Sql Server,Tsql,我试图用case语句编写一个where子句,该语句将查看@TimeType,然后只返回那些时间范围之间的行。所以基本上我有三次(早上、下午和晚上)。我在使用between时遇到语法错误。开始时间字段是sql时间数据类型。以下是我目前掌握的情况: declare @TimeType int select * from events where start_time = case when @TimeType = 0 then start_time between '00:00:00' and

我试图用case语句编写一个where子句,该语句将查看@TimeType,然后只返回那些时间范围之间的行。所以基本上我有三次(早上、下午和晚上)。我在使用between时遇到语法错误。开始时间字段是sql时间数据类型。以下是我目前掌握的情况:

declare @TimeType int

select * from events
where
start_time = case 
when @TimeType = 0 then start_time between '00:00:00' and '11:59:00' 
when @TimeType = 1 then start_time between '12:00:00' and '16:59:00' 
when @TimeType = 2 then start_time between '17:00:00' and '23:59:00' 
end

只需使用常规逻辑:

select e.* 
from events e
where (@TimeType = 0 and start_time between '00:00:00' and '11:59:00') or
      (@TimeType = 1 then start_time between '12:00:00' and '16:59:00') or 
      (@TimeType = 2 then start_time between '17:00:00' and '23:59:00');

通常,不鼓励在
where
子句中使用
case
表达式,因为这会妨碍优化器。这可能更难理解。通常,相同的逻辑可以使用基本布尔逻辑来表示。

您可以在
中使用布尔逻辑,其中
子句:

WHERE (@TimeType = 0 AND start_time between '00:00:00' and '11:59:00') OR
      (@TimeType = 1 AND start_time between '12:00:00' and '16:59:00') OR
      (@TimeType = 2 AND start_time between '17:00:00' and '23:59:00')