PostgreSQL - set a default cell value according to another cell value

时光毁灭记忆、已成空白 提交于 2019-11-30 14:31:18

问题


If i have a column say column a of any given values, and i want another column column b to have a default value according to the value of column a

In another words:
if column a = 'peter' then column b default value = 'doctor'.


回答1:


This is not possible with a simple DEFAULT value, as the manual clearly states:

The value is any variable-free expression (subqueries and cross-references to other columns in the current table are not allowed).

You could use a trigger instead:

CREATE OR REPLACE FUNCTION trg_foo_b_default()
  RETURNS trigger AS
$func$
BEGIN

-- For just a few constant options, CASE does the job:
NEW.b :=
   CASE NEW.a
    WHEN 'peter'  THEN 'doctor'
    WHEN 'weirdo' THEN 'shrink'
    WHEN 'django' THEN 'undertaker'
    ELSE NULL
   END;

/* -- For more, or dynamic options, you could use a lookup table:
SELECT INTO NEW.b  t.b
FROM   def_tbl t
WHERE  t.a = NEW.a;
*/

RETURN NEW;

END
$func$ LANGUAGE plpgsql;

CREATE TRIGGER b_default
BEFORE INSERT ON foo
FOR EACH ROW
WHEN (NEW.b IS NULL AND NEW.a IS NOT NULL)
EXECUTE PROCEDURE trg_foo_b_default();

To make this more effective I use a WHEN clause (available since Postgres 9.0) with the trigger definition. This way the trigger function is only executed, when it's actually useful. I am assuming here, we can let b IS NULL slide if a IS NULL.

Works in a similar, but subtly different fashion from a DEFAULT value.
With a default value, you can explicitly insert NULL to overrule the default. That's not possible here, NULL in b is replaced with the value derived from a.



来源:https://stackoverflow.com/questions/16737738/postgresql-set-a-default-cell-value-according-to-another-cell-value

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