【问题标题】:Execute a query for every row of a table inside a trigger function对触发器函数内的表的每一行执行查询
【发布时间】:2017-04-28 06:15:44
【问题描述】:

我做了以下查询,它本身就很完美,但是当我在触发函数中调用它时,我遇到了问题。

select insert_new_grade('title0', return3_6(0), return3_6(1), return3_6(2), s.code)
FROM "student" as s
where find_st(s.grade)>=5;

insert_new_grade 是一个函数,每次调用时都会在表中插入一个新行。

这里是触发器:

CREATE OR REPLACE FUNCTION insert_d() 
RETURNS TRIGGER AS $$ 
BEGIN
    select insert_new_grade('title0', return3_6(0), return3_6(1), return3_6(2), s.code)
    FROM "student" as s
    where find_st(s.grade)>=5;

    return new;
END;
$$ LANGUAGE plpgsql; 

这里是插入函数:

CREATE OR REPLACE FUNCTION insert_new_grade(title0 character(100), prof0 character(11), prof1 character(11)) 
RETURNS VOID AS $$
BEGIN
    INSERT INTO "d_table"(thes0, title, grade, prof, secProf) 
    VALUES (null, title0, null, prof0, prof1);
END
$$
LANGUAGE 'plpgsql';

有没有办法让查询在触发器函数中工作?如果我使用执行而不是选择插入功能没有结果。我读过游标,但我是 postgresql 的新手,我不知道该怎么做。有什么帮助吗?

【问题讨论】:

标签: sql postgresql function cursors


【解决方案1】:

我修改了你的触发功能:

在关闭 pgAdmin 中检查您的触发功能,是否可见 raise info 文本

CREATE OR REPLACE FUNCTION insert_d() 
RETURNS TRIGGER AS $$ 
declare
    rec record;
BEGIN

    for rec in (select * from student s where find_st(s.grade)>=5) loop

        raise info 'LOOP code = %',rec.code;
        PERFORM insert_new_grade('title0', return3_6(0), return3_6(1), return3_6(2), rec.code);

    end loop;

    return new;
END;
$$ LANGUAGE plpgsql; 

【讨论】:

  • @AthanasiaPavlidou,尝试不使用where find_st(s.grade)>=5 可能是错误
猜你喜欢
  • 1970-01-01
  • 2011-12-04
  • 2014-12-09
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 2016-03-05
相关资源
最近更新 更多