How to pass a comma separated list to a stored procedure?

前端 未结 11 2025
情书的邮戳
情书的邮戳 2020-12-10 01:32

So I have a Sybase stored proc that takes 1 parameter that\'s a comma separated list of strings and runs a query with in in an IN() clause:

CREATE PROCEDURE          


        
相关标签:
11条回答
  • 2020-12-10 02:27

    This is a little late, but I had this exact issue a while ago and I found a solution.

    The trick is double quoting and then wrapping the whole string in quotes.

    exec getSomething """John"",""Tom"",""Bob"",""Harry"""
    

    Modify your proc to match the table entry to the string.

    CREATE PROCEDURE getSomething @keyList varchar(4096)
    AS
    SELECT * FROM mytbl WHERE @keyList LIKE '%'+name+'%' 
    

    I've had this in production since ASE 12.5; we're now on 15.0.3.

    0 讨论(0)
  • 2020-12-10 02:29

    Regarding Kevin's idea of passing the parameter to a function that splits the text into a table, here's my implementation of that function from a few years back. Works a treat.

    Splitting Text into Words in SQL

    0 讨论(0)
  • 2020-12-10 02:29

    The problem with the calls like this: exec getSomething '"John","Tom"' is that it's treating '"John","Tom"' as a single string, it will only match an entry in the table that is '"John","Tom"'.

    If you didn't want to use a temp table as in Paul's answer, then you could use dynamic sql. (Assumes v12+)

    CREATE PROCEDURE getSomething @keyList varchar(4096)
    AS
    declare @sql varchar(4096)
    select @sql = "SELECT * FROM mytbl WHERE name IN (" + @keyList +")"
    exec(@sql)
    

    You will need to ensure the items in @keylist have quotes around them, even if they are single values.

    0 讨论(0)
  • 2020-12-10 02:30

    This is a quick and dirty method that may be useful:

    select  * 
    from    mytbl 
    where   "," + ltrim(rtrim(@keylist)) + "," like "%," + ltrim(rtrim(name)) + ",%"
    
    0 讨论(0)
  • 2020-12-10 02:37

    To touch on what @Abel provided, what helped me out was:

    My purpose was to take what ever the end user inputted from SSRS and use that in my where clause as an In (SELECT) Obviously @ICD_VALUE_RPT would be commented out in my Dataset query.

    DECLARE @ICD_VALUE_RPT VARCHAR(MAX) SET @ICD_VALUE_RPT = 'Value1, Value2'
    DECLARE @ICD_VALUE_ARRAY XML SET @ICD_VALUE_ARRAY = CONCAT('<id>', REPLACE(REPLACE(@ICD_VALUE_RPT, ',', '</id>,<id>'),' ',''), '</id>')
    

    then in my WHERE i added:

    (PATS_WITH_PL_DIAGS.ICD10_CODE IN (SELECT ParamValues.ID.value('.','VARCHAR(MAX)') FROM @ICD_VALUE_ARRAY.nodes('id') AS ParamValues(ID))
    OR PATS_WITH_PL_DIAGS.ICD9_CODE IN (SELECT ParamValues.ID.value('.','VARCHAR(MAX)') FROM @ICD_VALUE_ARRAY.nodes('id') AS ParamValues(ID))
    )
    
    0 讨论(0)
提交回复
热议问题