Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Split string using XML


Split string using XML

Author
Message
Jon Monahan
Jon Monahan
Hall of Fame
Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)

Group: General Forum Members
Points: 3529 Visits: 153
Very handy - thanks for the article and examples Divya. And thanks for the performance info Senthilnathan.
Adam Gojdas
Adam Gojdas
SSC Journeyman
SSC Journeyman (96 reputation)SSC Journeyman (96 reputation)SSC Journeyman (96 reputation)SSC Journeyman (96 reputation)SSC Journeyman (96 reputation)SSC Journeyman (96 reputation)SSC Journeyman (96 reputation)SSC Journeyman (96 reputation)

Group: General Forum Members
Points: 96 Visits: 1429
For splitting delimited lists I really like Jeff Moden's approach.

http://www.sqlservercentral.com/articles/T-SQL/63003/


Depending on how you use XML as was previously mentioned can cause an issue with the special XML characters. You would probably want to do an initial select to get it encoded properly possibly nesting it inside your code. Here is an example showing the characters getting entity encoded.:


DECLARE @data table(
someData varchar(255) NOT NULL PRIMARY KEY);

INSERT INTO @data (someData) VALUES ('SpecialChars, <>, & ');
INSERT INTO @data (someData) VALUES ('just, regular');

SELECT d.someData
FROM @data d
FOR XML PATH(''), TYPE


Goldie Lesser
Goldie Lesser
SSC-Addicted
SSC-Addicted (486 reputation)SSC-Addicted (486 reputation)SSC-Addicted (486 reputation)SSC-Addicted (486 reputation)SSC-Addicted (486 reputation)SSC-Addicted (486 reputation)SSC-Addicted (486 reputation)SSC-Addicted (486 reputation)

Group: General Forum Members
Points: 486 Visits: 1482
Cool concept and well written article, but this is not the best way to split a string.

I've performance tests on this and the SQL while loop.
The XML version seems slick at first, but slows down terribly when size of the string increases.

And Jeff's tally method leaves the while loop far behind.
http://www.sqlservercentral.com/articles/T-SQL/62867/
sam.walker
sam.walker
Grasshopper
Grasshopper (15 reputation)Grasshopper (15 reputation)Grasshopper (15 reputation)Grasshopper (15 reputation)Grasshopper (15 reputation)Grasshopper (15 reputation)Grasshopper (15 reputation)Grasshopper (15 reputation)

Group: General Forum Members
Points: 15 Visits: 107
The fastest way to do this is to

1 use a CLR scalar function to convert the delimitted string as a fixed width string.

2 split it using a tally table and substring



CREATE FUNCTION [dbo].[FnSplitQuick](@str nvarchar(max), @maxwidth int, @delimitter varchar(1))
RETURNS TABLE
RETURN
(
WITH dt as (
select
Data,
Offset = case when @maxwidth > 0 then 0 else 10 end,
Width = case when @maxwidth > 0 then @maxwidth else left(data,10) end,
MaxN = (len(data) - 2 - case when @maxwidth > 0 then 0 else 10 end) / case when @maxwidth > 0 then @maxwidth else left(data,10) end
from ( select data = dbsystem.dbo.[fnConvertToFixedWidth](isnull(@str,'')+@delimitter+'a', @maxwidth, @delimitter) ) d
)
select
Idx = N,
Value = rtrim(substring(data,N*Width+1 + Offset,Width))
from dt
inner join dbsystem..tally n
on n<= MaxN
)





and the clr




[Microsoft.SqlServer.Server.SqlFunction()]
public static SqlString ConvertToFixedFn(SqlString str, int padWidth, SqlString delimitter) {
// split
string[] arrStr = str.Value.Split(delimitter.Value[0]);
StringBuilder sb = new StringBuilder();

bool addWidth = (padWidth == 0);
if (addWidth) {
padWidth = 1;
for (int i = 0; i < arrStr.Length; i++) {
if (arrStr[i].Length > padWidth) {
padWidth = arrStr[i].Length;
}
}
}
if (addWidth) {
sb.Append(padWidth.ToString().PadRight(10));
}

foreach (string item in arrStr) {
sb.Append(item.PadRight(padWidth));
}

return new SqlString(sb.ToString());
}


G33kKahuna
G33kKahuna
Valued Member
Valued Member (72 reputation)Valued Member (72 reputation)Valued Member (72 reputation)Valued Member (72 reputation)Valued Member (72 reputation)Valued Member (72 reputation)Valued Member (72 reputation)Valued Member (72 reputation)

Group: General Forum Members
Points: 72 Visits: 313
Very cool concept ....

