Duplicate of
Dynamic SQL Comma Delimited Value Query
Parameterized Queries with Like and In
I have a SQL Server Stored Procedure where I would like to pass a varchar
full of comma delimited values to an IN
function. For example:
DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN (@Ids);
This does not work of course. I get the error:
Conversion failed when converting the varchar value '1,2,3,5,4,6,7,98,234' to data type int.
How can I accomplish this (or something relatively similar) without resorting to building dynamic SQL?
Don't use a function that loops to split a string!, my function below will split a string very fast, with no looping!
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
use this function to split your string, which does not loop and is very fast:
If you use SQL Server 2008 or higher, use table valued parameters; for example:
This works perfectly! The below answers are too complicated. Don't look at this as dynamic. Set up your store procedure as follows:
Without using dynamic SQL, you have to take the input variable and use a split function to put the data into a temp table and then join to that.
you can use this function as a table in a join:
Here is your example:
I think a very simple solution could be following: