REVERSE of a number in mysql - mysql

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 ;

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);

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 ;

Related

Handling unfound data in mySQL procedure loop

I think I'm narrowing in on my issue. I have a loop that is only firing once:
DELIMITER $$
DROP PROCEDURE IF EXISTS `thread_updates` $$
CREATE PROCEDURE `thread_updates`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE my_curr_id INT DEFAULT NULL;
-- DECLARE other vars
DECLARE fixer_cursor CURSOR FOR
SELECT DISTINCT(id)
FROM log
WHERE date >= '2018-01-01';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN fixer_cursor;
REPEAT
FETCH fixer_cursor INTO my_curr_id;
IF NOT done THEN
SELECT data FROM table WHERE id = my_curr_id; -- This may not exist
-- Do other stuff with 'data' or NULL from above
END IF;
UNTIL done END REPEAT;
CLOSE fixer_cursor;
END $$
DELIMITER ;
I think the issue may be that inside the IF NOT done THEN loop, I have a few select statements that may be trying to select results that don't exist (not found).
This is fine (for me) as the logic continues along using NULL values in those spots, but I suspect that my CONTINUE HANDLER FOR NOT FOUND is catching the NOT FOUND warning that these selects throw inside the loop and are thus stopping the entire loop prematurely.
How can I listen for NOT FOUND warning on my cursor only?
Or, how can I suppress the NOT FOUND warning in my MAYBE FOUND select statements inside my loop so my loop continues?
I think I have solved the issue by implementing a counter in a loop rather than relying on the NOT FOUND handler:
DELIMITER $$
DROP PROCEDURE IF EXISTS `thread_updates` $$
CREATE PROCEDURE `thread_updates`()
BEGIN
DECLARE my_total INT DEFAULT NULL; -- Declare total
DECLARE my_counter INT DEFAULT 0; -- Declare counter starting at 0
DECLARE my_curr_id INT DEFAULT NULL;
-- DECLARE other vars
DECLARE fixer_cursor CURSOR FOR
SELECT DISTINCT(id)
FROM log
WHERE date >= '2018-01-01';
OPEN fixer_cursor;
SELECT FOUND_ROWS() INTO my_total; -- Get total number of rows
my_fixerloop: LOOP
FETCH fixer_cursor INTO my_curr_id;
IF my_counter >= my_total THEN -- Compare counter to total
CLOSE fixer_cursor;
LEAVE my_fixerloop;
END IF;
SET my_counter = my_counter + 1; -- Increment by one for each record
SELECT data FROM table WHERE id = my_curr_id; -- This may not exist
-- Do other stuff with 'data' or NULL from above
END LOOP;
END $$
DELIMITER ;

Can't declare variable in MySQL [duplicate]

I don't get what is wrong with this script
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs)
SET crs = crs + 1;
END WHILE;
END;
I want it to insert 10 values into the table continent but there is an error at the second line.
declare variable in MySQL with # and assign with :=
SET #crs = 0; // declaration
--here your query
#crs := #crs+1 // assignment
References
user defined variables
assignment
MySQL does not support the execution of anonymous blocks of stored procedure code.
You need to create a stored procedure including that code and then invoke it.
Also, you were missing the semi-colon at the end of your insert statements. I fixed that. You also probably want to use concat() instead of + to generate the names, but I'll leave that change to you.
Create the procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_ten_rows $$
CREATE PROCEDURE insert_ten_rows ()
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs);
SET crs = crs + 1;
END WHILE;
END $$
DELIMITER ;
Invoke the procedure:
CALL insert_ten_rows();

In a MySQL select statement, can I split a text column and then sum the parts as floats?

