![]() |
|
SQL Monitor offers straightforward server monitoring through a web-based UI, to help you prioritize your workload:
Start monitoring your servers today with a free trial.

|
|
By: Greg Robidoux | Read Comments (12) | Related Tips: More > Functions - User Defined UDF |
There are several tips and articles on the internet that discuss how to split a delimited list into multiple rows. This tip shows two approaches to this problem a T-SQL function and a CLR function.
The following examples show two different approaches to splitting a delimited list into multiple rows. Both approaches return the same result set, but this tip will show the different techniques to deploy the functions.
There are several versions of a T-SQL approach that you can find on the internet, but here is one that parses a string based on a delimiter and returns one row per value. The code has been put together to show you how this is done versus finding the most optimal approach for this problem.
Just copy the code below and execute it in a query window.
CREATE FUNCTION [dbo].[fnParseStringTSQL] (@string NVARCHAR(MAX),@separator NCHAR(1))
RETURNS @parsedString TABLE (string NVARCHAR(MAX))
AS
BEGIN
DECLARE @position int
SET @position = 1
SET @string = @string + @separator
WHILE charindex(@separator,@string,@position) <> 0
BEGIN
INSERT into @parsedString
SELECT substring(@string, @position, charindex(@separator,@string,@position) - @position)
SET @position = charindex(@separator,@string,@position) + 1
END
RETURN
ENDThis can be done either manually or you can do this using Visual Studio. If you deploy from Visual Studio a lot of these steps are simplified.
Step 1 - CLR code
Before we get started the first thing that needs to be done is to enable the CLR on your SQL Server. This can be done by using the SQL Server Surface Area Configuration tool. Refer to this tip CLR String Sort Function in SQL Server 2005 for more information.
Copy and save the VB.Net code below in a file called: C:\fnParseString.vb or whatever you prefer.
Imports System.Collections
Imports Microsoft.SqlServer.Server
Partial Public Class UserDefinedFunctions
<Microsoft.SqlServer.Server.SqlFunction( _
FillRowMethodName:="GetNextToken", _
TableDefinition:="StringCol NVARCHAR(MAX)")> _
Public Shared Function parseStringCLR(<SqlFacet(MaxSize:=-1)> ByVal Input As String, _
ByVal Separator As Char) As IEnumerable
Dim Result() As String
Result = Input.Split(Separator)
Return Result
End Function Public Shared Sub GetNextToken(ByVal row As Object, ByRef TheToken As String)
TheToken = CStr(row)
End Sub
End ClassStep 2 - Compile CLR Code - (You only need to do this if you are not using Visual Studio to develop and deploy)
In order to use this code, the code has to be compiled first to create a DLL.
The following command is run from a command line to compile the CLR code using the vbc.exe application. This is found in the .NET 2.0 framework directory. This may be different on your server or desktop. Also, this code should be compiled on the machine where the code will run.
So from a command line run the following command:
The code should now be compiled in a file called: C:\fnParseString.dll
Step 3 - Create Assembly and Function - (You only need to do this if you are not using Visual Studio to develop and deploy)
After the code has been compiled you need to create the assembly and the function with SQL Server. To do this, run these commands in the database where you want to create the function.
For the function you will see three components that are referenced CLRFunctions.UserDefinedFunctions .parseStringCLR .
CREATE ASSEMBLY CLRFunctions FROM 'C:\fnParseStringCLR.dll' GO
CREATE FUNCTION [dbo].fnParseStringCLR(@string [nvarchar](4000), @separator [nchar](1)) RETURNS TABLE ( [StringCol] [nvarchar](max) NULL ) WITH EXECUTE AS CALLER AS EXTERNAL NAME CLRFunctions.UserDefinedFunctions.parseStringCLR
Step 4 - Test It
To test the functions, run the following SELECT statements.
SELECT * FROM dbo.fnParseStringTSQL('SQL Server 2000|SQL Server 2005|SQL Server 2008|SQL Server 7.0','|')
GO
SELECT * FROM dbo.fnParseStringCLR('SQL Server 2000|SQL Server 2005|SQL Server 2008|SQL Server 7.0','|')
GOSELECT * FROM dbo.fnParseStringTSQL('Apple,Banana,Pear',',')
GO
SELECT * FROM dbo.fnParseStringCLR('Apple,Banana,Pear',',')
GOHere is the output from the above queries:
Result set for the first two queries

Result set for the second two queries

