我怎样才能在sql中使用'when-between'语句?

时间:2009-05-06 08:44:50

标签: sql sql-server sql-server-2005

此查询在行之间给出了语法错误。我怎么解决他们?

alter FUNCTION [dbo].[fn_GetActivityLogsArranger]
(
@time AS nvarchar(max)
)

RETURNS  nvarchar(max)
AS
BEGIN
declare @Return varchar(30)

select @Return = case @time
when between '15:00' and '15:30' then '15:00-15:30'
when between '15:30' and '16:00' then '15:30-16:00'
when between '16:00' and '16:30' then '16:00-16:30'
when between '16:00' and '16:30' then '16:00-16:30' 
when between '16:30' and '17:00' then '16:30-17:00' 
when between '17:00' and '17:30' then '17:00-17:30' 
when between '17:30' and '18:00' then '17:30-18:00'
else 'Unknown'
 Return @Return
end

6 个答案:

答案 0 :(得分:4)

您无法使用案例语法的格式。你将不得不做一个检查的案例:

select @Return = case 
when @time between '15:00' and '15:30' then '15:00-15:30'
when @time between '15:30' and '16:00' then '15:30-16:00'
when @time between '16:00' and '16:30' then '16:00-16:30'
when @time between '16:00' and '16:30' then '16:00-16:30' 
when @time between '16:30' and '17:00' then '16:30-17:00' 
when @time between '17:00' and '17:30' then '17:00-17:30' 
when @time between '17:30' and '18:00' then '17:30-18:00'
else 'Unknown' END

Return @Return

另外,你在case语句的末尾错过了一个END(参见上面的END大写)。

答案 1 :(得分:4)

alter FUNCTION [dbo].[fn_GetActivityLogsArranger]
(
    @time AS varchar(30)
)
RETURNS  
varchar(30)AS
BEGIN
declare @Return varchar(30)
select @Return = case 
when @time between '15:00' and '15:30' then '15:00-15:30'
when @time between '15:30' and '16:00' then '15:30-16:00'
when @time between '16:00' and '16:30' then '16:00-16:30'
when @time between '16:00' and '16:30' then '16:00-16:30' 
when @time between '16:30' and '17:00' then '16:30-17:00' 
when @time between '17:00' and '17:30' then '17:00-17:30'
when @time between '17:30' and '18:00' then '17:30-18:00'
else 'Unknown' 
end
Return @Return
end

答案 2 :(得分:1)

案例语法: 案件      什么时候Boolean_expression THEN result_expression [... n]      [ELSE else_result_expression] END

答案 3 :(得分:0)

对于初学者来说,你需要在每个语句

中传递@variable
select @Return = case 
when @time between ('15:00' and '15:30') then '15:00-15:30'
when @time between ('15:30' and '16:00') then '15:30-16:00'
when @time between ('16:00' and '16:30') then '16:00-16:30'
when @time between ('16:00' and '16:30') then '16:00-16:30' 
when @time between ('16:30' and '17:00') then '16:30-17:00' 
when @time between ('17:00' and '17:30') then '17:00-17:30' 
when @time between ('17:30' and '18:00') then '17:30-18:00'
else 'Unknown'

答案 4 :(得分:0)

您需要在每个WHEN子句中包含变量 例如

case 
    when @time between '15:00' and '15:30' then '15:00-15:30'
    when @time between '15:30' and '16:00' then '15:30-16:00'

答案 5 :(得分:0)

你不应该使用这个函数,你应该有一个表或表值时间桶的函数,所以你可以对它进行纯连接。有关示例,请参阅my other post。到目前为止,连接将超越在行集上调用函数的方法。