我正在尝试创建这样的视图:
CREATE OR REPLACE FUNCTION calculate(datemin DATE,datemax DATE) RETURNS VOID AS
$BODY$
BEGIN
DROP VIEW IF EXISTS zdroits CASCADE;
CREATE VIEW zdroits AS
SELECT r.*
FROM rights r
WHERE r.date_paid BETWEEN datemin AND datemax;
-- the rest of the function will use the view
END;
$BODY$ LANGUAGE plpgsql;
但是PostgreSQL不允许我创建视图,说column datemin does not exist
。
如果相反,我用此替换WHERE
行,没关系:
WHERE r.date_paid BETWEEN '2011-01-01' AND '2016-12-31'
我不是要创建参数化视图。我想将传递给函数的参数用作“文字”。
试图理解this answer如何帮助我,我尝试了这样的事情:
EXECUTE '
CREATE VIEW zdroits AS
SELECT r.*
FROM rights r
WHERE r.date_paid BETWEEN $1 AND $2;
' USING (datemin,datemax);
但是编译器说“没有参数$ 1”。
有办法做到这一点吗?
答案 0 :(得分:2)
我不是在问你为什么要那样。正如a_horse_with_no_name所说 - 你可以使用函数本身和参数,但纯粹在学术上,你可以像nelow一样创建fn():
t=# create or replace function mv(a int,b int) returns void as $$
begin
drop view if exists va;
execute format('create view va as select least(%s,%s)',$1,$2) using(a,b);
end;
$$ language plpgsql
;
CREATE FUNCTION
t=# select mv(2,4);
NOTICE: view "va" does not exist, skipping
CONTEXT: SQL statement "drop view if exists va"
PL/pgSQL function mv(integer,integer) line 3 at SQL statement
mv
----
(1 row)
t=# select * from va;
least
-------
2
(1 row)
t=# select mv(7,4);
mv
----
(1 row)
t=# select * from va;
least
-------
4
(1 row)