简体   繁体   English

postgresql试图调用update返回多行

[英]postgresql trying to call update returning multiple rows

this example statement works fine in postgresql 9.1 and above. 这个示例语句在postgresql 9.1及更高版本中运行正常。 Unfortunately it does not work in older versions, the reason being that update does not support the with statement. 不幸的是,它在旧版本中不起作用,原因是更新不支持with语句。 How can I put the RETURNING in an array? 如何将RETURNING放入数组中? I am writing a function using plpgsql. 我正在使用plpgsql编写一个函数。

begin

create table testing(
i serial,
t text);

insert into testing
(t)
values (null),(null),(null);

with abc AS (
update testing
set t = null
returning i )
select array_agg(i)
from abc;

rollback

Thank you for your help! 谢谢您的帮助!

Unfortunately you can't do that on versions prior to 9.1, as writable common table expressions (AKA wCTE) was available only at 9.1 (see "Writable Common Table Expressions" on PostgreSQL feature matrix ). 遗憾的是,你不能在9.1之前的版本上做到这一点,因为可写的公用表表达式(AKA wCTE)仅在9.1处可用(参见PostgreSQL特征矩阵中的 “可写公用表表达式”)。

The only solution I can see is this case is doing this on your application or using a function, like: 我能看到的唯一解决方案是这种情况是在您的应用程序上执行此操作或使用函数,如:

CREATE OR REPLACE FUNCTION test()
RETURNS int[]
VOLATILE
LANGUAGE plpgsql AS $$
DECLARE
    ret int[];
    aux int;
BEGIN
    ret := '{}';
    FOR aux IN
        UPDATE testing
        SET t = null
        RETURNING i
    LOOP
        ret := ret || aux;
    END LOOP;
    RETURN ret;
END;
$$;

In any case, if you are using a version older than that, I'd recommend you to upgrade to the newer version (now 9.3) as soon as possible. 在任何情况下,如果您使用的是旧版本,我建议您尽快升级到较新版本(现在为9.3)。 The 8.4 version is about to lost support, and 9.0 will lost next year (see versioning policy ). 8.4版本即将失去支持,明年将丢失9.0(参见版本控制政策 )。

EDIT: 编辑:

To left a reference for those using PostgreSQL 9.1+, the above can be done with wCTE as the following: 要为使用PostgreSQL 9.1+的用户留下参考,可以使用wCTE完成上述操作,如下所示:

WITH updt AS (
    UPDATE testing
    SET t = null
    RETURNING i
)
SELECT array_agg(i) FROM updt;

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

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