SQL SERVER split column as multiple rows

Source: Internet
Author: User

--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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.