Trigger in MySQL - mysql

I am trying to create a trigger wherein it will insert a new row to a ADMIN_EMAIL_DOMAINS table.
CREATE TRIGGER email_domain_insert AFTER INSERT ON USERS
FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT * FROM (SELECT DISTINCT SUBSTRING_INDEX(USR_EMAIL, '#', -1) as domain FROM USERS) as a WHERE a.domain = SUBSTRING_INDEX(NEW.USR_EMAIL, '#', -1)) THEN
INSERT INTO ADMIN_EMAIL_DOMAINS (DOMAIN_NAME, VISIBLE) VALUES (SUBSTRING_INDEX(NEW.USR_EMAIL, '#', -1), 1);
END IF;
END //
What I would like to do is everytime I create a new user, i would check its email extension and then insert it to ADMIN_EMAIL_DOMAINS table if that DOMAIN_NAME is not yet existing.
My problem is it has an SQL error when i tried to execute it
#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 5
Am I missing something?

I could suggest you another way - make field DOMAIN_NAME as unique and try to insert new domains into the table ADMIN_EMAIL_DOMAINS with IGNORE option, e.g. -
DELIMITER $$
CREATE TRIGGER email_domain_insert
AFTER INSERT
ON users
FOR EACH ROW
BEGIN
INSERT IGNORE INTO ADMIN_EMAIL_DOMAINS (DOMAIN_NAME, VISIBLE) VALUES (SUBSTRING_INDEX(NEW.USR_EMAIL, '#', -1), 1);
END
DELIMITER ;

Related

Creating a trigger to add new row to another table after new record using if statement

I cannot seem to get this trigger to work. I keep getting this error.
#1064 - You have an error in your SQL syntax; check the manual
that corresponds to your MariaDB server version for the right syntax to
use near '' at line 6
SELECT * FROM website_queries;
CREATE DEFINER=`name`
TRIGGER `add_subscribed_users`
AFTER INSERT ON `website_queries` FOR EACH ROW
BEGIN
IF NEW.subscribed = 0 THEN
INSERT INTO users SET id=DEFAULT, firstName = NEW.firstName, lastName = NEW.lastName, mobile=DEFAULT, email = NEW.email, admin=DEFAULT, createdAt = NEW.createdAt, subscribed = NEW.subscribed;
END IF;
END; //
I am using 10.5.15-MariaDB-cll-lve doing this through phpMyAdmin
You do not need in IF.
CREATE DEFINER=`name` TRIGGER `add_subscribed_users`
AFTER INSERT ON `website_queries`
FOR EACH ROW
INSERT INTO users (firstName, lastName, email, createdAt, subscribed)
SELECT NEW.firstName, NEW.lastName, NEW.email, NEW.createdAt, NEW.subscribed
WHERE NEW.subscribed = 0;
In this single-statement form you do not need in BEGIN-END and DELIMITER too.

MySQL syntax error while creating a UPDATE Trigger

I am trying to create a trigger on updating the salary field of this table.
customers(ID, Name, Age, Address, Salary) from this site SQL Trigger
While creating it shows the following error
MySQL said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
' at line 2
Here is the code snippet:
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN `enter code here`
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END
Note that, I'm using phpMyAdmin. Does dbms_ouput.put_line() works there?
As said in the comments, you are using Oracle syntax, it can't work on MySQL.
Then, there's no reason to have this trigger on DELETE and INSERT because your aim is to compute the salary difference on a specific row before and after it get updated. You can't have a value NEW on DELETE, and you can't have a value OLD on INSERT.
Thus your computation is only meaningful on UPDATE.
Here's the correct MySQL syntax (I am assuming that you have a column sal_diff on your table)
DELIMITER $$
CREATE TRIGGER `update_sal_diff`
BEFORE UPDATE ON `customers `
FOR EACH ROW
BEGIN
SET NEW.sal_diff = NEW.salary - OLD.salary;
END $$
DELIMITER ;
If this is not what you are trying to achieve, edit your question and add clear requirements

How do I use IF THEN ELSE to SELECT and INSERT or UPDATE Queries?

