Declare variable MySQL trigger - mysql

My question might be simple for you, if you're used to MySQL. I'm used to PostgreSQL SGBD and I'm trying to translate a PL/PgSQL script to MySQL.
Here is what I have :
delimiter //
CREATE TRIGGER pgl_new_user
AFTER INSERT ON users FOR EACH ROW
BEGIN
DECLARE m_user_team_id integer;
SELECT id INTO m_user_team_id FROM user_teams WHERE name = "pgl_reporters";
DECLARE m_projects_id integer;
DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;
OPEN cur;
ins_loop: LOOP
FETCH cur INTO m_projects_id;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access)
VALUES (NEW.id, m_projects_id, now(), now(), 20);
END LOOP;
CLOSE cur;
END//
But MySQL Workbench gives me an error on DECLARE m_projects_id. I don't really understand because I've the same instruction two lines above...
Any hints ?
EDIT: neubert solved this error. Thanks.
But yet, when I try to insert into users :
Error Code: 1329. No data - zero rows fetched, selected, or processed
Do you have any idea ? Or better, do you know how I can get a better error message ?

All DECLAREs need to be at the top. ie.
delimiter //
CREATE TRIGGER pgl_new_user
AFTER INSERT ON users FOR EACH ROW
BEGIN
DECLARE m_user_team_id integer;
DECLARE m_projects_id integer;
DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;
SET #m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");
OPEN cur;
ins_loop: LOOP
FETCH cur INTO m_projects_id;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access)
VALUES (NEW.id, m_projects_id, now(), now(), 20);
END LOOP;
CLOSE cur;
END//

Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.
For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.
INSERT ... SELECT Syntax.

Related

Small Procedure with Cursor for autocreate rows in tables (MYSQL)

i created an event that execute one time per month. Three tables are important here, Cuota(fee), Alumno(studient) and CuotaxAlumno(fee per studient).
My objective is create a row in table Cuota(fee) one time per month and then with that fee create a payment row for every studient (in table CuotaxAlumno).
I having syntax error in te FETCH line, line 19, and i don't find the problem. i will appreciate the help.
IS WORKING NOW. CODE UPDATED 13-04-2017 Thanks!
DELIMITER $$
CREATE PROCEDURE crearCuotas()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE referenciaMonto INT;
DECLARE referenciaAlumno INT;
DECLARE referenciaCuota INT;
DECLARE fecha DATE;
DECLARE cursorAlumno CURSOR FOR SELECT idAlumno FROM alumno WHERE idEstado=1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET referenciaMonto = (SELECT idMontoCuota FROM montocuota ORDER BY idMontoCuota DESC LIMIT 1);
SET fecha = CURDATE();
INSERT INTO cuota (idMontoCuota, fecha) VALUES(referenciaMonto, fecha);
SET referenciaCuota = (SELECT idCuota FROM cuota ORDER BY idCuota DESC LIMIT 1);
OPEN cursorAlumno;
fetch_loop: LOOP
FETCH cursorAlumno INTO referenciaAlumno;
IF done THEN
LEAVE fetch_loop;
END IF;
INSERT INTO cuotaxalumno(idAlumno, idCuota, idEstado) VALUES(referenciaAlumno, referenciaCuota, 5);
END LOOP;
CLOSE cursorAlumno;
END;
DELIMITER ;
You need to add a loop label:
CREATE PROCEDURE crearCuotas()
BEGIN
/* yada */
OPEN cursorAlumno;
fetch_loop: LOOP
FETCH cursorAlumno INTO referenciaAlumno;
IF done THEN
LEAVE fetch_loop;
END IF;
INSERT INTO cuotaxalumno (idAlumno, idCuota, idEstado)
VALUES (referenciaAlumno, referenciaCuota, 5);
END LOOP;
CLOSE cursorAlumno;
END;
This is because while the label is not required for creating a loop, it is required for the leave statement.

How to make a while in a stored procedure with phpmyadmin, error #1064

