mysql insert statement as a variable [duplicate] - mysql

This question already has answers here:
How To have Dynamic SQL in MySQL Stored Procedure
(3 answers)
Closed 8 years ago.
is it possible to set a variable to an insert statement in a stored procedure?
Something like:
set variable1 = insert into table(field1, field2, field3) values(val1, val2, variable2);
If so, how should it be written?
I keep throwing errors and documentation in the wild is inconclusive.
I was going for brevity but the entire procedure is thus:
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `new_accession`(in barcode int, in accepted varchar(11), in wt float(11,2), in wtunit varchar(3),in draw date, in chist varchar(256), in ghist varchar(256), in meds varchar(256), in diffdiag varchar(256),in diseasesus varchar(256),in volume int, in facility int, in patient int, in employ int, in compromised int, in receiving int, in test int)
BEGIN
declare accessionId int;
declare accessionTest int;
declare tkInsert varchar(256);
declare hptInsert varchar(256);
declare calInsert varchar(256);
declare pthInsert varchar(256);
declare vitdtkInsert varchar(256);
declare cnpInsert varchar(256);
if wtunit = 'lb' then set wt = convertLbKg(wt);
end if;
INSERT INTO accession(barcode_accession,accepted_accession,weight_accession,req_weight_units,draw_date_accession,cancer_history_accession,general_history_accession,medication_accession,differential_diagnosis_accession,disease_suspect_accession,volume_accession,facility_doctor_index_id_facility_doctor_index,patient_id_patient,employee_id_employee,accession_compromised_id_accession_compromised,receiving_id,accession_typeof_id_accession_typeof)
VALUES (barcode,accepted,wt,wtunit,draw,chist,ghist,meds,diffdiag,diseasesus,volume,facility,patient,employ,compromised,receiving,1);
set accessionId = last_insert_id();
set tkInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,1,'Pending');
set hptInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,2,'Pending');
set calInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,3,'Pending');
set pthInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,4,'Pending');
if test = 1 then tkInsert,calInsert;
elseif test =2 the hptInsert,pthInsert;
else pthInsert;
end if;
END

It is not very clear what you want but if your goal is to store insert's outcome (affected rows) you could use ROW_COUNT().
ROW_COUNT() returns the number of rows changed, deleted, or inserted
by the last statement if it was an UPDATE, DELETE, or INSERT.
For other statements, the value may not be meaningful.
For example:
variable1 = (select ROW_COUNT());

