Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newbie - Errors when using CAST() and CONVERT()

I am very new to programming. I am learning SQL and am using SS2008 as a starting point. Firstly,thank you for your help! It makes the process of learning for someone like myself a lot easier.

I have read other threads but their code seems a lot more complicated.

I am going to keep this as simple as possible: I am querying a database wanting to perform a sum function on a particular column.

At present, the meta data of the column is of type varchar. I understand, to be able to use the sum function, the column in question needs to be of int.

To convert the column accordingly, I thought I could use either the cast/convert functions but incur errors when doing so:

/**
CAST:Charge_Pct FROM VARCHAR -> INT
**/


SELECT CAST(Charge_Pct AS NUMERIC(7,7)) 

FROM [Main].[Share_Class_Charges]

WHERE CHARGE_PCT <> 'None'

-- Arithmetic overflow error converting varchar to data type numeric.
/**
CONVERT: Charge_Pct FROM VARCHAR -> INT
**/

SELECT CONVERT(NUMERIC(7,7),Charge_Pct) 
 FROM [Main].[Share_Class_Charges]
WHERE CHARGE_PCT <> 'None'
-- Error converting data type varchar to numeric.

I am confused by where I am going wrong and what the error messages are saying. Please could someone help me by explaining what the error messages means and what needs to be done to correct the code?

Many thanks,

Al.

like image 795
user4907717 Avatar asked May 31 '26 16:05

user4907717


1 Answers

The NUMERIC(7,7) type describes a number with 0 digits before the decimal and 7 after. This means that if you try to cast a VARCHAR as small as 10.12 you will get an overflow error.

Try this query instead:

SELECT CAST(Charge_Pct AS NUMERIC(5,2)) 
FROM [Main].[Share_Class_Charges]
WHERE CHARGE_PCT <> 'None'

This will attempt to convert the Charge_Pct column (which I assume holds percentages) into a NUMERIC type consisting of 5 total numbers with 2 coming after the decimal place.

like image 99
Tim Biegeleisen Avatar answered Jun 02 '26 05:06

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!