postgresql无法识别WITH子句中引入的变量名

时间:2017-09-28 19:41:08

标签: sql postgresql

我在我的用户定义函数中遇到错误,并且在某种程度上,我理解错误(无法识别的列),但不是为什么它会被引起。以下是重现错误的最小代码:

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,在上面三行中出现错误?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

_name不是变量,它是派生表名,所以你的陈述应该是

with _name as (
    select name from foo where id = foo_id
)
insert into bar (name) select name from _name;