So far I have tried using CREATE VIEW <view_table_name> and
CREATE TABLE <table_name> and CREATE TEMPORARY <temporary_table_name>
and this methods are taking so much time because I have to (step 1) create a table and (step 2) insert a data. Then (step 3) select the created table. Finally, (step 4) drop the table.
This is my procedure: (My program doesn't look make any sense, I mean why am I doing this. The answer to your confusion is, this is just a part of my large code and I made it this way so that it may look simple.)
BEGIN
-- Main loop variables
DECLARE col_Name varchar(255);
DECLARE col_Description varchar(255);
-- Main Loop
Block2: BEGIN
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE statement CURSOR FOR SELECT `name`, `description` FROM `rules`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN statement;
REPEAT
MainLoop: LOOP
FETCH statement INTO col_Name, col_Description;
IF done THEN
LEAVE MainLoop;
END IF;
SELECT col_Name AS `Name`, col_Description AS `Description`;
END LOOP MainLoop;
UNTIL done END REPEAT;
CLOSE statement;
END Block2;
-- End of Main Loop
END
The result is:
The problem:
The result is separate. How do I combine this result into one table?
Declare a temporary table at the beginning ,populate data into temp table and then access it after loop ends
BEGIN
-- Main loop variables
DECLARE col_Name varchar(255);
DECLARE col_Description varchar(255);
create temporary table yourtable (name varchar(50),description varchar(50));
-- Main Loop
Block2: BEGIN
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE statement CURSOR FOR SELECT `name`, `description` FROM `rules`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN statement;
REPEAT
MainLoop: LOOP
FETCH statement INTO col_Name, col_Description;
IF done THEN
LEAVE MainLoop;
END IF;
insert into yourtable(name,description)
values (col_Name, col_Description)
END LOOP MainLoop;
UNTIL done END REPEAT;
CLOSE statement;
select * from yourtable
END Block2;
-- End of Main Loop
END
I think things can be easier.
you don't have to use a cursor, you just need to create an empty table in your procedure, and input the result from your query.
like below:
CREATE DEFINER=`root`#`localhost` PROCEDURE `temp`(val int)
BEGIN
DECLARE yourval datatype()
-- declare as many as you need.---
set #beginning = 0
set #ending = val
-- how many time do you need to repeat your code?
---CREATE AN EMPTY TABLE HERE---
while #beginning < #ending do
insert table TableCreatedAbove
---YOUR QUERY---
---YOU MAY NEED TO DO SOMETHING WITH YOUR DECLARED VARIABLE---
set #beginning = #beginning + 1;
end while;
commit;
END
when you need to use your combined table, just
select * from TableCreatedAbove
maybe you already solved your problem in somewhere else, but here is my answer.
Related
I have within a database several tables where they all have username column. I would like to update one username and naturally I should update it in all tables.
I have this working solution:
UPDATE `user`,
`user_images`,
`user_comments`
SET `user`.`username` = 'new_name',
`user_images`.`username` = 'new_name',
`user_comments`.`username` = 'new_name'
WHERE `user`.`username` = 'old_name'
AND `user_images`.`username` = 'old_name'
AND `user_comments`.`username` = 'old_name'
I am hoping for a better query that can do the same action, as if table numbers got increased, do I really need to do this in 100 lines?
It sounds painful if you have to update each table. I would suggest using a stored procedure to finish the tedious job. Fisrt of all , make a table(named tablelist) which list all the tablename you would like to update. Then call the procedure by providing the two parameters where the o_name is the name you would like to change and the n_name is the new name to be changed into.
delimiter //
drop procedure if exists update_name//
create procedure update_name (o_name varchar(30),n_name varchar(30))
begin
declare t_name varchar(30);
declare done bool default false;
declare csr cursor for select tablename from tablelist;
declare continue handler for not found set done=true;
open csr;
lp: loop
fetch csr into t_name;
if done=true then
leave lp;
end if;
set #prep=concat('update ',t_name,' set `username`= "',n_name,'" where `username`= "',o_name,'";');
prepare prep_stat from #prep;
execute prep_stat;
deallocate prepare prep_stat;
end loop lp;
close csr;
end//
delimiter ;
The following call will change the name from john(case insensitive) to Xero in all tables listed in the tablelist table.
call update_name('John','Xero');
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 ;
I have used a cursor in MySQL but it always runs one more time then I expect.
Code like this:
drop PROCEDURE if exists test_sp;
DELIMITER //
CREATE PROCEDURE test_sp()
BEGIN
DECLARE varid int;
DECLARE varExit_loop BOOLEAN;
DECLARE cursor_name CURSOR FOR
SELECT id
FROM test;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET varExit_loop = TRUE;
drop table if exists test;
create table test
(id int);
insert into test
values
(1),
(2),
(3);
OPEN cursor_name;
test_loop: LOOP
FETCH cursor_name INTO varid;
select varid;
IF varExit_loop THEN
CLOSE cursor_name;
LEAVE test_loop;
END IF;
END LOOP test_loop;
END; //
DELIMITER ;
After I run the SP, it will return 4 results, 1,2,3 and one more 3.
Is there any way to avoid having one more 3?
I have moved
IF varExit_loop THEN
CLOSE cursor_name;
LEAVE test_loop;
END IF;
END LOOP test_loop;
right under
FETCH cursor_name INTO varid;
and it worked fine.
I have a database where temp tables are created, those table names are randomly generated and saved in Checkouts.unid. I want to drop all those tables and truncate the table Checkouts. I thought the niftiest solution would be a procedure, but it will not work:
DROP PROCEDURE IF EXISTS `spCheckoutsCleanup`;
CREATE PROCEDURE `spCheckoutsCleanup` ()
SQL SECURITY INVOKER
BEGIN
DECLARE `t` VARCHAR(64);
DECLARE `ch` CURSOR FOR SELECT `unid` FROM `Checkouts`;
OPEN `ch`;
drop_tables: LOOP
FETCH `ch` INTO `t`;
DROP TABLE IF EXISTS `t`;
END LOOP;
CLOSE `ch`;
TRUNCATE TABLE `Checkouts`;
END
I always get "No data - zero rows fetched, selected, or processed" although those tables are there and the table Checkouts is not empty though.
You have to add something like this in order to end your loop:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET ...;
See example in the documentation.. E.g. ...
DROP PROCEDURE IF EXISTS `spCheckoutsCleanup`;
CREATE PROCEDURE `spCheckoutsCleanup` ()
SQL SECURITY INVOKER
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE `t` VARCHAR(64);
DECLARE `ch` CURSOR FOR SELECT `unid` FROM `Checkouts`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN `ch`;
drop_tables: LOOP
FETCH `ch` INTO `t`;
IF done THEN
LEAVE drop_tables;
END IF;
DROP TABLE IF EXISTS `t`;
END LOOP;
CLOSE `ch`;
TRUNCATE TABLE `Checkouts`;
END
Otherwise you will get an error once you reached the end of your cursor.
I got it working with this:
DROP PROCEDURE IF EXISTS `spCheckoutsCleanup`;
CREATE PROCEDURE `spCheckoutsCleanup` ()
SQL SECURITY INVOKER
BEGIN
DECLARE done int DEFAULT 0;
DECLARE t CHAR(64);
DECLARE ch CURSOR FOR SELECT `unid` FROM `Checkouts`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN ch;
drop_table: LOOP
FETCH ch INTO t;
IF done = 1 THEN
LEAVE drop_table;
END IF;
SET #sql := CONCAT('DROP TABLE IF EXISTS `', t, '`');
PREPARE dropt FROM #sql;
EXECUTE dropt;
END LOOP;
CLOSE ch;
TRUNCATE TABLE `Checkouts`;
END;
CALL spCheckoutsCleanup;
I am working on a MySQL procedure that creates a summary of one of my tables. The procedure retrieves a dataset and loops through it using a cursor. For each iteration of the loop, the procedure updates another table. The problem I'm having is the loop ends after a single iteration, event though I know that the query I'm running retrieves more than one row.
BEGIN
# Variable declaration section omitted for brevity
DECLARE cur CURSOR FOR SELECT
t.result_id,
t.athlete_id, t.`first`, t.middle, `last`, t.pref, t.birth,t.uss,
t.club_id,t.code,t.club_name,
t.meet_name,t.meet_id,t.`start`,t.`end`,
MIN(t.time) as time,t.age,t.type
FROM sometable t GROUP BY club_id ORDER BY time asc,t.start desc,club_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
read_loop: LOOP
FETCH cur INTO result_id,athlete_id, first_name, middle, last_name, pref, birth,uss,
club_id,club_code,club_name,
meet_name,meet_id,start_date,end_date,
result_time,age,type;
IF done=1 THEN
LEAVE read_loop;
END IF;
SET last_time = result_time;
INSERT INTO toptimes(`result_id`,`club_id`,`agegroup`,`sex`,`distance`,`course`,`stroke`,`data`,`published`)
VALUES(result_id,club_id,AgeGroupID,sex,distance,course,stroke,json,0);
END LOOP read_loop;
CLOSE cur;
END
I'm not clear what the problem is. When I run the select query manually, I get back several rows. Is there a problem running an insert statement inside the loop?
Your code chunk looks good to me.
How do you know that it's running only one iteration (i'm not seeing any
print or select statement for debug purpose)?
Are you getting any error while executing the stored procedure?
I tried to replicate the similar code with "sakila" database (mysql sample db). It's working perfectly. Please check this sql code sample, if it helps you.
DROP PROCEDURE IF EXISTS usp_select_dummy_data ;
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE usp_select_dummy_data()
BEGIN
-- Declare your variables
Declare _var_actor_id int default 0;
DECLARE _var_film_id int default 0;
-- Declare variable used for cursor and loop control
DECLARE done int;
DECLARE loop_counter INT DEFAULT 0;
-- Declare the cursor
DECLARE cur CURSOR FOR
SELECT
actor_id, film_id
FROM film_actor;
-- Declare handlers
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
-- Open the cursor
OPEN cur ;
-- Start the loop
read_loop: LOOP
FETCH cur
INTO _var_actor_id, _var_film_id ;
-- break out of the loop if
-- 1. if there is no rows or
-- 2. we've processed them all
IF done = 1 THEN
CLOSE cur ;
LEAVE read_loop ;
END IF;
-- Count the number of times looped
SET loop_counter = loop_counter + 1 ;
END LOOP read_loop ;
-- print the loop count
select loop_counter;
END