为什么这个PL / PgSql无效?

问题描述 投票:0回答:1

N00bie PL / PgSql问题:

create or replace function foo() returns int as $$
declare fff int;
begin
    declare fff int;
    select count(*) into fff from mytable;
    return fff;
end 
$$ language plpgsql

输出:

ERROR:  syntax error at or near "*"
LINE 5:   select count(*) into fff from mytable;
                 ^
CONTEXT:  invalid type name "count(*) into fff from mytable"

我究竟做错了什么?

postgresql plpgsql
1个回答
2
投票

你需要从declare块中删除begin/end

create or replace function foo() returns int as $$
declare fff int;
begin
    --   declare fff int;
    select count(*) into fff from mytable;
    return fff;
end 
$$ language plpgsql

db<>fiddle

啊。对。那么你能不在BEGIN ... END块中声明一个变量吗?

你在declare部分声明了变量。如果你需要,你可以嵌套块:

create or replace function foo() returns int as $$
declare fff int;
begin
    declare xxx INT;
    begin
    select count(*) into xxx from mytable;
    return xxx;
    end;
end 
$$ language plpgsql
© www.soinside.com 2019 - 2024. All rights reserved.