SQL - How to sort a page or chapter index numbers stored in a varchar fileld
1.3.1
1.3.2
1.3.3
1.1.3
1.10
1.10.1
1.10.2
1.10.3
1.2
1.2.1
1.2.10
1.2.11
Here is the solution for this...
-- Sample table with page or chapeter index to sort
SELECT
'1.1.0' PageIndex INTO #MY_TESTUNION SELECT '1.3.1' UNION SELECT '1.3.2' UNION SELECT '1.3.3' UNION SELECT '1.1.3' UNION SELECT '1.10' UNION SELECT '1.10.1' UNION SELECT '1.10.2' UNION SELECT '1.10.3' UNION SELECT '1.2' UNION SELECT '3.10.1'UNION SELECT '3.9.1'UNION SELECT '11.1.0'-- UD Function to sort the index numbers
create function dbo.SortNumber(@indexnum varchar(50))returns varchar(50)as
begindeclare @curlength int, @length intdeclare @rtnstring varchar(50)select @rtnstring = '', @curlength = 0while (@curlength < len(@indexnum)) -- loop until reach the last "." markbeginset @length = charindex('.', @indexnum, @curlength + 1)if @length = 0set @length = len(@indexnum) + 1-- pading with leading zeroset @rtnstring = @rtnstring + right('0000' + substring(@indexnum, @curlength + 1, @length - @curlength - 1), 4) + '.'set @curlength = @lengthendreturn @rtnstringend
--sample output of this function
SELECT dbo.SortNumber('1.10.1') = 0001.0010.0001.SELECT dbo.SortNumber('1.1.2') = 0001.0001.0002.
-- final result
SELECT PageIndex,dbo.SortNumber(PageIndex) SortedIndex FROM #MY_TEST ORDER BY SortedIndex
SELECT PageIndex,dbo.SortNumber(PageIndex) SortedIndex FROM #MY_TEST ORDER BY SortedIndex
No comments:
Post a Comment