2016-07-24 83 views
2

我試圖更新一個表,以便我可以從其中一列中刪除前置的零。我想要做這樣的事情:更新衝突什麼都不做postgres

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

的問題是,某些行已經沒有預謀零標識,因爲此列,就是要獨一無二,它拋出在這些情況下的錯誤。是否有可能做這樣的事情?

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