2016-06-21 53 views
3

是否可以在更新語句中引用/訪問/傳遞當前記錄?如何訪問更新語句中的當前記錄

CREATE TABLE t1 (
    id serial PRIMARY KEY, 
    name text 
); 

CREATE TABLE t2 (
    id serial PRIMARY KEY, 
    name text, 
    foo text 
); 

CREATE FUNCTION gen_t2_foo(_a t1, _b t2) RETURNS text AS $$ 
    SELECT _a.name || ' - ' || _b.name; 
$$ LANGUAGE sql; 

CREATE FUNCTION upd_t2(_min_id int, _max_id int, _a t1) RETURNS VOID AS $$ 
    UPDATE t2 SET 
    foo = gen_f2_name(_a, ???) -- How to pass the current t2 record? 
    WHERE id >= _min_id AND id <= _max_id; 
$$ LANGUAGE sql; 

回答

3

只是參考下表:

create function upd_t2(_min_id int, _max_id int, _a t1) 
returns void as $$ 
    update t2 
    set foo = gen_t2_foo (_a, t2) 
    where id >= _min_id and id <= _max_id; 
$$ language sql; 
+0

嗯,感謝的人! – hooblei

+0

...或使用別名'UPDATE s1.t1 r SET foo = gen_t2_foo(_a,r)...' – hooblei

1

它看起來第二功能,預計這兩個表中創建一個從外地name的值,並開始和結束指數之間,對不對?在這種情況下,請確保gen_t2_foo也接收索引以合併單個記錄的值(在兩個表中)。然後,你可以像你想的那樣使用它。

順便說一下,爲什麼你聲明upd_t2作爲返回VOID的函數?這將是什麼程序提供。