0

I want to split the query result in MSSQL.

Example is below:

ID (PK)      BorrowID
1            1,3,4
2            4,5
3            2,3
4            1,6
5            2,7

I want to create new tables using upper table data.

NewID(PK)    ID      BorrowID
1            1       1
2            1       3
3            1       4
4            2       4
5            2       5

So I want to split the BorrowID Data to create new tables.

How can i get this?

I already try to use SUBSTRING, CHARINDEX function, but it doesn't well.

Salman A
  • 262,204
  • 82
  • 430
  • 521
Somputer
  • 1,223
  • 2
  • 11
  • 20

2 Answers2

1

You can try this to get individual values for your comma seperated list in MSSQL,

SELECT row_number() OVER (ORDER BY ID,BorrowID) as NewID,ID,BorrowID 
FROM ( SELECT A.*,
         Split.a.value('.', 'VARCHAR(100)') AS [BorrowID] 
     FROM  
     (
         SELECT ID, 
             CAST ('<M>' + REPLACE( [BorrowID], ',', '</M><M>') + '</M>' AS XML) AS Data  
          FROM [Table]
     ) AS A CROSS APPLY  [Data].nodes ('/M') AS Split(a))d;
Ajan Balakumaran
  • 1,639
  • 1
  • 8
  • 16
1

If you are on Sql Server 2016+ you may use String_split:

select ROW_NUMBER() over (order by t1.id, t2.borrowid) as newid, t1.id, t2.borrowid
 from t1 
  cross apply (select value as borrowid from string_split(t1.borrowid, ',')) as t2

Returns:

newid   id  borrowid
1   1   1
2   1   3
3   1   4
4   2   4
5   2   5
6   3   2
7   3   3
vercelli
  • 4,717
  • 2
  • 13
  • 15