Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
postgresql无法识别WITH子句中引入的变量名_Sql_Postgresql - Fatal编程技术网

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

postgresql无法识别WITH子句中引入的变量名,sql,postgresql,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

我在用户定义的函数中遇到了一个错误,在某种程度上,我理解这个错误(无法识别的列),但不理解它的原因。以下是重现错误的最小代码:

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)

为什么它完全忽略了我在
with
子句中创建的
\u名称
,该子句位于引发错误的三行之上?如何修复此问题?

\u name
不是一个变量,它是一个派生表名,因此您的语句应该如下所示

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

\u name
不是一个变量,它是一个派生表名,因此您的语句应该如下所示

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

啊,我明白了。谢谢你的快速回答!如果有其他函数参数需要插入到
bar
,我将如何将它们添加到
insert
语句中?明白了
insert into bar(name,otherfield)从_name
中选择name,_otherfield,其中_otherfield是函数的附加参数,我明白了。谢谢你的快速回答!如果有其他函数参数需要插入到
bar
,我将如何将它们添加到
insert
语句中?明白了<代码>插入栏(名称,其他字段)从_name中选择名称,_otherfield,其中_otherfield是函数的附加参数