USEFUL SITES :
Write for Us
SET NOCOUNT ONGOIF EXISTS(SELECT 1FROM INFORMATION_SCHEMA.TABLESWHERE TABLE_NAME = 'Numbers'AND TABLE_SCHEMA = 'dbo'AND TABLE_TYPE = 'BASE TABLE')BEGINDROP TABLE dbo.NumbersENDGOCREATE TABLE dbo.Numbers(Number smallint IDENTITY(1, 1) PRIMARY KEY)GOWHILE 1 = 1BEGININSERT INTO dbo.Numbers DEFAULT VALUESIF @@IDENTITY = 8000 BEGINBREAKENDENDGO
Now let us address the problem at hand: "Sorting the characters within a string." The following script will use the Numbers table to split the string into individual characters and create a derived table, from which it creates a sorted string using an aggregate concatenation query. This is a much better approach towards this problem, compared to you implementing a sorting algorithm in your scripts. Why reinvent the wheel when SQL Server can do the required sorting?
DECLARE @input varchar(100), @output varchar(100), @len smallintSET @input = 'CDBEA'SET @output = ''SET @len = LEN(@input)SELECT @output = @output + Val FROM (SELECT TOP 100 PERCENT SUBSTRING(@input, Number, 1) AS ValFROM dbo.Numbers (NOLOCK)WHERE Number <= @lenORDER BY Val) AS DerivedSELECT @input AS 'Original string', @output AS 'Sorted string'
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. Again, this approach is making use of SQL Server's ability to return only distinct rows from a given set. It would be a complicated task if you have to implement this ability on your own.
DECLARE @input varchar(100), @output varchar(100), @len smallintSET @input = 'ABBCCCDDDD'SET @output = ''SET @len = LEN(@input)SELECT @output = @output + ValFROM(SELECT DISTINCT TOP 100 PERCENT SUBSTRING(@input, Number, 1) AS ValFROM dbo.Numbers (NOLOCK)WHERE Number <= @lenORDER BY Val) AS DerivedSELECT @input AS 'Original string',@output AS 'Sorted string with UNIQUE characters only'