For all interested in performance aspect, XML data types are powerful but expensive. For XML queries, execution plan means very little. As the XML payload/ nodes increase or node iteration increases, LOB parsing becomes extremely heavy. Processing raw XML without indexes or schema applied on it, is similar to a heap in concept but worse because XML parsing adds a heavy layer. Schema helps with the read-aheads and Iops. Adding indexes helps with the lookup. Caveat with the indexes, needs sufficient head room for growth. Some of the benchmarks from my a prior project, the index size is roughly 10-12 times the data size for a 500+ node XML. Here is a sample benchmark, 200 node XML of roughly 69K size has a 810K index size. The size of the data matters as well.

Without taking away the spotlight from Divya's cool technique, if there are numerous XML nodes I would
1. pin the XML data to physical table and column
2. create a schema and apply it on the XML column
3. make the table transient to save on disk space. This means maintenance to defrag
4. apply primary and at least secondary PATH index
5. maintain a seperate LUN for the table, if using the second example to split numerous rows in the table
Sean Terry
Sean Terry
SSC Rookie
SSC Rookie (39 reputation)SSC Rookie (39 reputation)SSC Rookie (39 reputation)SSC Rookie (39 reputation)SSC Rookie (39 reputation)SSC Rookie (39 reputation)SSC Rookie (39 reputation)SSC Rookie (39 reputation)

Group: General Forum Members
Points: 39 Visits: 347
I'd seen XML string splitting and concatenation before, but ran into issues with characters that aren't valid in XML. I found that just escaping all the invalid characters prior to splitting frequently took more time than the entire split operation using a tally table.

That said, if you can qualify your data enough to ensure you won't ever have those sorts of issues, then it is certainly easier to code than some other solutions.
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45241 Visits: 39927
Senthilnathan.Karunakaran (6/25/2009)
We did performance and scaling test to split the comma separated string value using XML query and SQL function.

The plan was better with XML split than SQL function; however XML query performance degraded when number of concurrent users increase. SQL function did better in scalability test.


Cool. Let's see the test code and the data generator.

--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
jo stovall
jo stovall
SSC-Enthusiastic
SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)

Group: General Forum Members
Points: 163 Visits: 5429
We are converting SS2000 DTS packages to SSIS 2005.
I need help using a User Defined Function within a query on a table.

The function performs correctly.
select * from fn_Split('13.0,13.1,14.0,14.1' ,',')
idx value
0 13.0
1 13.1
2 14.0
3 14.1

This is the table to run the function against, with a few sample record results.
Select versions from versiontable
13.0,13.1,14.0,14.1
13.0,13.1,14.0,14.1
13.0,13.1,14.0,14.1
13.0,13.1,14.0,14.1
11.0,11.1,12.0,12.1,13.0,13.1,14.0

I tried this. Now it no longer recognises the function. Is the syntax wrong?
select fn_Split(versions, ',') as SingleVersion from versiontable where versions is not null
Server: Msg 195, Level 15, State 10, Line 1
'fn_Split' is not a recognized function name.

Tried this also.
select dbo.fn_Split(versions, ',') as Version from versiontable where versions is not null
Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'dbo.fn_Split'.

Any suggestions to get the query to work or even better, a nifty method to accomplish this within my data flow task using one of the Data Flow Transformation. Seems like the pivot might be useful for this?
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45241 Visits: 39927
jo stovall (6/25/2009)
We are converting SS2000 DTS packages to SSIS 2005.
I need help using a User Defined Function within a query on a table.

The function performs correctly.
select * from fn_Split('13.0,13.1,14.0,14.1' ,',')
idx value
0 13.0
1 13.1
2 14.0
3 14.1

This is the table to run the function against, with a few sample record results.
Select versions from versiontable
13.0,13.1,14.0,14.1
13.0,13.1,14.0,14.1
13.0,13.1,14.0,14.1
13.0,13.1,14.0,14.1
11.0,11.1,12.0,12.1,13.0,13.1,14.0

I tried this. Now it no longer recognises the function. Is the syntax wrong?
select fn_Split(versions, ',') as SingleVersion from versiontable where versions is not null
Server: Msg 195, Level 15, State 10, Line 1
'fn_Split' is not a recognized function name.

Tried this also.
select dbo.fn_Split(versions, ',') as Version from versiontable where versions is not null
Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'dbo.fn_Split'.

Any suggestions to get the query to work or even better, a nifty method to accomplish this within my data flow task using one of the Data Flow Transformation. Seems like the pivot might be useful for this?


What do you get when you run the following?

SELECT *
FROM sys.Objects
WHERE Name = 'fn_Split'

If the answer is nothing, then you're either in the wrong database or the CREATE FUNCTION code didn't actually work.

As a side bar, you'd probably get a lot more "hits" on your question if you asked it in the proper forum instead of a thread dedicated to the discusssion of an article.

--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
jo stovall
jo stovall
SSC-Enthusiastic
SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)SSC-Enthusiastic (163 reputation)

Group: General Forum Members
Points: 163 Visits: 5429
Thanks for responding.
I reposted on the SSIS forum.
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search