2016-02-27 149 views
1

我需要在對錶進行SELECT操作之前調用postgreSQL中的FUNCTION。我的第一個想法是使用TRIGGER,但看起來你不能在選擇時觸發。執行函數首先在Postgres中

因此,要解決這個問題,我創建了一個VIEW,它可以同時在表和函數上運行select。即:

CREATE VIEW people_view AS 
    SELECT get_department(), name, title, department 
    FROM people_table 

所以,簡而言之...的get_department()函數將更新來自外部數據的部門列(這是所有采用國外的數據表和包裝)。

問題是,該函數執行後名稱,標題,部門被選中,而不是之前。所以如果我運行一次它不起作用。如果我運行它兩次它(因爲它在第一次運行後更新)。

對不起,如果這沒有多大意義。我通常不做數據庫工作。我想要做的是讓「get_department()」在SELECT中首先執行。我試圖把這個函數調用放在一個子查詢中,但它仍然沒有先執行。我留下的唯一想法可能是強制命令的明確聯合?我不知道:-(。

基本上,我只是想在運行查詢的人透明地SELECT之前執行一個函數...我想你不能用觸發器做到這一點,如果有更好的解決方法,我會很樂意給它一展身手。

感謝, Isekal

回答

2
with t(x) as (
    select get_department()) -- Function executes here 
select 
    t.x, ... 
from 
    t, people_table -- You does not provide any relation between your function and table... 

還檢查LATERAL功能。

+0

這工作完美!我從來不知道是否存在(現在我沒有做很多數據庫工作)。不幸的是,我在9.2上,所以LATERAL不是一種選擇(儘管我可能會升級)。 – isekal

1

可能是你構建返回你的表,包括選擇數據之前調用你的函數的函數。

CREATE OR REPLACE FUNCTION people_table() 
    RETURNS TABLE(name character varying, title character varying, department character varying) AS 
$BODY$ 
    BEGIN 

    -- do function call 
    SELECT get_department(); 

    RETURN QUERY 
    SELECT people_table.* FROM people_table;  

    END; 
    $BODY$ 
    LANGUAGE plpgsql VOLATILE 
    COST 100 
    ROWS 1000; 

-- then, later in your code, use table selecting on the new function 
    SELECT * from people_table(); 

-- notice the use of parenthesis. 

-- you may also 
    SELECT name FROM people_table() ORDER BY department DESC; 
-- and use the function as if it were the table itself. 

希望它他LPS。

相關問題