I have a MySQL column that is defined as text. The column, if not null, always contains a list floats separated by a newline character.
I have been tasked with making the total amount of those floats searchable with min and max constraints.
In the where clause, I would like to be able split the column by a newline character and sum all of the resulting strings as floats.
Is this possible?
You may have to define your own function.Here is an example I just tested, hope it is helpful to you(BTW: It is not advisable to implement such kind of functions in mysql. Maybe it is better to let the application servers to compute it instead of mysql :)).
DELIMITER $$
CREATE function split_n_sum(str text) returns DECIMAL(36,4)
begin
declare location int;
declare result decimal(36,4);
declare tmp_str varchar(1024);
declare _delimiter varchar(128);
set _delimiter='\r\n';
set result=0;
set tmp_str=ltrim(rtrim(str));
set location=INSTR(tmp_str,_delimiter);
if location=0 and length(tmp_str)>0 then
set result=cast(tmp_str as decimal(36,4));
set tmp_str='';
end if;
while location<>0 do
set result = result+cast(substring(tmp_str,1,location-length(_delimiter)) as decimal(36,4));
set tmp_str=substring(tmp_str,location+length(_delimiter), length(tmp_str));
set location=INSTR(tmp_str,_delimiter);
end while;
if length(tmp_str)>0 then
set result=result+cast(tmp_str as decimal(36,4));
end if;
return result;
end$$
Yes, you can: Use a function:
CREATE FUNCTION splitAndSum(inputStr VARCHAR)
RETURNS FLOAT;
BEGIN
DECLARE summedValues FLOAT;
DECLARE tempVal FLOAT;
DECLARE subString VARCHAR(200);
DECLARE tempLength INT;
SET subString=inputStr;
SET tempLength=0;
WHILE(TRUE) DO;
SET splitStr=MID(0,instr(subString," "));
SET tempLength=length(subString);
SET subString=MID(instr(subString," "));
SET tempVal=CAST(splitStr AS FLOAT);
SET tempVal=CAST(splitStr AS FLOAT);
SET summedValues=summedValues+tempVal;
IF(length(subString)==tempLength) break;
DONE;
RETURN summedValues;
END;
Call the function:
SELECT splitAndSum("1 2 3");
Should return: 6
Function needs to be tested...

Mysql syntax error on stored procedure

I run this code as a sql script from command line, and I get "you have an error in your SQL syntax" almost in all lines! Any ideas what is wrong here?
CREATE PROCEDURE updatemandate()
BEGIN
DECLARE _mandate_id BIGINT(20);
DECLARE _has_succesful_payment tinyint(1);
DECLARE done INT DEFAULT 0;
DECLARE cnt INT;
DECLARE mandateCursor CURSOR FOR Select mandate_id, has_succesful_payment From mandates;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN mandateCursor;
allmandates: LOOP
Fetch mandateCursor INTO _mandate_id, _has_succesful_payment;
IF done THEN LEAVE allmandates;
END IF;
Select COUNT(*) FROM payments WHERE mandate_id=_mandate_id AND status='OK' into cnt;
IF cnt>0 THEN
SET _has_succesful_payment=1;
END IF;
END LOOP allmandates;
CLOSE mandateCursor;
END
The ; character is the default delimiter, so when MySQL sees the first ; it thinks you are done. When you create a sproc, you need to declare a different delimiter character, like so:
DELIMITER $$
CREATE PROCEDURE updatemandate()
READS SQL DATA
BEGIN
DECLARE _mandate_id BIGINT(20);
DECLARE _has_succesful_payment tinyint(1);
DECLARE done INT DEFAULT 0;
DECLARE cnt INT;
DECLARE mandateCursor CURSOR FOR Select mandate_id, has_succesful_payment From mandates;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN mandateCursor;
allmandates: LOOP
Fetch mandateCursor INTO _mandate_id, _has_succesful_payment;
IF done THEN LEAVE allmandates;
END IF;
Select COUNT(*) FROM payment WHERE mandate_id=_mandate_id AND status='OK' into cnt;
IF cnt>0 THEN
SET _has_succesful_payment=1;
END IF;
END LOOP allmandates;
CLOSE mandateCursor;
END$$
DELIMITER ;
Also a good idea to add the READS SQL DATA to the sproc definition in case you need to support binary logging.
Have you tried putting delimiter // before the CREATE statement and change the last line with END //?

MYSQL declaring variables

I don't get what is wrong with this script
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs)
SET crs = crs + 1;
END WHILE;
END;
I want it to insert 10 values into the table continent but there is an error at the second line.
declare variable in MySQL with # and assign with :=
SET #crs = 0; // declaration
--here your query
#crs := #crs+1 // assignment
References
user defined variables
assignment
MySQL does not support the execution of anonymous blocks of stored procedure code.
You need to create a stored procedure including that code and then invoke it.
Also, you were missing the semi-colon at the end of your insert statements. I fixed that. You also probably want to use concat() instead of + to generate the names, but I'll leave that change to you.
Create the procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_ten_rows $$
CREATE PROCEDURE insert_ten_rows ()
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs);
SET crs = crs + 1;
END WHILE;
END $$
DELIMITER ;
Invoke the procedure:
CALL insert_ten_rows();