函数中的for循环无效

时间:2019-03-14 14:18:17

标签: postgresql function loops

我正在尝试使以下功能起作用:

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)

2 个答案:

答案 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;