我试着编写简单的函数:
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;
工作正常。所以我们不能把变量声明放到函数体中吗?
答案 0 :(得分:10)
您只能在块的DECLARE部分声明变量。但是你可以在块内编码块。这是直接从PostgreSQL docs on the structure of 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;