Recently, someone asked, how to sort the characters, within a string?
For example, a string contains 'CBA', and he wanted to sort the characters within the string and make it 'ABC'.
Instead of going for a procedural solution, just for fun, I tried approaching it in a relational way (T-SQL specific).
In this article, I'll show you how we can make use of a numbers table for writing this kind of innovative queries.

Let's first create a numbers table called 'Numbers', with only one column called 'Number'. The 'Number' column is an IDENTITY
column with a primary key and clustered index defined on it. A clustered index in this case improves the performance of the
queries as we will be querying this numbers table for ranges of numbers.

The following script will drop the 'Numbers' table if it already exists, creates it and populates the table with
numbers 1 to 8000 (We need only 8000 numbers as a char/varchar variable or column can have a maximum of 8000 characters):

This idea can be extended for other scenarios. How about extracting the unique characters from a given string? That is,
given an input of 'abbcccdddd', output 'abcd'. The following script will do exactly that, using the DISTINCT keyword:

If you can spare some 16 KB of memory, you can pin the Numbers table into memory, so that the pages of this table
remain in memory, once read into memory. This is okay with smaller tables like the 'Numbers' table, but do not try this
with larger tables as that can negatively impact SQL Server performance The following command can be used to pin the 'Numbers'
table in memory (Also see DBCC PINTABLE in SQL Server Books Online (BOL)):

EXEC sp_tableoption 'Numbers', 'pintable', 'true'
GO

That concludes this article. I concentrated only on string manipulations, but for sure, there's more that can be done
with a table of numbers. Watch out for more articles, code samples in the near future. Have fun!