If exists update else insert in table with foreign key postgres

0

I need to make an insert in a table with a foreign key, so if that record does not exist in the other table I need to do an insert, can I do this using if exists? Any solution?

    
asked by anonymous 08.05.2017 / 21:57

1 answer

1

You can use IF EXISTS , checking if the value exists in the table with FK:

IF NOT EXISTS (SELECT 1 FROM TabelaFK WHERE campo = valor) THEN
  -- insere os dados na tabela "FK"
END IF;

PostgreSQL ference: EXIST

It can also be done like this:

declare 
tot integer;

SELECT count(*) INTO tot
FROM forma_pagamento WHERE descricao like '%dinheiro%'

IF tot> 0 THEN
   insert into forma_pagamento (id_conta_preferencial, id_operadora_cartao, descricao, ativo, caixa, conta, cartao, cheque_proprio, cheque_terceiro) values (2, 2, 'dinheiro', true, false, false, false, false, false)
END IF;
    
08.05.2017 / 22:07