2010-04-20 15 views
6

자동 증가하지만 null 입력 가능한 정수 열이있는 PostgreSQL 8.4 테이블이 있습니다. 몇 가지 열 값을 업데이트하고이 열이 NULL이면 기본값 (시퀀스에서 자동 생성되는 정수)이되도록 이지만 두 경우 모두 해당 값을 반환하고 싶습니다. 그래서 이런 걸 원하는 :Postgres에서 열을 조건부로 기본값으로 설정합니다.

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

불행하게도,이 작동하지 않습니다 - DEFAULT이 특별하고 표현의 일부가 될 수없는 것 같다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까?

+0

당신이 incident_id 열의 목적을 오버로딩하는 것 같아요 여기에 비즈니스 로직을 포함. 키스. – Timothy

+0

기능 요청을 원하십니까? – adjenks

답변

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

당신의 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'; 

사용하기 :

update mytable set a = 
    coalesce(incidentid, get_default_value('mytable','a')::int) 
+0

죄송합니다. 작동하지 않습니다. 'column_default'는 "nextval (('incidents_s':: text) :: regclass)"를 리턴합니다 - 그 표현식의 값이 아닙니다. – EMP

+2

와우, 많은 코드가 있습니다. 내 쿼리에서 기본 표현식을 복제하는 것이 가장 좋습니다. 어쨌든 +1. – EMP

+0

그것은 아름다움입니다! schemaname은 변수 'public'을 사용하여 변수가 될 수 있습니다. –

관련 문제