Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 使用变量执行select查询_Postgresql_Function - Fatal编程技术网

Postgresql 使用变量执行select查询

Postgresql 使用变量执行select查询,postgresql,function,Postgresql,Function,通常,我在postgres中编写函数,如下所示 with detail_data as( select id from product p where category = PARAM1_HERE order by update_time) 现在我想将查询更改为动态顺序。我试了如下 with detail_data as( execute 'select id from product p where category = $1 order by $2'

通常,我在postgres中编写函数,如下所示

with detail_data as(
select
    id
from
    product p
where
    category = PARAM1_HERE 
order by update_time)
现在我想将查询更改为动态顺序。我试了如下

with detail_data as( 
execute 'select id from product p where category  = $1 order by $2'
    using PARAM1_HERE,PARAM2_HERE)
我在编译时出错:

错误:“执行”处或附近出现语法错误


如何解决它?

它不起作用,因为
EXECUTE
是一个PL/pgSQL命令,而不是
SQL
命令-以防不使用准备好的语句。也就是说,你可能想尝试使用一个真正的函数

测试数据

CREATE TABLE product (id INT, category INT, txt TEXT);
INSERT INTO product VALUES (1,1,'x'),(42,1,'f'),(8,1,'a'),(2,1,'j');
作用

CREATE OR REPLACE FUNCTION cte_function(INT,TEXT) 
RETURNS TABLE(res INT) AS $$
BEGIN  
RETURN QUERY 
  EXECUTE FORMAT('SELECT id FROM product WHERE category=%L ORDER BY %I',$1,$2);
END; $$ LANGUAGE plpgsql;
测试(按id订购)

测试(按txt排序)


您使整个查询动态化,而不仅仅是第一个CTE中的查询。我不想编写另一个函数,它有其他方法吗?@Tuấn我不知道在纯SQL语句中动态写入列名的方法。使用
PREPARE
越接近,但变量只用于值,不用于列。@Tuấ顺便说一句,这是一种使用预先准备好的语句(无需排序)的方法:
PREPARE mystm作为产品的SELECT id,其中category=$1;执行mystm(1)
SELECT * FROM cte_function(1,'id') ;
 res 
-----
   1
   2
   8
  42
(4 rows)
SELECT * FROM cte_function(1,'txt') ;
 res 
-----
   8
  42
   2
   1
(4 rows)