How to insert into mysql with Boolean condition - mysql

I have this statement that I wanna execute:
INSERT INTO kitchenitems (kno, `date`, added_Date, added_By)
VALUES (5,'2016-04-01', now(), 2);
but before it executes i wanna check whether "kno" has "5" or not. If not it should execute. If has it should not execute. Thanks in advance.

You can do something like this:
INSERT INTO kitchenitems (`kno`, `date`, `added_Date`,`added_By`)
SELECT kno,date,added_Date,added_By
FROM (SELECT '5' as kno, '2016-04-01' as date, NOW() as added_Date, '2' as added_By) a
WHERE NOT EXISTS (SELECT 1 FROM kitchenitems b WHERE a.kno = b.kno);
However, if you want unique values of kno, you should ensure that at server-side.

Hi there I think that can easealy be done with stored procedure... I would suggest you to read this article HERE I think that's the answer on your solution.
Here is SQL Fiddle to see how that works on your problem...
here is your stored procedure
CREATE PROCEDURE addItem
(IN inkno INT, IN inddate DATETIME, IN inadded_Date DATETIME, IN inadded_By INT)
BEGIN
DECLARE SomeId int;
DECLARE CheckExists int;
SET CheckExists = 0;
SELECT count(*) INTO CheckExists from kitchenitems WHERE kno = inkno;
IF (CheckExists > 0) THEN
SELECT kno INTO SomeId FROM kitchenitems WHERE kno = inkno;
ELSE
INSERT INTO kitchenitems (kno,ddate,added_Date,added_By)
VALUES (inkno, inddate,inadded_Date, inadded_By);
END IF;
END/

Related

SQL variable in IF exists

