溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在postgresql中調(diào)用存儲函數(shù)的變量

發(fā)布時(shí)間:2021-01-28 09:19:01 來源:億速云 閱讀:392 作者:Leah 欄目:開發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)怎么在postgresql中調(diào)用存儲函數(shù)的變量,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

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

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

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

select 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

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

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

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

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

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

--定義變量

a numeric;

方式一:

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

方式二:

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

上述就是小編為大家分享的怎么在postgresql中調(diào)用存儲函數(shù)的變量了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI