How do I sort a VARCHAR column in SQL server that contains numbers?

后端 未结 11 2004
慢半拍i
慢半拍i 2020-11-27 14:08

I have a VARCHAR column in a SQL Server 2000 database that can contain either letters or numbers. It depends on how the application is configured o

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 14:31

    One possible solution is to pad the numeric values with a character in front so that all are of the same string length.

    Here is an example using that approach:

    select MyColumn
    from MyTable
    order by 
        case IsNumeric(MyColumn) 
            when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
            else MyColumn
        end
    

    The 100 should be replaced with the actual length of that column.

提交回复
热议问题