使用Case语句根据另一个参数设置参数

时间:2015-09-16 14:52:51

标签: sql sql-server

我正在尝试根据传递到存储过程的不同SQL参数的数值设置SQL变量,但是在使用Case语句的确切语法时遇到问题

DECLARE @RangeText varchar(1)

SELECT CASE  
WHEN (@SecondsOnSiteRange = 1) 
THEN SET @RangeText = '=' END
WHEN (@SecondsOnSiteRange = 2) 
THEN SET @RangeText = '>' END
WHEN (@SecondsOnSiteRange = 3)  
THEN SET @RangeText = '<' END
ELSE NULL
END

我确信它会像丢失的关键字一样小,但当我搜索Google时,我似乎能够找到设置相同的变量,而不是第二个。

2 个答案:

答案 0 :(得分:3)

Correct syntax

Simple CASE expression: 
CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END 
Searched CASE expression:
CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

代码:

DECLARE @RangeText varchar(1)

SELECT @RangeText = CASE  
                      WHEN (@SecondsOnSiteRange = 1) THEN '=' 
                      WHEN (@SecondsOnSiteRange = 2) THEN '>' 
                      WHEN (@SecondsOnSiteRange = 3) THEN '<'
                      ELSE NULL
                    END

或:

SELECT @RangeText = CASE  @SecondsOnSiteRange 
                       WHEN 1 THEN '=' 
                       WHEN 2 THEN '>' 
                       WHEN 3 THEN '<' 
                       ELSE NULL
                    END

答案 1 :(得分:-2)

你应该只在最后使用end:

SELECT CASE  
WHEN (@SecondsOnSiteRange = 1) 
THEN SET @RangeText = '=' ELSE
WHEN (@SecondsOnSiteRange = 2) 
THEN SET @RangeText = '>' ELSE
WHEN (@SecondsOnSiteRange = 3)  
THEN SET @RangeText = '<' ELSE
ELSE NULL
END

我非常抱歉以上不正确。我确实忽略了,下面是应该怎么做......

SELECT @RangeText = 
CASE  WHEN (@SecondsOnSiteRange = 1) 
THEN '=' 
WHEN (@SecondsOnSiteRange = 2) 
THEN '>' 
WHEN (@SecondsOnSiteRange = 3)  
THEN '<' 
ELSE NULL
END