【发布时间】:2013-07-10 04:21:21
【问题描述】:
我有一个函数可以根据客户 ID 返回一个计算值表。我需要为所有客户获取价值;我做了一个游标,但我不能让它返回集合。
客户表:
id name
---- ----
CN102 Dude
CN103 Guy
CN104 Mate
功能:
SELECT * FROM get_custom_fields('CN104');
name field_value
---- -----
POP 9
Z44 blue
POP 19
请注意,可能有多行具有相同的名称。 这是我的光标:
CREATE OR REPLACE FUNCTION my_cursor ()
RETURNS SETOF RECORD AS $$
DECLARE
v_customer_rec RECORD;
v_pop RECORD;
BEGIN
FOR v_customer_rec IN SELECT ucn FROM customer LOOP
SELECT INTO v_pop field_value from get_custom_fields(v_customer_rec.ucn) where custom_field='POP';
RAISE NOTICE 'Customer % Value %', v_customer_rec.ucn,v_pop;
-- RETURN QUERY select field_value from get_custom_fields(v_customer_rec.ucn) where custom_field='POP';
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
这会返回:
db=# select my_cursor();
NOTICE: Customer CN102 Value (5)
NOTICE: Customer CN103 Value (12)
NOTICE: Customer CN104 Value (9)
NOTICE: Customer CN104 Value (19)
my_cursor
-------------
(0 rows)
所以我知道它应该工作。但是如果使用RETURN QUERY(如代码中所述)我会收到以下错误:
ERROR: set-valued function called in context that cannot accept a set CONTEXT: PL/pgSQL function "my_cursor" line 9 at RETURN QUERY
如何让它返回表或集合中的值?
我想得到:
ucn field_value
----- -----------
CN102 5
CN103 12
CN104 9
CN104 19
【问题讨论】:
-
函数
active_customers()在哪里定义的? -
我没有包含它,因为它只是在顶部吐出了客户表。假装它是来自客户的精选 *。
-
那么你应该在你的问题中使用
select * from customer。请修复它,所以它对公众有意义,而不仅仅是对你。在您的问题下方使用edit...
标签: postgresql types cursor postgresql-9.1 plpgsql