Using a comma-separated parameter in an IN clause

后端 未结 5 1978
余生分开走
余生分开走 2021-01-05 11:34

I have \'param1, param2, parma3\' coming from SSRS to a stored procedure as a varchar parameter: I need to use it in a query\'s IN cla

5条回答
  •  攒了一身酷
    2021-01-05 12:09

    "Best way" is arguable, but one classic approach that remains without "creating functions and table parameters" is to simply employ dynamic SQL in the stored procedure:

    -- FORNOW: local to act as the SP param and arg
    declare @values varchar(100) = 'param1, param2, param3'
    
    -- Add opening and closing single quotes, then quotes around each
    -- comma-separated list item.
    select @values = '''' + REPLACE(@values, ', ', ''', ''') + ''''
    
    -- FORNOW: for clarity/debugging
    print @values
    --'param1', 'param2', 'param3'
    
    -- Run the desired query as dynamic SQL.
    DECLARE @sql as nvarchar(250);
    SET @sql = 'select * from table1 where col1 in (' + @values + ')';
    
    EXEC sp_executesql @sql;
    

    This assumes a couple things, though:

    1. That commas in the list of values are followed by a space. Variations on this solution can address deviations in this respect of course, but it is important to be aware of this assumption.
    2. That the comma-separated values do not themselves have commas in them – unlikely but worth mentioning since whether values will satisfy this constraint sometimes goes unconsidered.

提交回复
热议问题