Joh*_*ohn 5 sql postgresql dynamic-sql
我在PostgreSQL中有这个功能:
CREATE OR REPLACE FUNCTION func1(a integer, b timestamp, c integer[])
RETURNS SETOF typ_new AS
$BODY$
declare
begin
CREATE OR REPLACE VIEW newView as (select * from func2($1,$2,$3));
end;
$BODY$
LANGUAGE plpgsql VOLATILE
Run Code Online (Sandbox Code Playgroud)
func2也会返回,SETOF typ_new因此它们兼容.
运行时我收到一个错误:ERROR: there is no parameter $1
如果我更改$1为参数名称,a则错误更改为
ERROR: column "a" does not exist
我也尝试过动态SQL:
sqlstr ='CREATE OR REPLACE VIEW newView (columns... ) as
(select * from func2('||$1||','||$2||','||$3||'))';
execute sqlstr;
Run Code Online (Sandbox Code Playgroud)
但它不起作用,因为$3是integer[]和||不能使用数组.
我该如何解决这个问题?
CREATE OR REPLACE FUNCTION func1(a integer, b timestamp, c integer[]) RETURNS void AS
$BODY$
BEGIN
EXECUTE 'CREATE OR REPLACE VIEW newView AS ' ||
'SELECT * FROM func2(' || $1 || ', ' || $2 || ', ' || array_to_string($3, ',') || ')';
RETURN;
END;
$BODY$ LANGUAGE plpgsql STRICT;
Run Code Online (Sandbox Code Playgroud)
请注意,此函数void不会返回,SETOF typ_new因为您正在创建视图,而不是从视图返回数据.
由于func2()返回typ_new您不必显式声明视图的列,因此它们将从SELECT语句中获取:typ_new类型的元素.
| 归档时间: |
|
| 查看次数: |
5277 次 |
| 最近记录: |