TSQL Variable With List of Values for IN Clause

前端 未结 4 1305
攒了一身酷
攒了一身酷 2021-01-04 19:27

I want to use a clause along the lines of \"CASE WHEN ... THEN 1 ELSE 0 END\" in a select statement. The tricky part is that I need it to work with \"value IN @List\".

4条回答
  •  难免孤独
    2021-01-04 19:55

    I solved this problem by using a CHARINDEX function. I wanted to pass the string in as a single parameter. I created a string with leading and trailing commas for each value I wanted to test for. Then I concatenated a leading and trailing commas to the string I wanted to see if was "in" the parameter. At the end I checked for CHARINDEX > 0

    DECLARE @CTSPST_Profit_Centers VARCHAR (256) 
    SELECT @CTSPST_Profit_Centers = ',CS5000U37Y,CS5000U48B,CS5000V68A,CS5000V69A,CS500IV69A,CS5000V70S,CS5000V79B,CS500IV79B,'
    
    SELECT 
       CASE
           WHEN CHARINDEX(','+ISMAT.PROFIT_CENTER+',' ,@CTSPST_Profit_Centers) > 0 THEN 'CTSPST'  
           ELSE ISMAT.DESIGN_ID  + ' 1 CPG' 
          END AS DESIGN_ID
    

    You can also do it in the where clause

    WHERE CHARINDEX(','+ISMAT.PROFIT_CENTER+',',@CTSPST_Profit_Centers) > 0
    

    If you were trying to compare numbers you'd need to convert the number to a text string for the CHARINDEX function to work.

提交回复
热议问题