Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write SQL query for this result?

I have so many long database so I used seq_no in commas separate using more than one sequence store in single column but now I want all sequence in a single column so I am confused how to create this sql result for this.

For example:

TABLE STRUCTURE 
SR_NO IS INT ,
SEQ_NO IS VARCHAR(MAX)
SR_NO   SEQ_NO
---------------------------------    
  1     1839073,
  2     1850097,1850098,
  3     1850099,1850100,1850110    

I need to get this result:

SEQ_NO 
--------------
1839073
1850097
1850098
1850099
1850100
1850110 

Thanks!

like image 577
Rajuu Parmar Avatar asked Jun 20 '26 05:06

Rajuu Parmar


2 Answers

declare @t table(Id int,seq varchar(100)) 
insert into @t (Id,seq) values (1,'1839073,'),(2,'1839073,1850098,'),(3,'1850099,1850100,1850110 ')



;With Cte as (
SELECT A.Id,  
     Split.a.value('.', 'VARCHAR(100)') AS Seq  
 FROM  
 (
     SELECT Id,  
         CAST ('<M>' + REPLACE(seq, ',', '</M><M>') + '</M>' AS XML) AS Data  
     FROM  @t
 ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a) )

 Select ID,Seq from Cte Where Seq > ''
like image 155
mohan111 Avatar answered Jun 23 '26 02:06

mohan111


Try splitting it with XML

SELECT SR_NO, t.c.value('.', 'VARCHAR(2000)') COL1
FROM (
  SELECT SR_NO, x = CAST('<t>' + 
        REPLACE(SEQ_NO, ',', '</t><t>') + '</t>' AS XML) 
        FROM 
       (values(1,'1839073'),(2, '1850097,1850098'),
        (3, '1850099,1850100,1850110')) y(SR_NO, SEQ_NO)

) a
CROSS APPLY x.nodes('/t') t(c)

Result:

SR_NO  COL1
1      1839073
2      1850097
2      1850098
3      1850099
3      1850100
3      1850110

You can replace this with your table:

 (values (1,'1839073'),(2, '1850097,1850098'),
  (3, '1850099,1850100,1850110')) y(SR_NO, SEQ_NO)
like image 31
t-clausen.dk Avatar answered Jun 23 '26 01:06

t-clausen.dk