?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
PL/pgSQL是一種塊結(jié)構(gòu)的語言。 函數(shù)定義的所有文本都必須是一個塊(block)??梢杂孟旅娴姆椒ǘx一個塊:
[ <<label>> ] [ DECLARE declarations ] BEGIN statements END [ label ];
塊中的每個聲明和每條語句都是用一個分號終止的, 如果一個子塊在另外一個塊里,那么END后面必須有個分號,如上所述; 不過結(jié)束函數(shù)體的最后的END可以不要這個分號。
Tip: 一個常見的錯誤是緊跟在BEGIN之后使用一個分號,這是不正確的,并且會返回一個語法錯誤。
如果你想標記出在EXIT聲明中的block,或者描述在block中所聲明的變量名字,此時,可以選擇使用標簽(label)。 如果是在END之后給出一個標簽,那么,它必須與block開始時定義的標簽相匹配。
所有的關(guān)鍵字都是不區(qū)分大小寫的,正如在SQL命令中一樣,會隱式的將其轉(zhuǎn)換成小寫,除非是使用雙引號。
如同在普通的SQL語句中一樣,在PL/pgSQL代碼中,用同樣的方式定義注釋: 在語句的最后,通過一個雙破折號(--)來開始一條行注釋。 而塊注釋是成對出現(xiàn)的,通過/*和*/來定義。
塊語句段里的任何語句都可以是一個子塊(subblock)。 子塊可以用于邏輯分組或者把變量局部化為作用于一個比較小的語句組。 Variables declared in a subblock mask any similarly-named variables of outer blocks for the duration of the subblock 該塊的范圍內(nèi); but you can access the outer variables anyway if you qualify their names with their block's label. For example:
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;
Note: There is actually a hidden "outer block" surrounding the body of any PL/pgSQL function. This block provides the declarations of the function's parameters (if any), as well as some special variables such as FOUND (see Section 39.5.5). The outer block is labeled with the function's name, meaning that parameters and special variables can be qualified with the function's name.
一定不要把PL/pgSQL里用于語句分組的BEGIN/END和用于事務(wù)控制的數(shù)據(jù)庫命令搞混了。 PL/pgSQL的BEGIN/END只是用于分組; 它們不會開始和結(jié)束一個事務(wù)。 函數(shù)和觸發(fā)器過程總是在一個由外層命令建立起來的事務(wù)里執(zhí)行, 它們無法開始或者提交事務(wù),因為PostgreSQL沒有嵌套事務(wù)。 不過,一個包含EXCEPTION子句的塊實際上形成一個子事務(wù), 它可以在不影響外層事務(wù)的情況下回滾。 更多相關(guān)信息請參閱Section 39.6.5。