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

后端 未结 11 1990
慢半拍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:32

    select
      Field1, Field2...
    from
      Table1
    order by
      isnumeric(Field1) desc,
      case when isnumeric(Field1) = 1 then cast(Field1 as int) else null end,
      Field1
    

    This will return values in the order you gave in your question.

    Performance won't be too great with all that casting going on, so another approach is to add another column to the table in which you store an integer copy of the data and then sort by that first and then the column in question. This will obviously require some changes to the logic that inserts or updates data in the table, to populate both columns. Either that, or put a trigger on the table to populate the second column whenever data is inserted or updated.

提交回复
热议问题