postgresql 存儲函數(shù)調(diào)用變量的3種方法小結(jié)
一、假設(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
以上三種方法都可以實現(xiàn)同樣的效果,實際應(yīng)用中,可以結(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語句來給變量賦值
--定義變量
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ù)賦值
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
PostgreSQL ERROR: invalid escape string 解決辦法
這篇文章主要介紹了PostgreSQL ERROR: invalid escape string 解決辦法,本文環(huán)境是JDBC+PostgreSQL,需要的朋友可以參考下2014-07-07Postgresql?REGEXP開頭的正則函數(shù)用法圖文詳解
正則表達(dá)式是指一個用來描述或者匹配一系列符合某個句法規(guī)則的字符串的單個字符串,下面這篇文章主要給大家介紹了關(guān)于Postgresql?REGEXP開頭的正則函數(shù)用法的相關(guān)資料,需要的朋友可以參考下2024-02-02postgreSQL 數(shù)字與字符串類型轉(zhuǎn)換操作
這篇文章主要介紹了postgreSQL 數(shù)字與字符串類型轉(zhuǎn)換操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12

postgresql關(guān)于like%xxx%的優(yōu)化操作