tags:

views:

101

answers:

1

I've got a PostgreSQL 8.4 table with an auto-incrementing, but nullable, integer column. I want to update some column values and, if this column is NULL then set it to its default value (which would be an integer auto-generated from a sequence), but I want to return its value in either case. So I want something like this:

UPDATE mytable
SET incident_id = COALESCE(incident_id, DEFAULT), other = 'somethingelse'
WHERE ...
RETURNING incident_id

Unfortunately, this doesn't work - it seems that DEFAULT is special and cannot be part of an expression. What's the best way to do this?

+2  A: 

use this:

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')
    )

if your incidentid is integer type, put a typecast on column_default

[EDIT]

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';

to use:

update mytable set a = 
    coalesce(incidentid, get_default_value('mytable','a')::int )
Michael Buen
Sorry, that doesn't work. `column_default` returns "nextval(('incidents_s'::text)::regclass)" - not the value of that expression, which is what I want.
Evgeny
Woah, that's a lot of code. Sounds like it's best to just duplicate the default expression in my query. +1, anyway.
Evgeny
It's a beauty! The schemaname could be a variable as well, using the default 'public'.
Frank Heikens