我正在尝试编写带case语句的where子句,该语句将查看@TimeType,然后仅返回这些时间范围之间的行。所以基本上我有3次(早上,下午和晚上)。我在使用之间出现语法错误。 start_time字段是sql time数据类型。这是我到目前为止的内容:
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
答案 0 :(得分:0)
只需使用常规逻辑:
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');
通常不建议在case
子句中使用where
表达式,因为这会阻碍优化器。 。 。而且可能很难遵循。通常,可以使用基本布尔逻辑来表示相同的逻辑。
答案 1 :(得分:0)
您可以在WHERE
子句中使用布尔逻辑:
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')