MySQL Cursors fetching null value - mysql

Data fetched from cursor is NULL. But number of row my query select id from Projects returning is correct. I have put a select statement in my procedure loop to debug. It's returning null for id.
I have followed this [https://dev.mysql.com/doc/refman/5.5/en/cursors.html]
What's wrong with this code?
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `ReportDiffProDiffFinYear`()
BEGIN
DECLARE id INT;
DECLARE sqlstr varchar(10000) default "select financialYear as 'name' ";
DECLARE done INT DEFAULT FALSE;
DECLARE cur1 CURSOR FOR select id from Projects; /* My CURSOR QUERY*/
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO id;
select id;
IF done THEN
LEAVE read_loop;
END IF;
set sqlstr = concat(sqlstr, ", sum(if(projects_id=",id,",0,1)) ");
END LOOP;
CLOSE cur1;
set #sqlstr = concat(sqlstr," from (select * from WaterPoints where status='Waterpoint Complete') as wp, (select id,financialYear from ProjectDetails) as pd where pd.id=wp.projectDetails_id group by pd.financialYear");
prepare stmt from #sqlstr;
execute stmt;
deallocate prepare stmt;
END

I believe that your variable name id clashes with the query for the cursor, therefore the cursor query fetches the value of the id variable (null), not the value of the id from the projects table. Either change the name of the variable or use projects.id to reference the column in the query.

Related

MYSQL stored procedure: read value from one table and use it in WHERE on another

I'm trying to create a simple stored procedure that reads IDs from one table and deletes records that reference these IDs from another. I have a cursor which works fine, the problem is using that cursor in WHERE clause (for development purposes I'm using SELECT instead of DELETE):
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE id CHAR(30);
DECLARE cur1 CURSOR FOR SELECT idea_id FROM projects WHERE DATEDIFF(DATE(NOW()), DATE(last_update)) > 14;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO id;
IF done THEN
LEAVE read_loop;
END IF;
SET #A:= CONCAT('select * from stats where idea = "',id,'"');
Prepare stmt FROM #A;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur1;
END
The problem is, that last select from the stats table always returns 0 results, even though the results are there if I manually get IDs from the cursor and paste them into the WHERE clause on stats. I suspect I'm not using the variable in the prepared statement correctly but I can't find a solution. Please help.
Nevermind, found the issue: the type of id declared in the procedure didn't match the type of idea_id field in the projects table and it was quietly truncated and then obviously no results matched. Please close.
I had the same issue as you, just set done to false after each loop
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE id CHAR(30);
DECLARE cur1 CURSOR FOR SELECT idea_id FROM projects WHERE DATEDIFF(DATE(NOW()), DATE(last_update)) > 14;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO id;
IF done THEN
LEAVE read_loop;
END IF;
SET #A:= CONCAT('select * from stats where idea = "',id,'"');
Prepare stmt FROM #A;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET done = FALSE;
END LOOP;
CLOSE cur1;
END

Can't specify table name on mysql stored procedure

