简体   繁体   English

如何在 Postgres/plpgsql 的视图定义中使用变量

[英]How to use variable in view definition in Postgres/plpgsql

I am using plpgsql with Postgres 10.6.我将 plpgsql 与 Postgres 10.6 一起使用。 I have a function that declares and gives value to a variable.我有一个 function 声明变量并为其赋值。 That function also defines a view, and I would like to use the variable within the definition.那 function 也定义了一个视图,我想在定义中使用变量。

  create view myview as
    select
      some_columns
    from
      mytable
    where      
      id = _id     /*_id is declared earlier in function */
  ;

In this case, the function can be defined, but when it is run it gives an error: UndefinedColumn: column "_id" does not exist在这种情况下,可以定义function,但运行时报错: UndefinedColumn: column "_id" does not exist

Is such a thing possible in Postgres?在 Postgres 中这样的事情是可能的吗? Can views include variables as part of their definition?视图可以将变量作为其定义的一部分吗?

I do see here that in BigQuery (which I have never used), what I am asking is not possible, which makes me think it may also not be possible in plpgsql.我确实在这里看到,在 BigQuery(我从未使用过)中,我所要求的是不可能的,这让我认为在 plpgsql 中也可能不可能。

It is not a big deal, but I am curious.这没什么大不了的,但我很好奇。 A workaround - and probably the recommended solution - is to pass the _id when I select from the view (eg select * from myview where id = 3 ).一种解决方法(可能是推荐的解决方案)是在我从视图中传递 _id 时 select (例如select * from myview where id = 3 )。 Or, if I really want to keep the select call simple (which I do, because my actual implementation is more complicated and has multiple variables), I could define the view as a string and use execute within the function (this is all internal stuff used in building up and creating a db, not in a situation where the various risks inherent to dynamic sql are a concern).或者,如果我真的想保持 select 调用简单(我这样做,因为我的实际实现更复杂并且有多个变量),我可以将视图定义为字符串并在 function 中使用execute (这都是内部的东西用于建立和创建数据库,而不是在动态 sql 固有的各种风险是一个问题的情况下)。

No, you can not pass a variable to a view.不,您不能将变量传递给视图。 But you can do this with a function:但是你可以用 function 做到这一点:

create function my_view_function(p_id integer)
  returns table (id int, column_1 int, column2 text)
as
$$
  select id, column_1, column_2
  from my_table
  where id = p_id;
$$
language sql
stable;

Then use it like this然后像这样使用它

select *
from my_view_function(42);

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

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