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.

SELECT *
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

SQLNewBlogger

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.