5

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
  • 1
    The absolute best way to deal with is to stop stuffing multiple values into a single tuple. This violates 1NF and causes unbelievable amounts of anguish. Commented Nov 23, 2016 at 19:20

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

3 Comments

delimitedSplit8K?
My bad! I forgot to mention, the "splitter" function I am using here is Jeff Moden's DelimitedSplit8K from this article: sqlservercentral.com/articles/Tally+Table/72993
I like this answer. Thanks. I need to add distinct in the query.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.