How to sort NvarChar as numbers instead of string?

Avatar
  • updated
  • Answered

A field is formatted as NvarChar but only contains numbers. How can we sort it as numbers instead of a string of characters?

Avatar
Andrey Zavyalov, PM
  • Answered

Hello, cast your field to numeric in the SQL query:  

"SELECT ..., CAST(MyNVarCharField AS NUMERIC(15,2)) ... "  or "SELECT ..., CAST(MyNVarCharField AS INTEGER)  ... "

Also, many servers provide alternative ways to do this.
- SQL Server has the CONVERT function:  CONVERT(DECIMAL(7,2), 12)

- In PostgreSQL you can use :: operator: SELECT ' 5800.79 '::DECIMAL

After the conversion, sorting data will obey the arithmetical rules.