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 2005 Forums
 Transact-SQL (2005)
 Parse string to new records

Author  Topic 

dadster
Starting Member

2 Posts

Posted - 2010-12-03 : 04:51:31
I am trying to fix some legacy data and need to parse data from a field to use to create new records

I have:

ID,Code,Data
-------------
1,aa/dd/ff/gg,some data
2,gg,more data
3,kk/ll/oo/pp,3535

and want to convert to:

ID,Code,Data
-------------
1,aa,some data
1,dd,some data
1,ff,some data
1,gg,some data
2,gg,more data
3,kk,3535
3,ll,3535
3,oo,3535
3,pp,3535

IE Parse the string in the code field and create new records if needed
I know I can do it with a cursor, but I'm struggling with a set based solution.

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2010-12-03 : 05:03:21
Something like

;with cte as
(
select id, data, code, locstrt = 1, locend=charindex('/',code) from tbl
union all
select id, data, code, locstrt = locend+1, locend=charindex('/',code,locend+1) from cte where locend<>0
)
select id, code=substring(code,locstrt,case when locend = 0 then len(code) else locend end - locstrt), data
from cte


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

dadster
Starting Member

2 Posts

Posted - 2010-12-03 : 05:15:30
Thanks nigelrivett - works perfectly. Haven't played much with CTE - I think I need to check it out!
Go to Top of Page

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2010-12-03 : 05:22:34
see
http://www.simple-talk.com/sql/t-sql-programming/sql-server-2005-common-table-expressions/

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -