0

I want to include a drop everything section in a script which (re)generates a sample database.

I know I can find a list of views in the current schema and generate the DROP VIEW statements this way:

SELECT 'DROP VIEW ' || tabname || ';'
FROM syscat.tables
WHERE TYPE='V' AND tabschema=current_schema;

What I don’t know is how to go about executing the result.

I have found the following:

  • Examples of EXECUTE or EXECUTE IMMEDIATE all have single statements, so I can’t see how to do this with with multiple statements.

I suppose I could try with:

WITH cte(dv) AS (
    SELECT 'DROP VIEW ' || tabname || ';'
    FROM syscat.tables
    WHERE TYPE='V' AND tabschema=current_schema
)
SELECT listagg(dv, ' ')
FROM cte;
  • Other examples I’ve found to do this dynamically involve running from the Linux command line, so that doesn’t suit my script - I need to do all of this in the SQL script.

What is the best way of doing this?

I’m running Db2 LUW 11 or 12 (two versions).

2
  • @mao I’ve edited my question. I’m trying to do all of this within the SQL script. Commented Mar 21 at 7:56
  • You should remove "what is the best way..." because that invites opinions and that is not allowed on stackoverflow. The command-line is by far the simplest method. Otherwise you can implenent and CALL a routine (e.g sproc) to run each DDL one by one (e.g by processing a session table). Commented Mar 21 at 8:11

1 Answer 1

2

Use a compound statement for this:

--#SET TERMINATOR @
BEGIN
  FOR C1 AS 
    SELECT 'DROP VIEW "' || VIEWSCHEMA || '"."' || VIEWNAME || '"' AS STMT
    FROM SYSCAT.VIEWS V
    WHERE VIEWSCHEMA = CURRENT_SCHEMA
    AND NOT EXISTS 
    (
      -- To avoid statistical views deletion associated with indexes using expressions
      SELECT 1 
      FROM SYSCAT.INDEXES I
      WHERE (I.VIEWSCHEMA, I.VIEWNAME) = (V.VIEWSCHEMA, V.VIEWNAME)
    )
  DO
    EXECUTE IMMEDIATE C1.STMT;
  END FOR;
END
@
Sign up to request clarification or add additional context in comments.

3 Comments

That seems to do the job, but I’m getting an error about an index. Somehow an index ix_customers_familyname has appears as a view ix_customers_familyname_v, and I get and error 42917 that it can’t be explicitly dropped.
@Manngo Try the updated answer...
That worked perfectly. Thanks for all your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.