2016-07-24 1 views
2

열 중 하나에서 앞에 0이 제거 될 수 있도록 테이블을 업데이트하려고합니다. 나는 이런 식으로 뭔가를 할 :충돌에 대한 update nothing postgres

UPDATE oh_person SET identifier = TRIM(LEADING '0' FROM identifier) 

문제는 행의 일부는 이미 추가되는 말머리 0이 붙지 않는 식별자를 가지고 있으며,이 열은 고유 한 의미이기 때문에, 그 경우에 오류가 발생합니다. 이런 식으로 할 수 있습니까?

UPDATE oh_person SET identifier = TRIM(LEADING '0' FROM identifier) ON CONFLICT (identifier) DO NOTHING 

나는 특정 쿼리가 가능하지 않을 것입니다하지만를 달성 할 다른 구문이 있음을 알아?

+0

는 우리에게 잘 어떤 일을, 첨가 된 제로와 식별자의 몇 가지 예를 줄 수 그게 오류를 던집니다? – Patrick

답변

1

예 데이터 :

create table oh_person(identifier text unique); 
insert into oh_person 
values ('012'), ('0012'), ('0015'), ('015'); 

사용 anonymous code block :

do $$ 
declare 
    r record; 
begin 
    for r in 
     select identifier 
     from oh_person 
     where left(identifier, 1) = '0' 
    loop 
    begin 
     update oh_person 
     set identifier = trim(leading '0' from identifier) 
     where identifier = r.identifier; 
    exception 
     when unique_violation then 
      raise notice '% not updated', r.identifier; 
    end; 
    end loop; 
end $$; 

NOTICE: 0012 not updated 
NOTICE: 015 not updated 

결과 :

select * from oh_person; 

identifier 
------------ 
0012 
015 
12 
15 
(4 rows) 
+0

덕분에,이 도움이되었습니다! – chris

관련 문제