4

I use this trigger

delimiter ||
create TRIGGER column_a_to_default 
BEFORE INSERT ON `property`
FOR EACH ROW
BEGIN  
  IF NEW.primary_image = '' THEN
    SET NEW.primary_image = default(NEW.primary_image);
  END IF;
END;
||
delimiter ;

If I insert into the table the trigger throws an error:

Field 'primary_image' doesn't have a default value.

But it does!

What is wrong here? It seems like the trigger isn't aware of default values!

EDIT

Table Create script

CREATE TABLE IF NOT EXISTS `property` (
  `id` varchar(10) NOT NULL,
  `images` text NOT NULL,
  `primary_image` varchar(100) NOT NULL DEFAULT '../no-image.png',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3
  • Please post the CREATE TABLE statement used. Thanks! Commented Mar 22, 2012 at 9:03
  • 1
    Doesn't default(property.primary_image) work? (Getting the default of the Real table, not the NEW holding-table) Commented Mar 22, 2012 at 9:20
  • @Dems: You are right. It does work. Post it as answer please. Commented Mar 22, 2012 at 16:17

2 Answers 2

4

Doesn't default(property.primary_image) work?

(Getting the default of the Real table, not the NEW holding-table)

Sign up to request clarification or add additional context in comments.

2 Comments

Really. It works. I had tried this too, but somehow it did not work for me. Anyway +1.
@Devart - I think you guys were trying default(NEW.primary_image), but the NEW table isn't that property table. It's just a similar table, with only what is necessary to log the changes. Querying property directly ensures you get what you want.
1

Somehow it does not work.

Try this workaround -

  IF NEW.primary_image = '' THEN
    SELECT COLUMN_DEFAULT INTO @def
      FROM information_schema.COLUMNS
    WHERE
      table_schema = 'database_name'
      AND table_name = 'property'
      AND column_name = 'primary_image';
    SET NEW.primary_image = @def;
  END IF;

3 Comments

Unfortunately it doesn't work. Error: Column primary_image cannot be null. Seems like it can't get the default value this way either.
INSERT INTO property (primary_image) VALUES (''); should work
I am sorry. It worked. I forgot to replace the database_name string. Thank you very much!

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.