How to pass string array in SQL parameter to IN clause in SQL

前端 未结 3 1278
慢半拍i
慢半拍i 2020-11-30 16:01

A logic which I am doing in a complex way.

I just need to execute this query in a stored procedure:

select Sizes, SUM(Quantity)
from tbl_SizeBreakup
         


        
3条回答
  •  借酒劲吻你
    2020-11-30 16:42

    You can pass a list in a csv(coma separated values): '1,2,3', this string in the SP is useless, but you can convert to a table, first create this function:

    CREATE FUNCTION fun_CSV_to_Table
    (
    @pcsvList varchar(max)
    )
    RETURNS @tableWithValues table(theColumn varchar(100))
    AS
    BEGIN 
        DECLARE @pos INT
        WHILE CHARINDEX(',', @pcsvList) > 0
        BEGIN
         SELECT @pos  = CHARINDEX(',', @pcsvList)   
    
         INSERT INTO @tableWithValues   
         SELECT LTRIM(RTRIM(SUBSTRING(@pcsvList, 1, @pos-1)))
    
         SELECT @pcsvList = SUBSTRING(@pcsvList, @pos+1, LEN(@pcsvList)-@pos)
        END
        --Insert the last value.
        INSERT INTO @tableWithValues SELECT @pcsvList
    
        RETURN
    END
    GO
    

    And then you can use it:

     SELECT SIZES, SUM(QUANTITY)
     FROM TBL_SIZEBREAKUP
     WHERE BRAND=@BRAND
     AND COMBO IN (select theColumn FROM dbo.fun_CSV_to_Table(@aList)) 
    
    /* @aList must be a csv: '1,2,3,...,n' */
    

    You should care about white spaces.

提交回复
热议问题