Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql syntax error creating trigger

Tags:

mysql

I want to create trigger and I have written this query but this does not execute. Please check my query

CREATE
    TRIGGER 'blog_after_insert' AFTER INSERT 
    ON 'blog' 
    FOR EACH ROW BEGIN

        IF NEW.deleted THEN
            SET @changetype = 'DELETE';
        ELSE
            SET @changetype = 'NEW';
        END IF;

        INSERT INTO audit (blog_id, changetype) VALUES (NEW.id, @changetype);

I am getting this 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 ''blog_after_insert' AFTER INSERT 
    ON 'blog' 
    FOR EACH ROW BEGIN

        IF NEW.del' at line 2 
like image 257
Harpreet Singh Avatar asked Feb 01 '15 15:02

Harpreet Singh


People also ask

What is the syntax for creating a trigger?

Explanation of syntax:create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name. [before | after]: This specifies when the trigger will be executed. {insert | update | delete}: This specifies the DML operation.

What is the correct syntax for creating a trigger in MySQL?

The following is the basic syntax to create a trigger: CREATE TRIGGER trigger_name trigger_time trigger_event. ON table_name FOR EACH ROW. BEGIN.

How do I create a trigger in SQL?

To create a trigger or drop a trigger, use the CREATE TRIGGER or DROP TRIGGER statement, described in Section 13.1. 22, “CREATE TRIGGER Statement”, and Section 13.1. 34, “DROP TRIGGER Statement”. Here is a simple example that associates a trigger with a table, to activate for INSERT operations.

How do you increase the error in a trigger?

For any errors in the user-written business logic as part of the trigger body, users can receive errors in a procedure variable using the RETURN SQLERROR error_string or RETURN SQLERROR char_variable statements.


1 Answers

Please run this query

DELIMITER $$
CREATE
    TRIGGER blog_after_insert  AFTER INSERT 
    ON blog 
    FOR EACH ROW BEGIN

        IF NEW.deleted THEN
            SET @changetype = "DELETE";
        ELSE
            SET @changetype = "NEW";
        END IF;

        INSERT INTO audit (blog_id, changetype) VALUES (NEW.id, @changetype);

    END$$
DELIMITER ;
like image 54
Jaskaran singh Rajal Avatar answered Sep 30 '22 21:09

Jaskaran singh Rajal