SQL Server - Is there a collation that provides natural order for numbers?

蓝咒 提交于 2019-12-10 20:09:42

问题


I'm using SQL Server 2008.

I have a table with a column of type VarChar. It is currently filled with strings which actually represent numbers. Unfortunately, the column must remain VarChar ('1', '2' ... , '1000' ).

I wish to query that field for the max number value but since this is a VarChar I get the Lexicographical max and not the natural order max.

I thought I'll try and solve this by using the COLLATE clause for that query and change to a collation that provides numerical natural order like in this link

  1. Is there a collation like this for SQL Server 2008 and if so, what should be the query?
  2. If a collation like this exists should I use this method or should I use cast?

Thanks.


回答1:


There is no collation option that will perform a natural sort on numbers.

You can however, cast the value as an integer if all the values are expected to be integers.

Try something like

SELECT MAX(CAST (Value as int))
FROM MyTable



回答2:


Just a note, a third option is to use a persisted computed column - which is the value cast to a numeric

That way it is only cast once - on create or update

-- Create Table with computed column
CREATE TABLE [dbo].[CCtest]
(
[myString] [varchar] NULL,
[myInt] AS (cast(myString as int)) PERSISTED
)
GO

It's then ok to create an index on the computed column.




回答3:


If all values are numeric, you can simply order by the value converted to an int without requiring a change to the collation or table structure;

SELECT * FROM test ORDER BY CONVERT(INT, value);

An SQLfiddle to test with.



来源:https://stackoverflow.com/questions/16935989/sql-server-is-there-a-collation-that-provides-natural-order-for-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!