简体   繁体   English

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

[英]can I pass an argument when I use a view in postgresql?

for instance, I want to make a view for a particular search, 例如,我想查看特定搜索,

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%';

it doesn't make sense because I can't modify search_string . 这没有任何意义,因为我无法修改search_string Is there a mechanism to provide a value for search_string so it will execute the view statement with proper modification, something like : 是否有一种机制可以为search_string提供一个值,以便它将执行经过适当修改的view语句,例如:

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

if it's not possible, what solution would you recommend me to use and achieve the same result? 如果不可能,您会推荐我使用哪种解决方案并获得相同的结果? The only solution I can think of, would be to make a function (for example, search_in_structure (IN search text, OUT a text, OUT b text ...) returns record ) and call it like : 我能想到的唯一解决方案是制作一个函数(例如, search_in_structure (IN search text, OUT a text, OUT b text ...) returns record )并像这样调用它:

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

But as I am still a postgresql noob, I want to have expert suggestions. 但是由于我仍然是postgresql新手,因此我想提出专家建议。

A function is the way to go: 函数是必经之路:

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;

Then you can do: 然后,您可以执行以下操作:

select *
from search_in_structure('foobar');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM