<p>We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.</p>

<p>Users can define their own sort, basically choosing what column to sort by.  Columns are dynamic - some have numeric values, some dates and some text.</p>

<p>While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.</p>

<p>For instance, sorting by a string record id gives something like:</p>

<pre><code>rec1
rec10
rec14
rec2
rec20
rec3
rec4
</code></pre>

<p>...and so on.</p>

<p>I want this to take account of the number, so:</p>

<pre><code>rec1
rec2
rec3
rec4
rec10
rec14
rec20
</code></pre>

<p>I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".</p>

<p>I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.</p>

<p>Does anyone know a way to quickly apply a natural sort in Sql server?</p>

<hr>

<p>We're using:</p>

<pre><code>ROW_NUMBER() over (order by {field name} asc)
</code></pre>

<p>And then we're paging by that.</p>

<p>We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.</p>

<hr>

<p>We have valid user input that follows different formats for different clients.</p>

<p>One might go rec1, rec2, rec3, ... rec100, rec101</p>

<p>While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301</p>

<p>When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.</p>

<p>These formats vary a lot, but are often mixtures of letters and numbers.</p>

<p>Sorting these in C# is easy - just break it up into <code>{ "grp", 20, "rec", 301 }</code> and then compare sequence values in turn.</p>

<p>However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.</p>

<p>SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.</p>

<p>@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.</p>

