2013-06-05 24 views
0

下面是一個函數,它有一個查詢,轉換成PostgreSQL動態查詢

現在我想轉換成動態查詢。我想要一個表名參數,以便查詢從多個表中返回數據。

請幫助我在這我在PostgreSQL新,感謝提前!

create or replace function GetEmployees() 
returns setof weather as 
'select * from weather;' 
language 'sql'; 
+2

您應該始終參考文檔。相信我,這是程序員最好的朋友。 http://www.postgresql.org/docs/current/static/sql-createfunction.html –

+0

Anu,這是一個後續http://stackoverflow.com/questions/16937848/convert-sql-server- stored-procedure-into-postgresql-stored-procedure? –

+0

如果你想傳遞表名,你不能輕易地將它作爲「返回setof」函數,因爲傳遞的表名可能與「weather」表有完全不同的結構。 –

回答

2

這是基本的PL/PgSQL。使用PL/PgSQL的EXECUTE .. USING statementformat函數與%I格式說明符。

create or replace function get_sometable(tablename regclass) 
returns setof whatever_type as 
BEGIN 
RETURN QUERY EXECUTE format('select * from %I";', tablename); 
END; 
language 'plpgsql'; 

這隻有在您可能傳遞的所有表名與返回兼容結果類型相同時才起作用,與分區一樣。否則,您必須返回SETOF RECORD,然後在函數調用中傳遞表格佈局。有關RECORDSETOF RECORD的討論,請參閱文檔。

查看RETURNS TABLE作爲表格類型不兼容的另一種方便的替代方法,但仍然可以通過合適的SELECT列表返回兼容的子集。

如果你正在進行表分區,你應該真的這樣做as the PostgreSQL documentation on table partitioning advises,使用表繼承和觸發器。

(詳細描述在Convert SQL Server stored procedure into PostgreSQL stored procedure