I try to create a stored procedure in phpmyadmin, but I get a error 1064 on line 12 (where the WHILE is). This is the first time I try to create a stored procedure.
BEGIN
DECLARE product_id INT;
DECLARE product_min_age nvarchar(500);
DECLARE cur CURSOR for
SELECT product_min_age, product_id FROM _vm_product;
open cur;
fetch next from cur into product_min_age, product_id;
while FETCH_STATUS = 0 BEGIN
INSERT INTO _virtuemart_product_customfields (virtuemart_product_id, virtuemart_custom_id, customfield_value, customfield_params) VALUES
( product_id, 5, product_min_age, 'addEmpty=0|selectType=0|');
fetch next from cur into product_min_age,product_id;
END;
close cur;
END
Thank you
You should change that to below. See Documentation for more information.
open cur;
read_loop: LOOP
fetch cur into product_min_age, product_id;
INSERT INTO _virtuemart_product_customfields (virtuemart_product_id, virtuemart_custom_id, customfield_value, customfield_params) VALUES
( product_id, 5, product_min_age, 'addEmpty=0|selectType=0|');
END LOOP;
close cur;
The accepted answer is indeed correct and so is your own answer. Unfortunately the approach is completely wrong!
One does not generally perform sql queries inside a loop unless as a last resort. Select / loop / insert is in fact a frequent pattern followed by people writing their first stored procedure. but there is a better way, a much much better way. And that is INSERT .. SELECT
With INSERT ... SELECT, you can quickly insert many rows into a table
from one or many tables. For example:
Your complex stored procedure reduces to:
INSERT INTO _virtuemart_product_customfields (virtuemart_product_id, virtuemart_custom_id, customfield_value, customfield_params)
SELECT product_id, 5, product_min_age, 'addEmpty=0|selectType=0|'
FROM _vm_product
That's it, just a simple select, no stored procedures!
A second issue is that you are stored delimited text in a column.
addEmpty=0|selectType=0|
I am not quite sure why you are doing this but it's most unusual.
If someone want to see my final result:
BEGIN
DECLARE _product_id INT;
DECLARE _product_min_age nvarchar(500);
DECLARE done INT DEFAULT 0;
DECLARE cur CURSOR for SELECT product_min_age, product_id FROM _vm_product;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
open cur;
read_loop: LOOP
fetch cur into _product_min_age, _product_id;
IF done = 1 THEN
LEAVE read_loop;
END IF;
INSERT INTO _virtuemart_product_customfields (virtuemart_product_id, virtuemart_custom_id, customfield_value, customfield_params) VALUES
( _product_id, 5, _product_min_age, 'addEmpty=0|selectType=0|');
END LOOP;
close cur;
END

Mysql Trigger null result

SET SQL_SAFE_UPDATES = 0;
use my_database;
DELIMITER $$
DROP PROCEDURE IF EXISTS Comit $$
CREATE PROCEDURE Comit ()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE ids INT;
DECLARE leftChilds INT;
DECLARE cur CURSOR FOR SELECT id FROM user;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
ins_loop: LOOP
FETCH cur INTO ids;
IF done THEN
LEAVE ins_loop;
END IF;
SET leftChilds = ( SELECT turnoverBalance FROM user WHERE proposer = ids AND side = 'left' LIMIT 1 );
INSERT INTO log(`log`) VALUES ( leftChilds );
END LOOP;
CLOSE cur;
END $$
When i call the procedure call Comit(); that return me this error :
1048 - Column 'log' cannot be null
Your subquery is generating NULL values, probably because there is no match on the proposer condition. Of course, your data could also have NULL values for turnoverBalance in user or rows with no 'left' side.
In any case, why are you using a cursor for something that is easily done as a single query? Something like this can replace all the logic:
INSERT INTO log(log)
SELECT turoverBalance
FROM user
WHERE proposer IN (SELECT id FROM user) AND side = 'left')
GROUP BY proposer;
First, its are stored procedure, not a trigger.
Check what your set leftChilds query returns, it should return some value, run it individually.
You can Check in stored procedure
If(leftChilds not NULL)
insert into log('log') values (leftChilds)

Stored procedure in pgsql

I am new to stored procedure in PostgreSQL (pgSQL) .I need some one help to crack my problem .I am doing the migration process from oracle to PostgreSQL for that I have used some stored procedure concept. I have tried in SQL stored procedure its working in SQL, but same code i have trying to convert into pgSQL. I have faced a issue in line by line .can any one help me to convert same code SQL into PostgreSQL. i have attached my SQL procedure code below. can any one suggest me aright way to process the code.
code:
delimiter;
drop procedure if exists patient_form_values;
delimiter $$
create procedure patient_form_values()
begin
declare columnName varchar(200) ;
declare done tinyint default 0;
declare cur1 cursor for select distinct COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'CASESHEETCOMPLAINTS' and table_schema='hms_empty_copy';
declare continue handler for not found set done = 1;
open cur1;
read_loop : loop
fetch from cur1 into columnName;
if done then leave read_loop;
end if;
set #insertValues := concat('INSERT INTO patient_form_temp(patient_id, form_template_id, creator_id, created_date)
SELECT c.patient_id as patient_id, 41 AS form_template_id, 2 AS creator_id, c.created_date AS created_date
FROM CASESHEETCOMPLAINTS c
WHERE c.', columnName,' IS NOT NULL GROUP BY c.patient_id, c.created_date');
select #insertValues;
prepare stmt from #insertValues;
execute stmt;
end loop;
close cur1;
end $$
delimiter ;
call patient_form_values();
drop procedure if exists patient_form_values;
--To delete the empty records.
DELETE FROM patient_form WHERE id NOT IN(SELECT patient_form_id FROM patient_form_value);
insert into patient_form(patient_id, form_template_id, creator_id, created_date)select patient_id, form_template_id, creator_id, created_date from patient_form_temp GROUP BY patient_id, created_date