I can't figure out the correct way to assign query output into a variable that i could later use in an INSERT clause.
The error I get is
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET #lennuid = (select lend_id from lend where sihtpunkt=in_kuhu AND kuupaev=in_' at line 8
I've tried looking at every guide on variables in SQL but none of them could help me solve this.
Iam using the below code:
CREATE PROCEDURE proov(
in_kuhu varchar(50), in_nimi1 varchar(50), in_nimi2 varchar(50), in_adre varchar(50), in_telo varchar(20), in_email varchar(100), in_date date)
BEGIN
DECLARE viga INTEGER DEFAULT 0 ;
DECLARE lennuid INT;
START TRANSACTION;
IF exists (
SET #lennuid = (select lend_id from lend where sihtpunkt=in_kuhu AND kuupaev=in_date)) THEN
INSERT INTO broneering
(lend_id, bron_aeg, eesnim, perenimi, aadress, telefon, email)
VALUES
(lennuid, NOW(), in_nimi1, in_nimi2, in_adre, in_telo, in_email);
ELSE
set viga=1;
SELECT 'Muudatus ebaonnestus ',viga;
END IF;
IF viga=0 then
COMMIT;
select 'korras';
ELSE
select 'tagasi';
ROLLBACK;
END IF;
THEN causing the issue.
IF exists (
SET #lennuid = (select lend_id from lend where sihtpunkt=in_kuhu AND kuupaev=in_date))
BEGIN -- Instead of THEN use BEGIN , END
INSERT INTO broneering
(lend_id, bron_aeg, eesnim, perenimi, aadress, telefon, email)
VALUES
(lennuid, NOW(), in_nimi1, in_nimi2, in_adre, in_telo, in_email);
END
ELSE
BEGIN
set viga=1;
SELECT 'Muudatus ebaonnestus ',viga;
END
END IF;
You might want to use SELECT INTO:
select lend_id into #lennuid
from lend
where sihtpunkt=in_kuhu AND kuupaev=in_date;
Alternatively:
select #lennuid := lend_id
from lend
where sihtpunkt=in_kuhu AND kuupaev=in_date;
Either way works the same, then you can use that variable however you like...
In your particular example, though, the problem is actually how your exists is being used along with the set. To fix this, use the following:
IF exists (select lend_id from lend where sihtpunkt=in_kuhu AND kuupaev=in_date) THEN ...
What the problem here is, is you were setting a variable with SET inside of the EXISTS check.
Or you could do your select first as a COUNT into a numeric variable:
DECLARE cnt INTEGER;
select Count(lend_id) into #cnt
from lend
where sihtpunkt=in_kuhu
and kuupaev=in_date;
IF #cnt > 0 THEN
END IF;

declaring variable inside mysql stored procedure

we are trying to declare a variable inside mysql stored procedure that has transaction implemented in it. but it seems to be giving a syntax error :
following is the syntax of the stored procedure:
CREATE PROCEDURE `sp_MarkAppointmentRefferal`(
p_AppId bigint,
p_NewLocation bigint,
p_userId bigint,
p_ReferralReason varchar(500),
p_NewLocationName varchar(100)
)
begin
declare v_OldLocation int default 0;
set v_OldLocation = (select LocationId FROM appointments where iAppID = p_AppId limit 1 );
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
select -1;
END;
START TRANSACTION;
update table
set is_referred = 1,
referred_timestamp = now(),
referral_reason = p_ReferralReason
where iAppID = p_AppId
limit 1;
-- create a new appointment for the new referred location..
insert into appointments
(vAppName, vAppType, dAppDate, vCell, iPatID, iAppStatus, iuserid, iActive,
dInsertDate, iHSID, daily_ticket_no, LocationId, visit_id, encounter_id, ReferredFrom,ReferredOPDName, opd_name )
select vAppName, vAppType, now(), vCell, iPatID, iAppStatus, p_userId,
1, now(), iHSID, fn_GenerateNextAppointmentTicket(now(),p_NewLocation) , p_NewLocation, visit_id, encounter_id+1,
(select LocationId FROM appointments where iAppID = p_AppId limit 1),
(select OPD_Name FROM appointments where iAppID = p_AppId limit 1), p_NewLocationName
FROM appointments
where iAppID = p_AppId limit 1;
select LAST_INSERT_ID();
COMMIT;
end;
the syntax checker is saying that declare command is not valid here.
have also tried to place this inside the transaction clause and similar error shows up ..
any help is appreciated..
All declare statements should be at the top of the stored procedure body. Moving DECLARE EXIT HANDLER before the SET statement should fix the problem.

MySQL stored procedure if statement not working

I have the following stored procedure in MySQL
CREATE DEFINER=`test_db`#`%` PROCEDURE `ADD_ATTENDANCE`(IN `programID` INT, IN `clientID` INT, IN `insDate` DATETIME, IN `updDate` DATETIME, IN `insUser` INT, IN `updUser` INT, IN `lessonDate` DATE, IN `lessonTime` TIME)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Add attedance to my calendar'
BEGIN
DECLARE max_sub, availability INT;
DECLARE cursor_max_sub CURSOR FOR SELECT max_sub FROM app_lesson WHERE id = programID;
DECLARE cursor_availability CURSOR FOR SELECT count(*) FROM attendance WHERE program_id = programID AND lesson_date = lessonDate AND lesson_time = lessonTime;
OPEN cursor_max_sub;
OPEN cursor_availability;
read_loop: LOOP
FETCH cursor_max_sub INTO max_sub;
FETCH cursor_availability INTO availability;
IF (availability < max_sub) THEN
insert into attendance (program_id, client_id, ins_date, upd_date, ins_user, upd_user, lesson_date, lesson_time)
values (programID, clientID, insDate, updDate, insUser, updUser, lessonDate, lessonTime);
LEAVE read_loop;
ELSE
insert into attendance_hold (program_id, client_id, ins_date, upd_date, ins_user, upd_user, lesson_date, lesson_time)
values (programID, clientID, insDate, updDate, insUser, updUser, lessonDate, lessonTime);
END IF;
END LOOP;
CLOSE cursor_max_sub;
CLOSE cursor_availability;
END;
Even though the cursor_max_sub is equal to 6 and the cursor_availability is equal to 4 my procedure always executes the else insert statement. Can you please help me out?
Thanks!!!
OK that was tricky... For some reason when i change the max_sub variable into maxNumberOfSubscription everything worked perfectly... Is max_sub some kind of reserved key word for MySQL or there was a complication because my variable had the same name with the returned field of select statement?

MySQL stored procedure pass select as parameter

could you please give me an advice how to CALL prcd with SELECT results? Or advice me pls better solution.. I am open minded to all working solution
I have a procedure to control inserting data ...
CREATE PROCEDURE control_insert (
)
And I need to pass data from SELECT results to procedure ...
SELECT t.c1, t.c2
FROM table t1
LEFT JOIN other_table t2
ON t1.id = t2.id
WHERE 1=1
The point is, I need to get some data via SELECT (around 6 tables joined to the base table) and I need to do control for each row before insert.. each row should meet some conditions .. if it doesn't meet them, it should just skip it and process next one ...
The procedure should look like:
CREATE PROCEDURE control_insert (
IN v_c1 INT,
IN v_c2 INT
)
BEGIN
IF v_c1 > 1 THEN
INSERT INTO controlled_table (id, type) VALUES (v_c1, v_c2);
ELSE
/* do nothing */
END IF;
END;
CALL control_insert ( SELECT .... );
Could you help me with that? Is there any possibility to do this via MySQL? I can write a PERL skript, but I want to avoid this type of solution ... I just one to do it only in MySQL way
Thank you
EDIT1: I need to check if ID of the SELECT result and LABEL is already in this table for specific date ... this code above is only an example to demonstrate the situation
SOLUTION
I've found the solution ... so for the other visitors:
calling procedure:
CALL controlInsert();
procedure body:
CREATE PROCEDURE controlInsert()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE v_id INT;
DECLARE v_id_dupl INT;
DECLARE v_label INT;
DECLARE v_date DATE;
DECLARE v_type VARCHAR(100);
DECLARE v_category VARCHAR(255);
DECLARE v_user VARCHAR(255);
DECLARE v_country VARCHAR(255);
DECLARE c1 CURSOR FOR SELECT id, label, date, type, category, user, country FROM t1 LEFT JOIN ... /* whole select with 6 joins ended by ; */
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
## open cursor
OPEN c1;
## loop through the cursor
read_loop: LOOP
## fetch cursor into variables
FETCH c1 INTO v_id , v_label, v_date, v_type, v_category, v_user, v_country;
## check if there is any record
IF done THEN
LEAVE read_loop;
END IF;
## get count of existing records
SELECT count(*) INTO v_id_dupl
FROM
WHERE 1=1
AND id = v_id
AND label= v_label
AND date = v_date;
## if v_id_dupl = 0 => no rows found (ok to load)
IF (v_id_dupl = 0) THEN
INSERT INTO target_table (id, label, date, type, category, user, country)
VALUES (v_id , v_label, v_date, v_type, v_category, v_user, v_country);
END IF;
END LOOP;
CLOSE c1;
END
If that is all your stored procedure is doing, then you don't actually need it. You can do the whole thing in a single statement:
INSERT INTO controlled_table (id, type)
SELECT t.c1, t.c2
FROM table t1
LEFT JOIN other_table t2 ON t1.id = t2.id
WHERE something = somethingElse
AND t.c1 > 1
Essentially, I've just combined your original query with the INSERT statement in your procedure.
If your procedure is more complex and needs to do multiple operations on each row, then you should look into using a cursor.

MySQL Stored Procedure, One INSERT not functioning with different field name?

This is quite a strange problem, so first I will post the procedure:
DELIMITER $$
USE `blahblahblah`$$
DROP PROCEDURE IF EXISTS `duplicateTradeIn`$$
CREATE DEFINER=`blahblahblah` PROCEDURE `duplicateTradeIn`(duplicate_claim INT(12))
BEGIN
DECLARE valuation INT(12) DEFAULT 0;
DECLARE claim INT(12) DEFAULT 0;
DECLARE serialNumber VARCHAR(255);
DECLARE duplicates INT(12);
DECLARE i INT(12) DEFAULT 1;
DECLARE claimID INT(12);
SET #claimID = duplicate_claim;
SET #duplicates = (SELECT COUNT(*) FROM `duplicates`);
SET #i = 1;
WHILE #i <= #duplicates DO
SET #serialNumber = (SELECT `serial` FROM `duplicates` WHERE id = #i);
INSERT INTO valuations (`pID`,`boughtproduct`,`valuationType`,`valuationAmount`,`working`,`accessories`,`age`,`brand`,`qty`,`created`,`valuationStatus`)
SELECT `pID`,`boughtproduct`,`valuationType`,`valuationAmount`,`working`,`accessories`,`age`,`brand`,`qty`,`created`,`valuationStatus`
FROM valuations WHERE vID = (SELECT vID FROM claims WHERE cID = #claimID);
SET #valuation = (SELECT LAST_INSERT_ID());
INSERT INTO claims (`vID`, `pID`, `email`, `title`, `firstname`, `lastname`, `customerType`, `company`, `position`, `address1`,`address2`,`town`,`county`,`postCode`,`telephone`,`mobile`,`emailBusiness`,`emailConsumer`,`contactPost`,`contactTelephone`,`contactMobile`,`contactEmail`,`invoiceNum`,`invoiceDate`,`invoiceInc`,`reseller`,`dateOfOrder`,`heardAbout`,`salesPerson`,`method`,`cleanseCert`,`blanccoCert`,`created`,`modified`,`noInvEmailDated`,`lateRejEmailSent`,`invAddressEmailSent`,`revalueEmailSent`,`signed`,`dated`,`sessionID`,`received`,`receiptSent`,`processedDate`,`validatedDate`,`rejectedDate`,`rejectReason`,`notes`,`claimStatus`,`origin`,`invoiceexported`)
SELECT #valuation, `pID`, `email`, `title`, `firstname`, `lastname`, `customerType`, `company`, `position`, `address1`,`address2`,`town`,`county`,`postCode`,`telephone`,`mobile`,`emailBusiness`,`emailConsumer`,`contactPost`,`contactTelephone`,`contactMobile`,`contactEmail`,`invoiceNum`,`invoiceDate`,`invoiceInc`,`reseller`,`dateOfOrder`,`heardAbout`,`salesPerson`,`method`,`cleanseCert`,`blanccoCert`,`created`,`modified`,`noInvEmailDated`,`lateRejEmailSent`,`invAddressEmailSent`,`revalueEmailSent`,`signed`,`dated`,`sessionID`,`received`,`receiptSent`,`processedDate`,`validatedDate`,`rejectedDate`,`rejectReason`,`notes`,`claimStatus`,`origin`,`invoiceexported`
FROM claims WHERE cID = #claimID;
SET #claim = (SELECT LAST_INSERT_ID());
INSERT INTO documents (`claimid`,`serial`,`filename`,`filenameOrig`,`filenameTemp`,`filetype`,`filesize`)
SELECT #claim,`serial`,`filename`,`filenameOrig`,`filenameTemp`,`filetype`,`filesize`
FROM documents WHERE claimid = #claimID;
INSERT INTO redemptions (`cID`,`pID`,`prID`,`bundleNo`,`serialNum`,`price`,`cashback`,`created`,`modified`,`claimStatus`)
SELECT #claim,`pID`,`prID`,`bundleNo`,#serialNumber,`price`,`cashback`,`created`,`modified`,`claimStatus`
FROM redemptions WHERE cID = #claimID;
INSERT INTO tradeins (`vID`,`cID`,`valuationType`,`valuationAmount`,`working`,`accessories`,`age`,`created`,`brand`,`claimStatus`)
SELECT #valuation,#claim,`valuationType`,`valuationAmount`,`working`,`accessories`,`age`,`created`,`brand`,`claimStatus`
FROM tradeins WHERE cID = #claimID;
SET #i = (#i + 1);
END WHILE;
END$$
DELIMITER ;
EDIT: Sorry!
The problem is when it tries to insert into documents (So refer to the documents table insert). If I rename the column (claimid) in the WHERE clause and INSERT to cID (by altering the table and query) it works, but otherwise it refuses to insert the new rows when it is named claimid not cID. If you have any ideas or insight into this it would be much appreciated.
To try and clarify:
Documents table with field and query as cID not claimid works.
Documents table with field and query as claimid does not insert rows.
All of the other queries seem to work fine and it only occurred to me to try cID in the documents table as that was the only difference.
Again sorry for the vagueness before and I hope the question is now clearer.
Thanks!
Just to clear this up. It is as I stated and maybe a bug in mySQL? If there is a table with a field where the ID name differs. In this example cID and claimid then it will not recognise the second declared field claimid and not perform the query.
In order for this to work I had to revise the documents table from claimID to cID.