dynamic query postgres

筅森魡賤 提交于 2019-12-29 09:21:48

问题


I am new to postgres and running following dynamic query

EXECUTE 'Select * from products';

I get following response.

ERROR: syntax error at or near "'Select * from products'" 
LINE 1: EXECUTE 'Select * from products';

I Know this would be something basic I m missing


回答1:


There is the EXECUTE statement of plpgsql, which would do what you are trying to do - execute an SQL query string. You tagged dynamic, so this may be what you are looking for.

Only works inside plpgsql functions or DO statements (anonymous code blocks). The distinction between EXECUTE and SQL-EXECUTE made clear in the fine manual:

Note: The PL/pgSQL EXECUTE statement is not related to the EXECUTE SQL statement supported by the PostgreSQL server. The server's EXECUTE statement cannot be used directly within PL/pgSQL functions (and is not needed).

If you want to return values from a dynamic SELECT query as your example indicates, you need to create a function. DO statements always return void. More about returning values from a function in the very fine manual.




回答2:


From the fine manual:

Synopsis

EXECUTE name [ ( parameter [, ...] ) ]

Description

EXECUTE is used to execute a previously prepared statement.

So EXECUTE doesn't execute a string of SQL, it execute a prepared statement that is identified by a name and you need to prepare the statement separately using PREPARE:

=> prepare stmt as select * from products;
=> execute stmt;
-- "select * from products" output goes here...


来源:https://stackoverflow.com/questions/10709624/dynamic-query-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!