如何修复postgres-utils eval()错误:缺少表“foo”的FROM子句条目?

时间:2016-04-29 13:27:08

标签: sql postgresql eval plpgsql

我正在寻找一种方法来评估Postgres 9.1 +

中存储在数据库中的价格表达式

我在回答中尝试了以下代码 How to evaluate expression in select statement in Postgres

但收到错误

ERROR:  missing FROM-clause entry for table "product"
LINE 1: select product.price*0.95

如何解决?

也许可以将客户和产品当前行作为eval参数传递并在eval expresion中使用它们?

create or replace function eval( sql  text ) returns text as $$
declare
  as_txt  text;
begin
  execute 'select ' ||   sql  into  as_txt ;
  return  as_txt ;
end;
$$ language plpgsql;


create table customer
( id int primary key,
  priceexpression text );
insert into customer values (1, 'product.price*0.95'),(2,'cost+12.0' );

create table product
( id char(20) primary key,
   price numeric(12,4),
   cost numeric(12,4) );
insert into product values ('PRODUCT1', 120, 80),('PRODUCT2', 310.5, 290);


select
  customer.id as customer,
  product.id as product,
  eval(priceexpression) as price
 from customer,product

2 个答案:

答案 0 :(得分:1)

Serg 基本上是正确的。 您的 dyna-SQL 是“自行执行”所以它需要是一个有效的SQL语句(“知道”所有涉及的表 )。我updated my answer in the referred thread反映了这一点。

但要在此处正确引用它,您的示例应该是这样的(实际上您应该使用第二个eval( sql text, keys text[], vals text[] )变体!):

eval(  
  'select '||c.price_expression||' from product where id=:pid',
  '{"{cost}",:pid}',  
  array[ p.cost, p.id ]  
)      as cust_cost

这应该比 Serg 的建议更直接,更健壮,更模块化。

答案 1 :(得分:0)

只需添加表名somwhere即可。可能是

insert into customer values (1, 'product.price*0.95 FROM product'),(2,'cost+12.0 FROM product' );

或可能是

 execute 'select ' ||   sql || ' FROM product' into  as_txt ;

根据您的选择。

希望priceexpression不会向用户公开,只会向受限制的管理员公开,因为它是危险的sql注入安全漏洞。