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.SplitGO 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">'<d>'</span> + REPLACE(@<span class="kwrd">data</span>, @delimiter, <span class="str">'</d><d>'</span>) + <span class="str">'</d>'</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">'.'</span>, <span class="str">'nvarchar(max)'</span>) <span class="kwrd">AS</span> <span class="kwrd">data</span> <span class="kwrd">FROM</span> @textXML.nodes(<span class="str">'/d'</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. :)
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. |