Stored Procedure to return multiple inputs between commas

I would like to be able to take input from a user that is separated by commas:

for example:


Then i want to use the values in a where clause taken from a variable in a stored procedure.

I will make the variable nvarchar (4000) and use it in a like clause in a query. This way i can get multiple values from teh user. Sometimes they may use one or up to 10 values. What is the best way that i can accomplish this goal ?
Auerelio VasquezETL DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
with the function like below, you can do it easily:

SELECT * FROM yourtable
WHERE yourfield IN ( SELECT VALUE FROM dbo.ParmsToList('a,b,c,d', ','))
create FUNCTION dbo.ParmsToList (@Parameters varchar(500), @delimiter varchar(10) )
returns @result TABLE (Value varchar(8000))
    declare @dx varchar(9)
    --declare @loops int
    -- set @loops = 0
     DECLARE @TempList table
          Value varchar(8000)
     if @delimiter is null  set @delimiter = ' '
     if datalength(@delimiter) < 1 set @delimiter = ' '
     set @dx = left(@delimiter, datalength(@delimiter)-1)
     DECLARE @Value varchar(8000), @Pos int
     SET @Parameters = @Parameters + @delimiter
     SET @Pos = CHARINDEX(@delimiter, @Parameters, 1)
     IF REPLACE(@Parameters, @delimiter, @dx) <> ''
          WHILE @Pos > 0 --and @Loops < 100
              -- set @loops = @loops + 1
               SET @Value = LEFT(@Parameters, @Pos - 1)
               IF @Value <> ''
                    INSERT INTO @TempList (Value) VALUES (@Value) --Use Appropriate conversion
               SET @Parameters = SUBSTRING(@Parameters, @Pos+ datalength(@delimiter),500)
               SET @Pos = CHARINDEX(@delimiter, @Parameters, 1)
     INSERT @result
     SELECT value
        FROM @TempList

Open in new window

Auerelio VasquezETL DeveloperAuthor Commented:
What if the passed in values are variable? For example, they user goes to a reporting services screen, and in teh Text Box, types in A,B,C,D

How can i handle that situation in either of the above situations? It looks like the values are hardcoded, but if i want to pass in those values, it's a little bit confusing in teh above examples:

so my query woudl look like this

select * from table where field_name in dbo.ParmsToList(@input_variable) -- From stored procedure input variable.....will these examples handle this type of input?
Acronis True Image 2019 just released!

Create a reliable backup. Make sure you always have dependable copies of your data so you can restore your entire system or individual files.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
same, indeed:

SELECT * FROM yourtable
WHERE yourfield IN ( SELECT VALUE FROM dbo.ParmsToList(@inut_variable, ','))

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Yes both of the posted solutions will handle that.  I might as well throw my method in the mix too.

You'll have to create the view (vw_Nums) first but that is included in the comments.  But if your database already has a numbers table, you can you that table name in place of vw_Nums and the number column in place of n in my query.
if object_id('[dbo].[fn_DelimitedToTable]') is not null
     drop function [dbo].[fn_DelimitedToTable]
create function [dbo].[fn_DelimitedToTable](@DelimitedString nvarchar(max), @Delimiter nvarchar(32))
returns @Values TABLE
     (ident         int not null identity primary key clustered
     ,thePosition   int not null
     ,theValue      nvarchar(max)
*    Author:        Brandon Galderisi
*    Last modified: 07-Oct-2008
*    Purpose:       splits an input string (@DelimitedString) 
*                   on a delimiter (@delimiter) and outputs 
*                   a table of values.
insert into @Values (thePosition,theValue)
		select n, substring(@delimiter + @DelimitedString + @delimiter, n + (datalength(@delimiter)/2), charindex(@delimiter, @delimiter + @DelimitedString + @delimiter, n + datalength(@delimiter)/2) - n - datalength(@delimiter)/2) as string_value
		from	dbo.vw_Nums
			n <= (datalength(@delimiter + @DelimitedString + @delimiter)/2) - (datalength(@delimiter)/2)
			and substring(@delimiter + @DelimitedString + @delimiter, n, (datalength(@delimiter)/2)) = @delimiter
-- The purpose of vw_Nums is if the source database does not have a numbers table.  This view (vw_nums)
-- will allow the parsing of up to 4 billion+ character strings with the above function.  Whether a static
-- table or this view is used for fn_DelimitedToTable, it can only split a string as long as the source 
-- numbers table.
Requires a nunbers table or this view:
create view vw_Nums
with   cte0 as (select 1 as c union all select 1), 
       cte1 as (select 1 as c from cte0 a, cte0 b), 
       cte2 as (select 1 as c from cte1 a, cte1 b), 
       cte3 as (select 1 as c from cte2 a, cte2 b), 
       cte4 as (select 1 as c from cte3 a, cte3 b), 
       cte5 as (select 1 as c from cte4 a, cte4 b), 
       nums as (select row_number() over (order by c) as n from cte5)
       select n from nums 
Sample Usage:
select * from [dbo].[fn_DelimitedToTable]('a|%25basdf|%25c|%25d','|%25')
select theValue from [dbo].[fn_DelimitedToTable]('a','|')
select * from [dbo].[fn_DelimitedToTable]('a basdf c d',' ')

Open in new window

Auerelio VasquezETL DeveloperAuthor Commented:

Is there a way to use your function for a wild card? for example:

if they chose %aabnm% as one of the paramaters, and also they may not want to have a wild care liek abcd

they want to be able to use these to search multiple items.... How can i use your function to do so?

Thanks a million.
Guy Hengel [angelIII / a3]Billing EngineerCommented:
SELECT t.* FROM yourtable t
JOIN dbo.ParmsToList(@inut_variable, ',') l
  ON t.yourfield LIKE l.value 

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.