join the MSSQLTips community

Today's Site Sponsor


 

SQL Compare quickly and easily compares and synchronizes SQL Server database schemas
 




SQL Server CLR and T-SQL functions to parse a delimited string

Written By: Greg Robidoux -- 1/14/2009 -- read/post comments -- print -- Bookmark and Share

Rating: (not rated yet) Rate

Problem
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.

Solution
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.

T-SQL Version

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
END

CLR Version

This 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 Class

Step 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:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\vbc /target:library C:\fnParseString.vb

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 .

  • CLRFunctions - the assembly reference
  • UserDefinedFunctions - the class reference in the VB code
  • parseStringCLR - the function reference in the VB code
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','|')
GO
SELECT * FROM dbo.fnParseStringTSQL('Apple,Banana,Pear',',')
GO
SELECT * FROM dbo.fnParseStringCLR('Apple,Banana,Pear',',')
GO

Here 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 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.

 

 

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.

Next Steps

  • Give this example a try and see what other functions you could write that could take advantage of the CLR
  • If you have CLR functions that you want to share with the rest of the MSSQLTips.com community, please send them to tips@mssqltips.com so we can post them for others to use.
  • If you don't know how to write either VB or C# now is the time to begin learning.  You will find a lot of things these languages will make a lot easier to implement.
  • Do some testing and also take on other functions that you have written in T-SQL to see if they can run any faster in the CLR
Readers Who Read This Tip Also Read Free Live Webcast Comment or Ask Questions About This Tip


Sponsor Information
Free SQL Server performance monitoring dashboard – Idera SQL check

The SQL Toolbelt – Red Gate’s essential tools for SQL Server

Make the most out of SQL Server - Guaranteed Results - Innovative SQL Server DBAs

Come learn SharePoint @ MSSharePointTips.com

Free whitepaper - Managing Complex Database Changes


Get Our Tips Newsletter

We keep 50,000+ SQL Server professionals informed.



Idera - SQL secure

Idera SQL secure collects and analyzes permissions data from SQL Server and Active Directory as well as the file system and registry to show who has access to what database objects and how that access is granted. SQL secure also monitors changes made to access rights so that unapproved changes can be easily identified and fixed. SQL secure also collects and evaluates key security settings within SQL Server and provides proactive recommendations to improve server security.

Download now!

More SQL Server Tools
SQL compliance manager

SQL safe backup

SQL Backup

SQL Prompt

SQL comparison toolset




Copyright (c) 2006-2010 Edgewood Solutions, LLC All rights reserved
privacy statement | disclaimer | copyright | advertise | write for mssqltips | feedback | about
Some names and products listed are the registered trademarks of their respective owners.


CareerQandA.com | MSSharePointTips.com | MSSQLTips.com