Skip to content

Sort a Delimited String

A scalar function that sorts the pieces of a delimited string and rejoins them with the same delimiter.

Published Dec 24, 2006

A small utility that takes a delimited string, splits it with STRING_SPLIT, sorts the pieces alphabetically, and rejoins them with the same delimiter. Useful for normalizing lists stored in a single column so that comparisons work regardless of the order the values were entered in.

Example: SELECT dbo.SortStringByDelimiter('25/20/15/10/05', '/') -- returns 05/10/15/20/25

ALTER FUNCTION SortStringByDelimiter
(
	@String nvarchar(500),
	@Delimiter nvarchar(10)
)
RETURNS nvarchar(500)
AS
BEGIN
	DECLARE @Result nvarchar(500) = ''
	DECLARE @Value nvarchar(500)

	DECLARE AllValues CURSOR FOR
		SELECT
			value
		FROM
			STRING_SPLIT(@String, @Delimiter)
		ORDER BY
			value
	OPEN AllValues
	FETCH FROM AllValues INTO @Value

	WHILE(@@FETCH_STATUS = 0)
	BEGIN--WHILE
		--------------------------------------------------------------------------------

		SET @Result = @Result + @Value

		--------------------------------------------------------------------------------
		FETCH FROM AllValues INTO @Value

		IF(@@FETCH_STATUS = 0)
		BEGIN--IF
			SET @Result = @Result + @Delimiter
		END--IF
	END--WHILE

	CLOSE AllValues DEALLOCATE AllValues

	RETURN @Result
END
GO
An unhandled error has occurred. Reload 🗙