I want some Moore

Blog about stuff and things and stuff...
mostly about SQL server and .Net
posts - 158, comments - 1438, trackbacks - 33

My Links

SQLTeam.com Links

News

Hi! My name is 
Mladen Prajdić  I'm from Slovenia and I'm currently working as a .Net (C#) and SQL Server developer. I'm also a MCP and MCTS for SQL Server. 
Welcome to my blog.

Search this Blog
 

My Blog Feed via Email


Get your Google PageRank
Users Online: who's online

Article Categories

Archives

Post Categories

Cool software

Other Blogs

Other stuff

SQL stuff

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
    
    DECLARE @textXML XML;
    SELECT    @textXML = CAST('<d>' + REPLACE(@data, @delimiter, '</d><d>') + '</d>' AS XML);

    INSERT INTO @t(data)
    SELECT  T.split.value('.', 'nvarchar(max)') AS data
    FROM    @textXML.nodes('/d') T(split)
    
    RETURN
END
GO

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

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

 

Enjoy it. :) kick it on DotNetKicks.com

Print | posted on Tuesday, May 22, 2007 7:23 PM

Feedback

# re: SQL Server 2005: Split string XML Style

The only problem is that it's really slow to parse XML, especially as the size increases beyond 8000 bytes. The numbers table-based methods will easily outperform this if you need to pass hundreds or thousands of items...
5/22/2007 8:21 PM | Adam Machanic

# re: SQL Server 2005: Split string XML Style

Check out this link and make sure you read the comments for other solutions

http://sqlblog.com/blogs/peter_debetta/archive/2007/02/12/multiple-valued-parameters.aspx#comments

Denis

5/22/2007 10:08 PM | Denis the SQL Menace

# re: SQL Server 2005: Split string XML Style

cool!
5/23/2007 9:18 AM | Mladen

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 5 and 4 and type the answer here:

Powered by: