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
486 views
in Technique[技术] by (71.8m points)

tsql - SQL Server 2008 - split multi-value column into rows with unique values

In a SQL Server 2008 database, I have a column with multiple values separated by semi-colons. Some values contain colons. Sample data:

key:value;key2:value;blah;foo;bar;A sample value:whee;others
key:value;blah;bar;others
A sample value:whee

I want to get all the unique values from each row in separate rows:

key:value
key2:value
blah
foo
bar
A sample value:whee
others

I've looked at various split functions, but they all seem to deal with hard-coded strings, not strings coming from a column in a table. How can I do this?

Edit: Thomas' answer got it! Here was my final query:

With SampleInputs As
    (
    select distinct myColumn from [myDatabase].[dbo].myTable where myColumn != ''
    )
    , XmlCte As
    (
    Select Cast( '<z>' + Replace( myColumn, ';', '</z><z>' ) + '</z>' As xml ) As XmlValue
    From SampleInputs As I
    )
Select Distinct Y.z.value('.','nvarchar(max)') As Value
From XmlCte
    Cross Apply XmlValue.nodes('//z') Y(z)

I'm guessing the XmlValue.nodes and Y.z.value stuff is magic. O_o

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

With a split function you use cross apply:

select distinct SS.part
from YourTable
  cross apply dbo.SplitString(YourColumn, ';') as SS

Here the SplitString takes two arguments, the string column and the separator and has a column called part where the values are returned.


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

...