SQL Server sort comma separated string in one colu

2019-02-28 06:39发布

问题:

How do I sort within a varchar column?

Such as I have a column called [Country], it may contain all kinds of country names.

Country column may contain

"Russia, USA, France, UK, Japan, Russia, France, China".

How do I distinct within [Country] column and sort the string alphabetically?

In the end, I want to get:

"China, France, Japan, Russia, UK, USA"

in [Country] column.

回答1:

Just as a side note: what TheGameiswar posted will work very well if provided that @string don't coptain any special XML characters. If it did you would need to make a small adjustment. This:

for xml path('')),1,1,'')

Would need to become this:

for xml path(''),TYPE).value('.', 'varchar(1000)'),1,1,'');

Consider the following query along with my comments:

declare @string varchar(max)
set @string='<tag3>,<tag1>,<tag2>';

-- Note the output here:
;with cte
as
(
select *
from dbo.delimitedSplit8K(@string,',')
)
select stuff( (select ',' +item 
from cte
order by item
for xml path('')),1,1,'');

-- this will handle special XML characters:
WITH cte
as
(
select *
from dbo.delimitedSplit8K(@string,',')
)
select stuff( (select ',' +item 
from cte
order by item
for xml path(''),TYPE).value('.', 'varchar(1000)'),1,1,'');

The change I'm showing will reduce the performance a little but handles special XML characters correctly.

Edit: I forgot to mention- the "splitter" I am using is from This article: http://www.sqlservercentral.com/articles/Tally+Table/72993/



回答2:

You will need to use one of the split string functions from here and then combine them again..

declare @string varchar(max)
set @string='Russia, USA, France, UK, Japan, Russia, France, China'

;with cte
as
(
select *
from [dbo].[SplitStrings_Numbers](@string,',')
)
select stuff( (select ',' +item 
from cte
order by item
for xml path('')),1,1,'')