我在postgresql中使用视图时可以传递参数吗?

时间:2017-06-25 14:53:56

标签: postgresql

例如,

我想为特定搜索创建一个视图,

create view search_in_structure as
select a,b,c,d,e
from
  t1 natural inner join t2 natural inner join t3 ...
where
   a ilike '%search_string%'
or b ilike '%search_string%'
or c ilike '%search_string%'
or f ilike '%search_string%';

它没有意义,因为我无法修改search_string。是否有一种为search_string提供值的机制,因此它将通过适当的修改执行view语句,如:

select a,b from search_in_structure where search_string='postgresql 4ever';

如果不可能,您建议我使用什么解决方案并获得相同的结果? 我能想到的唯一解决方案是创建一个函数(例如,search_in_structure (IN search text, OUT a text, OUT b text ...) returns record)并将其称为:

select a,b from (select search_in_structure('postgresql 4ever'));

但由于我还是一名postgresql菜鸟,我希望得到专家建议。

1 个答案:

答案 0 :(得分:2)

一个功能是要走的路:

create function search_in_structure(p_search_value text)
  returns table (a text, b text, c text, d text)
as
$$
select a,b,c,d,e
from t1 
   natural join t2 
   natural join t3 ...
where
   a ilike '%'||p_search_value||'%'
or b ilike '%'||p_search_value||'%'
or c ilike '%'||p_search_value||'%'
or f ilike '%'||p_search_value||'%'
$$
language sql;

然后你可以这样做:

select *
from search_in_structure('foobar');