Set variable if null in trigger - mysql

I have a table for categories with "order" column for ordering the categories.
I'm trying to set order incrementally in trigger before insert:
CREATE TRIGGER `categories_set_order` BEFORE INSERT ON `categories` FOR EACH ROW BEGIN
DECLARE max_order INT DEFAULT 0;
SELECT MAX(categories.order) INTO max_order FROM categories;
SET NEW.order = max_order + 1;
END;
But if there are no records in the db, order column is being set to NULL.
I've modified the trigger code:
CREATE TRIGGER `categories_set_order` BEFORE INSERT ON `categories` FOR EACH ROW BEGIN
DECLARE max_order INT DEFAULT 0;
SELECT MAX(categories.order) INTO max_order FROM categories;
IF (ISNULL(#max_order)) THEN BEGIN
SET max_order = 0;
END;
SET NEW.order = max_order + 1;
END;
And I'm getting the following error:
Error Code: 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 9
Line 9 is:
IF (ISNULL(#max_order)) THEN BEGIN
I've tried to remove the "#", but still getting the same error. How to fix it?

You need to change the delimiter. Otherwise the DB thinks your trigger definition ends at the first ; which would be incomplete.
Also remove the BEGIN from your IF statement and add use END IF to end your IF
delimiter |
CREATE TRIGGER `categories_set_order` BEFORE INSERT ON `categories`
FOR EACH ROW BEGIN
DECLARE max_order INT DEFAULT 0;
SELECT MAX(categories.order) INTO max_order FROM categories;
IF (ISNULL(#max_order)) THEN
SET max_order = 0;
END IF;
SET NEW.order = max_order + 1;
END
|
delimiter ;

Besides delimiter you need an END IF
DELIMITER //
CREATE TRIGGER `categories_set_order` BEFORE INSERT ON `categories` FOR EACH ROW BEGIN
DECLARE max_order INT DEFAULT 0;
SELECT MAX(categories.order) INTO max_order FROM categories;
IF (ISNULL(#max_order)) THEN
SET max_order = 0;
END IF;
SET NEW.order = max_order + 1;
END; //
DELIMITER ;

Related

Create mysql trigger before insert (Syntax error)

Hi i am creating some trigger for update the value in insert query before insert the row like this
CREATE TRIGGER `Insert members in Posts` BEFORE INSERT ON
`posts` FOR EACH ROW
BEGIN
DECLARE name_ varchar(100);
DECLARE contact_ varchar(16);
DECLARE status_ int;
DECLARE deleted_ int;
SELECT
`members`.`name`,
`members`.`contact`,
`members`.`status`,
`members`.`deleted`
INTO name_, contact_, status_, deleted_
FROM
`members`
WHERE
`members`.`member_id` = NEW.member_id;
SET NEW.member_name = name_;
SET NEW.member_contact = contact_;
SET NEW.member_status = status_;
SET NEW.member_deleted = deleted;
END
But i received the error like
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 4
I am little confused what's the error in line no 4. Please explain someone. Thanks.
Depending on the client/ide used you may need to set delimiter for example
drop trigger if exists t;
delimiter $$
CREATE TRIGGER t BEFORE INSERT ON
`posts` FOR EACH ROW
BEGIN
DECLARE name_ varchar(100);
DECLARE contact_ varchar(16);
DECLARE status_ int;
DECLARE deleted_ int;
SELECT
`members`.`name`,
`members`.`contact`,
`members`.`status`,
`members`.`deleted`
INTO name_, contact_, status_, deleted_
FROM
`members`
WHERE
`members`.`member_id` = NEW.member_id;
SET NEW.member_name = name_;
SET NEW.member_contact = contact_;
SET NEW.member_status = status_;
SET NEW.member_deleted = deleted;
END $$
delimiter ;
please review https://dev.mysql.com/doc/refman/8.0/en/stored-routines.html

Error in if condition on mysql trigger

I have written a small trigger function in MySQL . This is the trigger query i have written and the condition are not checked direct default value of created_id is assigned.
CREATE TRIGGER `complain_attend_log` AFTER INSERT ON `attend_complain`
FOR EACH ROW BEGIN
DECLARE attend_created INT;
DECLARE created_id INT default 5;
SET attend_created = (SELECT attend_created FROM allotments WHERE complain_id = NEW.complain_id);
IF(attend_created = 1) THEN
SET created_id = 6;
END IF;
INSERT INTO complain_logs
VALUES(null,NEW.complain_id,NEW.allotment_id,NEW.attend_complain_id,NEW.is_closed,created_id,1,now(),1,now());
END

Syntax error near $$DELIMITER

i'm getting an error while creating a stored procedure, where it says that i have a syntax error, but i can't find where it is...
MySql Error:
"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 '$$DELIMITER
CREATE PROCEDURE 'entradas_sai'(IN ID_VEICULO VARCHAR(45), OUT' at
line 1
Here is the code related to the topic:
$$DELIMITER
CREATE PROCEDURE 'entradas_sai'(
IN ID_VEICULO VARCHAR(45), OUT retcode INT)
BEGIN
DECLARE '_rollback' BOOL DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET '_rollback' = 1;
START TRANSACTION;
INSERT INTO SAIDAS(data, hora) VALUES(CURDATE("yyyy-MM-dd"),CURTIME("hh:mm:ss))
UPDATE ENTRADAS(SAI) WITH VALUES(#SAI)
IF '_rollback' THEN
SET retcode = 0;
ROLLBACK;
ELSE
SET retcode = 1;
COMMIT;
END IF;
END$$
DELIMITER ;
Here is a screenshot of my MySqlWB:
EDIT:
Here is the log:
>Executing:
>USE `portaria`;
>DROP unknown IF EXISTS `unknown_SYNTAX_ERROR`;
>
>DELIMITER $$
>USE `portaria`$$
>DELIMITER $$
>
>CREATE PROCEDURE 'entradas_sai'(
>IN ID_VEICULO VARCHAR(45), OUT retcode INT)
>BEGIN
> DECLARE '_rollback' BOOL DEFAULT 0;
> DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET '_rollback' = 1;
> START TRANSACTION;
> INSERT INTO SAIDAS(data, hora) VALUES(date(now()) ,time(now()))
> UPDATE ENTRADAS(SAI) WITH VALUES(#SAI)
> IF '_rollback' THEN
> SET retcode = 0;
> ROLLBACK;
> ELSE
> SET retcode = 1;
> COMMIT;
> END IF;
>END$$
>
>DELIMITER ;$$
>
>DELIMITER ;
>
>ERROR 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 >'unknown IF EXISTS `unknown_SYNTAX_ERROR`' at line 1
>SQL Statement:
>DROP unknown IF EXISTS `unknown_SYNTAX_ERROR`
Here i got a scenarion of what i want my procedure to do...
I have a table called "Entradas" and one called "Saidas". Both have
the column "data" and "hora". With that in mind, since the "data" and
"hora column of "entradas" mean that a car joined at that date and
time, and the values from the columns "data" and "hora" of "saidas"
are mean to be inserted as i click a button, inserting the current
date and time. I'm requesting a sql syntax that could insert the
values "data" and "hora" into the table "saidas" and update a value of
"entradas" called "sai" which is equal to 0 and i want it to change to
1 on button press... Any sugestion?
delimiter symbol ($$) come after DELIMITER keyword. also use date(now()) instead CURDATE("yyyy-MM-dd") and time(now()) instead CURTIME("hh:mm:ss"))
Try This
DELIMITER $$
CREATE PROCEDURE `entradas_sai`(IN ID_VEICULO VARCHAR(45), OUT retcode INT)
BEGIN
DECLARE _rollback boolean DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET _rollback = 1;
START TRANSACTION;
INSERT INTO SAIDAS(data, hora) VALUES(date(now()) ,time(now()));
UPDATE ENTRADAS SET SAI = #SAI;
IF _rollback = 1 THEN
SET retcode = 0;
ROLLBACK;
ELSE
SET retcode = 1;
COMMIT;
END IF;
END$$
DELIMITER ;
If i'm right, you mistyped $$DELIMITER, it should be DELIMITER $$
EDIT: after adding the screenshot to the question, i believe you shouldn't quote the procedure name. I have update the code-block, try it again please.
DELIMITER $$
CREATE PROCEDURE entradas_sai(
IN ID_VEICULO VARCHAR(45), OUT retcode INT)
BEGIN
DECLARE '_rollback' BOOL DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET '_rollback' = 1;
START TRANSACTION;
INSERT INTO SAIDAS(data, hora) VALUES(CURDATE("yyyy-MM-dd"),CURTIME("hh:mm:ss"))
UPDATE ENTRADAS(SAI) WITH VALUES(#SAI)
IF '_rollback' THEN
SET retcode = 0;
ROLLBACK;
ELSE
SET retcode = 1;
COMMIT;
END IF;
END$$
DELIMITER ;
I figured what was wrong, and it wasn't only about "DELIMITER" but with a couple things more...
Here is the fixed code:
CREATE PROCEDURE entradas_sai (
IN ID_VEICULO VARCHAR(45), OUT retcode INT)
BEGIN
DECLARE _rollback BOOL DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET _rollback = 1;
START TRANSACTION;
INSERT INTO SAIDAS(data, hora) VALUES(date(now()) ,time(now()));
UPDATE ENTRADAS SET SAI=1;
IF '_rollback' THEN
SET retcode = 0;
ROLLBACK;
ELSE
SET retcode = 1;
COMMIT;
END IF;
END $$
Steps: Removed the "Delimiter $$" and "Delimiter ;" and then restructured the UPDATE query. That was the main problem, because the syntax wasn't on the spot... Thanks all who tryied to help.
In this case the value of "1" wasn't the value i want... So, i changed it to #sai, which means that the value is given at a button click, which is a increment of the parameter #sai, being equal to 1,2,3,4 and so on.

mysql procedure questions?

when the table user delete fail,why the next sql will be exceute.who can give me a full example for mysql procedure.i want to delete example.please help?
use test;
delimiter //
create procedure proc_name(in paramter int)
begin
declare t_error int default 0;
declare continue handler for sqlexception set t_error=1;
set autocommit = 0;
START TRANSACTION;
delete from `user` where id = paramter;
delete from `user_info` where uid = paramter;
if t_error=1 then
rollback;
else
commit;
end if;
end;
//
delimiter ;
Dinel, I would change a little bit of your logic to achieve what you are looking for:
use test;
delimiter //
create procedure proc_name(in paramter int)
begin
declare continue handler for sqlexception set t_error=1;
SET #t_error = 0;
START TRANSACTION;
delete from `user` where id = paramter;
SELECT #t_error := COUNT(*) from `user` where id = paramter;
if #t_error != 0 then
ROLLBACK;
else
DELETE FROM `user_info` WHERE uid = paramter;
COMMIT;
end if;
end;
//
delimiter ;
I didn't try the syntax, but it should work. ;-)

1193 error when creating a mysql stored procedure

I am trying to create this procedure but there is an error that I cannot solved. It gives me
error 1193 Unknown system variable p_salida.
I have looked at other topics here, but I find nothing that is useful to me.
Thanks!
bloque: BEGIN
-- PK / UK
DECLARE EXIT HANDLER FOR 1062
BEGIN
ROLLBACK;
SET p_salida=-5;
END;
-- FK
DECLARE EXIT HANDLER FOR 1452
BEGIN
ROLLBACK;
SET p_salida=-6;
END;
DECLARE v_Direccion int;
DECLARE v_CodUsuario int;
If not EXISTS (SELECT * From usuarios where Nombre = p_nombre and Apellido
= p_Apellido and Correo = p_correo and Contrasena=p_contrasena) THEN
-- SET p_salida = -1;
LEAVE bloque;
END IF;
SELECT codDireccion into v_Direccion
From direcciones
Order by codDireccion
DESC LIMIT 1;
SET v_Direccion = v_Direccion + 1;
SELECT codUsuario into v_CodUsuario
From usuarios
Order by codusuario
DESC LIMIT 1;
SET v_CodUsuario = v_CodUsuario + 1;
START TRANSACTION;
INSERT Into direcciones (CodDireccion, CodigoPostal, Domicilio, Localidad,
Provincia)
VALUES (v_Direccion, p_CodPostal,
p_Domicilio,p_Localidad,p_Provincia);
INSERT into Usuarios (Apellido, CodUsuario, Contrasena, Correo,
Direccion,FechaNacimiento, nombre)
VALUES (p_Apellido, v_CodUsuario, p_Contrasena, p_Correo, v_Direccion,
p_FechaNacimiento,p_nombre);
COMMIT;
SET p_salida = 1;
END bloque
You have to declare your variable before you can use it. Something like this, placed just after your begin statement (or at least some time before you try to use the variable):
DECLARE p_salida INT DEFAULT 1;
Documentation: https://dev.mysql.com/doc/refman/8.0/en/declare-local-variable.html