2011-07-26 8 views
1

の視認性は、私は(整数で、アウト整数)の表に作成を機能コピーを持っていると言うMYTABLEによって識別される行の複製におけるパラメータ。新しい行の識別子が返されます。のPostgreSQL - 更新 - 関数

私が代わりに古い行を、新しい/重複した行にアップデートを適用したいと思います:

update mytable set field = ... where identifier = (select copy(1)); 

これが動作するようには思えません。複製は作成されますが、古い値が残っています。 where句が評価されたときに新しい行がまだ表示されないことが予想されます。つまり、更新は行われていません。

次のいずれかの動作しません:

update mytable set field = ... from copy(1) as c where identifier = c.copy; 

私は2つのラインでそれを書くとき、それは完璧に動作します:

select copy(1); 
update mytable set field = ... where identifier = <value returned by copy(1)>; 

私は2つの質問があります。

(1) 1ライナーでこれを行うことはできますか?

(2)それは、書き換えルールを書いたり、重複をバックグラウンドで作成され、更新が重複した/新しい行に適用されている間、私も

​​

を書くことができるようトリガすることは可能ですか?私は無限ループに終わらない解決策を見ることができません。

サンプルコード

drop table if exists t cascade; 

create table t 
(
    identifier serial primary key, 
    title  text 
); 

create or replace function copy(in integer, out integer) as 
$$ 
     begin 
       insert into t (title) values ((select title from t where identifier = $1)) returning identifier into $2; 
     end 
$$ language plpgsql; 

insert into t (title) values ('title - old'); 
update t set title = 'title - new' where identifier = (select copy(1)); 
select * from t; 

行は別々の変数に正常に取り込まれ()コピーにご注意ください。簡単にするために、このサンプルコードで直接タイトルを取得しました。

+0

'copy()'機能コードを投稿できますか? – Kev

+0

Kev、これを説明するサンプルコードをいくつか追加しました。これは迅速かつ汚れていることに注意してください。しかし、それは私の質問を説明しています。 –

答えて

1

私は、PG 9.1以降を除いて文を返すことができないのと同じ理由で動作していないと思います。これは、9.1で正常に動作する必要があります:

drop table if exists t cascade; 

create table t (
    identifier  serial  primary key, 
    title       text 
); 

insert into t (title) values ('title - old'); 

with copy as (
insert into t (title) select title from t where identifier = 1 
returning identifier 
) 
update t set title = 'title - new' from copy where t.identifier = copy.identifier; 

select * from t; 

編集:可能な9.0の提案は動作しませんでした。

+0

2番目のスニペットが9.04で動作しないことを確認できます。 – Kev

+0

剥がした。チェックしていただきありがとうございます(iPadではできません)。 –

+0

私はあなたの提案を9.1ベータ3で試してみましたが、それでも新しいタイトルが残っています。 (私は、更新ステートメントの 'コピーから'を追加しなければならなかった)。何か案は? –

関連する問題