Postgresql的pl/pgql使用操作--將多條執行語句作為一個事務
Postgresql的pl/pgql用法--將多條執行語句作為一個事務
DO $$ DECLARE v_id bigint; begin --1. INSERT INTO r_test_a (name,value,unit,mode,uid,create_ts) SELECT 't_t','',2,extract(epoch from now())::bigint WHERE NOT EXISTS (SELECT id FROM r_test_a WHERE name = 't_t' AND value = '' AND unit = '' AND uid =0); --2. SELECT id into v_id from r_test_a WHERE name = 't_t' AND value = '' AND unit = '' AND uid = 0; --3. DELETE FROM r_test_b a WHERE a.obj_id = 'xxx' AND a.file_id = 'ooo' AND a.id IN (SELECT id FROM r_test_a b WHERE b.name = 't_t' AND b.uid=0); --4. INSERT INTO r_test_b (id,obj_id,file_id,create_ts) SELECT v_id,'xxx','ooo',extract(epoch from now())::bigint ; end $$;
補充:PostgreSql 的PL/pgSQL 塊結構 (在pgAdmin查詢工具中如何執行語句塊)
本文我們學習PL/pgSQL結構塊,包括如何寫結構塊和執行結構塊。
什麼是結構塊
PL/pgSQL是結構塊語言,因此,PL/pgSQL函式或過程是通過結構塊進行組織。完整結構塊的語法如下:
[ <<label>> ] [ DECLARE declarations ] BEGIN statements; ... END [ label ];
詳細說明如下:
塊有兩部分組成:宣告部分和主體部分。宣告部分是可選的,而主體部分是必須的。塊在end關鍵字後面使用分號(;)表示結束。
塊可以有個可選的標籤在開始和結尾處。如果你想在塊主體中使用exit語句或限定塊中宣告的變數名稱時,需要使用塊標籤。
主體部分是編寫程式碼的地方,每條語句需要使用分號結束。
PL/pgSQL 塊結構示例
下面示例描述一個簡單塊結構,一般稱為匿名塊:
DO $$ <<first_block>> DECLARE counter integer := 0; BEGIN counter := counter + 1; RAISE NOTICE 'The current value of counter is %',counter; END first_block $$;
執行結果:
NOTICE: The current value of counter is 1
從pgAdmin中執行塊,點選圖示按鈕:
注意DO語句不屬於塊結構。它用於執行匿名塊。PostgreSQL 在9.0版本中引入DO語句。
在宣告部分定義變數counter並設定為0.
在主體部分,是counter值加1,通過RAISE NOTICE語句輸出其值。
first_block 標籤僅為了演示需要,本例中沒有啥意義。
** 什麼是雙 ($$) 符號?**
($$) 符號 是單引號(')的替代符號。開發PL/pgSQL 時,無論是函式或過程,必須把主體部分放在一個字串中。因此必須對主體部分的單引號進行轉義表示:
DO '<<first_block>> DECLARE counter integer := 0; BEGIN counter := counter + 1; RAISE NOTICE ''The current value of counter is %'',counter; END first_block';
使用($$) 符號可以避免引號問題。也可以在$之間使用標識,如之間使用標識,如之間使用標識,如function$,procedureprocedureprocedure.
PL/pgSQL 子結構塊
PL/pgSQL可以一個塊在另一個塊的主體中。一個塊嵌入在另一個塊中稱為子塊,包含子塊的塊稱為外部塊。
子塊用於組織語句,這樣大塊能被分為更小和更多邏輯子塊。子塊的變數的名稱可以與外部塊變數名稱同名,雖然這在實踐中不建議。當在子塊中宣告一個與外部變數同名的變數,外部變數在子塊中被隱藏。如果需要訪問外部塊的變數,可以使用塊標籤作為變數的限定符,如下面示例:
DO $$ <<outer_block>> DECLARE counter integer := 0; BEGIN counter := counter + 1; RAISE NOTICE 'The current value of counter is %',counter; DECLARE counter integer := 0; BEGIN counter := counter + 10; RAISE NOTICE 'The current value of counter in the subblock is %',counter; RAISE NOTICE 'The current value of counter in the outer block is %',outer_block.counter; END; RAISE NOTICE 'The current value of counter in the outer block is %',counter;
執行結果如下:
NOTICE: The current value of counter is 1 NOTICE: The current value of counter in the subblock is 10 NOTICE: The current value of counter in the outer block is 1 NOTICE: The current value of counter in the outer block is 1
首先,在外部塊中宣告變數counter。
接著在子塊中也聲明瞭一個同名變數。
在進入子塊之前,變數的值為1。在子塊中,我們給變數counter值加10,然後打印出來。注意,這個改變僅影響子塊中counter變數。
然後,我們通過標籤限定符引用外部變數:outer_block.counter
最後,我們列印外部塊變數,其值保持不變。
總結
本文我們學習PL/pgSQL塊結構,通過DO語句可以執行匿名塊。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。