问题
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
- Is there a collation like this for SQL Server 2008 and if so, what should be the query?
- 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