I have that procedure which returns rows associated by ID with passed argument, i.e 1,5,7,9
ALTER PROCEDURE [dbo].[get_data]
@MyCodes as varchar(max) = ''
AS
BEGIN
DECLARE @query as nvarchar(max)
set @query = 'SELECT name FROM user WHERE id IN (@p_MyCodes)'
exec SP_EXECUTESQL @query,
N'@p_MyCodes varchar(max)',
@p_MyCodes = @MyCodes
END
That procedure generates an error : Error converting data type varchar to numeric. when I pass as an argument e.g. 3,7,5
What’s wrong ?
I don’t think this is going to accomplish what you are expecting it to. The error you are getting is because it can’t convert the string ‘3,7,5’ to a number (note that it is NOT trying to parse out your individual values).
Two ways to get what you want:
1) Create a table value function that takes a CSV string and returns the results (I’m sure there are many on the web; Here’s a related question: Split function equivalent in T-SQL?). This is nice because you can get rid of the SP_EXECUTESQL sproc call entirely; Your query becomes:
2) Change your set to something like:
I don’t recommend #2, it offers a SQL injection hole.