0

In Firebird I have the following code to check if table exists:

SET TERM ^ ;
EXECUTE BLOCK AS
BEGIN
  IF (NOT EXISTS(SELECT 1 FROM RDB$RELATIONS WHERE RDB$RELATION_NAME = 'TESTE')) THEN
BEGIN
  EXECUTE STATEMENT
    'CREATE TABLE TESTE( ' ||
      'CDTESTE VARCHAR(7) NOT NULL, ' ||
      'FATURA VARCHAR(7)); ';
  EXECUTE STATEMENT 'ALTER TABLE TESTE ADD CONSTRAINT PK_TESTE PRIMARY KEY (CDTESTE)';
END
END^
SET TERM ; ^

How can I do that in Postgres using anonymous block? Sorry my english.

1

2 Answers 2

8

No need for a check:

CREATE TABLE IF NOT EXISTS TESTE(
   CDTESTE VARCHAR(7) NOT NULL, 
   FATURA VARCHAR(7)
);

ALTER TABLE TESTE ADD CONSTRAINT PK_TESTE PRIMARY KEY (CDTESTE);
Sign up to request clarification or add additional context in comments.

Comments

1

I found the solution:

DO $$     
begin 
  if not (SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE 
  upper(table_name) = 'TB_INGREDIENTE')) then
  CREATE TABLE tb_rep_ingredientes
  (
  cod_rep_ingrediente serial PRIMARY KEY,
  cod_ingrediente bigint,
  cod_filial bigint,
  nome character varying(30),
  preco_compra money,
  saldo real    
  );
end if;  
end
$$;

Comments

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.