Vissa plattformar stöder inte dollarnotering. I ditt specifika exempel bör du ha ett semikolon efter den sista END
. Du kan behöva lägga till en DECLARE
uttalande också.
DO
$$
DECLARE
BEGIN
IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'categories'))
THEN
CREATE TABLE IF NOT EXISTS categories
(
id SERIAL NOT NULL,
name character varying(40),
CONSTRAINT categories_pkey PRIMARY KEY (id)
);
INSERT INTO categories (name) VALUES ('Games');
INSERT INTO categories (name) VALUES ('Multimedia');
INSERT INTO categories (name) VALUES ('Productivity');
INSERT INTO categories (name) VALUES ('Tools');
INSERT INTO categories (name) VALUES ('Health');
INSERT INTO categories (name) VALUES ('Lifestyle');
INSERT INTO categories (name) VALUES ('Other');
END IF;
END;
$$ LANGUAGE PLPGSQL;
För plattformar som inte känner igen dollarnotering kan du använda '
istället. Du måste escape någon '
i kroppen av den anonyma funktionen dock.
Som så:
DO
'
DECLARE
BEGIN
IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''categories''))
THEN
CREATE TABLE IF NOT EXISTS categories
(
id SERIAL NOT NULL,
name character varying(40),
CONSTRAINT categories_pkey PRIMARY KEY (id)
);
INSERT INTO categories (name) VALUES (''Games'');
INSERT INTO categories (name) VALUES (''Multimedia'');
INSERT INTO categories (name) VALUES (''Productivity'');
INSERT INTO categories (name) VALUES (''Tools'');
INSERT INTO categories (name) VALUES (''Health'');
INSERT INTO categories (name) VALUES (''Lifestyle'');
INSERT INTO categories (name) VALUES (''Other'');
END IF;
END;
' LANGUAGE PLPGSQL;
DBFiddle för att se ett fungerande exempel.