我尝试编写简单的函数:
CREATE OR REPLACE FUNCTION add_mail_settings_column() RETURNS void AS $$
BEGIN
asd text := 'asd';
END $$
LANGUAGE plpgsql;
但它不起作用:
ERROR: syntax error at or near "asd"
LINE 3: asd text := 'asd';
但是如果我按如下方式移动它:
CREATE OR REPLACE FUNCTION add_mail_settings_column() RETURNS void AS $$
DECLARE
asd text := 'asd';
BEGIN
END $$
LANGUAGE plpgsql;
它工作正常。所以我们不能把变量声明放到函数体中,对吗?
您只能在块的 DECLARE 部分中声明变量。但是您可以在块内对块进行编码。这是直接从 PostgreSQL 文档中复制的关于 PL/pgSQL 结构的
。CREATE FUNCTION somefunc() RETURNS integer AS $$
<< outerblock >>
DECLARE
quantity integer := 30;
BEGIN
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 30
quantity := 50;
--
-- Create a subblock
--
DECLARE
quantity integer := 80;
BEGIN
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 80
RAISE NOTICE 'Outer quantity here is %', outerblock.quantity; -- Prints 50
END;
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 50
RETURN quantity;
END;
$$ LANGUAGE plpgsql;