In this example we will create a function that returns power of given number. MySql already has a function named power for this process. But we will create the function ourselves.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
DELIMITER $$ CREATE FUNCTION `Fn_Power`( `floor` INT, `ceil` INT ) RETURNS INT BEGIN SET @i = 0,@result = 1; WHILE (@i < CEIL) do SET @result = @result * FLOOR; SET @i = @i + 1; END WHILE; RETURN @result; END $$ DELIMITER ; |
After running the above code, you can run the codes below and calculate different number’s power.
Sample1
1 |
Select Fn_Power(2,4) |
Result : 16
Sample2
1 |
Select Fn_Power(5,2) |
Result : 25
Sample3
1 |
Select Fn_Power(7,2) |
Result : 49