2014-01-21 26 views
0

我想在PostgreSQL創建一個用戶定義的函數:無法創建一個簡單的PostgreSQL函數

CREATE FUNCTION get_balance(user_id integer, statuses integer[]) RETURNS INTEGER 
AS $$ 
select SUM(table1.credit) 
from table1 

inner join table2 
on table2.field1 = table1.id 

inner join table3 
on table3.field1 = table2.id 
where table3.status_id in (statuses); $$ 

LANGUAGE SQL; 

的錯誤是:

ERROR: operator does not exist: integer = integer[] 
LINE 11: where table3.status_id in (statuses); $$ 

我在做什麼錯?

回答

1

此:

table3.status_id in (statuses) 

可以簡化的例子爲:

regress=> SELECT 1 IN (ARRAY[1,2,3]); 
ERROR: operator does not exist: integer = integer[] 
LINE 1: SELECT 1 IN (ARRAY[1,2,3]); 
       ^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 

...但IN預計文字列表,如:

regress=> SELECT 1 IN (1, 2, 3); 

既然你想要傳遞一個數組,你需要使用= ANY(...),它需要一個數組輸入:

regress=> SELECT 1 = ANY (ARRAY[1,2,3]); 
?column? 
---------- 
t 
(1 row)