- 函数传递表名和另外一个参数示例
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;