Firebird, insert with where not exists

4

I'm trying to insert a record into the table, but this record will only be inserted if it does not already exist there, so I'm trying to do it like this:

INSERT INTO R01 (NUMERO,EXPORTADOR, IMPORTADOR, DATAANTECIPADO, STATUS)
VALUES
(64, 'CCB TESTE LTDA.', 'CCB TESTE LTDA.', (select     cast('Now' as date) from rdb$database), 'A')
WHERE NOT EXISTS ( SELECT * FROM R01 WHERE NUMERO=64 ,SERIE='CTE' );

The error message is this:

  

Dynamic SQL Error.   SQL error code = -104.   Token unknown - line 4, char 1.   WHERE.

    
asked by anonymous 20.07.2015 / 16:07

3 answers

2

I understood what you need; you can do a procedure and execute when you need it. Just take it into account of course, that you will have to make some adjustments to it, because I do not know your database. It follows:

CREATE OR ALTER PROCEDURE SP_STACKOVERFLOW (
    p_numero integer,
    p_serie varchar(3),
    p_exportador varchar(255),
    p_importador varchar(255))
as
declare variable existe integer;
declare variable dataatual integer;
begin

  select
     count(r01.<id da sua tabela>)
  from
    R01
  where
    numero = :P_NUMERO and
    serie = :p_serie
  into
    :existe;

  if (existe = 0) then
  begin

    dataatual = current_date;

    INSERT INTO R01 (NUMERO, EXPORTADOR, IMPORTADOR, DATAANTECIPADO, STATUS)
    VALUES
        (:p_numero, :p_exportador, :p_importador, :dataatual, 'A');
  end

end

To use the procedure, run a script with the following code:

execute procedure SP_STACKOVERFLOW(64, 'CTE', 'CCB TESTE LTDA.', 'CCB TESTE LTDA.');

I hope I have helped!

    
22.07.2015 / 14:04
2

Good afternoon,

This post already has some time, but I needed this feature today and I managed to solve with the example below (Firebird), based on the previous response:

Insert Into TBCFOP
  (CODCFOP, DESCRICAO)
Select '5.505', 'REM DE MERCADORIAS ADQ OU RECEB P/ FORM DE LOTE P/ EXP'
  From RDB$DATABASE
 Where Not Exists
       (
         Select 1
           From TBCFOP
          Where CODCFOP = '5.505'
       );
    
23.01.2018 / 19:06
0

Good afternoon,

It would not be the right way but you can 'fetch' values from dummy this way so you can use 'where':

    INSERT INTO R01 (NUMERO,EXPORTADOR, IMPORTADOR, DATAANTECIPADO, STATUS)
    select 64, 'CCB TESTE LTDA.', 'CCB TESTE LTDA.', 
    (select cast('Now' as date) from rdb$database), 'A')
    from dummy
    WHERE NOT EXISTS ( SELECT 1 FROM R01 WHERE NUMERO=64 ,SERIE='CTE' ); 
    
25.11.2016 / 20:20