[{'answer_id': 35382, 'author': 'Grzegorz Gierlik', 'author_id': 1483, 'author_profile': 'https://Stackoverflow.com/users/1483', 'pm_score': -1, 'selected': False, 'text': "<p>I still don't understand (probably because of my poor English).</p>\n\n<p>You could try:</p>\n\n<pre><code>ROW_NUMBER() OVER (ORDER BY dbo.human_sort(field_name) ASC)\n</code></pre>\n\n<p>But it won't work for millions of records.</p>\n\n<p>That why I suggested to use trigger which <em>fills</em> <em>separate</em> column with <em>human value</em>.</p>\n\n<p>Moreover:</p>\n\n<ul>\n<li>built-in T-SQL functions are really\nslow and Microsoft suggest to use\n.NET functions instead.</li>\n<li><em>human value</em> is constant so there is no point calculating it each time\nwhen query runs.</li>\n</ul>\n"}, {'answer_id': 77373, 'author': 'Chris Wuestefeld', 'author_id': 10082, 'author_profile': 'https://Stackoverflow.com/users/10082', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re having trouble loading the data from the DB to sort in C#, then I\'m sure you\'ll be disappointed with any approach at doing it programmatically in the DB. When the server is going to sort, it\'s got to calculate the "perceived" order just as you would have -- every time. </p>\n\n<p>I\'d suggest that you add an additional column to store the preprocessed sortable string, using some C# method, when the data is first inserted. You might try to convert the numerics into fixed-width ranges, for example, so "xyz1" would turn into "xyz00000001". Then you could use normal SQL Server sorting.</p>\n\n<p>At the risk of tooting my own horn, I wrote a CodeProject article implementing the problem as posed in the CodingHorror article. Feel free to <a href="http://www.codeproject.com/KB/dotnet/SortingStringsForHumans.aspx" rel="nofollow noreferrer">steal from my code</a>.</p>\n'}, {'answer_id': 523012, 'author': 'JazzHands', 'author_id': 63173, 'author_profile': 'https://Stackoverflow.com/users/63173', 'pm_score': 3, 'selected': False, 'text': "<p>I know this is a bit old at this point, but in my search for a better solution, I came across this question. I'm currently using a function to order by. It works fine for my purpose of sorting records which are named with mixed alpha numeric ('item 1', 'item 10', 'item 2', etc) </p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnMixSort]\n(\n    @ColValue NVARCHAR(255)\n)\nRETURNS NVARCHAR(1000)\nAS\n\nBEGIN\n    DECLARE @p1 NVARCHAR(255),\n        @p2 NVARCHAR(255),\n        @p3 NVARCHAR(255),\n        @p4 NVARCHAR(255),\n        @Index TINYINT\n\n    IF @ColValue LIKE '[a-z]%'\n        SELECT  @Index = PATINDEX('%[0-9]%', @ColValue),\n            @p1 = LEFT(CASE WHEN @Index = 0 THEN @ColValue ELSE LEFT(@ColValue, @Index - 1) END + REPLICATE(' ', 255), 255),\n            @ColValue = CASE WHEN @Index = 0 THEN '' ELSE SUBSTRING(@ColValue, @Index, 255) END\n    ELSE\n        SELECT  @p1 = REPLICATE(' ', 255)\n\n    SELECT  @Index = PATINDEX('%[^0-9]%', @ColValue)\n\n    IF @Index = 0\n        SELECT  @p2 = RIGHT(REPLICATE(' ', 255) + @ColValue, 255),\n            @ColValue = ''\n    ELSE\n        SELECT  @p2 = RIGHT(REPLICATE(' ', 255) + LEFT(@ColValue, @Index - 1), 255),\n            @ColValue = SUBSTRING(@ColValue, @Index, 255)\n\n    SELECT  @Index = PATINDEX('%[0-9,a-z]%', @ColValue)\n\n    IF @Index = 0\n        SELECT  @p3 = REPLICATE(' ', 255)\n    ELSE\n        SELECT  @p3 = LEFT(REPLICATE(' ', 255) + LEFT(@ColValue, @Index - 1), 255),\n            @ColValue = SUBSTRING(@ColValue, @Index, 255)\n\n    IF PATINDEX('%[^0-9]%', @ColValue) = 0\n        SELECT  @p4 = RIGHT(REPLICATE(' ', 255) + @ColValue, 255)\n    ELSE\n        SELECT  @p4 = LEFT(@ColValue + REPLICATE(' ', 255), 255)\n\n    RETURN  @p1 + @p2 + @p3 + @p4\n\nEND\n</code></pre>\n\n<p>Then call</p>\n\n<pre><code>select item_name from my_table order by fnMixSort(item_name)\n</code></pre>\n\n<p>It easily triples the processing time for a simple data read, so it may not be the perfect solution.</p>\n"}, {'answer_id': 579005, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<pre><code>order by LEN(value), value\n</code></pre>\n\n<p>Not perfect, but works well in a lot of cases.</p>\n'}, {'answer_id': 750888, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>You can use the following code to resolve the problem:</p>\n\n<pre><code>Select *, \n    substring(Cote,1,len(Cote) - Len(RIGHT(Cote, LEN(Cote) - PATINDEX('%[0-9]%', Cote)+1)))alpha,\n    CAST(RIGHT(Cote, LEN(Cote) - PATINDEX('%[0-9]%', Cote)+1) AS INT)intv \nFROM Documents \n   left outer join Sites ON Sites.IDSite = Documents.IDSite \nOrder BY alpha, intv\n</code></pre>\n\n<p>regards,\nrabihkahaleh@hotmail.com</p>\n"}, {'answer_id': 751040, 'author': 'M.Turrini', 'author_id': 83623, 'author_profile': 'https://Stackoverflow.com/users/83623', 'pm_score': 0, 'selected': False, 'text': "<p>I've just read a article somewhere about such a topic. The key point is: you only need the integer value to sort data, while the 'rec' string belongs to the UI. You could split the information in two fields, say alpha and num, sort by alpha and num (separately) and then showing a string composed by alpha + num. You could use a computed column to compose the string, or a view.\nHope it helps</p>\n"}, {'answer_id': 2060952, 'author': "D'Arcy Rittich", 'author_id': 39430, 'author_profile': 'https://Stackoverflow.com/users/39430', 'pm_score': 6, 'selected': True, 'text': '<p>Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was <em>way</em> too slow.</p>\n\n<p>Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics:</p>\n\n<ul>\n<li>will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter)</li>\n<li>properly sorts decimals, so 123.333 comes before 123.45</li>\n<li>because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code</li>\n<li>supports sorting a string with an arbitrary number of numbers within it</li>\n<li>will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter)</li>\n</ul>\n\n<p>The code is here:</p>\n\n<pre><code>using System;\nusing System.Data.SqlTypes;\nusing System.Text;\nusing Microsoft.SqlServer.Server;\n\npublic class UDF\n{\n    [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)]\n    public static SqlString Naturalize(string val)\n    {\n        if (String.IsNullOrEmpty(val))\n            return val;\n\n        while(val.Contains("  "))\n            val = val.Replace("  ", " ");\n\n        const int maxLength = 1000;\n        const int padLength = 25;\n\n        bool inNumber = false;\n        bool isDecimal = false;\n        int numStart = 0;\n        int numLength = 0;\n        int length = val.Length &lt; maxLength ? val.Length : maxLength;\n\n        //TODO: optimize this so that we exit for loop once sb.ToString() &gt;= maxLength\n        var sb = new StringBuilder();\n        for (var i = 0; i &lt; length; i++)\n        {\n            int charCode = (int)val[i];\n            if (charCode &gt;= 48 &amp;&amp; charCode &lt;= 57)\n            {\n                if (!inNumber)\n                {\n                    numStart = i;\n                    numLength = 1;\n                    inNumber = true;\n                    continue;\n                }\n                numLength++;\n                continue;\n            }\n            if (inNumber)\n            {\n                sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));\n                inNumber = false;\n            }\n            isDecimal = (charCode == 46);\n            sb.Append(val[i]);\n        }\n        if (inNumber)\n            sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));\n\n        var ret = sb.ToString();\n        if (ret.Length &gt; maxLength)\n            return ret.Substring(0, maxLength);\n\n        return ret;\n    }\n\n    static string PadNumber(string num, bool isDecimal, int padLength)\n    {\n        return isDecimal ? num.PadRight(padLength, \'0\') : num.PadLeft(padLength, \'0\');\n    }\n}\n</code></pre>\n\n<p>To register this so that you can call it from SQL Server, run the following commands in Query Analyzer:</p>\n\n<pre><code>CREATE ASSEMBLY SqlServerClr FROM \'SqlServerClr.dll\' --put the full path to DLL here\ngo\nCREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000) \nEXTERNAL NAME SqlServerClr.UDF.Naturalize\ngo\n</code></pre>\n\n<p>Then, you can use it like so:</p>\n\n<pre><code>select *\nfrom MyTable\norder by dbo.Naturalize(MyTextField)\n</code></pre>\n\n<p><strong>Note</strong>: If you get an error in SQL Server along the lines of <em>Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option.</em>, follow the instructions <a href="http://www.novicksoftware.com/TipsAndTricks/tip-sql-server-2005-enable-clr-programming.htm" rel="nofollow noreferrer">here</a> to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration.</p>\n\n<p><strong>Note2</strong>: This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome!</p>\n\n<p><strong>Edit:</strong> Renamed the function to <em>Naturalize</em> instead of <em>NaturalSort</em>, since it does not do any actual sorting.</p>\n'}, {'answer_id': 3887921, 'author': 'Seph', 'author_id': 288747, 'author_profile': 'https://Stackoverflow.com/users/288747', 'pm_score': 4, 'selected': False, 'text': "<p>I know this is an old question but I just came across it and since it's not got an accepted answer.</p>\n\n<p>I have always used ways similar to this:</p>\n\n<pre><code>SELECT [Column] FROM [Table]\nORDER BY RIGHT(REPLICATE('0', 1000) + LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX)))), 1000)\n</code></pre>\n\n<p>The only common times that this has issues is if your column won't cast to a VARCHAR(MAX), or if LEN([Column]) > 1000 (but you can change that 1000 to something else if you want), but you can use this rough idea for what you need.</p>\n\n<p>Also this is much worse performance than normal ORDER BY [Column], but it does give you the result asked for in the OP.</p>\n\n<p>Edit: Just to further clarify, this the above will not work if you have decimal values such as having <code>1</code>, <code>1.15</code> and <code>1.5</code>, (they will sort as <code>{1, 1.5, 1.15}</code>) as that is not what is asked for in the OP, but that can easily be done by:</p>\n\n<pre><code>SELECT [Column] FROM [Table]\nORDER BY REPLACE(RIGHT(REPLICATE('0', 1000) + LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX)))) + REPLICATE('0', 100 - CHARINDEX('.', REVERSE(LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX))))), 1)), 1000), '.', '0')\n</code></pre>\n\n<p>Result: <code>{1, 1.15, 1.5}</code></p>\n\n<p>And still all entirely within SQL. This will not sort IP addresses because you're now getting into very specific number combinations as opposed to simple text + number.</p>\n"}, {'answer_id': 5587314, 'author': 'plalx', 'author_id': 1211528, 'author_profile': 'https://Stackoverflow.com/users/1211528', 'pm_score': 3, 'selected': False, 'text': "<p>Here's a solution written for SQL 2000. It can probably be improved for newer SQL versions.</p>\n\n<pre><code>/**\n * Returns a string formatted for natural sorting. This function is very useful when having to sort alpha-numeric strings.\n *\n * @author Alexandre Potvin Latreille (plalx)\n * @param {nvarchar(4000)} string The formatted string.\n * @param {int} numberLength The length each number should have (including padding). This should be the length of the longest number. Defaults to 10.\n * @param {char(50)} sameOrderChars A list of characters that should have the same order. Ex: '.-/'. Defaults to empty string.\n *\n * @return {nvarchar(4000)} A string for natural sorting.\n * Example of use: \n * \n *      SELECT Name FROM TableA ORDER BY Name\n *  TableA (unordered)              TableA (ordered)\n *  ------------                    ------------\n *  ID  Name                        ID  Name\n *  1.  A1.                         1.  A1-1.       \n *  2.  A1-1.                       2.  A1.\n *  3.  R1             --&gt;          3.  R1\n *  4.  R11                         4.  R11\n *  5.  R2                          5.  R2\n *\n *  \n *  As we can see, humans would expect A1., A1-1., R1, R2, R11 but that's not how SQL is sorting it.\n *  We can use this function to fix this.\n *\n *      SELECT Name FROM TableA ORDER BY dbo.udf_NaturalSortFormat(Name, default, '.-')\n *  TableA (unordered)              TableA (ordered)\n *  ------------                    ------------\n *  ID  Name                        ID  Name\n *  1.  A1.                         1.  A1.     \n *  2.  A1-1.                       2.  A1-1.\n *  3.  R1              --&gt;         3.  R1\n *  4.  R11                         4.  R2\n *  5.  R2                          5.  R11\n */\nALTER FUNCTION [dbo].[udf_NaturalSortFormat](\n    @string nvarchar(4000),\n    @numberLength int = 10,\n    @sameOrderChars char(50) = ''\n)\nRETURNS varchar(4000)\nAS\nBEGIN\n    DECLARE @sortString varchar(4000),\n        @numStartIndex int,\n        @numEndIndex int,\n        @padLength int,\n        @totalPadLength int,\n        @i int,\n        @sameOrderCharsLen int;\n\n    SELECT \n        @totalPadLength = 0,\n        @string = RTRIM(LTRIM(@string)),\n        @sortString = @string,\n        @numStartIndex = PATINDEX('%[0-9]%', @string),\n        @numEndIndex = 0,\n        @i = 1,\n        @sameOrderCharsLen = LEN(@sameOrderChars);\n\n    -- Replace all char that have the same order by a space.\n    WHILE (@i &lt;= @sameOrderCharsLen)\n    BEGIN\n        SET @sortString = REPLACE(@sortString, SUBSTRING(@sameOrderChars, @i, 1), ' ');\n        SET @i = @i + 1;\n    END\n\n    -- Pad numbers with zeros.\n    WHILE (@numStartIndex &lt;&gt; 0)\n    BEGIN\n        SET @numStartIndex = @numStartIndex + @numEndIndex;\n        SET @numEndIndex = @numStartIndex;\n\n        WHILE(PATINDEX('[0-9]', SUBSTRING(@string, @numEndIndex, 1)) = 1)\n        BEGIN\n            SET @numEndIndex = @numEndIndex + 1;\n        END\n\n        SET @numEndIndex = @numEndIndex - 1;\n\n        SET @padLength = @numberLength - (@numEndIndex + 1 - @numStartIndex);\n\n        IF @padLength &lt; 0\n        BEGIN\n            SET @padLength = 0;\n        END\n\n        SET @sortString = STUFF(\n            @sortString,\n            @numStartIndex + @totalPadLength,\n            0,\n            REPLICATE('0', @padLength)\n        );\n\n        SET @totalPadLength = @totalPadLength + @padLength;\n        SET @numStartIndex = PATINDEX('%[0-9]%', RIGHT(@string, LEN(@string) - @numEndIndex));\n    END\n\n    RETURN @sortString;\nEND\n</code></pre>\n"}, {'answer_id': 5682368, 'author': 'jack.mike.info', 'author_id': 707910, 'author_profile': 'https://Stackoverflow.com/users/707910', 'pm_score': 1, 'selected': False, 'text': "<p>Simply you sort by</p>\n\n<pre><code>ORDER BY \ncast (substring(name,(PATINDEX('%[0-9]%',name)),len(name))as int)\n\n ##\n</code></pre>\n"}, {'answer_id': 7410173, 'author': 'Gut Feeling', 'author_id': 816701, 'author_profile': 'https://Stackoverflow.com/users/816701', 'pm_score': 2, 'selected': False, 'text': '<p>For the following <code>varchar</code> data:</p>\n\n<pre><code>BR1\nBR2\nExternal Location\nIR1\nIR2\nIR3\nIR4\nIR5\nIR6\nIR7\nIR8\nIR9\nIR10\nIR11\nIR12\nIR13\nIR14\nIR16\nIR17\nIR15\nVCR\n</code></pre>\n\n<p>This worked best for me:</p>\n\n<pre><code>ORDER BY substring(fieldName, 1, 1), LEN(fieldName)\n</code></pre>\n'}, {'answer_id': 13375351, 'author': 'Simon', 'author_id': 888392, 'author_profile': 'https://Stackoverflow.com/users/888392', 'pm_score': 2, 'selected': False, 'text': '<p>Here is an other solution that I like:\n<a href="http://www.dreamchain.com/sql-and-alpha-numeric-sort-order/" rel="nofollow noreferrer">http://www.dreamchain.com/sql-and-alpha-numeric-sort-order/</a></p>\n<p>It\'s not Microsoft SQL, but since I ended up here when I was searching for a solution for Postgres, I thought adding this here would help others.</p>\n<p><strong>EDIT: Here is the code, in case the link goes away.</strong></p>\n<pre><code>CREATE or REPLACE FUNCTION pad_numbers(text) RETURNS text AS $$\n  SELECT regexp_replace(regexp_replace(regexp_replace(regexp_replace(($1 collate &quot;C&quot;),\n    E\'(^|\\\\D)(\\\\d{1,3}($|\\\\D))\', E\'\\\\1000\\\\2\', \'g\'),\n      E\'(^|\\\\D)(\\\\d{4,6}($|\\\\D))\', E\'\\\\1000\\\\2\', \'g\'),\n        E\'(^|\\\\D)(\\\\d{7}($|\\\\D))\', E\'\\\\100\\\\2\', \'g\'),\n          E\'(^|\\\\D)(\\\\d{8}($|\\\\D))\', E\'\\\\10\\\\2\', \'g\');\n$$ LANGUAGE SQL;\n</code></pre>\n<p>&quot;C&quot; is the default collation in postgresql; you may specify any collation you desire, or remove the collation statement if you can be certain your table columns will never have a nondeterministic collation assigned.</p>\n<p>usage:</p>\n<pre><code>SELECT * FROM wtf w \n  WHERE TRUE\n  ORDER BY pad_numbers(w.my_alphanumeric_field)\n</code></pre>\n'}, {'answer_id': 19471828, 'author': 'Roman Starkov', 'author_id': 33080, 'author_profile': 'https://Stackoverflow.com/users/33080', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/a/2060952/33080">RedFilter\'s answer</a> is great for reasonably sized datasets where indexing is not critical, however if you want an index, several tweaks are required.</p>\n\n<p>First, mark the function as not doing any data access and being deterministic and precise:</p>\n\n<pre><code>[SqlFunction(DataAccess = DataAccessKind.None,\n                          SystemDataAccess = SystemDataAccessKind.None,\n                          IsDeterministic = true, IsPrecise = true)]\n</code></pre>\n\n<p>Next, MSSQL has a 900 byte limit on the index key size, so if the naturalized value is the only value in the index, it must be at most 450 characters long. If the index includes multiple columns, the return value must be even smaller. Two changes:</p>\n\n<pre><code>CREATE FUNCTION Naturalize(@str AS nvarchar(max)) RETURNS nvarchar(450)\n    EXTERNAL NAME ClrExtensions.Util.Naturalize\n</code></pre>\n\n<p>and in the C# code:</p>\n\n<pre><code>const int maxLength = 450;\n</code></pre>\n\n<p>Finally, you will need to add a computed column to your table, and it must be persisted (because MSSQL cannot prove that <code>Naturalize</code> is deterministic and precise), which means the naturalized value is actually stored in the table but is still maintained automatically:</p>\n\n<pre><code>ALTER TABLE YourTable ADD nameNaturalized AS dbo.Naturalize(name) PERSISTED\n</code></pre>\n\n<p>You can now create the index!</p>\n\n<pre><code>CREATE INDEX idx_YourTable_n ON YourTable (nameNaturalized)\n</code></pre>\n\n<p>I\'ve also made a couple of changes to RedFilter\'s code: using chars for clarity, incorporating duplicate space removal into the main loop, exiting once the result is longer than the limit, setting maximum length without substring etc. Here\'s the result:</p>\n\n<pre><code>using System.Data.SqlTypes;\nusing System.Text;\nusing Microsoft.SqlServer.Server;\n\npublic static class Util\n{\n    [SqlFunction(DataAccess = DataAccessKind.None, SystemDataAccess = SystemDataAccessKind.None, IsDeterministic = true, IsPrecise = true)]\n    public static SqlString Naturalize(string str)\n    {\n        if (string.IsNullOrEmpty(str))\n            return str;\n\n        const int maxLength = 450;\n        const int padLength = 15;\n\n        bool isDecimal = false;\n        bool wasSpace = false;\n        int numStart = 0;\n        int numLength = 0;\n\n        var sb = new StringBuilder();\n        for (var i = 0; i &lt; str.Length; i++)\n        {\n            char c = str[i];\n            if (c &gt;= \'0\' &amp;&amp; c &lt;= \'9\')\n            {\n                if (numLength == 0)\n                    numStart = i;\n                numLength++;\n            }\n            else\n            {\n                if (numLength &gt; 0)\n                {\n                    sb.Append(pad(str.Substring(numStart, numLength), isDecimal, padLength));\n                    numLength = 0;\n                }\n                if (c != \' \' || !wasSpace)\n                    sb.Append(c);\n                isDecimal = c == \'.\';\n                if (sb.Length &gt; maxLength)\n                    break;\n            }\n            wasSpace = c == \' \';\n        }\n        if (numLength &gt; 0)\n            sb.Append(pad(str.Substring(numStart, numLength), isDecimal, padLength));\n\n        if (sb.Length &gt; maxLength)\n            sb.Length = maxLength;\n        return sb.ToString();\n    }\n\n    private static string pad(string num, bool isDecimal, int padLength)\n    {\n        return isDecimal ? num.PadRight(padLength, \'0\') : num.PadLeft(padLength, \'0\');\n    }\n}\n</code></pre>\n'}, {'answer_id': 71357605, 'author': 'ShrapNull', 'author_id': 1652234, 'author_profile': 'https://Stackoverflow.com/users/1652234', 'pm_score': 0, 'selected': False, 'text': "<p>I'm fashionably late to the party as usual. Nevertheless, here is my attempt at an answer that seems to work well (I would say that). It assumes text with digits at the end, like in the original example data.</p>\n<p>First a function that won't end up winning a &quot;pretty SQL&quot; competition anytime soon.</p>\n<pre><code>CREATE FUNCTION udfAlphaNumericSortHelper (\n@string varchar(max)\n)\nRETURNS @results TABLE (\n    txt varchar(max),\n    num float\n)\nAS\nBEGIN\n\n  DECLARE @txt varchar(max) = @string\n  DECLARE @numStr varchar(max) = ''\n  DECLARE @num float = 0\n  DECLARE @lastChar varchar(1) = ''\n\n  set @lastChar = RIGHT(@txt, 1)\n  WHILE @lastChar &lt;&gt; '' and @lastChar is not null\n  BEGIN \n    IF ISNUMERIC(@lastChar) = 1\n    BEGIN \n        set @numStr = @lastChar + @numStr\n        set @txt = Substring(@txt, 0, len(@txt))\n        set @lastChar = RIGHT(@txt, 1)\n    END\n    ELSE\n    BEGIN \n        set @lastChar = null\n    END\n  END\n  SET @num = CAST(@numStr as float)\n\n  INSERT INTO @results select @txt, @num\n  RETURN;\nEND\n</code></pre>\n<p>Then call it like below:</p>\n<pre><code>declare @str nvarchar(250) = 'sox,fox,jen1,Jen0,jen15,jen02,jen0004,fox00,rec1,rec10,jen3,rec14,rec2,rec20,rec3,rec4,zip1,zip1.32,zip1.33,zip1.3,TT0001,TT01,TT002'\n\n\nSELECT tbl.value  --, sorter.txt, sorter.num\nFROM STRING_SPLIT(@str, ',') as tbl\nCROSS APPLY dbo.udfAlphaNumericSortHelper(value) as sorter\nORDER BY sorter.txt, sorter.num, len(tbl.value)\n</code></pre>\n<p>With results:\nfox\nfox00\nJen0\njen1\njen02\njen3\njen0004\njen15\nrec1\nrec2\nrec3\nrec4\nrec10\nrec14\nrec20\nsox\nTT01\nTT0001\nTT002\nzip1\nzip1.3\nzip1.32\nzip1.33</p>\n"}]
['https://Stackoverflow.com/questions/34509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/905/']