I think you're looking for prepared statements.
PREPARE tkInsert FROM CONCAT("insert into pending(accession_facility_index,reagent_type,`status`)values(?, 1,'Pending')";
Then you execute it with:
EXECUTE tkInsert USING accessionId;

Related

MySQL using trigger to insert into several tables parallelly

I am trying to insert large amount of data (500M rows) into MySQL. I put the whole line into a first table and use an insert after trigger. Since this inserts data to 7 different tables (for normalization purposes) I was wondering whether it would be possible to do the 7 inserts at the same time. Presently I am using MySQL 5.1 which does not allow me to create more triggers on the same table. Can you suggest me something how to increase the insert speed:
CREATE TRIGGER temptable_tr AFTER INSERT ON temp
FOR EACH ROW
BEGIN
DECLARE TR_00 INT;
DECLARE TR_1G INT;
DECLARE TR_2G INT;
DECLARE TR_3G INT;
DECLARE TR_1S INT;
DECLARE TR_2S INT;
DECLARE TR_3S INT;
/* This part repeats 7 times, instead of 00, we can put 1G, 2G, 3G, 1S, 2S, 3S
Since these 7 parts insert into seven independent tables, would it possible to run them parallely?*/
BEGIN
DECLARE T_MD5_00 CHAR(32);
DECLARE SBN_00 INT;
DECLARE S_MD5_00 CHAR(32);
DECLARE SBS_MD5_00 VARCHAR(500);
SET T_MD5_00 = SELECT MD5(NEW.tr_00) FROM DUAL;
SET TR_00 = (SELECT tr_00_id FROM trans_00 WHERE trans_00_MD5 = T_MD5_00);
SET SGN_00 = REPLACE( substring(NEW.tr_00,1,((select LOCATE('>', NEW.tr_00)-1))) ,'[*:1]','[*]') ;
SET S_MD5_00 = SELECT MD5(SGN_00) FROM DUAL;
SET SBN_00 = (SELECT subs_00_id FROM substr_00 WHERE subs_00_MD5 = S_MD5_00);
IF (TR_00 IS NULL OR SBN_00 IS NULL) THEN
IF (TR_00 IS NULL) THEN
INSERT INTO trans_00(transform_00) values(NEW.tr_00);
INSERT INTO trans_00(trans_00_MD5) values(T_MD5_00);
SET TR_00 = LAST_INSERT_ID();
END IF;
IF (SBN_00 IS NULL) THEN
INSERT INTO substr_00(substruct00,subs_00_MD5) values(SGN_00,S_MD5_00);
SET SBN_00 = LAST_INSERT_ID();
END IF;
INSERT INTO tr_subs_00(tr_00_id,subs_00_id) VALUES(TR_00,SBN_00);
END IF;
END;
.....
/* At the end collect the TR_?? ids and insert them into an other table:*/
INSERT INTO pairs(tr_00_id,tr_1G_id,tr_2G_id,tr_3G_id,tr_1S_id,tr_2S_id,tr_3S_id) VALUES(TR_00,TR_1G,TR_2G,TR_3G,TR_1S,TR_2S,TR_3S
END;
Oracle has "INSERT ALL". Doesn't MySQL have it too?
https://www.techonthenet.com/oracle/questions/insert_rows.php

MySQL stored procedure syntax error in variables

I have table group with begindate lesson count and weekdays columns. I would like write MySQL procedure for adding data to another table named lessons according to group. But I couldn't handle with syntax of MySQL. Could you please help me resolve problems with that procedure:
CREATE PROCEDURE simpleproc (IN idGroup INT, IN groupName varchar(20),IN beginDate date, IN weekday1 INT, IN weekday2 INT, IN lessonCount INT)
BEGIN
DECLARE i;
SET i:=1;
WHILE i<=lessonCount DO
DATE_ADD(beginDate,INTERVAL 1 DAY)
IF (WEEKDAY(beginDate)=weekday1) OR (WEEKDAY(beginDate)=weekday2) THEN
SET name:=groupName+i;
SET price:=DIV(price,8)
insert into lessons (lessonName, idGroup, lessonPrice, datePassed)
values (name,idGroup,price,begindate);
SET i:=i+1
END IF;
END WHILE;
END
After solving problems I will add this code to prepared statement in Java
This will run. Make sure: 1. That you increment i in a proper place of your code inside the while loop. 2. Avoid usind reserved words (like name) for fields and variables. 3. Define price variable somewhere before making integer division of it. You know the code and your tables' structure. Nobody is capable to do it for you.
DROP PROCEDURE IF EXISTS `simpleproc`;
DELIMITER ;;
CREATE DEFINER=`root`#`localhost` PROCEDURE `simpleproc`(IN idGroup INT, IN groupName varchar(20),IN beginDate date, IN weekday1 INT, IN weekday2 INT, IN lessonCount INT)
BEGIN
DECLARE i int;
DECLARE name1 int;
DECLARE price int;
SET i:=1;
WHILE i<=lessonCount DO
SET beginDate:=DATE_ADD(beginDate,INTERVAL 1 DAY);
IF WEEKDAY(beginDate) in(weekday1,weekday2) THEN
SET name1:=groupName+i;
SET price:=price DIV 8;
insert into lessons (lessonName, idGroup, lessonPrice, datePassed)
values (name1,idGroup,price,begindate);
END IF;
SET i:=i+1;
END WHILE;
END
;;
DELIMITER ;

MySQL 5.6 Declare Issue

Let's see if I can edit this and put the whole procedure in.
I am trying to convert an Oracle database to MySQL. I have all the tables, keys, indexes, and views converted. I now need to convert a stored procedure to MySQL.
I have most of it done, and there is only one hang up on my code:
set dns1_tmp = X.X.X.X;
SET dns2_tmp = X.X.X.X;
This gives me an error of 1064 Syntax Error: Missing semicolon
I have tested the rest of my procedure, and it works fine. It creates it, runs it, and retrieves data from it, but only if I remove those two lines.
Any ideas on what I can do?
Whole stored procedure:
DELIMITER //
USE `TEST`//
DROP PROCEDURE IF EXISTS `proc_IN`//
CREATE DEFINER=`root`#`localhost` PROCEDURE `proc_IN`
(IN DNIS VARCHAR(20),
IN MSISDN VARCHAR(20),
IN AVPAIR1 VARCHAR(20),
IN AVPAIR2 VARCHAR(20),
IN GROUPID VARCHAR(20),
OUT DNS1 VARCHAR(15),
OUT DNS2 VARCHAR(15),
OUT AUTHSTAT VARCHAR(100))
BEGIN
declare dns1_tmp varchar(15);
declare dns2_tmp varchar(15);
set dns1_tmp = X.X.X.X;
SET dns2_tmp = X.X.X.X;
DECLARE avpair1_tmp varchar(15);
DECLARE avpair2_tmp varchar(15);
DECLARE grpid_tmp varchar(15);
DECLARE C_USER CURSOR FOR SELECT AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID FROM GRP, ALLMEMBER WHERE ALLMEMBER.GROUPID=GRP.GROUPID
UNION
SELECT AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID FROM GRP;
OPEN C_USER;
FETCH C_USER INTO AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID;
LOOP
FETCH C_USER INTO avpair1_tmp, avpair2_tmp, dns1_tmp, dns2_tmp, grpid_tmp;
INSERT INTO duplog VALUES(DNIS, MSISDN, avpair1_tmp, avpair2_tmp, dns1_tmp,dns2_tmp, grpid_tmp, SYSDATE);
END LOOP;
IF C_USER%ROWCOUNT > 1 THEN
INSERT INTO duplog VALUES(DNIS, MSISDN, AVPAIR1, AVPAIR2, DNS1,DNS2, GROUPID, SYSDATE);
SET AUTHSTAT := 'ok';
elseif C_USER%ROWCOUNT = 1 THEN
SET AUTHSTAT := 'ok';
ELSE
SET AUTHSTAT := NULL;
END IF;
CLOSE C_USER;
COMMIT;
END //
DELIMITER ;

how to check if row exist with trigger in mysql?

I want to check if a row exist with a trigger before insert here is my table and my trigger
Table students: ID | Name
Trigger validation :
CREATE TRIGGER `validation` BEFORE INSERT ON `students`
FOR EACH ROW
begin
declare var_name varchar(255);
declare check_row varchar(255);
set var_name = new.name;
select name into check_row from students where name = var_name;
end
If you are using a stored procedure, you can accomplish this with a handler if the column has a unique key on it
CREATE PROCEDURE `student_create` (IN name_in VARCHAR(64), ...)
BEGIN
SET #name = name_in;
DECLARE EXIT HANDLER FOR SQLSTATE '23000'
SET #name = CONCAT('dupe_',name_in);
INSERT INTO students (name, ...) VALUES (#name, ...);
END$$
If you are really set on using a trigger, all you need is an if
IF (SELECT id FROM students WHERE name = NEW.name) THEN
SET var_name = CONCAT('dupe_',NEW.name);
END IF;
Replace the CONCAT with whatever transformation you want perform on the name

MySQL Syntax Error In Variable Declaration

I have the following MySQL query:
DELIMITER //
CREATE PROCEDURE InsertResult (IN winnerID INT, IN loserID INT)
BEGIN
INSERT INTO KomperResult (WinnerID, LoserID) VALUES (#winnerID, #loserID);
DECLARE winnerScore, loserScore INT;
SELECT Score INTO #winnerScore FROM KomperPerson WHERE ID = #winnerID;
SELECT Score INTO #loserScore FROM KomperPerson WHERE ID = #loserID;
IF (#loserScore >= #winnerScore) THEN UPDATE KomperPerson SET Score = #loserScore + 1 WHERE ID = #winnerID; END IF;
END//
I get an error on:
DECLARE winnerScore, loserScore INT;
What am I doing wrong?
DECLAREs need to go on the first line of your procedure.
From the docs:
DECLARE is permitted only inside a
BEGIN ... END compound statement and
must be at its start, before any other
statements.