Postgresql自定义函数—表名作为函数参数

  • 函数传递表名和另外一个参数示例

CREATE OR REPLACE FUNCTION some_f(_tbl text, col text, OUT result bool)

LANGUAGE plpgsql AS

func

BEGIN

EXECUTE format('SELECT (EXISTS (SELECT FROM %s WHERE b = $1))', _tbl,col) using col INTO result;

END

func;

函数调用:

test=# select some_f('test','test'); --这里只传递了2个参数

some_f


t

(1 row)

使用using子句给format函数传递参数($1),这里是数字'壹'。%s的含义,见第四部分说明

  • 表名作为参数,返回表中记录数

CREATE OR REPLACE FUNCTION get_table_info(tablenames text)

RETURNS int AS $$

DECLARE

rowcount int;

BEGIN

EXECUTE format('SELECT count(*) FROM %I', tablenames) INTO rowcount;

return rowcount;

END

LANGUAGE plpgsql; 函数调用: test=# select get_table_info('test'); get_table_info ---------------- 2 (1 row) * 表名作为参数,返回表中记录值 CREATE OR REPLACE FUNCTION get_table_info(tablenames text) RETURNS table(a int,b varchar) AS

DECLARE

rowcount int;

BEGIN

return query EXECUTE format('SELECT * FROM %I', tablenames);

END

LANGUAGE plpgsql; 函数调用: test=# select get_table_info('test'); get_table_info ---------------- (10,test) (1,testtest) 这种调用方式,返回表的数据,作为元组形式 或者 test=# select \* from get_table_info('test'); a \| b ----+---------- 10 \| test 1 \| testtest (2 rows) 这种调用方式,返回表的数据同正常查询结果的返回 * 几个注意问题 1. Out参数,在调用时,不需要在调用时传递 2. 当需要返回table类型时,可以使用return query或者return next 3. Format函数参数的说明: %I is equivalent to quote_ident, and %L is equivalent to quote_nullable. The format function can be used in conjunction with the USING clause: EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname) USING newvalue, keyvalue;

相关推荐
小碗羊肉27 分钟前
【JavaWeb | 第十二篇】项目实战——登录功能
java·前端·数据库
想唱rap28 分钟前
五种IO模型和非阻塞IO
linux·运维·服务器·网络·数据库·tcp/ip
m0_7335654632 分钟前
如何指定PHP版本运行phpMyAdmin_多版本共存配置
jvm·数据库·python
xcLeigh1 小时前
IoTDB JDBC 完整使用教程:连接、查询、批处理与字符集配置
开发语言·数据库·qt·iotdb·查询·批处理·连接
chunyublog1 小时前
数据挖掘环境搭建
数据库
阿洛学长1 小时前
CSDN、掘金、简书博客文章如何转为Markdown?
运维·数据库·架构·php·持续部署
zuozewei1 小时前
国产化之达梦数据库性能优化方案
数据库·性能优化
Volunteer Technology2 小时前
Spring AI MCP 案例-WebFlux SSE传输模式 (九)
java·数据库·人工智能·spring
betazhou3 小时前
SQL server数据库镜像同步技术
数据库·sql server·高可用·数据库镜像
mpHH3 小时前
postgresql-分区表
数据库·postgresql