Sorting Values in a Column

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

This was a post that caught my eye, since I’d just written a piece on STRING_SPLIT(). Someone had this data:

DECLARE @Names VARCHAR(8000) = 'Steve, Grant, Kathi, Kendra';

They wanted this returned as a string that was sorted, so that the values would be:

Grant, Kathi, Kendra, Steve

String manipulation isn’t the strength of SQL Server, but we can do this with STRING_SPLIT(). If we use STRING_SPLIT(), we get a list of values. We want to remove the spaces after the comma, so we use REPLACE to remove that.

FROM STRING_SPLIT(REPLACE(@Names, ' ', ''), ',')
ORDER BY value;

We can then aggregate these back together in a variable assignment, adding the comma for each row.

SELECT @newtext = @newtext + Value + ', '
FROM STRING_SPLIT(REPLACE(@Names, ' ', ''), ',')
ORDER BY value;

This gives us:

2018-12-21 15_05_08-SQLQuery1.sql - Plato_SQL2017.sandbox (PLATO_Steve (55))_ - Microsoft SQL Server


A quick T-SQL application of some skills I learned. Can you do something similar? Maybe order dates or numbers that are in a string in the wrong order?

That should be a 10-15 minute post.

About way0utwest

Editor, SQLServerCentral
This entry was posted in Blog and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.