8

In a function, I have a SELECT query in a string, for example:

sql='SELECT * FROM A'

I want to execute sql output result of: SELECT * FROM A

How can I execute the string sql in PostgreSQL?

1

2 Answers 2

9

Inside a function use EXECUTE.
http://www.postgresql.org/docs/current/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

Sign up to request clarification or add additional context in comments.

Comments

-1

below one works fine in postgres 8.4

UDBI=> PREPARE query as select 1 as a;
PREPARE
UDBI=> PREPARE query
UDBI=> EXECUTE query;
 a 
---
 1
(1 row)

UDBI=> 

1 Comment

This is not a dynamic query - the select 1 as a part is not sent as a string, but as part of the SQL statement. If executed immediately and once only like this, it is equivalent to just typing select 1 as a; on its own.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.