在Postgres中有条件地将列设置为其默认值

EMP*_*EMP 6 sql postgresql

我有一个PostgreSQL 8.4表,其中包含一个自动递增但可以为空的整数列.我想更新一些列值,如果此列为NULL,则将其设置为其默认值(这将是从序列自动生成的整数),我想在任一情况下返回其值.所以我想要这样的东西:

UPDATE mytable
SET incident_id = COALESCE(incident_id, DEFAULT), other = 'somethingelse'
WHERE ...
RETURNING incident_id
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用 - 它似乎DEFAULT很特殊,不能成为表达的一部分.最好的方法是什么?

Mic*_*uen 4

用这个:

update mytable set a = 
    coalesce(incidentid, 
    (
     select column_default::int 
     from information_schema.columns 
     where table_schema = 'public' 
     and table_name = 'mytable' and column_name = 'incidentid')
    )
Run Code Online (Sandbox Code Playgroud)

如果您的 Incidentid 是整数类型,请对 column_default 进行类型转换

[编辑]

create or replace function get_default_value(_table_name text,_column_name text) 
returns text
as
$$
declare r record;
s text;
begin

    s = 'SELECT ' || coalesce(

    (select column_default 
    from information_schema.columns 
    where table_schema = 'public' 
    and table_name = _table_name and column_name = _column_name)

    , 'NULL') || ' as v';

    EXECUTE s into r;
    return r.v;
end;
$$
language 'plpgsql';
Run Code Online (Sandbox Code Playgroud)

使用:

update mytable set a = 
    coalesce(incidentid, get_default_value('mytable','a')::int )
Run Code Online (Sandbox Code Playgroud)

  • 哇,有很多代码。听起来最好只复制查询中的默认表达式。无论如何,+1。 (2认同)