Unable to execute "IF EXISTS" query - mysql

I am trying to run a SQL query, but something is messed up and I can't get below query to check if the data exists or not in the specified table.
The code I have is:
IF EXISTS(SELECT brth_day FROM sms.birthdaycheck WHERE brth_day = '2015-02-10')
THEN
BEGIN
UPDATE sms.birthdaycheck SET cnt = 1 WHERE brth_day = '2015-02-10'
END
ELSE
BEGIN
INSERT INTO sms.birthdaycheck(cnt,brth_day) VALUES (1,'2015-02-10')
END
END IF;

Edited solution :
delimiter ;;
create procedure XYZ(...parameters...)
begin
if exists(
SELECT brth_day FROM sms.birthdaycheck WHERE brth_day = '2015-
02-10')
then
UPDATE sms.birthdaycheck SET cnt = 1 WHERE brth_day = '2015-02-10';
else
INSERT INTO sms.birthdaycheck(cnt,brth_day) VALUES (1,'2015-02-10');
end if;
end;;

In MySQL, if control block must used inside a function or stored procedure.
So you need to rewrite your query:

Related

What is wrong with the 'when' clause?

CREATE TRIGGER UPDATE_CAR_DETALS
AFTER UPDATE ON BOOKING_DETALS
FOR EACH ROW
WHEN (IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME),NULL) <> 'NULL' OR
NEW.BOOKING_STATUS ='C')
Multi statements in triggers need a BEGIN and END
Also when you use query tabs you need also DELIMITER
CASE WHEN you would use if you have multiple choices, but you use better IF THEN
DELIMITER $$
CREATE TRIGGER UPDATE_CAR_DETALS
AFTER UPDATE ON BOOKING_DETALS
FOR EACH ROW
BEGIN
IF (IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME),NULL) <> 'NULL' OR NEW.BOOKING_STATUS ='C') then
BEGIN
IF NEW.BOOKING_STATUS ='C' THEN
UPDATE CAR SET AVAILABILITY_FLAG = 'A' , LOC_ID = NEW.PICKUP_LOC
WHERE REGISTRATION_NUMBER = NEW.REG_NUM;
ELSE
IF IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME),NULL) <> NULL THEN
UPDATE CAR SET AVAILABILITY_FLAG = 'A' , LOC_ID = NEW.DROP_LOC, MILEAGE = MILEAGE+GET_MILEAGE
WHERE REGISTRATION_NUMBER = NEW.REG_NUM;
END IF;
END IF;
END;
END IF;
END;
DELIMITER ;

Error #1109 in MySql

This is my trigger.
I want to make trigger on 1 table (rezervare).
Trigger
DELIMITER //
CREATE TRIGGER verificare_nr_locuri
BEFORE INSERT ON Rezervare
FOR EACH ROW
BEGIN
IF ( SELECT Masa.NrLocuri FROM Rezervare, Masa
WHERE Masa.NumarMasa = Rezervare.NumarMasa ) < Rezervare.NumarPersoane THEN
SET NEW.NumarMasa = NULL;
END IF;
END //
DELIMITER ;
INSERT INTO Rezervare VALUES (123,106,2,'2016-12-11','2016-12-24',5);
INSERT INTO Rezervare VALUES (124,106,2,'2016-12-11','2016-12-24',4);
When I execute the trigger, it has been created. But, when I insert data into table rezervare, It become
#1109 - Unknown table 'rezervare' in field list.
How can I resolve this?
Table
I think you might need to use a JOIN for your SELECT clause.
BEGIN
IF (SELECT Masa.NrLocuri, Rezervare.NumarMasa FROM Masa JOIN Rezervare
WHERE Masa.NumarMasa = Rezervare.NumarMasa) < Rezervare.NumarPersoane THEN
SET NEW.NumarMasa = NULL;
END IF;

Mysql trigger to update empty field with condition

I have a MySQL table , look like this
t id lang title
1 7 en_UK my_title
1 7 kh_KH
I want write a trigger that update title to my_title with the same id is 7
Result
t id lang title
1 7 en_UK my_title
1 7 kh_KH my_title
From my understanding.
DELIMITER $$
CREATE TRIGGER upd_title BEFORE UPDATE ON `term`
FOR EACH ROW BEGIN
IF (NEW.title IS NULL OR NEW.title= '') THEN
SET NEW.title= ??? ;
END IF;
END$$
DELIMITER ;
[UPDATE1]->not works (trigger not being created)
DELIMITER $$
DROP TRIGGER IF EXISTS `update_category_after_insert`
CREATE TRIGGER `update_category` AFTER INSERT ON `categories`
FOR EACH ROW BEGIN
DECLARE loc_title text;
IF (NEW.libelle_categorie IS NULL OR NEW.libelle_categorie= '') THEN
select libelle_categorie into loc_title from categories where NEW.num_noeud= num_noeud and langue = 'en_UK';
SET NEW.libelle_categorie = loc_title;
END IF;
END
DELIMITER ;
[UPDATE2]
DELIMITER $$
CREATE TRIGGER ``update_category_after_insert`` BEFORE INSERT ON `categories`
FOR EACH ROW BEGIN
DECLARE loc_title text;
IF (NEW.libelle_categorie IS NULL OR NEW.libelle_categorie= '') THEN
select libelle_categorie into loc_title from categories where NEW.num_noeud= num_noeud and langue = 'en_UK';
SET NEW.libelle_categorie = loc_title;
END IF;
END
DELIMITER ;
Finally , I found the good solution for my case
UPDATE categories c INNER JOIN categories c2 ON (
c.num_noeud = c2.num_noeud
) SET c.libelle_categorie = c2.`libelle_categorie`
Can you clarify?
Are you trying to pull the value from the title column in the 'en_UK' row that exists when you insert an new row with the same id that HAS the title column not entered?
okay
CREATE TRIGGER upd_title BEFORE UPDATE ON `term`
FOR EACH ROW BEGIN
DECLARE loc_title VARCHAR(20);
IF (NEW.title IS NULL OR NEW.title= '') THEN
select title into loc_title from term where NEW.id = id and lang = 'en_UK';
SET NEW.title= loc_title;
END IF;
END
This should do the trick.
This was my trigger def:
CREATE DEFINER = CURRENT_USER TRIGGER `therinks`.`glreturndata_BEFORE_UPDATE` BEFORE UPDATE ON `glreturndata` FOR EACH ROW
BEGIN
DECLARE myVal VARCHAR(20);
if NEW.DESCRIPTION IS NULL or new.description = '' THEN
SELECT min(description) into myVal from glreturndata where category = NEW.category and new.idglreturndata <> idglreturndata;
Set NEW.DESCRIPTION = myval;
end if;
END
It seems that you can't do all this in a trigger. According to the documentation:
Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.
According to this answer, it seems that you should:
create a stored procedure, that inserts into/Updates the target table, then updates the other row(s), all in a transaction.
With a stored proc you'll manually commit the changes (insert and update). I haven't done this in MySQL, but this post looks like a good example.

