Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase ««12345»»»

Split string using XML Expand / Collapse
Author
Message
Posted Thursday, June 25, 2009 6:47 AM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Thursday, March 27, 2014 2:06 PM
Points: 2,513, Visits: 112
Very handy - thanks for the article and examples Divya. And thanks for the performance info Senthilnathan.
Post #741760
Posted Thursday, June 25, 2009 7:55 AM
SSC Journeyman

SSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC Journeyman

Group: General Forum Members
Last Login: Friday, November 01, 2013 8:49 AM
Points: 79, Visits: 1,328
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

Post #741829
Posted Thursday, June 25, 2009 8:19 AM
SSC-Addicted

SSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-Addicted

Group: General Forum Members
Last Login: Thursday, April 03, 2014 10:37 AM
Points: 478, Visits: 1,401
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/
Post #741850
Posted Thursday, June 25, 2009 10:07 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, September 04, 2012 2:14 AM
Points: 14, Visits: 93
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());
}

Post #741960
Posted Thursday, June 25, 2009 10:23 AM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Thursday, October 31, 2013 8:04 PM
Points: 68, Visits: 278
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
Post #741977
Posted Thursday, June 25, 2009 11:20 AM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Wednesday, August 28, 2013 1:49 PM
Points: 35, Visits: 315
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.
Post #742043
Posted Thursday, June 25, 2009 12:36 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 5:22 PM
Points: 36,016, Visits: 30,308
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."

"Change is inevitable. Change for the better is not." -- 04 August 2013
(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #742111
Posted Thursday, June 25, 2009 12:53 PM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Tuesday, June 11, 2013 1:45 PM
Points: 163, Visits: 5,428
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?
Post #742126
Posted Thursday, June 25, 2009 1:17 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 5:22 PM
Points: 36,016, Visits: 30,308
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."

"Change is inevitable. Change for the better is not." -- 04 August 2013
(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #742137
Posted Thursday, June 25, 2009 2:09 PM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Tuesday, June 11, 2013 1:45 PM
Points: 163, Visits: 5,428
Thanks for responding.
I reposted on the SSIS forum.
Post #742166
« Prev Topic | Next Topic »

Add to briefcase ««12345»»»

Permissions Expand / Collapse