I've been trying to use the following query
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(INSERT INTO users (id, username) VALUES (2, user2))
ELSE
(UPDATE users SET username = 'userUpdated')
But I keep getting
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO users (id) VALUES (2)) ELSE (UPDATE users SET id = 11)' at line 1 */
Also tried using the following query
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(SELECT username FROM users WHERE id = 1)
ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'))
But this time I got
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'))' at line 4 */
Am I doing or understood something wrong?
The if statement can only be used in programming blocks, such as stored procedures, functions, and triggers.
In any case, MySQL offers simpler syntax for this functionality: insert . . . on duplicate key update.
To use it, id must have a unique index, unique constraint, or be defined as the primary key. Let me assume that a column so-named is already so-defined.
Then:
INSERT INTO users (id, username)
VALUES (2, user2)
ON DUPLICATE KEY UPDATE username = 'userUpdated';
Are you missing the END IF (and semi colons)?
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(SELECT username FROM users WHERE id = 1);
ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'));
END IF;
Try This.
IF EXISTS (SELECT id FROM users WHERE id = 1)
begin
INSERT INTO users (id, username) VALUES (2, 'user2')
end
ELSE
UPDATE users SET username = 'userUpdated'
In MariaDB 10.1 and newer, you can use compound statements outside of stored procedures. This blog post gives a good description of what you can do with it.
Here's an example the blog:
BEGIN NOT ATOMIC
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
stmt1;
....
stmtN;
COMMIT;
END

MySQL: Insert with conditional

I must perform the following situation down, but when you run got the error:
SQL 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 'INTO produto_seriais(serial_id) VALUES( SELECT id
FROM seriais WHERE serial =' at line 5
SELECT CASE WHEN (
SELECT COUNT(id) FROM seriais WHERE serial = '2020'
) > 1
THEN
(INSERT INTO produto_seriais(serial_id) VALUES(
SELECT id FROM seriais WHERE serial = '2020'
))
ELSE (
INSERT INTO seriais (serial) VALUE('2020');
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO produto_seriais (serial_id) VALUES (#last_id_in_table1);
)
END;
The case is as follows:
I'll get in "serial" table by serial "X". If it already exists, unless your ID in the "produto_seriais" table. If there is (serial), I will save the same, recover your ID and save to "produto_seriais". Any suggestions for how to do this?
Important Note: This routine will run will be thousands of times each execution (10,000 or more, depending on the quantity of serial).
P.s.: Sorry for my bad english.
Try a stored procedure
DELIMITER //
CREATE PROCEDURE sp_produto_seriais(IN `p_serial_id`)
IF EXISTS (SELECT * FROM seriais WHERE serial = p_serial_id )
BEGIN
INSERT INTO produto_seriais (serial_id)
SELECT id
FROM seriais
WHERE serial = p_serial_id
END
ELSE
BEGIN
INSERT INTO seriais (serial) VALUE(p_serial_id);
INSERT INTO produto_seriais (serial_id) VALUES (LAST_INSERT_ID());
END //
DELIMITER ;
usage:
CALL sp_produto_seriais('2020')
You could use the if exists..else statement.
If exists (select * from ....)
Begin
Insert into ... Select id from table
End
Else
Begin
Insert..
End
Please fill .... with your statements. You could use the link here to convert it for MySQL.
Convert if exists for MySQL

Cannot create trigger in mysql at phpmyadmin

I'm trying to create an ID by combining fields after a row has been inserted into the database in phpmyadmin. I get an error on line 3 of the following trigger statement:
DROP TRIGGER IF EXISTS `scanID2`;
CREATE DEFINER=`root`#`localhost`
TRIGGER `scanID2`
AFTER INSERT ON db_name.`scan_data`
FOR EACH ROW
BEGIN
UPDATE db_name.scan_data
SET #data1 = concat(RIGHT(scanContent,2), RIGHT(operatorID,2), RIGHT(deviceID,2), RIGHT (scanDate, '-', ''), REPLACE (scanTime, ':', ''));
INSERT INTO db_name.scan_data(scanID) VALUES (#data1);
END
//
The error is:
#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 'CREATE DEFINER=`root`#`localhost`
TRIGGER `scanID2`
AFTER INSERT ON db_name' at line 2
OK, so I figured how to get the query executed. The trigger has been created but I don't think it does what it's supposed to do. The records don't get updated. Here's the new code:
BEGIN
SET #data1 = concat(RIGHT(scanContent,2), RIGHT(operatorID,2), RIGHT(deviceID,2), REPLACE (scanDate, '-', ''), REPLACE (scanTime, ':', ''));
INSERT INTO vacseen1_connect.scan_data(scanID) VALUES (#data1);
END
There are several things to consider:
Use BEFORE event for the trigger instead of AFTER. This way you can set the value of scanID the same time a row is being inserted.
Use NEW keyword to access fields of a row being inserted.
Since it's one statement trigger now you don't need to change delimiter and use BEGIN ... END block.
You most likely meant to use REPLACE for scanDate.
Try
CREATE TRIGGER scanID2
BEFORE INSERT ON scan_data
FOR EACH ROW
SET NEW.scanID = CONCAT(
RIGHT(NEW.scanContent, 2),
RIGHT(NEW.operatorID, 2),
RIGHT(NEW.deviceID, 2),
REPLACE(NEW.scanDate, '-', ''),
REPLACE (NEW.scanTime, ':', '')
);
Here is a SQLFiddle demo