[英]how to select rows data as single column in sql server
我在SQL Server中有一个表:
T_Id Supplimentary_keywords
-------------------------------------------------------------------------------------------
1 Animal, Animals, 1, One, Single,live,living Organism
2 Animals, Animal, Two, 2,live,living Organism
3 Animals, Animal, Three, 3,live,living Organism
4 Animals, Animal, Four, 4,live,living Organism
5 Animals, Animal, 5, Five,live,living Organism
6 Group Of Animals, Small Group, Group, Groups, Small Size Group
7 Group Of Animals, Animals, Animal, Group, Groups, Grouping,live,living Organism
8 Group Of Animals, Animals, Animal, Group, Groups, Grouping,large Group,live
9 Head, Heads
10 Neck, Necks
现在,我想从选择数据Supplimentary_keywords
与distinct
是这样的:
Supplimentary_keywords
----------------------
Animal
Animals
1
One
Single
live
living Organism
Two
2
live
Three
3
.......
我正在使用以下代码
SELECT DISTINCT
Split.a.value('.', 'VARCHAR(100)') Kwd
FROM
(SELECT
T_Id,
CAST('<M>' + Replace(Supplimentary_keywords, ',', '</M><M>')
+ '</M>' AS XML) AS Data from KWD_Theaurus_tbl) AS A
CROSS APPLY
data.nodes ('/M') AS Split(a)
并得到错误
讯息9421,第16级,状态1,第1行
XML解析:第1行,字符11,非法名称字符
如果我做错了,请帮助我如何实现这一目标或纠正我。
create table #temp (id int,suppl varchar(1000))
insert into #temp
select 1 , 'Animal, Animals, 1, One, Single,live,living Organism'
union all
select 2 , 'Animals, Animal, Two, 2,live,living Organism'
union all
select 3 , 'Animals, Animal, Three, 3,live,living Organism'
union all
select 4 , 'Animals, Animal, Four, 4,live,living Organism'
union all
select 5 , 'Animals, Animal, 5, Five,live,living Organism'
union all
select 6 , 'Group Of Animals, Small Group, Group, Groups, Small Size Group'
union all
select 7 , 'Group Of Animals, Animals, Animal, Group, Groups, Grouping,live,living Organism'
union all
select 8 , 'Group Of Animals, Animals, Animal, Group, Groups, Grouping,large Group,live'
union all
select 9 , 'Head, Heads'
union all
select 10 , 'Neck, Necks'
SELECT distinct Split.a.value('.', 'VARCHAR(100)') data
FROM (select id,Cast ('<M>'
+ Replace(suppl, ',', '</M><M>')
+ '</M>' AS XML) AS Data from #temp) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
尝试这个..
SELECT distinct Split.a.value('.', 'VARCHAR(100)') data
FROM (select id,Cast ('<M>'
+ replace(Replace(suppl, ',', '</M><M>'),'&','&')
+ '</M>' AS XML) AS Data from #temp) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
如果您还有其他任何spl字符,请相应替换。
无效的特殊字符及其在xml中的替代
& - &
< - <
> - >
" - "
' - '
SELECT DISTINCT Split.a.value('.', 'VARCHAR(100)') AS Supplimentary_keywords
FROM (SELECT id,
Cast ('<M>'
+ Replace(Supplimentary_keywords, ',', '</M><M>')
+ '</M>' AS XML) AS Supplimentary_keywords
FROM #temp) AS A
CROSS APPLY Supplimentary_keywords.nodes ('/M') AS Split(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.