- Community Pick
Why would I do that you ask? Let's say that you need to pass multiple parameters into a stored procedure to search for. For our sake, we'll say that we want to return a list of items with their details, given a list of item numbers.
- 1
Create the view the function depends on
Execute the following code to create the vw_Nums view. You will need to run it in SQL Server Management Studio's Query tool, not in the query builder. I use a view to generate a list of 4 billion numbers. But if your database has a numbers table, you can use it as well. Just update vw_Nums in the function with your table name and "n" (without quotes) with your column name. Just be sure that you have enough numbers. There has to be at least as many numbers as characters in your input string. The view's code is also in a comment in the function so that if it gets dropped, it can be recreated by copying the text out of the function.
- 2
Create the function
The below code snippet will create the function.
- 3
Enjoy
The code is ready
You are now ready to use it. Above in the comment you will see that I have 3 sample calls.
select * from [dbo].[fn_DelimitedToTable
select theValue from [dbo].[fn_DelimitedToTable
select * from [dbo].[fn_DelimitedToTable
The first shows using a multi character delimiter. This is useful because single character delimiters mean that that character is not valid inside of the string you are parsing. Depending on your needs, that may be OK. For example, a comma (,) is often a good delimiter. The output of the query is 3 columns.
Ident - An identity field representing the "chunk" of the string.
thePosition - The starting position of the string.
theValue - The value!
The first query returns the following:
1 1 a
2 6 basdf
3 15 c
4 20 d
Second:
a
Third:
1 1 a
2 3 basdf
3 9 c
4 11 d
This shows that many different delimiters, including a space, can be used to output data.
Now back to the item list example. Let's say that you have a table called items. This code sample will setup an items table, populate it with data, and show you how to select data from is using the function with a stored procedure.
This topic is also covered on my site SQL Server Nation under the title Converting a delimited string into a table. Stop over there and check out the site!
by: mwvisa1 on 2008-11-24 at 04:47:36ID: 411
Nice, Brandon. The common table expression to generate the numbers view always impresses me.