PG 存儲函數調用變量的3種方法。


一、假設有表student,字段分別有id,remark,name等字段。

二、寫一個存儲函數,根據傳過去的變量ID更新remark的內容。

     調用該存儲函數格式如下:select  update_student(1);

三、存儲函數示例如下:    

復制代碼
CREATE OR REPLACE FUNCTION public.update_student(id integer)
  RETURNS text AS
$BODY$

declare sql_str_run text; 
BEGIN /* --method 1 select 'update student set remark ='''|| now() ||''' where student.id = '|| $1 into sql_str_run ; execute sql_str_run; --method 2 execute 'update student set remark =now() where student.id=$1' using $1; */ --method 3 update student set remark =now() where student.id=$1; return 'update is ok' ; end $BODY$ LANGUAGE plpgsql VOLATILE
復制代碼

以上三種方法都可以實現同樣的效果,實際應用中,可以結合場景來使用。比較簡單的情況下直接用method 3。

比如,表名、字段名本身是變量,那么method 3 就無法實現,需要根據method 1或method 2來實現。

method 1或method 2 有什么區別呢?

如果需要拼的變量可以直接獲取的,則用method2即可。如果變量本身也是需要需要通過函數或語句的計算來獲得,一般建議用method 1,先拼成一個字符串,再調用execute來實現。


免責聲明!

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



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