我有一个布尔列,其中添加了默认值false。据我了解,当我向表中添加新行时,默认值将生效。但是,当行也更新时,我希望默认值为false。有可能吗?
例如:
ALTER TABLE mytable ALTER COLUMN mycolumn SET DEFAULT false;
-- In below query the mycolumn should default to false
update mytable set somecolumn = 'somevalue'
where somecolumn = 'anothervalue'
-- In below query mycolumn should be true since the value is specified
update mytable set somecolumn = 'somevalue' mycolumn = true
where somecolumn = 'anothervalue'
答案 0 :(得分:1)
您可以如下创建触发器:
CREATE FUNCTION mytriggerfunction()
RETURNS TRIGGER AS '
BEGIN
IF NEW.mycolumn IS NULL OR NEW.mycolumn='''' THEN
NEW.mycolumn := ''somedefaultvalue'';
END IF;
RETURN NEW;
END' LANGUAGE 'plpgsql';
CREATE TRIGGER mytrigger
BEFORE UPDATE ON mytable
FOR EACH ROW
EXECUTE PROCEDURE mytriggerfunction();
答案 1 :(得分:0)
有可能。但仅当您添加触发器时。 create table
语句中没有特殊的子句。