2014-12-19 79 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; 
相關問題