MYSQL Trigger insert or update different table

I've been wrapping my head around this SQL statement I'm trying to make and I've reached a wall so to speak, if you could lend any advise as to what I am doing wrong that would be a big help. I get the error around the 2nd where statement but I dont really expect the last part of the code to work yet.
CREATE TRIGGER UpdateScores
AFTER INSERT ON CharSheet FOR EACH ROW
begin
DECLARE id_exists Boolean;
SELECT
1
INTO
#id_exists
FROM
ScoresTable
WHERE
ScoresTable.PlayerID= NEW.PlayerID;
IF #id_exists = 1
THEN
UPDATE
ScoresTable
SET
Exp = :New.Exp;
WHERE
ScoresTable.PlayerID = :NEW.PlayerID;
END IF;
IF #id_exists = 0
THEN
-- I don't expect this part to work yet.
INSERT INTO ScoresTable VALUES (:New.PlayerID, :New.Race, :New.Class, :New.Exp);
END IF;
END;
$$
The problem is in this block of code:
THEN
UPDATE
ScoresTable
SET
Exp = :New.Exp;
WHERE
ScoresTable.PlayerID = :NEW.PlayerID;
END IF;
Remove the semicolon at the end of the set statement.

PREPARED STATEMENT in a WHILE loop

I have a table autos that has a column name, I want to check first 5 rows in the table and if name value is "toyota", in table mytable write "yes", else write "no".
I write stored procedure, but mysqli_error() returns error in line, where I have EXECUTE ....
If in WHEN I write not PREPARED STATEMENT, but directly the query, the procedure works.
Please see my code and tell me, where is it wrong?
CREATE PROCEDURE proc_auto()
BEGIN
DECLARE start INT;
SET start = 0;
PREPARE stmt FROM ' SELECT name FROM autos ORDER BY id LIMIT ?,1 ';
WHILE start < 5 DO
CASE
WHEN (EXECUTE stmt USING #start ) = 'toyota'
THEN INSERT INTO mytable (log) VALUES('yes');
ELSE
INSERT INTO mytable (log) VALUES('no');
END CASE;
SET start = start + 1;
END WHILE;
END;
(The suggestion about EXECUTE is removed as incorrect and potentially confusing.)
The problem you are trying to solve with a stored procedure could in fact be solved without it, using an entirely different approach: just use a single INSERT ... SELECT statement instead:
INSERT INTO mytable (log)
SELECT
CASE name
WHEN 'toyota' THEN 'yes'
ELSE 'no'
END
FROM autos
ORDER BY id
LIMIT 5
That is, the above statement does the same as your stored procedure: it retrieves first 5 rows from autos and inserts 5 rows into mytable. Depending on the value of name it generates either yeses or nos.
Andriy M's INSERT statement is the most elegant solution, but if you still want to use a procedure, this will work:
CREATE PROCEDURE proc_auto()
BEGIN
DECLARE start INT DEFAULT 0;
PREPARE stmt FROM
'SELECT name INTO #name FROM autos ORDER BY id LIMIT ?,1';
WHILE start < 5 DO
SET #start = start;
EXECUTE stmt USING #start;
IF #name = 'toyota' THEN
INSERT INTO mytable (log) VALUES('yes');
ELSE
INSERT INTO mytable (log) VALUES('no');
END IF;
SET start = start + 1;
END WHILE;
END;
but, in this case, using a CURSOR would yield better performance:
CREATE PROCEDURE proc_auto()
BEGIN
DECLARE start INT DEFAULT 0;
DECLARE b_not_found BOOL DEFAULT FALSE;
DECLARE cur CURSOR FOR
'SELECT name FROM autos ORDER BY id LIMIT 5';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET b_not_found = TRUE;
OPEN cur;
loop1: WHILE start < 5 DO
FETCH cur INTO #name;
IF b_not_found THEN
LEAVE loop1;
END IF;
IF #name = 'toyota' THEN
INSERT INTO mytable (log) VALUES('yes');
ELSE
INSERT INTO mytable (log) VALUES('no');
END IF;
SET start = start + 1;
END WHILE;
CLOSE cur;
END;