PL/pgSQL语法错误

9

我有一个非常简单的PL/pgSQL脚本:

     declare x varchar(100);

当我运行它时,会出现以下提示信息:
    [WARNING  ] declare x varchar(100)
        ERROR:  syntax error at or near "varchar"
        LINE 1: declare x varchar(100)
                          ^

我真的不明白这个有什么问题。

展示整个创建函数脚本。 - Clodoaldo Neto
这是整个脚本。 - user1544745
2
您必须将其封装在 create function 命令中。 - Clodoaldo Neto
1
这不是一个完整(且语法正确)的 PL/pgSQL “脚本”。 - user330315
3个回答

25

在PostgreSQL中,您只能在函数体内使用过程语句

Translated:

you can use procedural statements only inside function body in PostgreSQL.

CREATE OR REPLACE FUNCTION foo()
RETURNS int AS 
$$ -- here start procedural part
   DECLARE x int;
   BEGIN
     x := 10;
     RETURN x;
   END;
$$ -- here finish procedural part
LANGUAGE plpgsql; -- language specification 

或者在临时函数(匿名块)中

DO $$
DECLARE x int;
BEGIN
  x := 10;
  RAISE NOTICE '>>>%<<<', x;
END;
$$;

不能像T-SQL那样将过程性语句用作SQL语句。


0
我通过以下代码解决了这个问题:
do $$
declare TypeId int;
declare MasterId int;
begin
   TypeId := null;
   MasterId := null;
end;
$$;

0

使用示例

DO $$
Declare
  test varchar;
begin
   test := 'teste';
   if (char_length(test) > 0) then
      RAISE NOTICE '>>>%<<<', test;
   end if;
end;
$$;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接