SQL in (@Variable) query

前端 未结 3 768
时光取名叫无心
时光取名叫无心 2020-12-11 18:23

I have the following code, the problem is that my variable list @LocationList is essentially a csv string. When I use this as part of the where LocationID in (@LocationList

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 19:05

    The most efficient way to do this is with Dynamic SQL such as rt2800 mentions (with injection warnings by Michael Allen)

    However you can make a function:

    ALTER  FUNCTION [dbo].[CSVStringsToTable_fn] ( @array VARCHAR(8000) )
    RETURNS @Table TABLE ( value VARCHAR(100) )
    AS 
        BEGIN
            DECLARE @separator_position INTEGER,
                @array_value VARCHAR(8000)  
    
            SET @array = @array + ','
    
            WHILE PATINDEX('%,%', @array) <> 0 
                BEGIN
                    SELECT  @separator_position = PATINDEX('%,%', @array)
                    SELECT  @array_value = LEFT(@array, @separator_position - 1)
    
                    INSERT  @Table
                    VALUES  ( @array_value )
    
                    SELECT  @array = STUFF(@array, 1, @separator_position, '')
                END
            RETURN
        END
    

    and select from it:

    DECLARE @LocationList VARCHAR(1000)
    SET @LocationList = '1,32'
    
    SELECT  Locations 
    FROM    table
    WHERE   LocationID IN ( SELECT   *
                               FROM     dbo.CSVStringsToTable_fn(@LocationList) )
    

    OR

    SELECT  Locations
    FROM    table loc
            INNER JOIN dbo.CSVStringsToTable_fn(@LocationList) list
                ON list.value = loc.LocationID
    

    Which is extremely helpful when you attempt to send a multi-value list from SSRS to a PROC.

提交回复
热议问题