Here is another test that has over 1000 delimited items. With this amount of data we can see that the CLR code is faster. Although each time you run this you may get different execution times, in my tests the CLR was always almost three times faster.


A reader asked how these functions can be used against data that exists in a table. Here is a simple example of populating a table and then using these functions:
CREATE TABLE #temp (id int, stringData varchar(100)) INSERT INTO #temp VALUES (1,'SQL Server 2000,SQL Server 2005,SQL Server 2008,SQL Server 7.0,SQL Server 2012,SQL Server 2008 R2') INSERT INTO #temp VALUES (2,'Apple,Banana,Pear')
SELECT y.id, fn.string FROM #temp AS y CROSS APPLY dbo.fnParseStringTSQL(y.stringData, ',') AS fn
DROP TABLE #temp

Summary
With the above you can see the two different approaches to tackling this issue. For the most part you are probably fine with either code set, but do some testing to see which approach works best.
| Wednesday, January 14, 2009 - 3:37:29 AM - elsuket | Read The Tip |
|
Hello, You can also use CTEs under SQL Server 2005 to do the same thing. The advantage is that you can specify a JOIN on a CTE :
|
|
| Wednesday, January 14, 2009 - 9:15:45 AM - admin | Read The Tip |
|
Thanks for the alternate approaches. |
|
| Wednesday, March 21, 2012 - 8:41:14 AM - Paul | Read The Tip |
|
Thanks so much for your script. You saved me ages of time. |
|
| Saturday, June 30, 2012 - 12:40:10 PM - Robert | Read The Tip |
|
As in most examples I have seen, this works great as long as you have a variable or supply a delimited string for it to work on. I'm sure you know what RBAR means, and I'm trying to avoid that by diong set related processing, sin instead of typing in a string, what if I have a table with onle colum in it and 2000 entries of string text I want to process? All the examples I have tried return one recors, I want to iterate (try not to use the word loop) through all 2000 entries and insert the results into a table, but I can't get to work, and there are no examples of this, but hundreds of examples on how to do just one string.
Robert. |
|
| Monday, January 14, 2013 - 4:04:38 PM - Venkat | Read The Tip |
|
@Robert.. You have to create table valued function as mentioned in the post and then cross apply or outer apply (depends on your requirement) with your table with the column having delimited string. Select (fn.Resultcolumn_function) From yourtable AS y CROSS APPLY tablevaluedfunction (y.delimitedstring, delimiter) AS fn |
|
| Tuesday, January 15, 2013 - 9:32:50 AM - Greg Robidoux | Read The Tip |
|
@Venkat - thanks for your reply. I have updated the tip based on your feedback. |
|
| Thursday, January 17, 2013 - 10:16:44 AM - Regan Wick | Read The Tip |
|
There are faster T-SQL solution which use set-based processing. Some are detailed here: http://sqlrecords.blogspot.com/2012/11/converting-delimited-list-to-table.html From Jeff Moden's efforts, this is the best performing UDF I have seen which uses a Numbers table CREATE FUNCTION[dbo].[fnListToTable8K](
@ListVARCHAR(8000) --ISNULL\NULLIF logic handles last element eliminating need to append delimiter
,ElementStartAndLengthCTE SELECT
SUBSTRING(@List,Start,Length) AS Item
|
|
| Thursday, January 17, 2013 - 1:38:41 PM - Steven Willis | Read The Tip |
|
In a cooperative effort over the last few years Jeff Moden over at SQLServerCentral has pretty much put this issue to rest. http://www.sqlservercentral.com/articles/Tally+Table/72993/ ... go to the bottom of the article and download all the code. The function DelimitedSplit8K has been objectively performance tested against many other non-CLR versions. Jeff Moden even provides the testing script and procedures for anyone to use. The latest version of the function does not require an external numbers/tally table. I have personally tested this and competing versions of splitter functions using Jeff's test harness and DelimitedSplit8K cannot be beat without using a CLR. By the way, Jeff also provides the code for a splitter CLR (and test results) and the CLR is by far the fastest splitter method. But if one is working on servers without full sysadmin control it is often not possible to build and run CLRs. Both functions produce exactly the same output columns so they can be used interchageably. The DelimitedSplit8K function's only limitation is that the string being parsed must be be less than VARCHAR(8000) or NVARCHAR(4000). Splitting a value that requires a VARCHAR(MAX) datatype will kill performance and there are some other splitters that handle those rare situations better, though splitting such blobs will always be a performance problem. The function is also optimized for a single delimiter only with values of any size including random sizes. For strings with multiple delimiters (i.e., 2-dimenisonal) there is a variation of DelimitedSplit8K that has been shown to perform faster than trying to do multiple CROSS APPLYs with the same query. Details on that variation can be found here: http://www.sqlservercentral.com/Forums/FindPost1401102.aspx DelimitedSplit8K is an iTVF and thus produces a virtual table as output. As in the example in a previous post the function can be used by using a JOIN or a CROSS APPLY. Here is the code for anyone to use: /***************************************************************************************/ CREATE FUNCTION [dbo].[DelimitedSplit8K] --===== Define I/O parameters ( @pString VARCHAR(8000) ,@pDelimiter CHAR(1) ) --WARNING!!! DO NOT USE MAX DATA-TYPES HERE! IT WILL KILL PERFORMANCE! RETURNS TABLE WITH SCHEMABINDING AS RETURN --===== "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000... -- enough to cover VARCHAR(8000) WITH E1(N) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ), --10E+1 or 10 rows E2(N) AS ( SELECT 1 FROM E1 a ,E1 b ), --10E+2 or 100 rows E4(N) AS ( SELECT 1 FROM E2 a ,E2 b ), --10E+4 or 10,000 rows max cteTally(N) AS ( --==== This provides the "base" CTE and limits the number of rows right up front -- for both a performance gain and prevention of accidental "overruns" SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY ( SELECT NULL )) FROM E4 ), cteStart(N1) AS ( --==== This returns N+1 (starting position of each "element" just once for each delimiter) SELECT 1 UNION ALL SELECT t.N + 1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter ), cteLen(N1,L1) AS ( --==== Return start and length (for use in substring) SELECT s.N1 ,ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0) - s.N1,8000) FROM cteStart s ) --===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found. SELECT ItemNumber = ROW_NUMBER() OVER (ORDER BY l.N1) ,Item = SUBSTRING(@pString,l.N1,l.L1) FROM cteLen l ;
/***************************************************************************************/
|
|
| Thursday, January 17, 2013 - 2:06:58 PM - Steven Willis | Read The Tip |
|
Also, for those needing an example of how to CROSS APPLY a tvf splitter function: /***********************************************************************/
DECLARE @InputString VARCHAR(8000) ,@Delimiter1 CHAR(1)
--this would be an example of a delimited string to be split
SET @InputString = '38469,38471,38474' SET @Delimiter1 = ','
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable
CREATE TABLE #TempTable ( [ID] INT IDENTITY(1,1) NOT NULL, [Col1] INT NULL, [Col2] NVARCHAR(50) NULL, PRIMARY KEY (ID))
--this is a sample data with keys to be matched against the values in the delimited string INSERT INTO #TempTable SELECT 38469,'Bob' UNION SELECT 38471,'George' UNION SELECT 38473,'John' UNION SELECT 38474,'Alice' UNION SELECT 38474,'Carol' UNION SELECT 38477,'Randy'
--this query uses a CROSS APPLY to match the table keys with the values in the delimited string SELECT ID ,Col1 ,Col2 FROM #TempTable AS tt CROSS APPLY dbo.DelimitedSplit8K(@InputString,@Delimiter1) AS dsk WHERE tt.Col1 = dsk.Item /***********************************************************************/
The output:
IDCol1Col2
138469Bob
238471George
438474Alice
538474Carol
|
|
| Thursday, May 02, 2013 - 11:05:41 AM - shoham | Read The Tip |
|
Thanks!!! |
|
| Friday, June 07, 2013 - 3:22:01 AM - Shariz | Read The Tip |
|
The above examples gets the values into different rows. How to get the all the values of one id into one row and different columns. Like - Column1 Column2 Column3 Column4 Column5 1 SQL Server 2000 SQL Server 2005 SQL Server 2008 SQL Server 2012 |
|
| Friday, June 07, 2013 - 8:58:28 AM - Greg Robidoux | Read The Tip |
|
@Shariz - take a look at these tips on PIVOT http://www.mssqltips.com/sqlservertip/1019/crosstab-queries-using-pivot-in-sql-server/ http://www.mssqltips.com/sqlservertip/2783/script-to-create-dynamic-pivot-queries-in-sql-server/ |
|
|
privacy | disclaimer | copyright | advertise | about authors | contribute | feedback | giveaways | user groups Some names and products listed are the registered trademarks of their respective owners. Edgewood Solutions LLC | MSSharePointTips.com | MSSQLTips.com |