0
create or replace function fibonacci(int) returns int 
as $$
declare
    a int;
    res int := 0;
begin
    a := $1;
    if(a = 1 or a = 2) then
        res :=1;
    else
        res := fibonacci(a - 2) + fibonacci(a - 1);
    end if;
    return res;
end;
language plpgsql;

显示的错误消息并且我没有看到错误,因为我以多种方式进行了探测,同样继续显示的是斐波那契数列

ERROR:  una cadena separada por $ está inconclusa en o cerca de «$$
declare
    a int;
    res int := 0;
begin
    a := $1;
    if(a = 1 or a = 2) then
        res :=1;
    else
        res := fibonacci(a - 2) + fibonacci(a - 1);
    end if;
    return res;
end;
language plpgsql;»
LINE 3: as $$
           ^
SQL state: 42601
Character: 106
4

1 回答 1

0

听起来像意大利语版本的:

错误:在“$$”处或附近未终止的美元引号字符串

那是因为缺少收盘美元报价:

create or replace function fibonacci(int) returns int 
as $$
declare
    a int;
    res int := 0;
begin
    a := $1;
    if(a = 1 or a = 2) then
        res :=1;
    else
        res := fibonacci(a - 2) + fibonacci(a - 1);
    end if;
    return res;
end;
$$                 -- !!!
language plpgsql;

看:

但是您可以在很大程度上简化 PL/pgSQL 函数:

CREATE OR REPLACE FUNCTION fibonacci(int)
  RETURNS int
  LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE AS
$func$
BEGIN
   IF $1 IN (1,2) THEN
     RETURN 1;
   ELSE
     RETURN fibonacci($1 - 2) + fibonacci($1 - 1);
   END IF;
END
$func$;

或者使用更简单的 SQL 函数:

CREATE OR REPLACE FUNCTION fibonacci(int)
  RETURNS int
  LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
$func$
SELECT CASE WHEN $1 IN (1,2)
            THEN 1
            ELSE fibonacci($1 - 2) + fibonacci($1 - 1) END;
$func$;
于 2022-01-30T04:14:56.073 回答