一、假設(shè)有表student,字段分別有id,remark,name等字段。
二、寫一個(gè)存儲(chǔ)函數(shù),根據(jù)傳過(guò)去的變量ID更新remark的內(nèi)容。
調(diào)用該存儲(chǔ)函數(shù)格式如下:
select 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)景來(lái)使用。比較簡(jiǎn)單的情況下直接用method 3。
比如,表名、字段名本身是變量,那么method 3 就無(wú)法實(shí)現(xiàn),需要根據(jù)method 1或method 2來(lái)實(shí)現(xiàn)。
如果需要拼的變量可以直接獲取的,則用method2即可。如果變量本身也是需要需要通過(guò)函數(shù)或語(yǔ)句的計(jì)算來(lái)獲得,一般建議用method 1,先拼成一個(gè)字符串,再調(diào)用execute來(lái)實(shí)現(xiàn)。
補(bǔ)充:postgresql存儲(chǔ)函數(shù)/存儲(chǔ)過(guò)程用sql語(yǔ)句來(lái)給變量賦值
--定義變量
a numeric;
select sqla into a from table1 where b = '1' ; --這是sql語(yǔ)句賦值
sql1:= 'select a from table1 where b = ' '1' ' '; execute sql1 into a; --這是執(zhí)行存儲(chǔ)函數(shù)賦值
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
標(biāo)簽:昭通 溫州 濮陽(yáng) 海西 辛集 榆林 寶雞 杭州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《postgresql 存儲(chǔ)函數(shù)調(diào)用變量的3種方法小結(jié)》,本文關(guān)鍵詞 postgresql,存儲(chǔ),函數(shù),調(diào)用,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。