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