一个接受SELECT查询结果的PostgreSQL函数。

huangapple go评论123阅读模式
英文:

postgres function that takes the result of a select query

问题

我正在尝试编写一个 PostgreSQL 函数,该函数接受一个 SELECT 语句的结果作为参数。需要注意的是,我在语句级触发器的上下文中,因此我有 NEWOLD 伪表,并且我想将它们作为参数调用一个函数。

我想能否从类似的 UPDATE 触发器中调用 the_other_func,该触发器也包含伪表。

这种情况是否可行?谢谢!(我使用的是 PostgreSQL 14)

英文:

I'm trying to write a postgres function that takes the result of a select. The detail that requires this use-case is that I'm within the context of a statement-level trigger, so I have the NEW and OLD pseudo-tables, and I'd like to call a function with them as the argument.

  1. CREATE TRIGGER my_trg
  2. AFTER INSERT ON my_table
  3. REFERENCING
  4. NEW TABLE AS my_inserted_records
  5. FOR EACH STATEMENT
  6. EXECUTE PROCEDURE my_trigger_func();
  1. CREATE FUNCTION my_trigger_func()
  2. RETURNS TRIGGER
  3. AS $$
  4. BEGIN
  5. SELECT the_other_func(
  6. (SELECT * FROM my_inserted_records)
  7. );
  8. RETURN NULL;
  9. END;
  10. $$ LANGUAGE plpgsql;
  1. CREATE FUNCTION the_other_func(
  2. ...what here???...
  3. )
  4. RETURNS JSONB
  5. AS $$
  6. -- do something
  7. $$ LANGUAGE sql;

I want to be able to call the_other_func from a similar UPDATE trigger, which also contains the pseudo-tables.

Is this possible? Thanks! (I'm using postgres 14)

答案1

得分: 1

你无法从这里到达那里,函数参数必须是单个值,包括记录类型和数组,但不能是结果集或表格。

寻找一种方法,使the_other_func成为触发函数,也许可以使用参数来为不同的表格自定义其操作。这可能比以下的解决方案更清晰。

由于允许使用数组,你可以尝试使用记录的数组。

  1. CREATE FUNCTION my_trigger_func()
  2. RETURNS TRIGGER
  3. AS $$
  4. BEGIN
  5. PERFORM the_other_func (array_agg(i))
  6. FROM my_inserted_records AS i ;
  7. RETURN NULL;
  8. END;
  9. $$ LANGUAGE plpgsql;

其中,the_other_func的定义如下:

  1. CREATE FUNCTION the_other_func(
  2. newdata my_table[]
  3. )
  4. ...
英文:

you can't get there from here, function arguments must be single values, including record types and arrays, but not result-sets or tables.

look for a way to have the the_other_func be a trigger function
perhaps using arguments customize its operation for different tables. that will probably be a cleaner solution than the following

As arrays are allowed perhaps you could try an array of records.

  1. CREATE FUNCTION my_trigger_func()
  2. RETURNS TRIGGER
  3. AS $$
  4. BEGIN
  5. PERFORM the_other_func (array_agg(i))
  6. FROM my_inserted_records AS i ;
  7. RETURN NULL;
  8. END;
  9. $$ LANGUAGE plpgsql;

with the otherfunc being defined as.

  1. CREATE FUNCTION the_other_func(
  2. newdata my_table[]
  3. )
  4. ...

huangapple
  • 本文由 发表于 2023年8月9日 04:01:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定