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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With