6

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 
2
  • 2
    Just remove the quotes. Commented Feb 1, 2015 at 15:28
  • Only use single quotes for string and date constants. Commented Feb 1, 2015 at 15:33

2 Answers 2

12

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 ;
Sign up to request clarification or add additional context in comments.

Comments

0

Single quotes (') denote string literals - object names, like triggers and tables should use forward quotes, or no quotes at all:

CREATE
    TRIGGER blog_after_insert AFTER INSERT -- here
    ON blog -- and here
    FOR EACH ROW BEGIN
    -- rest of code...

2 Comments

i have made the changes which you have suggested me, but still getting error.. please look into my query where i am doing mistake ----- CREATE TRIGGER blog_after_insert AFTER INSERT -- here ON blog -- and here 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 have put spaces in special characters @ because stack overflow consider it as a user..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.