我在我的用户定义函数中遇到错误,并且在某种程度上,我理解错误(无法识别的列),但不是为什么它会被引起。以下是重现错误的最小代码:
create table foo (id serial primary key, name varchar not null);
create table bar (id serial primary key, name varchar not null);
create function foo_to_bar(foo_id int) returns void as $$
begin
with _name as (
select name from foo where id = foo_id
)
insert into bar (name) values (_name);
-- error here: ~~~~~
end;
$$ language plpgsql;
insert into foo (name) values ('slimshady');
-- id of first entry will be 1
select foo_to_bar(1);
错误:
ERROR: column "_name" does not exist
LINE 4: insert into bar (name) values (_name)
^
HINT: Perhaps you meant to reference the column "bar.name".
QUERY: with _name as (
select name from foo where id = foo_id
)
insert into bar (name) values (_name)
为什么它完全忽略我在_name
子句中创建的with
,在上面三行中出现错误?我该如何解决这个问题?
答案 0 :(得分:2)
_name
不是变量,它是派生表名,所以你的陈述应该是
with _name as (
select name from foo where id = foo_id
)
insert into bar (name) select name from _name;