err1
err1

Reputation: 499

How to control postgres script execution

I've a script that I simply paste into an SQL query window in POSTGRES 9.1 and run.

eg -- Begin Scripts -- Part 1

    DO
    $$
    BEGIN
    CREATE SEQUENCE base_listing_id_seq
      INCREMENT 1
      MINVALUE 1
      MAXVALUE 9223372036854775807
      START 1
      CACHE 1;
    ALTER TABLE base_listing_id_seq
      OWNER TO postgres;
    EXCEPTION
        WHEN duplicate_table THEN RAISE NOTICE 'sequence base_listing_id_seq already exists';
    END
    $$ LANGUAGE plpgsql;

    -- Part 2

    CREATE TABLE IF NOT EXISTS aes_fba_details
    (
      id serial NOT NULL,
      product_id integer NOT NULL,
      shippingprice numeric DEFAULT 0,
      fbadatetime date NOT NULL,
      currency text,
      CONSTRAINT aes_fba_details_pkey PRIMARY KEY (id)
    )
    WITH (
      OIDS=FALSE
    );
    ALTER TABLE aes_fba_details
      OWNER TO postgres;

    -- End Scripts

What I want to do is to run part 1 or part 2 depending on a value (a version string if you like) that is read in from a table.

eg

    myVariable = SELECT version-string FROM versionTable;

    ... 
    DO PART 1
    ...

    If myVariable > 1 then
        ...
        DO PART 2
        ...
    End if

Is this even possible? I apologies in advance if I've mixed up the terminology.

Upvotes: 0

Views: 141

Answers (1)

Craig Ringer
Craig Ringer

Reputation: 324265

It's possible, but you'll need to do all your DDL within a big DO block that uses IF conditions to decide what to do.

You cannot use variables or IF statements in plain SQL, only in PL/PgSQL.

Upvotes: 1

Related Questions