I am mass assigning new id numbers to things in the DB to make room for some stuff at the beginning of each table. I created a procedure that works, but when I try adding input parameters to allow scripting, it can't find the table
delimiter |
CREATE PROCEDURE changeID
( IN in_table_name varchar(64))
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE a,b INT DEFAULT 800000;
DECLARE cur1 CURSOR FOR SELECT id FROM in_table_name ORDER BY id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO b;
IF done THEN
LEAVE read_loop;
END IF;
UPDATE in_table_name SET id = a + 1 where id = b;
SET a = a+1;
END LOOP;
CLOSE cur1;
END;
|
delimiter ;
When I run this using call changeID('users'), I get the error:
[Err] 1146 - Table 'databaseName.in_table_name' doesn't exist
I was hoping to loop through using a simple list of commands like this so it could run unattended instead of manually changing the in_table_name between each execution:
call changeID('users');
call changeID('appointments');
call changeID('groups');
You can't dynamically pass a table name in a query, however, you can concatenate a string and then execute it as a statement. You of course want to be careful and ensure that this data has been sanitized etc. I wasn't able to test this, but something to this effect should get you going.
...
END IF;
SET #Query = CONCAT('UPDATE ',in_table_name,' SET `id` = ',a+1,' WHERE `id`=',b);
PREPARE stmt FROM #Query;
EXECUTE stmt;
...
https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
KChason got me started in the right direction, but I had to take it a little further to get the first part working from tips here: https://forums.mysql.com/read.php?98,138495,138908#msg-138908.
DROP PROCEDURE
IF EXISTS `workingversion`;
delimiter |
CREATE PROCEDURE `workingversion` (IN tableName VARCHAR(100))
BEGIN
DECLARE done INT DEFAULT 0 ;
DECLARE a,
b INT DEFAULT 800000 ;
DROP VIEW IF EXISTS v1;
SET #stmt_text = CONCAT("CREATE VIEW v1 AS SELECT id FROM ", tableName, " ORDER BY id") ;
PREPARE stmt
FROM
#stmt_text ; EXECUTE stmt ; DEALLOCATE PREPARE stmt ;
BEGIN
DECLARE cur1 CURSOR FOR SELECT * FROM v1 ;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000'
SET done = 1 ; OPEN cur1 ;
REPEAT
FETCH cur1 INTO b ;
IF NOT done THEN
SET #Query = CONCAT('UPDATE ',tableName,' SET `id` = ',a+1,' WHERE `id`=',b);
PREPARE stmt FROM #Query;
EXECUTE stmt;
SET a = a+1;
END
IF ; UNTIL done
END
REPEAT
; CLOSE cur1 ;
END ;
END

MySQL stored procedure value of variable returns to null after loop ends

Here is my simplified, the value of rent_ids string returns to null after the loop. I already know that the loop is working properly and that the value of rent_ids changes with every itiration.
BEGIN
DECLARE rent_ids VARCHAR(265);
DECLARE tmp_rent_id int;
create temporary table due_rent_ids (rent_id int);
SET rent_ids = "";
set #test = "Insert into due_rent_ids (rent_id) select unit_id from tbl_rent";
PREPARE stmt1 FROM #test;
EXECUTE stmt1;
BEGIN
DECLARE cur1 CURSOR for select rent_id from due_rent_ids;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO tmp_rent_id;
IF rent_ids = "" THEN
SET rent_ids = tmp_rent_id;
ELSE
SET rent_ids = concat(rent_ids, ", ", tmp_rent_id);
END IF;
END LOOP;
CLOSE cur1;
END;
select * from tbl_unit where unit_id in (rent_ids);
DEALLOCATE PREPARE stmt1;
END
You're doing this all wrong. You can't put a comma-separated string in IN (...), the commas have to be in the actual SQL code.
The right way to do this is:
SELECT *
FROM tbl_unit
WHERE unit_id IN (SELECT rent_id FROM due_rent_ids)
Or:
SELECT t1.*
FROM tbl_unit AS t1
JOIN due_rent_ids AS t2 ON t1.unit_id = t2.rent_id
The second form tends to perform better in MySQL.

loop though results from information schema mysql

