客户在PSQL中使用绑定变量传递实参遇到如下问题
template1=# CREATE FUNCTION test(name varchar(100) )returns int AS
$$
template1$# DECLARE
template1$#
template1$# BEGIN
template1$#
return 0;
template1$# END;
template1$# $$ LANGUAGE plpgsql;
CREATE
FUNCTION
template1=#
template1=#
template1=# \set bookname
program
template1=# \echo :bookname
program
template1=# select
test(:bookname);
ERROR: column "program" does not exist
LINE 1: select
test(program);
^
psql没有把绑定变量当做一个文本处理,而是认为他是一个列所以出现这样的错误,然后以为加上单引号可以解决问题。但是实际上问题依然存在,看下面的例子
template1=# \echo
:name
happy
template1=#
template1=#
template1=#
template1=#
template1=#
CREATE or replace FUNCTION test(name varchar) RETURNS integer AS
$$
template1$# DECLARE
template1$#
template1$# BEGIN
template1$#
execute 'create table '||quote_ident(name)||' (id int) distributed by
(id)';
template1$# return 0;
template1$# END;
template1$# $$ LANGUAGE
plpgsql;
CREATE
FUNCTION
template1=#
template1=#
template1=#
template1=# select
test('''||:name||''');
test
------
0
(1 row)
template1=#
\d
List of relations
Schema | Name |
Type | Owner |
Storage
--------+-----------------+-------+---------+----------------------
public
| '||:name||' | table | gpadmin | heap
(1 rows)
在传递实参时,依然不可以正确处理引号。在设置绑定变量时,使用$$定义参数值,问题解决,如下
CREATE or replace FUNCTION test(v_name varchar) RETURNS integer AS
$$
DECLARE
BEGIN
execute 'create table '||v_name||' (id int)
distributed by (id)';
return 0;
END;
$$ LANGUAGE
plpgsql;
sales_history=# \set name $$happy$$
sales_history=# select
test(:name);
test
------
0
(1 row)
sales_history=#
\d
List of relations
Schema |
Name | Type | Owner |
Storage
---------------+---------------+-------+---------+----------------------
sales_history
| happy | table | gpadmin | heap
(1 rows)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/25548387/viewspace-696740/
,如需转载,请注明出处,否则将追究法律责任。