database - PostgreSQL:无法在规则的内部查询中引用 NEW

标签 database postgresql

这是对 PostgreSQL: Inserting into a View made from two tables 的后续问题

我已经改变了我的规则:

CREATE RULE Insert_Post AS ON INSERT TO abcd1234.Posts DO INSTEAD
(
    WITH Temp AS
    (
        INSERT INTO abcd1234.Ratable_Entity VALUES
            (NEW.Id, NEW.User_Id, NEW.Publish_Date)
            RETURNING Id
    )
    INSERT INTO abcd1234.Post
        (SELECT Id, NEW.Title, NEW.Content FROM Temp)
);

但是现在我遇到了以下错误:

ERROR:  cannot refer to NEW within WITH query

有什么不同的方法吗?我也试过在没有 WITH 的情况下执行 RETURNING Id INTO temp_id,但出现语法错误。

最佳答案

为此创建函数:

/*
drop rule if exists ri_vt on vt;
drop function if exists fn_ivt(text, text);
drop view if exists vt;
drop table if exists t2;
drop table if exists t1;
*/
create table t1(i serial, x text);
create table t2(i serial, t1_i int, y text);
insert into t1(x) values('foo');

create view vt as select t1.i, x, y from t1 left join t2 on (t1.i = t2.t1_i);

create function fn_ivt(p_x text, p_y text) returns setof vt language sql as $$
  with ins_t1 as (insert into t1(x) values(p_x) returning *)
    insert into t2(t1_i, y) select ins_t1.i, p_y from ins_t1 returning t1_i as i, p_x, p_y
$$;

create rule ri_vt as on insert to vt do instead select * from fn_ivt(new.x, new.y);

insert into vt(x,y) values('a','b'),('c','d');
select * from vt;

╔═══╤═════╤══════╗
║ i │  x  │  y   ║
╠═══╪═════╪══════╣
║ 1 │ foo │ ░░░░ ║
║ 2 │ a   │ b    ║
║ 3 │ c   │ d    ║
╚═══╧═════╧══════╝
(3 rows)

关于database - PostgreSQL:无法在规则的内部查询中引用 NEW,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40641990/

相关文章:

database - 如何决定是否需要从 sqlite 过渡

sql - 删除约束时出现错误消息

sql - 如何使用时间戳正确处理夏令时

sql - SQL 中 1 总是等于 '1' 吗?

PHP - 用于将某些 HTML 标签列入白名单的插件或库

mysql - 如何构建具有多个连接表的数据库

sql - 是否所有 RDBMS 都有可与 Oracle 相媲美的数据字典?

mysql - 将大型 csv 导入规范化关系数据库(具有多个表)的最佳实践是什么

SQL 语句 - 问题

sql - PostgreSQL 如果删除临时表查询为空