Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

Splitting Comma separated values in columns to multiple rows in Sql Server

My table has three columns. One of the columns [Col3] has multiple values. So, when I make a select command on the table :

Select col1, col2, col3 from MyTable

It gives me the below result:

         Col1       Col2         Col3
         ------------------------------
Row 1    430        A319         N1160 N1336
Row 2    abc        efg          G3489 M5678 N5643

If there any way to get the output as:

         Col1       Col2         Col3
         ------------------------------
Row 1    430        A319         N1160
Row 2    430        A319         N1336
Row 3    abc        efg          G3489
Row 4    abc        efg          M5678
Row 5    abc        efg          N5643

Like if the column has multiple values, then a new row is displayed corresponding to each value in the column and other columns should contain the duplicated data.

I hope I am pretty clear with the problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
SELECT col1,
       col2,
       Split.a.value('.', 'VARCHAR(100)') col3
FROM   (SELECT col1,
               col2,
               Cast ('<M>' + Replace(col3, ' ', '</M><M>') + '</M>' AS XML) AS Data
        FROM   [table]) AS A
       CROSS APPLY Data.nodes ('/M') AS Split(a) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...