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
 General SQL Server Forums
 New to SQL Server Programming
 Display the column data in multiple lines

Author  Topic 

sqldev6363
Yak Posting Veteran

54 Posts

Posted - 2014-04-14 : 16:02:39
I have data like this

TableA

ID JunkData
1 1234jdueakj34jfjj4
2 345j5uttuvj5575jkf
3 sjhsdfk283ncfkjsf9

I need the Result to display like this. Split the JunkData Column Data in multiple lines, each line should contain 5 characters.

ID JunkData
1 1234d
ueakj
34jfj
j4
2 345j5
uttuv
j5575
jkf

Could some one help me to write the T-SQL Code.


dev

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2014-04-14 : 16:35:23
One way is to use a table with integers (like master..spt_values) or a numbers function:

;with TableA (ID, JunkData) as
(
select 1, '1234jdueakj34jfjj4' union all
select 2, '345j5uttuvj5575jkf' union all
select 3, 'sjhsdfk283ncfkjsf9'
)

select a.ID
,substring(a.junkData, n.number+1, 5) [SplitData5]
from TableA a
join master..spt_values n
on n.type = 'P'
and n.number % 5 = 0
where n.number < len(a.junkData)


OUTPUT:
ID SplitData5
----------- ----------
1 1234j
1 dueak
1 j34jf
1 jj4
2 345j5
2 uttuv
2 j5575
2 jkf
3 sjhsd
3 fk283
3 ncfkj
3 sf9


Be One with the Optimizer
TG
Go to Top of Page

sqldev6363
Yak Posting Veteran

54 Posts

Posted - 2014-04-14 : 18:03:17
Thanks TG

dev
Go to Top of Page
   

- Advertisement -