1. 程式人生 > 實用技巧 >PostgreSQL-儲存過程(一)基礎篇

PostgreSQL-儲存過程(一)基礎篇

儲存過程其實就是函式,由一組 sql 語句組成,實現比較複雜的資料庫操作;

儲存過程 是 儲存在 資料庫伺服器 上的,使用者可以像呼叫 sql 自帶函式一樣 呼叫儲存過程

語法解析

CREATE [OR REPLACE] FUNCTION function_name (arguments)   
RETURNS return_datatype AS $variable_name$  
  DECLARE  
    declaration;  
    [...]  
  BEGIN  
    < function_body >  
    [...]  
    RETURN { variable_name | value }  
  END; LANGUAGE plpgsql;

很容易理解,不多解釋

下面我對一張表進行簡單操作,逐步遞進的介紹儲存過程的語法

步驟1-基礎版

into 表示把結果賦值給 後面的變數,該變數必須在 declare 提前宣告

呼叫儲存過程

select mycount3()

步驟2-把 sql 語句賦給變數

create or replace function mycount3()
returns integer as $$

declare
 mysql text;
 counts integer;

begin
mysql:='select count("CD_ID") from "CDS"';
execute mysql into counts;
return counts;
end;

$$ language plpgsql;

步驟3-帶變數,且 sql 語句用字串拼接

create or replace function mycount4(tableName text, columnName text)
returns text as $$

declare
 mysql text;

begin
mysql:='select count('
    || quote_ident(columnName) 
    || ') from '
    || quote_ident(tableName);

return mysql;

end;

$$ language plpgsql;

1. 函式的引數必須宣告型別

2. || 表示字串拼接符號

3. 儲存過程中的物件不能直接引用變數,要用 quote_ident,它的作用是為字串加上 雙引號

4. 在 sql 語句中,大寫,全部會變成小寫,如果想保留大寫,需要加 雙引號

呼叫儲存過程

select mycount4('CDS', 'CD_ID');

返回

select count("CD_ID") from "CDS"

可以看到,輸入引數是單引號,經過quote_ident 後,自動變成雙引號,保留了大寫

步驟4-換一種拼接方式,並且函式體加了 if 判斷

create or replace function mycount4(tableName text, columnName text)
returns integer as $$

declare
 mysql text;
 counts integer;

begin
mysql:='select count("' || $2 || '") from "' || $1 || '" ';
execute mysql into counts using tableName, columnName;

if counts > 100 then
    return counts;
else return 1;
end if;

end;

$$ language plpgsql;

1. 用 using 調取變數,此時需要自己加 雙引號 以保留 大寫

2.112 對應的是函式的引數位置,跟 using 後的順序無關

3. if 後面有個 then

4. text 可變長度字串

5. 每句末尾必須帶分號