Abhishek Ginani
Abhishek Ginani

Reputation: 4751

How to execute a query which is stored in a table column PostgreSql?

I have a table column which contains following text data:

"drop table log_history_2_2015"
"drop table log_history_3_2015"
"drop table log_history_4_2015"
"drop table log_history_5_2015"
"drop table log_history_6_2015"

How can I execute them in single shot without looping through all these rows and executing them individually.

Upvotes: 2

Views: 5222

Answers (2)

Craig Ringer
Craig Ringer

Reputation: 324751

A more general solution is to use a DO block to execute the dynamic SQL:

DO
LANGUAGE plpgsql
$$
DECLARE
  stmt text;
BEGIN
  FOR stmt IN
    SELECT statement FROM the_table
  LOOP
    EXECUTE stmt;
  END LOOP;
END;
$$;

Note that this runs in a single transaction.

Upvotes: 9

Vao Tsun
Vao Tsun

Reputation: 51599

use SELECT string_agg(COLUMN_NAME,';')||chr(10) - it will give you single line to run

Upvotes: 4

Related Questions