Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide two integers to get a float in MySQL

I'm working on a user defined function in MySQL that takes an integer (mediumint) and divides it by 100 (i.e. 10785 / 100 = 107.85). The supplied integer is a parameter called time. I've tried

DECLARE dtime FLOAT;
SET dtime = time / 100;
DECLARE ftime VARCHAR(10);

which is causing an error, I assume because I'm dividing two integers and assigning it to a float

MySQL said: #1064 - You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax to use near 
'DECLARE ftime VARCHAR(10);

I've also tried

SET dtime = CAST(time as FLOAT) / 100.0;

But that throws an error because it appears you can't cast a number to a float. Finally, I tried using decimal

DECLARE dtime DECIMAL(10,10);
SET dtime = CAST(time AS decimal(10,10)) / CAST(100 as decimal(10,10);
DECLARE ftime VARCHAR(10);

But throws the same error (near 'Declare ftime...). What is the proper way to accomplish this?

like image 562
Robbert Avatar asked Oct 27 '25 11:10

Robbert


2 Answers

Can you try this?

SELECT CAST(time AS decimal) / CAST(100 AS decimal)
like image 93
user1874538 Avatar answered Oct 29 '25 01:10

user1874538


Please read the documentation for the DECLARE statement syntax.

Quoting from the reference manual (the above link):

DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

Declarations must follow a certain order. Cursor declarations must appear before handler declarations. Variable and condition declarations must appear before cursor or handler declarations.

like image 30
Barranka Avatar answered Oct 28 '25 23:10

Barranka