I need to split the data in single column to multi column.
I have the data like this
ID NAME COMMENT
1 TEST Reg: 0001 Inv: B0001 Cus: A0001 Br: F0001
2 TEST1 Reg: 0002 Inv: B0002 Cus: A0002 Br: F0002
3 TEST2 Reg: 0003 Inv: B0003 Cus: A0003 Br: F0003
4 TEST3 Reg: 0004 Inv: B0004 Cus: A0004 Br: F0004
5 TEST4 Reg: 0005 Inv: B0005 Cus: A0005 Br: F0005
5 TEST4 Reg: 00010 Inv: B00010 Cus: A00010 Br: F00010
And I need to split the data in table comment, so it become like this:
REG INV BR
0001 B0001 F0001
0002 B0002 F0002
0003 B0003 F0003
0004 B0004 F0004
0005 B0005 F0005
00010 B00010 F00010
Any suggestions how to do this?
My Code .
;WITH Split_Names (Comment)
AS
-- Define the CTE query.
(
SELECT
CONVERT(XML,'<COMMENTS><Comment>'
+ REPLACE(
REPLACe(
REPLACE(
REPLACE(
REPLACE(
REPLACE(Comment,'Reg:',''),'Inv:',','),'Cus:',','),'Br:',','),' ' ,'')
,',', '</Comment><Comment>') + '</Comment></COMMENTS>') AS xmlComments
FROM GenTransaction
)
-- Define the outer query referencing the CTE name.
SELECT
Comment.value('/COMMENTS[1]/Comment[1]','varchar(100)') AS Reg,
Comment.value('/COMMENTS[1]/Comment[2]','varchar(100)') AS Inv,
Comment.value('/COMMENTS[1]/Comment[3]','varchar(100)') AS Cus,
Comment.value('/COMMENTS[1]/Comment[4]','varchar(100)') AS Br
FROM Split_Names