sql - 如何修复 postgres-utils eval() 错误 : missing FROM-clause entry for table "foo"?

标签 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

如何修复?

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

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

最佳答案

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

但要在此处正确引用它,您的示例应该类似于(实际上您应该使用第二个 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 的建议更直接、更强大和模块化。

关于sql - 如何修复 postgres-utils eval() 错误 : missing FROM-clause entry for table "foo"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36939625/

相关文章:

mysql - 我应该引用字段 ID 还是将实际数据放在同一行中?

mysql - 正值或负值取决于关系 - 可以在单个语句中选择 SUM(...) 吗?

mysql - 1292 : Incorrect datetime value: '' for column at row 1

sql - PostgreSQL 上的语法错误创建没有双引号的表

PostgreSQL 触发器 : check total number of rows in WHEN conditon

python - python 中的 eval 和 exec 有什么区别?

mysql - 在 MYSQL 5.1 中使用@DECLARE

python - 从 Airflow Postgres Hook 中检索完整连接 URI

python - 使用 dict 进行单元测试 __repr__ 的正确方法

lua - 使用 eval 命令在 Lua 脚本中分配局部变量