Passing multiple values for one SQL parameter

后端 未结 3 1173
梦如初夏
梦如初夏 2020-12-10 08:54

I have a CheckBoxList where users can select multiple items from the list. I then need to be able to pass these values to my Stored Procedure so they can be used in a WHERE

相关标签:
3条回答
  • 2020-12-10 09:25
    alter procedure c2
    (@i varchar(5))
    as
    begin
        declare @sq nvarchar(4000)
        set @sq= 'select * from test where id in (<has_i>) '
        SET @sq= REPLACE(@sq, '<has_i>', @i)
        EXECUTE sp_executesql  @sq
    end
    
    exec c2 '1,3'
    
    0 讨论(0)
  • 2020-12-10 09:28

    I did find a solution for a similar problem. It is used for a data driven subscription, but can be easily altered for use in a parameter. check my blog post here with a detailed description

    If you are having problem converting it to a stored procedure call, just let me know.

    0 讨论(0)
  • 2020-12-10 09:32

    There's a few ways of doing it. You could pass in the parameter as an XML blob like this example:

    CREATE PROCEDURE [dbo].[uspGetCustomersXML]
        @CustomerIDs XML
    AS
    BEGIN
    SELECT c.ID, c.Name
    FROM [dbo].[Customer] c
    JOIN @CustomerIDs.nodes('IDList/ID') AS x(Item) ON c.ID = Item.value('.', 'int' )
    END
    GO
    
    --Example Use:
    EXECUTE [dbo].[uspGetCustomersXML] '<IDList><ID>1</ID><ID>10</ID><ID>100</ID></IDList>'
    

    Or pass in the values as CSV and use a split function to split the values out into a table variable (there's a lot of split functions out there, quick search will throw one up).

    CREATE PROCEDURE [dbo].[uspGetCustomersCSV]
        @CustomerIDs VARCHAR(8000)
    AS
    BEGIN
    SELECT c.Id, c.Name
    FROM [dbo].[Customer] c
    JOIN dbo.fnSplit(@CustomerIDs, ',') t ON c.Id = t.item
    END
    GO
    
    --Example Use:
    EXECUTE [dbo].[uspGetCustomersCSV] '1,10,100'
    

    If you were using SQL 2008 or later, you could have used Table Valued Parameters which allow you to pass a TABLE variable in as a parameter. I blogged about these 3 approaches a while back, with a quick performance comparison.

    0 讨论(0)
提交回复
热议问题