如果我有一个列表示任何给定值的列a,并且我想要另一个列列b根据列a的值具有默认值
换句话说:
如果列a =’peter’,则列b默认值=’doctor’.
这是不可能的简单的一个DEFAULT值,如
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).
您可以使用trigger:
- 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();
为了使此更有效,我使用WHEN子句(可从Postgres 9.0开始使用)与触发器定义.这样触发功能只能在实际使用时执行.我假设在这里,如果一个IS NULL,我们可以让b IS NULL幻灯片.
以与DEFAULT值相似但略有不同的方式工作.使用默认值,您可以显式地插入NULL以覆盖默认值.这是不可能的,NULL被替换为来自b的值.