2014-12-19 80 views
0

我试着写简单的功能:我们可以在plpgsql函数的开始 - 结束块中声明变量吗?

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

块中使用的所有变量都必须在块的声明部分中声明。 – Houari 2014-12-19 12:05:34

回答

8

只能在块的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; 
相关问题