REVERSE of a number in mysql

旧时模样 提交于 2021-02-10 15:49:31

问题


used the following stored procedure to find reverse of a number , but it is showing error:use the right syntax to use near loop.

DELIMITER //

CREATE PROCEDURE ggrepeat1()

begin

declare num1 int;

declare num2 int; 

declare rev int default 0;

set @num1:='&num1';

while num1>0

loop

set @num2:=num1 mod 10;

set @rev:=num2+(rev*10);

set @num1:=floor(num1/10);

end loop;

dbms_output.put_line('Reverse number is: '||rev);

end//

DELIMITER ;

回答1:


The while loop in mysql should be used in this like.
This is the first problem

while n>0 do
    content..
end while

The second problem is

dbms_output.put_line('Reverse number is: '||rev);

In mysql you cannot use the above code.
Instead you can use this

Select 'The reverse of number is 'rev;

So your code would be

DELIMITER //

CREATE PROCEDURE ggrepeat1()

begin

declare num1 int;

declare num2 int; 

declare rev int default 0;

set @num1:='&num1';

while num1>0 do

set @num2:=num1 mod 10;

set @rev:=num2+(rev*10);

set @num1:=floor(num1/10);

end while;

Select 'Reverse number is: 'rev;

end//

DELIMITER ;



回答2:


As noted in the comments, you can't use oracle syntax in mysql. Regardless, I think you're over-complicating things. A simpler approach would be to cast your number to a string, reverse it using built-in functions and cast it back to a number:

CREATE FUNCTION reverse_int(num INT)
RETURNS INT DETERMINISTIC
RETURN CAST(REVERSE(CAST(num AS CHAT)) AS INT);


来源:https://stackoverflow.com/questions/47853539/reverse-of-a-number-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!