I am trying to find all the tables that has a column name called RecordID and then loop over those tables to see if the RecordID > 5000 or not.
CREATE PROCEDURE check_IDs ()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE result varchar(50);
DECLARE cur1 CURSOR for SELECT table_name FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name = 'RecordID' ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO result;
IF done THEN
LEAVE read_loop;
END IF;
Select * from `result` where RecordID > 5000;
END LOOP;
close cur1;
END;
it says table result not found.
It's got to be
PREPARE stmt FROM CONCAT('SELECT * FROM `', result, '`WHERE RecordID > 5000;)';
EXECUTE stmt;
DEALLOCATE stmt;
instead of
Select * from `result` where RecordID > 5000;
see the examples (last one) of SQL Syntax for Prepared Statements
Your statement will use the hardcoded table name result. It seems, there's no such table in your database.

Join all tables with same structure in one MYSQL

I'm working on an old database already in use for years and really crappy designed.
There is a table, "Articles", which contains a "code" column that will be our PK.
And many tables like "idXXXXX" where XXXXX is a "code" value with exactly the same structure.
I looked at the application using this database and saw that relations between tables is made there.
I'm not affraid of redesign the database access in the application, but I don't want to lose years of entries in the database.
I want to create a "campain" table which will have an "id" PK and a "id_code" as FK linking "campain" to "articles"
I'm not a SQL master but I know I can get tables names with
SELECT TABLE_NAME FROM INFORMATION_SCHEMA WHERE TABLE_NAME LIKE 'id%'
But I have really no idea about how to deal with the result (which is fine).
So how can I access to every tables named "idXXX" and insert every rows in the "campain" table + set "id_code" column to "XXX"?
Here is the procedure I saved (I didn't add every fields in the INSERT line for testing purpose) :
CREATE PROCEDURE JoinAllTables()
BEGIN
DECLARE done INT default 0;
DECLARE tableName CHAR(9);
DECLARE buffStr CHAR(7);
DECLARE buffId INT default 0;
DECLARE cur1 CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'id%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO tableName;
IF done THEN
LEAVE read_loop;
END IF;
SET buffStr = SUBSTRING(tableName, 3);
SET buffId = CAST(buffStr AS SIGNED);
set #sql = CONCAT("INSERT INTO campagnes(id, id_code) SELECT null, bufId FROM ",tableName); # Dynamically building sql statement
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur1;
END;
As u can see, I sub 'idXXXXX' to 'XXXXX' then CAST it AS INTEGER (SIGNED).
But I guess that in the "INSERT INTO" line, second tableName doesn't point to the variable. That's why I'm getting a
"#1446 - Tabble 'bddsoufflage.tablename'doesn't exist" Error :) Any idea ?
Edit: Updated answer
We can't have the tableName dynamically changed inside a prepared statement, so we must go through DynamicSQL to build the query using CONCAT, then compile the SQL with PREPARE, EXECUTE it and DEALLOCATE it.
DELIMITER //
CREATE PROCEDURE JoinAllTables()
BEGIN
DECLARE done INT default 0;
DECLARE tableName CHAR(9);
DECLARE buffStr CHAR(7);
DECLARE buffId INT default 0;
DECLARE cur1 CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'id%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO tableName;
IF done THEN
LEAVE read_loop;
END IF;
SET buffStr = SUBSTRING(tableName, 3);
SET buffId = CAST(buffStr AS SIGNED);
set #sql = CONCAT("INSERT INTO campagnes(id, id_code) SELECT null, ", buffId, " FROM ",tableName); # Dynamically building sql statement
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur1;
END; //
See also this answer MySQL Pass table name to cursor select
Old answer
The procedure should look something like this. Thanks Mchl for providing an Insert Into query example, I simply added it to the rest of the procedure.
DELIMITER //
CREATE PROCEDURE JoinAllTables()
BEGIN
DECLARE done INT default 0;
DECLARE tableName CHAR(7); # Variable to contain table names CHAr(7) is assuming id + 5Xs as characters.
DECLARE cur1 CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA WHERE TABLE_NAME LIKE 'id%'; # Create a cursor to iterate over the tables
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO tableName;
IF done THEN
LEAVE read_loop;
END IF;
#Your Insert statement here, using tableName as a field.
INSERT INTO campain (id, id_code, otherfields) SELECT null, tableName, otherfields FROM tableName;
END LOOP;
CLOSE cur1;
END;//
Easiest way would be to run the information_schema query you have within some script (PHP,Python,Perl - whichever suits you best) and use it's results to create queries like:
INSERT INTO
campain (id, id_code, otherfields)
SELECT
null, 'idXXXX', otherfields FROM idXXXX