Operand data type varchar is invalid for divide operator

I've just started using SQL and I have a pretty basic question:

I'm tried dividing 2 columns (amount/rate) - I converted them from 'money' to 'INT' but when I tried executing it gave me this error:

Operand data type varchar is invalid for divide operator.

This is the query I typed:

select referenceid, CONVERT(decimal(15,3), sellamount) as 'amount', CONVERT(decimal(15,3), rateactual) as 'Rate', CONVERT(decimal(15,3), 'amount' / 'rate') as 'local amount' FROM currencyfxconversions 

Can someone help me understand what I did wrong?

6

3 Answers

Try like this,

SELECT referenceid ,CONVERT(DECIMAL(15, 3), sellamount) AS 'amount' ,CONVERT(DECIMAL(15, 3), rateactual) AS 'Rate' ,CONVERT(DECIMAL(15, 3), (CONVERT(DECIMAL(15, 3), sellamount) / CONVERT(DECIMAL(15, 3), rateactual))) AS 'local amount' FROM currencyfxconversions 
1

In the original query,

convert(decimal(15,3),'amount' / 'rate') 

Must be replaced with:

CONVERT(CONVERT(decimal(15,3), sellamount) / CONVERT(decimal(15,3), rateactual)) 
1

Your issue is that you're using a column that you use in the same context. You can't use am alias as a table column in the select context. You must repeat the last alias queries, as follows:

SELECT referenceid ,CONVERT(DECIMAL(15, 3), sellamount) AS 'amount' ,CONVERT(DECIMAL(15, 3), rateactual) AS 'Rate' ,CONVERT(DECIMAL(15, 3), (CONVERT(DECIMAL(15, 3), sellamount) / convert(DECIMAL(15, 3), rateactual))) AS 'local amount' 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like