--Create a test tableCreate Table#Temp(seqint Identity, namesvarchar( $))Insert into#Temp(names)Values('Zhang San, John Doe'),('China, USA, Brazil'),('Shenzhen, Shanghai, Beijing, Guangzhou, Harbin'),('football, basketball, table tennis, billiards')
The goal is to split the names column separated by commas into multiple rows, resulting in the result:
1 sheets of three
1 John Doe
2 China
2 USA
2 Brazil
3 Shenzhen
3 Shanghai
3 Beijing
3 Guangzhou
3 Harbin
4 Football
4 Basketball
4 Table Tennis
4 Billiards
1; withCte as(2 Select 0 asN3 Union All4 SelectN+1 fromCtewhereN< -5 )6, IDX as (7 SelectA.seq,b.n,row_number () Over(Partition byA.seqOrder byB.N) asId','+A.names+',' asnames8 from#Tempa9 Inner JoinCTE b onB.n<=Len(','+A.names+',' )Ten where SUBSTRING(','+A.names+',', B.N,1)=',' One ) A SelectA.seq,substring(A.NAMES,A.N+1, B.N-A.n-1) asname - fromidx a - Inner JoinIDX b onA.seq=B.seq anda.ID=b.ID-1
SQL SERVER split column as multiple rows