我正在尝试使以下功能起作用:
CREATE OR REPLACE FUNCTION validate_count(devices TEXT[], campaign_id INTEGER) RETURNS void AS $$
DECLARE
devices_array TEXT[] := devices;
devices_count INTEGER := array_length(devices, 1);
row_id INTEGER := campaign_id;
BEGIN
FOR device IN unnest(devices_array) LOOP
IF my_count('my_table', device, row_id) != 1;
RAISE EXCEPTION 'invalid_count %', row_id
ENDIF
END LOOP;
END
$$ LANGUAGE plpgsql;
my_count
是一个工作函数,返回INTEGER。
定义失败,并显示以下错误:
ERROR: syntax error at or near "unnest"
LINE 7: FOR device IN unnest(devices_array) LOOP
您能发现问题吗?谢谢!
我打算如下调用该函数:
select validate_count('{foo, bar}', 1)
答案 0 :(得分:1)
使用FOREACH循环:
CREATE OR REPLACE FUNCTION validate_count(devices TEXT[], campaign_id INTEGER)
RETURNS void
AS
$$
DECLARE
device text;
devices_count INTEGER := array_length(devices, 1);
BEGIN
FOREACH device IN ARRAY devices LOOP
IF my_count('my_table', device, campaign_id) <> 1 then
RAISE EXCEPTION 'invalid_count %', campaign_id;
END IF;
END LOOP;
END
$$
LANGUAGE plpgsql;
答案 1 :(得分:1)
需要做一些修改才能使其生效。
FOR
循环在SELECT
之前需要unnest
,即:
FOR device IN SELECT unnest(devices_array) LOOP
您需要在顶部声明device
,例如:
DECLARE device RECORD;
IF
语句需要THEN
而不是;
,即:
IF my_count('my_table', device, row_id) != 1 THEN
RAISE EXCEPTION
语句在行末需要一个分号,即:
RAISE EXCEPTION 'invalid_count %', row_id;
END
语句的IF
应该是END IF;
。
END
语句的LOOP
应该是END LOOP;
。
这是最终结果:
CREATE OR REPLACE FUNCTION validate_count(devices TEXT[], campaign_id INTEGER) RETURNS void AS $$
DECLARE
devices_array TEXT[] := devices;
devices_count INTEGER := array_length(devices, 1);
row_id INTEGER := campaign_id;
device RECORD;
BEGIN
FOR device IN SELECT unnest(devices_array) LOOP
IF my_count('my_table', device, row_id) != 1 THEN
RAISE EXCEPTION 'invalid_count %', row_id;
END IF;
END LOOP;
END
$$ LANGUAGE plpgsql;