在循环中移动/获取光标(PostgreSQL)

时间:2013-05-21 17:52:57

标签: postgresql

我需要创建触发器来检查新插入元素的 id 是否不重复。问题出在LOOP语句中,控制台吐出错误:

CONTEXT:  SQL statement in PL/PgSQL function "foo" near line 7
LINE 1: move forward 1 from  $1

这是我的功能:

create function foo() returns trigger as'
declare xyz cursor for select id from accounts; 
    begin
        LOOP
            if NEW.id = xyz then
                raise notice ''Id is just used!'';
            else
                move forward 1 from xyz;
            end if;
        END LOOP;
    return NEW;
    close xyz;
    end;
' language 'plpgsql';

create trigger foo before insert on accounts for each
row execute procedure foo();

1 个答案:

答案 0 :(得分:1)

您的示例没有意义(您无法将标量值与游标进行比较)。光标自身就像没有任何值的指针。

  if NEW.id = xyx then

你为什么不这样做

BEGIN
  IF EXISTS(SELECT * FROM accounts a WHERE a.id = NEW.id) THEN
    RAISE NOTICE ''Id is used''; -- better RAISE EXCEPTION
  END IF;
  RETURN NEW;
END;

第二个废话

  RETURN NEW;
  CLOSE xyz; -- no statement is executed after RETURN