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. $1 $2 對應的是函數的參數位置,跟 using 后的順序無關

3. if 后面有個 then

4. text 可變長度字符串

5. 每句末尾必須帶分號

 

 

參考資料:

https://www.yiibai.com/postgresql/postgresql-functions.html

https://www.cnblogs.com/ssqhan/p/7289931.html#top


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM