我有一个 PostgreSQL 8.4 表,其中有一个自动递增但可为空的整数列。我想更新一些列值,如果该列为 NULL,则将其设置为其默认值(这将是从序列自动生成的整数),but无论哪种情况我都想返回它的值。所以我想要这样的东西:
UPDATE mytable
SET incident_id = COALESCE(incident_id, DEFAULT), other = 'somethingelse'
WHERE ...
RETURNING incident_id
不幸的是,这不起作用 - 似乎DEFAULT
是特殊的,不能是表达式的一部分。最好的方法是什么?
用这个:
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')
)
如果您的 Incidentid 是整数类型,请对 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 )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)