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:
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?
The cast and convert functions provide similar functionality. They are used to convert a value from one data type to another. So let's take a look at a practical example. The example is developed in SQL Server 2012 using the SQL Server Management Studio.
To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.
In theatrical terms, double-casting is when two actors are both cast in the same role, and take turns playing the role during alternating performances. It is different than casting an understudy. An understudy only performs when the actor in the role is away or ill.
The examples below shows the conversion of a string to the int type. A varchar variable and an int variable are declared, then the value of the varchar variable is set. It converts varchar to int type with the help of cast and convert functions. The varchar variable must contain numeric characters.
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
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With