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

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

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

  域名預(yù)訂/競(jìng)價(jià),好“米”不錯(cuò)過

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

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

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

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

1select update_student(1);

三、存儲(chǔ)函數(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é)合場(chǎng)景來使用。比較簡(jiǎn)單的情況下直接用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,先拼成一個(gè)字符串,再調(diào)用execute來實(shí)現(xiàn)。

補(bǔ)充:postgresql存儲(chǔ)函數(shù)/存儲(chǔ)過程用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í)行存儲(chǔ)函數(shù)賦值

文章來源:腳本之家

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

申請(qǐng)創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!

相關(guān)文章

熱門排行

信息推薦