Tuesday, April 20, 2010

Getting the default value of column

Somebody in Stackoverflow wanted to do something like this:

UPDATE emp SET subordinate_of = COALESCE(subordinate_of, DEFAULT), other = 'somethingelse'
WHERE conditionhere

But it cannot yet be done in Postgres. So we will just obtain the column's default value from information_schema.



create function default_of(_table_name text, _column_name text) returns text
as 
$$
begin
    return default_of(_table_name, _column_name, CURRENT_SCHEMA);
end;
$$ language 'plpgsql';


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

    s = 'SELECT ' || coalesce(

    (select column_default 
    from information_schema.columns 
    where table_schema = _schema_name
    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 emp SET subordinate_of = COALESCE( subordinate_of, default_of('emp','subordinate_of') ), 
other = 'somethingelse'
WHERE conditionshere

No comments:

Post a Comment