In MySQL, I have this stored procedure with a LOOP:
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
DECLARE a INT Default 0 ;
simple_loop: LOOP
SET a=a+1;
select a;
IF a=5 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
It always prints 1. What is the correct syntax for a MySQL Loop?
drop table if exists foo;
create table foo
(
id int unsigned not null auto_increment primary key,
val smallint unsigned not null default 0
)
engine=innodb;
drop procedure if exists load_foo_test_data;
delimiter #
create procedure load_foo_test_data()
begin
declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;
truncate table foo;
start transaction;
while v_counter < v_max do
insert into foo (val) values ( floor(0 + (rand() * 65535)) );
set v_counter=v_counter+1;
end while;
commit;
end #
delimiter ;
call load_foo_test_data();
select * from foo order by id;
While loop syntax example in MySQL:
delimiter //
CREATE procedure yourdatabase.while_example()
wholeblock:BEGIN
declare str VARCHAR(255) default '';
declare x INT default 0;
SET x = 1;
WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;
select str;
END//
Which prints:
mysql> call while_example();
+------------+
| str |
+------------+
| 1,2,3,4,5, |
+------------+
REPEAT loop syntax example in MySQL:
delimiter //
CREATE procedure yourdb.repeat_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 5;
SET str = '';
REPEAT
SET str = CONCAT(str,x,',');
SET x = x - 1;
UNTIL x <= 0
END REPEAT;
SELECT str;
END//
Which prints:
mysql> call repeat_loop_example();
+------------+
| str |
+------------+
| 5,4,3,2,1, |
+------------+
FOR loop syntax example in MySQL:
delimiter //
CREATE procedure yourdatabase.for_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = -5;
SET str = '';
loop_label: LOOP
IF x > 0 THEN
LEAVE loop_label;
END IF;
SET str = CONCAT(str,x,',');
SET x = x + 1;
ITERATE loop_label;
END LOOP;
SELECT str;
END//
Which prints:
mysql> call for_loop_example();
+-------------------+
| str |
+-------------------+
| -5,-4,-3,-2,-1,0, |
+-------------------+
1 row in set (0.00 sec)
Do the tutorial: http://www.mysqltutorial.org/stored-procedures-loop.aspx
If I catch you pushing this kind of MySQL for-loop constructs into production, I'm going to shoot you with the foam missile launcher. You can use a pipe wrench to bang in a nail, but doing so makes you look silly.
Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below
CREATE TABLE `table1` (
`col1` VARCHAR(50) NULL DEFAULT NULL
)
Now if you want to insert number from 1 to 50 in that table then use following stored procedure
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
DECLARE a INT Default 1 ;
simple_loop: LOOP
insert into table1 values(a);
SET a=a+1;
IF a=51 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
To call that stored procedure use
CALL `ABC`()
You can exchange this local variable for a global, it would be easier.
DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
SET #a = 0;
simple_loop: LOOP
SET #a=#a+1;
select #a;
IF #a=5 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
Related
delimiter $$
create procedure increase_charge()
begin
declare v_name VARCHAR(120);
declare v_oldchg VARCHAR(120);
declare v_newchg VARCHAR(120);
declare not_found int default 0;
declare c_nur cursor for select n_name,n_charge
from Nurses
Where n_charge < 70;
declare continue handler for not found set not_found = 1;
open c_nur;
loop_label:
loop
fetch c_nur into v_name,v_oldchg;
if not_found = 1 then LEAVE loop_label; END IF;
set v_newchg= v_oldchg+( v_oldchg*0.20);
UPDATE Nurses
SET n_charge = v_newchg
WHERE Nurses.n_name = v_name;
SELECT'Nurse name',ifnull(v_name, '');
SELECT'Old change per hour',ifnull(v_oldchg, '');
SELECT'New charge per hour',ifnull(v_newchg, '');
end loop;
close c_nur;
end;
delimiter;
call increase_charge;
There is nothing wrong with your code and it works as expected with the minor syntax corrections.
drop table if exists nurses;
create table nurses(n_name varchar(3),n_charge int);
insert into nurses values('aaa',10),('bbb',80);
drop procedure if exists increase_charge;
delimiter $$
create procedure increase_charge()
begin
declare v_name VARCHAR(120);
declare v_oldchg VARCHAR(120);
declare v_newchg VARCHAR(120);
declare not_found int default 0;
declare c_nur cursor for select n_name,n_charge
from Nurses
Where n_charge < 70;
declare continue handler for not found set not_found = 1;
open c_nur;
loop_label:
loop
fetch c_nur into v_name,v_oldchg;
if not_found = 1 then LEAVE loop_label; END IF;
set v_newchg= v_oldchg+( v_oldchg*0.20);
UPDATE Nurses
SET n_charge = v_newchg
WHERE Nurses.n_name = v_name;
SELECT'Nurse name',ifnull(v_name, '');
SELECT'Old change per hour',ifnull(v_oldchg, '');
SELECT'New charge per hour',ifnull(v_newchg, '');
end loop;
close c_nur;
end $$
delimiter ;
call increase_charge();
select * from nurses;
+--------+----------+
| n_name | n_charge |
+--------+----------+
| aaa | 12 |
| bbb | 80 |
+--------+----------+
2 rows in set (0.001 sec)
BTW this can be done with a simple update statement
update nurses
set n_charge = n_charge + (n_charge * .2)
where n_charge < 70;
I'm looking to do some validation of data replication between some different database systems, with different character sets (potentially) and a third party software that migrates the data. To help test an aspect of this, I'm looking to do something like the following.
ASCII(foo) returns the value for the first character in the string. Is there a way to get the ascii values for all characters in a string in one go, in one select statement? Something like concating the values together, separated by a space. E.g. If the string was hello then the output would be 104 101 108 108 111
Reference:
select ascii('h'); -- 104
select ascii('e'); -- 101
select ascii('l'); -- 108
select ascii('o'); -- 111
Just had the same problem, so here is a procedure that does the work:
DELIMITER $$
CREATE PROCEDURE string_to_ascii(IN inputStr VARCHAR(255))
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE idx INT DEFAULT 0;
DECLARE current_char VARCHAR(1);
DECLARE current_char_ascii VARCHAR(10);
DECLARE outputStr TEXT;
IF inputStr IS NULL THEN
SET inputStr = '';
END IF;
SET strLen = CHAR_LENGTH(inputStr);
SET idx = 1;
WHILE idx <= strLen DO
SET current_char = SUBSTR(inputStr, idx, 1);
SET current_char_ascii = ASCII(current_char);
IF idx = 1 THEN
SET outputStr = current_char_ascii;
ELSE
SET outputStr = CONCAT(outputStr, ",", current_char_ascii);
END IF;
SET idx = idx+1;
END WHILE;
SELECT outputStr;
END
$$
DELIMITER ;
Usage:
> CALL string_to_ascii('hello');
+---------------------+
| outputStr |
+---------------------+
| 104,101,108,108,111 |
+---------------------+
If you prefer to use it as a function:
DELIMITER //
CREATE FUNCTION string_to_ascii ( inputStr TEXT )
RETURNS TEXT
DETERMINISTIC
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE idx INT DEFAULT 0;
DECLARE current_char VARCHAR(1);
DECLARE current_char_ascii VARCHAR(10);
DECLARE outputStr TEXT;
IF inputStr IS NULL THEN
SET inputStr = '';
END IF;
SET strLen = CHAR_LENGTH(inputStr);
SET idx = 1;
WHILE idx <= strLen DO
SET current_char = SUBSTR(inputStr, idx, 1);
SET current_char_ascii = ASCII(current_char);
IF idx = 1 THEN
SET outputStr = current_char_ascii;
ELSE
SET outputStr = CONCAT(outputStr, ",", current_char_ascii);
END IF;
SET idx = idx+1;
END WHILE;
RETURN outputStr;
END; //
DELIMITER ;
And then the usage will be:
> SELECT string_to_ascii('hello');
+--------------------------+
| string_to_ascii('hello') |
+--------------------------+
| 104,101,108,108,111 |
+--------------------------+
i'm having hard time with my homework , because im beginner using mysql procedure.
to search total numbers odd and even between 20-50 with looping.
i want to make output like this using mysql procedure to call:
total_odd_numbers :15
total_even_numbers:16
i tried for sum up for even numbers like this :
`DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `genap`()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
declare total int;
SET x = 20;
SET str = '';
set total = 0;
loop_label: LOOP
IF x = 50 THEN
LEAVE loop_label;
END IF;
SET x =x+1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
SET total= total+x;
END IF;
END LOOP;
SELECT sum(total);
END`
Try this procedure:
DROP PROCEDURE IF EXISTS ShowOddEvesBetween;
DELIMITER ;;
CREATE PROCEDURE ShowOddEvesBetween(IN fromNum INT, IN toNum INT)
BEGIN
DECLARE odds INT DEFAULT 0;
DECLARE evens INT DEFAULT 0;
DECLARE x INT;
SET x = fromNum;
WHILE x <= toNum DO
IF x % 2 THEN
SET odds = odds + 1;
ELSE
SET evens = evens + 1;
END IF;
SET x = x + 1;
END WHILE;
SELECT CONCAT("total_odd_numbers: ", odds, ", total_even_numbers: ", evens) AS "Odds & Evens";
END;
;;
Then call it
CALL ShowOddEvesBetween(20, 50);
Will output what you want
MariaDB [test]> CALL ShowOddEvesBetween(20, 50);
+-----------------------------------------------+
| Odds & Evens |
+-----------------------------------------------+
| total_odd_numbers: 15, total_even_numbers: 16 |
+-----------------------------------------------+
1 row in set (0.00 sec)
I have created mysql function to split the string in rows using temporary table, it gives correct in temp table, but not when i call the function it returns 1 as output.
My code is as below
DELIMITER $$
DROP FUNCTION IF EXISTS `split`$$
CREATE FUNCTION `split`(`String` VARCHAR(8000), `Delimiter` CHAR(1)) RETURNS VARCHAR(8000) CHARSET latin1
BEGIN
DECLARE idx INT;
DECLARE slice VARCHAR(8000);
DECLARE result INT DEFAULT 0;
DROP TEMPORARY TABLE IF EXISTS tmp;
CREATE TEMPORARY TABLE `tmp` (items VARCHAR(8000));
-- set #tmptab = tmp;
SET idx = 1;
label: WHILE LENGTH(`String`)<1 OR `String` IS NULL DO
LEAVE label;
END WHILE;
loop_lable: WHILE (idx<>0) DO
SET idx = LOCATE(`Delimiter`,`String`);
IF (idx<>0) THEN
SET slice = LEFT(`String`,idx - 1);
ELSE
SET slice = `String`;
END IF;
IF(LENGTH(slice)>0) THEN
INSERT INTO tmp(Items) VALUES(slice) ;
SET result = 1;
END IF;
SET `String` = RIGHT(`String`,LENGTH(`String`) - idx);
IF LENGTH(`String`) = 0 THEN
LEAVE loop_lable;
END IF;
END WHILE;
RETURN result;
END$$
DELIMITER ;
MySQL 5.5
CREATE TABLE `card` (
`id` int,
`cardnumber` varchar(100),
`customer` varchar(100),
PRIMARY KEY (`id`)
);
INSERT INTO `card` VALUES (1, '5000', 'Google');
DELIMITER //
CREATE PROCEDURE `test` ()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE cardnumber varchar(20) DEFAULT "";
DECLARE cursor1 CURSOR FOR SELECT cardnumber FROM card WHERE customer = 'Google';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN cursor1;
get_card: LOOP
FETCH cursor1 INTO cardnumber;
IF finished = 1 THEN
LEAVE get_card;
END IF;
END LOOP get_card;
SELECT cardnumber;
CLOSE cursor1;
END //
DELIMITER ;
CALL test();
Returns no results, what did I do wrong?
There would be a ambiguity in identifying a column and a local variable if they are defined a same name. It IS always better practice to define a different naming convention in stored procedures, functions and trigger bodies when dealing with database object names like column.
To cross check, execute following procedure and see the result.
delimiter //
drop procedure if exists `same_name_test` //
create procedure `same_name_test`()
begin
DECLARE cardnumber varchar(20) DEFAULT "";
-- this statement will print empty string
SELECT cardnumber as cn
FROM card
WHERE customer = 'Google';
end;
//
delimiter ;
call `same_name_test`;
+------+
| cn |
+------+
| |
+------+
Modified Stored Procedure:
DELIMITER //
drop procedure if exists `test` //
CREATE PROCEDURE `test`()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE card_number varchar(20) DEFAULT "";
DECLARE cursor1 CURSOR FOR
SELECT cardnumber
FROM card_so_q23811277
WHERE customer = 'Google';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN cursor1;
get_card: LOOP
-- read cursor into new local variable
FETCH cursor1 INTO card_number;
IF finished = 1 THEN
LEAVE get_card;
END IF;
END LOOP get_card;
-- using new name of variable
SELECT card_number;
CLOSE cursor1;
END;
//
DELIMITER ;
Now call the Stored Procedure:
CALL `test`;
+-------------+
| card_number |
+-------------+
| 5000 |
+-------------+