Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

tsql - SQL Server sort comma separated string in one column

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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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,'')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...