检查postgres中是否存在表格

时间:2018-01-30 17:38:04

标签: postgresql

在Firebird中,我有以下代码来检查表是否存在:

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 ; ^

如何使用匿名阻止在Postgres中执行此操作?对不起我的英文。

2 个答案:

答案 0 :(得分:0)

我找到了解决方案:

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
$$;

答案 1 :(得分:0)

无需检查:

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

ALTER TABLE TESTE ADD CONSTRAINT PK_TESTE PRIMARY KEY (CDTESTE);