我试图在我的SQL查询的where子句中添加一个case或if语句.
我有一个开始和结束日期的旅程时间表,每天都有一个布尔字段,表示当天旅行发生的地方.这是我到目前为止,但我得到错误的语法错误:
我有一个开始和结束日期的旅程时间表,每天都有一个布尔字段,表示当天旅行发生的地方.这是我到目前为止,但我得到错误的语法错误:
declare @date datetime set @Date = '05/04/2012' declare @day nvarchar(50) set @day = 'Monday' Select * From Times WHERE (StartDate <= @Date) AND (EndDate >= @Date) CASE WHEN @day = 'Monday' THEN AND (Monday = 1) WHEN @day = 'Tuesday' THEN AND (Tuesday = 1) ELSE AND (Wednesday = 1) END
解决方法
你不需要在where语句中的case,只需使用括号和/或
Select * From Times WHERE StartDate <= @Date AND EndDate >= @Date AND ( (@day = 'Monday' AND Monday = 1) OR (@day = 'Tuesday' AND Tuesday = 1) OR Wednesday = 1 )
另外,您的语法错误.它不会将东西附加到字符串 – 它返回一个值.你会想要这样的东西,如果你真的要使用一个case语句(你不应该):
Select * From Times WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND 1 = CASE WHEN @day = 'Monday' THEN Monday WHEN @day = 'Tuesday' THEN Tuesday ELSE Wednesday END
只需要额外的一点,你可以使用之间的运算符你的日期:
where @Date between StartDate and EndDate
进行最终查询:
select * from Times where @Date between StartDate and EndDate and ( (@day = 'Monday' and Monday = 1) or (@day = 'Tuesday' and Tuesday = 1) or Wednesday = 1 )