尝试从更新中设置变量不起作用

时间:2017-05-05 08:51:37

标签: sql postgresql sql-update plpgsql

有人能指出我以下代码有什么问题吗? 它看起来像完全合法的语法,但当我运行它时,我得到:

ERROR:  syntax error at or near "conctest"
LINE 7:  ret_id := (update conctest set id=id+1 where name = 'Billy ...
                           ^
********** Error **********

ERROR: syntax error at or near "conctest"
SQL state: 42601
Character: 66

代码破碎:

DO $$

    declare ret_id integer;

begin

    ret_id := (update conctest set id=id+1 where name = 'Billy Bob' returning id);

    DROP TABLE IF EXISTS tmpTable;
    CREATE TEMPORARY TABLE tmpTable AS
        select  ret_id;

END $$;

select * from tmpTable;

这有效:

DO $$

    declare ret_id integer;

begin

    update conctest set id = id + 1 where name = 'Billy Bob';
    ret_id := (select id from conctest where name = 'Billy Bob');

    DROP TABLE IF EXISTS tmpTable;
    CREATE TEMPORARY TABLE tmpTable AS
        select ret_id;

END $$;

select * from tmpTable;

顺便说一句,我从工作的SQL查询窗口复制了update子句,并手动添加了" returning id",因此没有奇怪的字符。 怎么了?

TVMIA,

亚当。

1 个答案:

答案 0 :(得分:0)

根据docs

  

UPDATE ... RETURNING表达式INTO [STRICT]目标;

尝试使用into代替:

t=# create table s111(i int);
CREATE TABLE
Time: 37.521 ms
t=# insert into s111 select 1;
INSERT 0 1
Time: 1.016 ms
t=# do
$$
declare _i int;
begin
update s111 set i =2 returning i into _i;
raise info '%',_i;
end;
$$
;
INFO:  2
DO
Time: 0.944 ms