HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

Mysql create trigger if not exist

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
triggercreateexistmysqlnot

Problem

I have a script that creates triggers,
I would like to run it multiple times and if a trigger already exist it needs to skip the creation part.

Is there a "create if not exist" in mysql triggers?

I tried :

IF NOT EXISTS ((SELECT TRIGGER_NAME
        FROM information_schema.triggers
        WHERE TRIGGER_SCHEMA = 'xxx_admin' AND TRIGGER_NAME = 'test_AFTER_UPDATE')) 
        THEN
    CREATE DEFINER=`root`@`localhost` TRIGGER `xxx_admin`.`test_AFTER_UPDATE` AFTER UPDATE ON `test` FOR EACH ROW
        BEGIN
        INSERT INTO auditTest 
        select *, now() from test where id = NEW.id;
        END;
  END IF;


I get : syntex error " 'IF' is not valid input at this location

Solution

There is no CREATE TRIGGER IF NOT EXISTS

There is DROP TRIGGER IF EXISTS

You must execute the trigger's creation as follows:

USE xxx_admin
DELIMITER $
DROP TRIGGER IF EXISTS test_AFTER_UPDATE $
CREATE DEFINER=`root`@`localhost` TRIGGER `xxx_admin`.`test_AFTER_UPDATE`
AFTER UPDATE ON `test` FOR EACH ROW
BEGIN
    INSERT INTO auditTest 
    select *, now() from test where id = NEW.id;
END $
DELIMITER ;


GIVE IT A TRY !!!

As for you error, using IF like that is not valid from the CLI.

Code Snippets

USE xxx_admin
DELIMITER $$
DROP TRIGGER IF EXISTS test_AFTER_UPDATE $$
CREATE DEFINER=`root`@`localhost` TRIGGER `xxx_admin`.`test_AFTER_UPDATE`
AFTER UPDATE ON `test` FOR EACH ROW
BEGIN
    INSERT INTO auditTest 
    select *, now() from test where id = NEW.id;
END $$
DELIMITER ;

Context

StackExchange Database Administrators Q#112104, answer score: 4

Revisions (0)

No revisions yet.