如何在SQL SELECT中执行CASE语句?

时间:2015-12-03 17:08:04

标签: sql sql-server tsql case

如何在SQL SELECT语句中执行IF...THEN?我可以更改为Case..then到IF..THEN,我在Case..then中有错误

DECLARE  @Display Varchar(10)   SET @Display = '210120'
DECLARE  @ret     Varchar(5)    SET @ret     = '12345'
DECLARE  @ret2    Varchar(5)    SET @ret2    = '6789'

DECLARE  @Custom2 Varchar(10)
SELECT (CASE 
          WHEN CHARINDEX(LEFT(@Display, 1),@ret) > 0 THEN
              SET @Custom2 = 'None'
          WHEN CHARINDEX(LEFT(@Display, 1),@ret2) > 0 THEN
              SET @Custom2 = @ret+'_'+@Display 
       END ) as Custom

提前谢谢

2 个答案:

答案 0 :(得分:0)

您的语法略有偏差,请尝试以下方法:

SELECT @Custom2 = CASE WHEN CHARINDEX(LEFT(@Display, 1),@ret) > 0 
                       THEN 'None'
                  WHEN CHARINDEX(LEFT(@Display, 1),@ret2) > 0 
                       THEN @ret + '_' + @Display 
                  END As Custom

答案 1 :(得分:0)

你在这里发生的事情不匹配。您不能像使用案例表达式一样控制流程......但是您也可以将其作为列。你在这里尝试做什么并不完全清楚,但也许这会有所帮助。

DECLARE  @Display Varchar(10)   SET @Display = '210120'
DECLARE  @ret     Varchar(5)    SET @ret     = '12345'
DECLARE  @ret2    Varchar(5)    SET @ret2    = '6789'

SELECT CASE WHEN CHARINDEX(LEFT(@Display, 1),@ret) > 0 THEN
              'None'
          WHEN CHARINDEX(LEFT(@Display, 1),@ret2) > 0 THEN
              @ret+'_'+@Display 
       END as Custom