2

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.

2 Answers 2

9

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.

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

4 Comments

Code-Monk asked without looping so Do block would be same one line for execute
@VaoTsun I presumed it was to avoid client-side looping. There is no meaningful difference between executing them in a loop in PL/PgSQL vs a multi-statement. The PostgreSQL backend just loops over the statements, exactly like you did it in PL/PgSQL, if you send a multi-statement.
Can we use this in Redshift? I wasn't able to run it until now
@GarouDan almost certainly not. Redshift is based on super ancient PostgreSQL - 8.2 IIRC.
4

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

5 Comments

Thanx for answer.what is the use of ||chr(10) in query?
||chr(10) brakes single line to miltiples - adds tens ASCCI char after semicolon
Okay, Thanx for your help
@Code-Monk No worries. My pleasure
chr(10) is the ASCII line-feed. You can also write it as E'\r' in PostgreSQL. This code appends a single line feed at the end of the whole series of statements. If you want one after each semicolon you need to move the ||chr(10) inside the function call. I would instead write the delimiter as E';\r' or simply include a literal linefeed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.