How to select into multiple variables inside a trigger function?

时间:2019-01-09 22:04:26

标签: postgresql plpgsql database-trigger

This is what I'd like to achieve:

CREATE FUNCTION f() RETURNS trigger AS $$
  BEGIN
    SELECT COUNT(*) AS total_num, SUM(width) AS total_width
    FROM some_table WHERE foo = NEW.foo;
    IF total_num > 0 AND total_width > 100
    THEN
      RAISE EXCEPTION 'this is bad';
    END IF;
    RETURN NEW;
  END;
$$ LANGUAGE plpgsql;

But it's not yet syntactically correct.

I've read I first need to DECLARE the variables (in this case total_num and total_width) so I can use those and use SELECT INTO but I've seen examples with a single variable / SELECT statement only. What if I have more of them?

2 个答案:

答案 0 :(得分:1)

Edit: I'm not sure whether the emphasis here is on the use of variables or the actual IF. This is meant as an answer on the latter:


You can do this without variables using HAVING and EXISTS.

IF EXISTS (SELECT ''
                  FROM some_table
                  WHERE foo = new.foo
                  HAVING count(*) > 0
                         AND sum(width) > 100) THEN
  RAISE EXCEPTION 'this is bad';
END IF;

答案 1 :(得分:1)

You can list multiple variables in the into part. And the declare section needs to come before the first begin:

CREATE FUNCTION f() RETURNS trigger 
AS $$
declare
  total_num bigint;
  total_width bigint;
BEGIN
   SELECT COUNT(*), SUM(width)
       into total_num, total_width
   FROM some_table 
   WHERE foo = NEW.foo;

   IF total_num > 0 AND total_width > 100 THEN
      RAISE EXCEPTION 'this is bad';
   END IF;
   RETURN NEW;
END;
$$ LANGUAGE plpgsql;