首页 > 解决方案 > 将整个 select 语句作为参数传递 - PostgreSQL 函数

问题描述

我将整个 select 语句作为参数传递给 Postgres 函数,如下所示...

select * from demo_spnsearch('select* from public.tbl_spnsearch where spnid=78 and spnyear=2000::varchar and region=Australia')

我收到一个错误

SQL 错误 [42703]:错误:列“澳大利亚”不存在其中:PL/pgSQL 函数 demo_spnsearch(text) 第 6 行,位于 RETURN QUERY

但是当我通过同样的无区域时

select * from demo_spnsearch('select* from public.tbl_spnsearch where spnid=78 and spnyear=2000::varchar ')

它工作正常。

请帮忙...

标签: postgresqlstored-procedures

解决方案


您必须将region价值放在引号内。您可以使用以下任何选项

SELECT *
FROM demo_spnsearch('select* from public.tbl_spnsearch where spnid=78 and spnyear=2000::varchar and region=''Australia''') -- note the quotes here region=''Australia''

通过使用 Postgres 内置的format()函数。

SELECT *
FROM  demo_spnsearch(format('select* from public.tbl_spnsearch where spnid=%s and spnyear=%s::varchar and region=%L', 78, 2000, 'Australia'))

推荐阅读