小编典典

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

sql

我正在寻找一种评估Postgres 9.1+数据库中存储的价格表达方式的方法

我尝试了下面的代码,如何在Postgres中的select语句中评估表达式

但是有错误

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

怎么修 ?

也许可以将客户和产品当前行作为评估参数传递并在评估表达式中使用它们?

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

阅读 246

收藏
2021-05-16

共1个答案

小编典典

Serg 基本上是正确的。 您的 dyna-SQL 是“单独 执行”的, 因此它必须是有效的SQL语句(
“知道”所有涉及的表)。

但是要在这里正确引用它,您的示例应该类似于(实际上,您应该 使用2ndeval( 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 的建议相比,这应该更加直接,健壮和模块化。

2021-05-16