简体   繁体   English

在pl / pgsql中的表中插入一行

[英]insert a row into table in pl/pgsql

I am trying to update two tables by inserting some rows into the other. 我试图通过将一些行插入另一个来更新两个表。 But when I try to do something like this : 但是当我尝试做这样的事情时:

BEGIN
    FOR id IN (SELECT id FROM table1) LOOP
     PERFORM (INSERT INTO anothertable VALUES(id));
    END LOOP;
END;

It gives an error I don't know why. 它给出了一个我不知道为什么的错误。 syntax error at or near "INTO" . syntax error at or near "INTO"

Is it even possible to do such thing without cursors and such updating one by one ? 甚至没有游标就可以做这样的事情,并且可以一一更新吗?

This is example of bad using PERFORM and bad plpgsql programming style. 这是使用PERFORM的错误和plpgsql编程样式的错误的示例。 You must not use a PERFORM there. 您不得在此处使用PERFORM。 You should not use a parenthesis there (PL/pgSQL is based on ADA language - not C!). 您不应该在此处使用括号(PL / pgSQL基于ADA语言-而不是C!)。 Some correct patterns are: 一些正确的模式是:

FOR _id IN 
          SELECT s.id 
             FROM sometab s
LOOP
  INSERT INTO othertab(id) VALUES(_id);
END LOOP;

or faster (and shorter) pattern 或更快(或更短)的模式

INSERT INTO othertab(id)
   SELECT id 
       FROM other tab

I used a qualified name and prefixes to reduce a risk of conflict between SQL identifiers and PL/pgSQL variables. 我使用了合格的名称和前缀来减少SQL标识符和PL / pgSQL变量之间发生冲突的风险。

Note: PERFORM is implemented as SELECT statement without result processing. 注意:PERFORM被实现为SELECT语句,而没有结果处理。 So your statement was SELECT (INSERT INTO tab ...) what is unsupported feature now. 因此,您的声明是SELECT(INSERT INTO选项卡...),现在不支持该功能。

why don't you insert it like this: 为什么不这样插入呢?

insert into anothertable
select id from table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM