Mladen Prajdić Blog

Blog about stuff and things and stuff. Mostly about SQL server and .Net

SQL Server 2005: Split string XML Style

Here's a Split function using XML datatype.

It's preety neat and simple compared to all others that i've seen.

Forget While Loops and recursive CTE's.

Enter XML: 

 

IF OBJECT_ID('dbo.Split') IS NOT NULL
    DROP FUNCTION dbo.Split

GO CREATE FUNCTION dbo.Split(@data NVARCHAR(MAX), @delimiter NVARCHAR(5)) RETURNS @t TABLE (data NVARCHAR(max)) AS BEGIN

<span class="kwrd">DECLARE</span> @textXML XML;
<span class="kwrd">SELECT</span>    @textXML = <span class="kwrd">CAST</span>(<span class="str">&#39;&lt;d&gt;&#39;</span> + REPLACE(@<span class="kwrd">data</span>, @delimiter, <span class="str">&#39;&lt;/d&gt;&lt;d&gt;&#39;</span>) + <span class="str">&#39;&lt;/d&gt;&#39;</span> <span class="kwrd">AS</span> XML);

<span class="kwrd">INSERT</span> <span class="kwrd">INTO</span> @t(<span class="kwrd">data</span>)
<span class="kwrd">SELECT</span>  T.split.<span class="kwrd">value</span>(<span class="str">&#39;.&#39;</span>, <span class="str">&#39;nvarchar(max)&#39;</span>) <span class="kwrd">AS</span> <span class="kwrd">data</span>
<span class="kwrd">FROM</span>    @textXML.nodes(<span class="str">&#39;/d&#39;</span>) T(split)

<span class="kwrd">RETURN</span>

END GO

DECLARE @text NVARCHAR(max) SELECT @text = REPLICATE('ab,', 300) + 'ab'

SELECT * FROM dbo.Split(@text, ',')

 

Enjoy it. :) kick it on DotNetKicks.com

Legacy Comments


Mladen
2007-05-23
re: SQL Server 2005: Split string XML Style
cool!

Halil Güler
2009-06-15
re: SQL Server 2005: Split string XML Style
thanks

sqlgirl
2009-10-02
re: SQL Server 2005: Split string XML Style
I have a ntext field that I want to use this function on but it's not vorking on ntext data type.
Any solutions on that.

Thank You,
N.T.