25

I have problem with my query when I was trying to convert the varchar field to double (numeric). I have this sql statement:

SELECT fullName, CAST(totalBal as numeric(9,2) FROM client_info ORDER BY totalBal DESC

Actually I want to display the values of totalBal in descending order. But since that field is in varchar, the resultset is sometimes wrong. This is the resultset when I tried to query using this statement:

SELECT fullName, totalBal FROM client_info ORDER BY totalBal DESC 

Resultset is:

enter image description here

The sorting of totalBal is not correct. So I decided to convert the varchar to numeric so that it might be sorted perfectly. Any idea?

Jay Marz
  • 1,861
  • 10
  • 34
  • 54

2 Answers2

47

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • 1
    Thank you for this idea... updated the code with this... `SELECT fullName, CAST( totalBal AS DECIMAL( 9, 2 ) ) AS totBal FROM client_info ORDER BY totBal DESC` – Jay Marz Jan 24 '13 at 07:47
3

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
TheTechGuy
  • 16,560
  • 16
  • 115
  • 136