在T-SQL Case表达式中评估变量

时间:2014-07-09 17:03:05

标签: sql sql-server tsql case

我得到了

  

' ='"附近的语法不正确对于所有' ='

在以下案例中:

DECLARE @TipoRegisto    AS VARCHAR(1)
DECLARE @idTipoRegisto  AS INT

SELECT 
       CASE @TipoRegisto            
              WHEN @idTipoRegisto = 0 THEN 'R' 
              WHEN @idTipoRegisto = 1 THEN 'I' 
              WHEN @idTipoRegisto = 2 THEN 'C' 
              ELSE  '' 
       END

有人可以解释原因吗?

2 个答案:

答案 0 :(得分:1)

您非常接近,Case返回您要将变量设置为

的值
DECLARE @TipoRegisto    AS VARCHAR(1)
DECLARE @idTipoRegisto  AS INT

SELECT @TipoRegisto = CASE
                           WHEN @idTipoRegisto = 0 THEN 'R' 
                           WHEN @idTipoRegisto = 1 THEN 'I' 
                           WHEN @idTipoRegisto = 2 THEN 'C' 
                           ELSE  '' 
                      END

答案 1 :(得分:0)

试试这个:

DECLARE @TipoRegisto    AS VARCHAR(1)
DECLARE @idTipoRegisto  AS INT

SET @TipoRegisto = (SELECT 
                           CASE @idTipoRegisto            
                                WHEN 0 THEN 'R' 
                                WHEN 1 THEN 'I' 
                                WHEN 2 THEN 'C' 
                           ELSE  '' 
                     END)