2012-04-08 35 views
0

我曾經讀過的郵件列表中找到相關http://archives.postgresql.org/pgsql-hackers/2005-06/msg01481.phpPLPGSQL關聯數組argumnent

SELECT * 
FROM foo_func(
    c => current_timestamp::timestamp with time zone, 
    a => 2, 
    b => 5 
); 

現在我需要這個kindof解決方案,我可以通過關聯數組參數傳遞給函數。 我是否需要製作一個虛擬表,然後將該表用作參數類型?或者有任何直接的解決方法呢?或者這個黑客已經實施?

或者我可以使用pl/python模擬相同嗎?

+0

你的意思是你想hstore值傳遞到函數? http://www.postgresql.org/docs/9.0/static/hstore.html – Edmund 2012-04-08 09:17:32

+0

嗯不錯的選擇但我越來越'錯誤:類型「hstore」不存在'我正在使用8.4 – 2012-04-08 10:18:43

+0

啊,我認爲這只是當時的一個貢獻模塊。應該工作,如果你安裝它。 http://www.postgresql.org/docs/8.4/static/hstore.html – Edmund 2012-04-08 10:29:51

回答

2

下面是用於與hstore和PG-8.4爲Debian應答的步驟。

1)如果尚未安裝,安裝的contrib包

 
# apt-get install postgresql-contrib-8.4 

2)在相關數據庫

 
$ psql -U postgres -d dbname 
# \i /usr/share/postgresql/8.4/contrib/hstore.sql 

2之二)如果未安裝PLPGSQL語言,安裝它安裝hstore(仍在psql中作爲postgres用戶)

 
# CREATE LANGUAGE plpgsql; 

3)創建以hstore爲函數輸入。下面是plpgsql中的一個示例,其中列舉了鍵和值:

CREATE OR REPLACE function enum_hstore(in_h hstore) returns void 
as $$ 
declare 
    kv record; 
begin 
    for kv in select * from (select (each(in_h)).*) as f(k,v) loop 
    raise notice 'key=%,value=%',kv.k,kv.v; 
    end loop; 
end 
$$ language plpgsql; 

4)調用函數。由於鍵和值是文本類型,因此可能需要將文本中的非文字條目轉換爲問題中的current_timestamp調用。例如:

select enum_hstore(
    hstore('c',current_timestamp::text) || 
    'a=>2,b=>5'::hstore 
); 

結果從上面的功能期待:

 NOTICE: key=a,value=2 
NOTICE: key=b,value=5 
NOTICE: key=c,value=2012-04-08 16:12:59.410056+02 
+0

正在獲取:語言'plpgsql'在步驟3中不存在 – 2012-04-08 14:41:16

+0

然後步驟#2應該有額外的SQL命令:'CREATE LANGUAGE plpgsql' – 2012-04-08 14:51:09

+0

現在我有一個大錯誤。'ERROR:語法錯誤處於或接近'CREATE' LINE 2:CREATE OR REPLACE函數enum_hstore(in_h hstore)返回...'附註:如果我嘗試使用'language sql',我得到'語法錯誤在或接近'記錄「' – 2012-04-08 14:54:14

1

這在version 9.0實施:

4.3.2. Using named notation

In named notation, each argument's name is specified using := to separate it from the argument expression. For example:

SELECT concat_lower_or_upper(a := 'Hello', b := 'World'); 
concat_lower_or_upper 
----------------------- 
hello world 
(1 row) 
+0

謝謝,但我運行8.4我會在穩定的debian版本中獲得9.0嗎?以及如何在函數中處理這些鍵,值對? – 2012-04-08 09:49:37

+0

但名稱a和b必須是函數內參數的名稱,不是嗎?我不確定,但我認爲Neel的問題想要傳遞一個任意的關聯數組到該函數(儘管我可能是錯的)。 – Edmund 2012-04-08 10:32:08

+0

是的我需要傳遞任意關聯數組而不是參數。我很抱歉,如果我的問題導致不同的含義 – 2012-04-08 10:36:17