SQL variable in IF exists - mysql

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;

Related

MySQL migrate data from one table to another

I'm attempting to move data from one table to another, as part of a restructure to the database architecture. I'm using PHPMyAdmin and MySQL to do so.
The SQL is meant to, for each emergency_contacts.id, move e_c.id and e_c.activity_id to activities_emergency_contacts, where the pair will form a composite key to link a contact with an activity.
The following SQL returns an error:
CREATE PROCEDURE dowhile()
BEGIN
SET #cid = (SELECT MIN(`id`) FROM `emergency_contacts`);
SET #aid = (SELECT `activity_id` FROM `emergency_contacts` WHERE `id` = #cid);
WHILE #cid IS NOT NULL DO
INSERT INTO activities_emergency_contacts (activity_id, contact_id)
VALUES (#aid, #cid);
SET #cid = (SELECT MIN(id) FROM emergency_contacts WHERE #cid < id);
SET #aid = (SELECT activity_id FROM emergency_contacts WHERE id = #cid);
END WHILE;
END;
CALL dowhile();
SQL query:
CREATE PROCEDURE dowhile() BEGIN SET #cid = (SELECT MIN(id) FROM
emergency_contacts)
MySQL said:
#1064 - 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 '' at line 3
I have searched the MySQL specific documentation to try and find any issues with my SET, WHILE, BEGIN/END, INSERT, CREATE - just about every line. I'm unsure how to proceed. Any advice would be greatly appreciated.
EDIT: I missed a closing bracket inside the WHILE on SELECT MIN (id), however I've fixed this and am still getting the exact same issue.
EDIT: The issue was that I was not using DELIMITER. Correct SQL:
DELIMITER $$
CREATE PROCEDURE dowhile()
BEGIN
SET #cid = (SELECT MIN(`id`) FROM `emergency_contacts`);
SET #aid = (SELECT `activity_id` FROM `emergency_contacts` WHERE `id` = #cid);
WHILE #cid IS NOT NULL DO
INSERT INTO activities_emergency_contacts (activity_id, contact_id) VALUES (#aid, #cid);
SET #cid = (SELECT MIN(id) FROM emergency_contacts WHERE #cid < id);
SET #aid = (SELECT activity_id FROM emergency_contacts WHERE id = #cid);
END WHILE;
END$$
DELIMITER ;
CALL dowhile();

How to insert into mysql with Boolean condition

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/

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?

Issue with stored procedure and COUNT IF statement

So I need to make a stored procedure called AddComment, that will add a comment to my Comments table , then add an entry into the Commenters table if that commenters name does not exist.
DELIMITER //
CREATE PROCEDURE AddComment(Name VARCHAR(60), Title VARCHAR(60), Comments VARCHAR(60))
BEGIN
INSERT INTO Comments(Name, Title, Comments)
VALUES (Name, Title, Comments);
DECLARE name_count INT;
SELECT COUNT(Name) INTO name_count
FROM Commenters
WHERE Name = Name;
IF name_count = 0
THEN INSERT INTO Commenters(Name)
VAlUES(Name);
ELSEIF name_count = 1
THEN INSERT IGNORE Commenters(Name)
VALUES(Name);
END IF;
END;
//
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version fo
r the right syntax to use near 'DECLARE name_count INT;
SELECT COUNT(Name) INTO name_count
FROM Commenters
^ Is the error I'm getting. I keep tweaking my code trying to figure it out, but nothing is working.
You need a cursor to use syntax like that, but you can use SET:
SET name_count = (SELECT COUNT(*) ...);
Or better yet, since you don't actually use the value, eliminate the variable entirely:
IF NOT EXISTS (SELECT * FROM ...) THEN

Mysql stored procedure syntax

I am trying to write simple mysql stored procedure and it seems that I can't get it right, so far I have
delimiter //
create procedure addRecord(_login varchar(15),_artist varchar(50),_record varchar(50))
begin
declare dbArtist varchar(50);
delcare dbRecord varchar(50);
set dbArtist = (select artistname from artists where lower(artistname) = lower(_artist));
set dbRecord=(select recordname from records where lower(recordname)=lower(_record));
if not exists (select * from Artists where lower(artistname)=lower(_artist)) then
begin
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
end
if not exists (select * from Records as R inner join Artists as A on R.ArtistId=A.ArtistId where lower(R.RecordName)=lower(_record) and A.ArtistName=dbArtist) then
begin
INSERT INTO `Records`(`ArtistId`, `RecordName`) VALUES ((select artistid from artists where artistname=dbArtist),_record);
set dbRecord=_record;
end
end
but I get syntax error in line 4:
#1064 - 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 'dbRecord varchar(50);
set dbArtist = (select artistname from artists where lowe' at line 4
this message error was returned to me by phpMyAdmin, can anyone tell me why do I get an error?
edit: modified version, still not good
delimiter //
create procedure addRecord(_login varchar(15),_artist varchar(50),_record varchar(50))
begin
declare dbArtist varchar(50);
declare dbRecord varchar(50);
set dbArtist = (select artistname from artists where lower(artistname) = lower(_artist));
set dbRecord=(select recordname from records where lower(recordname)=lower(_record));
if not exists (select * from Artists where lower(artistname)=lower(_artist)) then
begin
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
end
if not exists
(select * from Records as R inner join Artists as A on R.ArtistId = A.ArtistId where lower(R.RecordName)=lower(_record) and A.ArtistName=dbArtist)
then
begin
INSERT INTO `Records`(`ArtistId`, `RecordName`) VALUES ( (select artistid from artists where artistname=dbArtist) ,_record);
set dbRecord=_record;
end
end
now error in line 14 and message:
#1064 - 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 'if not exists (select * from Records as R inner join Artists as A on R.ArtistId' at line 14
The problem is that you misspelled DECLARE:
delcare dbRecord varchar(50);
UPDATE: For your next error, the problem is your illegal use of NOT EXISTS.
Within a stored procedure the proper approach is to count the existing rows, and then conditionally insert a value if the count is 0.
Something like this:
SELECT COUNT(*)
INTO #v_row_count
FROM Artists
WHERE LOWER(artistname)=LOWER(_artist);
IF (#v_row_count = 0)
THEN
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
END IF;
P.S. To avoid poor performance on on your select query, you should consider using a collation that is not case-sensitive so you don't need to apply the LOWER() function to the artistname column.