MySQL Trigger doesn't know default value

佐手、 提交于 2019-12-12 12:08:41

问题


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;

回答1:


Doesn't default(property.primary_image) work?

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




回答2:


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;


来源:https://stackoverflow.com/questions/9818956/mysql-trigger-doesnt-know-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!