Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass list of items as parameter to a stored procedure

I have a stored procedure

create PROCEDURE [dbo].[SP] 
(
    @OrderList varchar(500)
)
AS
Begin
    select * 
    from table 
    where id in ('+ @OrderList +')

Here I am passing orderlist....

When I execute like this

exec sp 'iss005,iss006'

I am not getting data

but when I hardcode in sp like this ...

   select * from table where id in ('iss005','iss006')

then am getting data...

Thank you

like image 635
anilpab Avatar asked Oct 16 '25 13:10

anilpab


2 Answers

Unfortunately it won't work that way. If you change your procedure to something like the following, this will work:

Create Procedure dbo.SP
    @OrderList varchar(500)
AS

Declare @SQL VarChar(1000)

Select @SQL = 'SELECT * FROM table '
Select @SQL = @SQL + 'WHERE id in (' + @OrderList +')'

Exec ( @SQL)

GO

Looking more into your query, your ID's value varchar, so the procedure will fail as you'll still be getting :

WHERE id in (iss005,iss006)

when you want :

WHERE id in ('iss005','iss006')

You would need to either pass in the quote values, e.g. :

@OrderList = 'iss005','iss006'

Or work out some SQL to split the @OrderList by comma and use the QUOTENAME() function to add the quotes to the new variable.

like image 191
Neil Knight Avatar answered Oct 18 '25 08:10

Neil Knight


I strongly recommend in this case the use of XML parameters, will give you a lot of flexibility.

Your XML might be something like

<ids>
   <id>iss006</id>
   <id>iss005</id>
</ids>

Your procedure should be something like this:

create PROCEDURE [dbo].[SP] 
(
    @OrderList XML
)
AS
Begin
    select *  from table 
    where id in (
            select ParamValues.ID.value('.','VARCHAR(50)') 
                    FROM @OrderList.nodes('/ids/id') as ParamValues(id)
            )

Besides the use of store procedures outputs I also would recommend the use of functions but that is up to you. Regards.

like image 45
Pedro Angel Avatar answered Oct 18 '25 07:10

Pedro Angel