Search code examples
mysqlsqlsyntax-errormysql-error-1064

SQL Trigger Creation - How do I check if NULL or empty?


I'm having some issues with my SQL syntax it seems. I'm trying to create a trigger and then check if data is NULL or empty.

This is the code now thanks to Bill & Gordon:

DROP TRIGGER IF EXISTS `tablename_OnInsert`;

    DELIMITER $$

    CREATE TRIGGER `tablename_OnInsert` BEFORE INSERT ON `users`
    FOR EACH ROW
    BEGIN
        IF NEW.`swid` IS NULL OR NEW.`swid` = '' THEN
            SET NEW.`swid` = CONCAT('{', uuid(), '}');
        END IF
    END$$
    ;

The server still responds with an 1064:

/* 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 'END' at line 7 */

I've been looking around to see what I am doing wrong here, but I just don't get it.


Solution

  • Well:

    DROP TRIGGER IF EXISTS `tablename_OnInsert`;
    
    DELIMITER $$
    
    CREATE TRIGGER `tablename_OnInsert` BEFORE INSERT ON `users`
    FOR EACH ROW
    BEGIN
        IF NEW.`swid` IS NULL OR NEW.`swid` = '' THEN
            SET NEW.`swid` = CONCAT('{', uuid(), '}');
        END IF;
    END$$
    

    Your problem appears to be the extra ) in the IF. However, I recommend BEGIN/END and setting the delimiter.