Mysql Stored procedure with cursor

Mysql cursor issue?
I have written a stored procedure which will travel's record from one table and insert those into 2-3 different tables
using insert statements.
Problem is that i am checking if record is not exists in table1 then I am inserting record from temptable to table1 ,table2 sequentially
,but the condition is having some problem i don't know it its always going into else part.
Code sample is as follows:
CREATE PROCEDURE `insertData`(In clientNo INT,In usedID INT)
BEGIN
declare mame varchar(100);
declare address varchar(100);
declare city varchar(50);
declare IdentityNO1 varchar(20)
declare cur1 cursor for select * from temptable;
declare continue handler for not found set done=1;
SET #clientNo = clientNO;
SET #userID = userID;
set done = 0;
open cur1;
igmLoop: loop
fetch cur1 into Name,Address,City,IdentityNO1,clientNo;
if done = 1 then leave igmLoop; end if;
//If no record exists in some records table1,table2.
IF ( (SELECT COUNT(*) FROM table1
WHERE IndentityNo=IdentityNo1
AND clientNo=#clientNo) < = 0)
INSERT INTO table1 (Name,IdentityNO) VALUES (name,IdentityNO1);
INSERT INTO table2 (Address,City) VALUES(address,city);
ELSE
INSERT INTO tblexceptional(Name,Address,City,IdentityNo)
VALUES(name,address,city,IdentityNo1);
end loop igmLoop;
close cur1;
END
There is no THEN nor END IF keywords, the procedure cannot compile.
Check this link for proper syntax of IF statement: http://dev.mysql.com/doc/refman/5.7/en/if.html
Use EXIST operator instead of (SELECT count(*)... ) <=0,
read this link to know the reason: http://sqlblog.com/blogs/andrew_kelly/archive/2007/12/15/exists-vs-count-the-battle-never-ends.aspx
IF EXISTS(
SELECT null FROM table1
WHERE IndentityNo=IdentityNo1
AND clientNo=#clientNo
)
THEN
INSERT INTO table1 (Name,IdentityNO) VALUES (name,IdentityNO1);
INSERT INTO table2 (Address,City) VALUES(address,city);
ELSE
INSERT INTO tblexceptional(Name,Address,City,IdentityNo)
VALUES(name,address,city,IdentityNo1);
END IF;
I recommend using some prefixes for procedure arguments and variable names to avoid ambiguity, for example use p_ for parameters and v_ for variables. It's hard to guess, looking at this code, which name is a column name, a variable or a procedure parameter. This can lead to mistakes and errors.
Avoid using SELECT * - this code will fail if someone will change the table structure. Explicitely list required columns in the cursor declaration:
declare cur1 cursor for
select name,Address,City,IdentityNO,clientNo
from temptable;
The corrected procedure might look like this:
CREATE PROCEDURE `insertData`(In p_clientNo INT,In p_usedID INT)
BEGIN
declare v_name varchar(100);
declare v_address varchar(100);
declare v_city varchar(50);
declare v_IdentityNO varchar(20)
declare v_clientNo int
declare cur1 cursor for
select name,Address,City,IdentityNO,clientNo
from temptable;
declare continue handler for not found set done=1;
set done = 0;
open cur1;
igmLoop: loop
fetch cur1 into v_name,v_Address,v_City,v_IdentityNO,v_clientNo;
if done = 1 then leave igmLoop; end if;
//If no record exists in some records table1,table2.
IF EXISTS( SELECT 1 FROM table1
WHERE IndentityNo = v_IdentityNo
AND clientNo = v_clientNo)
INSERT INTO table1 (Name,IdentityNO) VALUES (v_name,v_IdentityNO);
INSERT INTO table2 (Address,City) VALUES(v_address,v_city);
ELSE
INSERT INTO tblexceptional(Name,Address,City,IdentityNo)
VALUES(v_name,v_address,v_city,v_IdentityNo);
END IF;
end loop igmLoop;
close cur1;
END