當前位置:首頁 >  站長 >  數(shù)據(jù)庫 >  正文

postgresql 存儲函數(shù)調(diào)用變量的3種方法小結(jié)

 2021-05-22 16:53  來源: 腳本之家   我來投稿 撤稿糾錯

  域名預訂/競價,好“米”不錯過

這篇文章主要介紹了postgresql 存儲函數(shù)調(diào)用變量的3種方法小結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧。

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

二、寫一個存儲函數(shù),根據(jù)傳過去的變量ID更新remark的內(nèi)容。

調(diào)用該存儲函數(shù)格式如下:

1select update_student(1);

三、存儲函數(shù)示例如下:

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

 

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

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

method 1或method 2 有什么區(qū)別呢?

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

補充:postgresql存儲函數(shù)/存儲過程用sql語句來給變量賦值

--定義變量

1a numeric;

方式一:

1select sqla into a from table1 where b = '1' ; --這是sql語句賦值

方式二:

sql1:= 'select a from table1 where b = ' '1' ' ';
execute sql1 into a; --這是執(zhí)行存儲函數(shù)賦值

文章來源:腳本之家

來源地址:https://www.jb51.net/article/204911.htm

申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!

相關文章

熱門排行

信息推薦