繁体   English   中英

如何在 postgresql 的事务中运行多个插入语句?

[英]How to run multiple insert statements in a transaction in postgresql?

BEGIN;

    DECLARE o_id int;
    DECLARE p_id int;

    INSERT INTO properties (address, created_at, updated_at)
    VALUES ('100 street, city, country, 1b1 b1b', current_timestamp, current_timestamp);
    
    INSERT INTO ownerships (share, created_at, updated_at)
    VALUES (1, current_timestamp, current_timestamp)
    RETURNING id INTO o_id;
    
    INSERT INTO profiles (first_name, last_name, created_at, updated_at)
    values ('j', 'p', current_timestamp, current_timestamp)
    RETURNING id INTO p_id;
    
    INSERT INTO profile_ownerships (profile_id, ownership_id, created_at, updated_at)
    VALUES (o_id, p_id, current_timestamp, current_timestamp);
    
COMMIT;

我正在尝试将这些插入行运行到属性、配置文件和所有权中。 然后返回连接表 profile_ownerships 的配置文件和所有权 ID。 上面的 sql 正在返回一个关于“returning id into Ownership_id;”的错误。 我不知道为什么。

原来这正是我想要的。 不过,仍然不确定为什么需要将其包装在 DO.. END 块中。 因此,如果有人对此有答案,我将不胜感激。

DO $$
DECLARE
    o_id INTEGER;
    p_id INTEGER;

BEGIN

    INSERT INTO properties (address, created_at, updated_at)
    VALUES ('test 7', current_timestamp, current_timestamp);

    INSERT INTO ownerships (shares, created_at, updated_at)
    VALUES (4, current_timestamp, current_timestamp)
    RETURNING id INTO o_id;

    INSERT INTO profiles (first_name, last_name, created_at, updated_at)
    VALUES ('p', 'j', current_timestamp, current_timestamp)
    RETURNING id INTO p_id;

    INSERT INTO profile_ownerships (profile_id, ownership_id, created_at, updated_at)
    VALUES (p_id, o_id, current_timestamp, current_timestamp);
    
END $$;

暂无
暂无

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

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