Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 string splitting

Author  Topic 

sigmas
Posting Yak Master

172 Posts

Posted - 2013-08-03 : 08:12:52
Hi,
I have a string value like this:

"just_test <id = 1> some_value <id = 30> a_value <id = 5>"

I want the result set like this:

value |id
--------------
just_test |1
some_value |30
a_value |5


is it possible to implement that by using XML.

stepson
Aged Yak Warrior

545 Posts

Posted - 2013-08-03 : 09:09:02
Hi,


declare @str as varchar(100)='just_test <id = 1> some_value <id = 30> a_value <id = 5>'
declare @strXML as xml

set @str =replace(@str,' <id = ','|')
/* get rideoff last >*/
set @str = substring(@str,1,len(@str)-1)
/*convert to cast .That could be done also in FROM */
set @strXML=cast('<root><element>'+ replace(@str,'>','</element><element>')+'</element></root>' as XML)


select
SUBSTRING(t.u.value('.','varchar(100)'),1,CHARINDEX('|',t.u.value('.','varchar(100)'))-1) as [value]
,SUBSTRING(t.u.value('.','varchar(100)'),CHARINDEX('|',t.u.value('.','varchar(100)'))+1,len(t.u.value('.','varchar(100)'))-CHARINDEX('|',t.u.value('.','varchar(100)'))) as [id]
from
(select @strXML as strXML) m
cross apply strXML.nodes('root/element') as t(u)



you can inspire from this:
[url]http://visakhm.blogspot.in/2013/01/delimited-string-split-xml-parsing.html[/url]


it's ugly , maybe someone come with something more elegant ;)

S


Ce-am pe mine am si-n dulap, cand ma-mbrac zici ca ma mut
sabinWeb
Go to Top of Page

jethrow
Starting Member

37 Posts

Posted - 2013-08-04 : 15:43:59
Here's a simple example w/o using XML:

declare @t table (value varchar(20), id varchar(5))
declare @str as varchar(100)='just_test <id = 1> some_value <id = 30> a_value <id = 5>'
declare @pos int = 1, @st int = 0, @field1 varchar(20)

set @pos = CharIndex('>', @str)
while @pos > 0 begin
set @field1 = LTrim(SubString(@str, @st, @pos-@st))
insert @t values (SubString(@field1,1,CharIndex(' ',@field1)-1),
SubString(@field1,CharIndex('= ',@field1)+2,Len(@field1)))
set @st = @pos+1
set @pos = CharIndex('>', @str, @st)
end

Select * From @t;
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-04 : 20:31:17
Do you have to use XML sigmas? That is one of the most inefficient methods for splitting a string. The fastest that I have seen is Jeff Moden's string splitter here: http://www.sqlservercentral.com/articles/Tally+Table/72993/
The splitter function is in Figure 21
Go to Top of Page

productkeyfinding
Starting Member

1 Post

Posted - 2013-08-04 : 23:09:47
unspammed
Go to Top of Page
   

- Advertisement -