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

前端 未结 11 2036
情书的邮戳
情书的邮戳 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条回答
  •  Happy的楠姐
    2020-12-10 02:12

    This works in SQL. Declare in your GetSomething procedure a variable of type XML as such:

    DECLARE @NameArray XML = NULL
    

    The body of the stored procedure implements the following:

    SELECT * FROM MyTbl WHERE name IN (SELECT ParamValues.ID.value('.','VARCHAR(10)')
    FROM @NameArray.nodes('id') AS ParamValues(ID))
    

    From within the SQL code that calls the SP to declare and initialize the XML variable before calling the stored procedure:

    DECLARE @NameArray XML
    
    SET @NameArray = '<id>Name_1</id><id>Name_2</id><id>Name_3</id><id>Name_4</id>'
    

    Using your example the call to the stored procedure would be:

    EXEC GetSomething @NameArray
    

    I have used this method before and it works fine. If you want a quick test, copy and paste the following code to a new query and execute:

    DECLARE @IdArray XML
    
    SET @IdArray = '<id>Name_1</id><id>Name_2</id><id>Name_3</id><id>Name_4</id>'
    
    SELECT ParamValues.ID.value('.','VARCHAR(10)')
    FROM @IdArray.nodes('id') AS ParamValues(ID)
    

提交回复
热议问题