SQL Server 2008 - 将多值列拆分为具有唯一值的行
在 SQL Server 2008 数据库中,我有一列包含用分号分隔的多个值。某些值包含冒号。示例数据:
key:value;key2:value;blah;foo;bar;A sample value:whee;others
key:value;blah;bar;others
A sample value:whee
我想从单独的行中获取每行的所有唯一值:
key:value
key2:value
blah
foo
bar
A sample value:whee
others
我查看了各种 split
函数,但它们似乎都处理硬编码字符串,而不是来自表中的一列。我该怎么做?
编辑:托马斯的回答明白了!这是我的最终查询:
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)
我猜 XmlValue.nodes
和 Yzvalue
的东西很神奇。奥奥
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 split 函数,您可以使用交叉应用:
这里 SplitString 接受两个参数,即字符串列和分隔符,并有一个名为
part
的列,其中返回值。With a split function you use cross apply:
Here the SplitString takes two arguments, the string column and the separator and has a column called
part
where the values are returned.更新
这是上述处理实体的版本:
Update
Here's a version of the above that handles entities: