MySQL - Can you retrieve the default value of a column?

℡╲_俬逩灬. 提交于 2019-12-02 07:58:52

问题


I was looking at creating a TRIGGER that will set the value of a column to its DEFAULT if the INSERT value happens to be an empty string.

My TRIGGER looks like this:

CREATE TRIGGER column_a_to_default 
BEFORE INSERT ON table
FOR EACH ROW
BEGIN
IF NEW.a = '' THEN
SET NEW.a = 'some value';
END IF;
END

I would like to know if I can replace 'some value' with a way to set it to the DEFAULT value of the column. i.e.

SET NEW.a = a.DEFAULT

Thanks


回答1:


This should work for you

SET NEW.a = DEFAULT(NEW.a)

EDIT: It looks like that doesn't work.

Use this workaround

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

You can also try

SET NEW.a = DEFAULT(table_name.a)


来源:https://stackoverflow.com/questions/9817632/mysql-can-you-retrieve-the-default-value-of-a-column

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