Condition (if) does not work to insert data

0

I made this query to insert data. I should only enter data if there is nothing in the OIT1980 table. Then I mounted a cursor and ran and put an IF. If I remove the IF, it works, but if I leave it there, I do not know if the way I compare is correct, but see the code below:

set nocount on
declare 
@id_novo_rea int,
@id_exm_rea int,
@id_oit int, 
@i int

declare exame_cur cursor
 for
 select distinct er.id_exm_rea from t_cmo_Exame_Realizado er 
 inner join t_cmo_planilha_leitura pl on er.ID_XFC = pl.ID_XFC
 inner join t_cmo_exame ex on er.id_exm = ex.ID_EXM
 where er.id_exm = 3936 and pl.NO_EXM = 'TÓRAX: P.A.' and er.NO_RX in(select pl.RX_NUM from t_cmo_planilha_leitura pl)
 order by er.id_exm_rea

 open exame_cur
 fetch next from exame_cur into @id_exm_rea

 set @id_oit = (select max(id_oit) as id_oit from t_cmo_oit1980)

 while @@fetch_status = 0
 begin
    set @id_oit = @id_oit + 1

    set @id_novo_rea = (select distinct oit.id_exm_rea from t_cmo_planilha_leitura pl
    inner join t_cmo_Exame_Realizado er on pl.ID_XFC = er.ID_XFC and pl.RX_NUM = er.NO_RX
    inner join t_cmo_oit1980 oit on er.ID_EXM_REA = oit.ID_EXM_REA
    inner join t_cmo_exame ex on er.ID_EXM = ex.ID_EXM
    inner join t_cmo_oit1980_leitura  ol on oit.ID_OIT = ol.ID_OIT
    where er.ID_EXM_REA = @id_exm_rea)

    if @id_novo_rea = 0
    begin
        insert into t_cmo_oit1980_temp1 values
        (@id_oit,
         @id_exm_rea)
    end
    fetch next from exame_cur into @id_exm_rea
 end

 CLOSE exame_cur
 DEALLOCATE exame_cur

The result of the select is zero (0) The idea is popular, with new registrations and not with existing

    
asked by anonymous 24.04.2017 / 21:03

1 answer

0

I changed and resolved. I did so:

set nocount on
declare 
@id_novo_rea int,
@id_exm_rea int,
@id_oit int, 
@i int

declare exame_cur cursor
 for
 select distinct er.id_exm_rea from t_cmo_Exame_Realizado er 
 inner join t_cmo_planilha_leitura pl on er.ID_XFC = pl.ID_XFC
 inner join t_cmo_exame ex on er.id_exm = ex.ID_EXM
 where er.id_exm = 3936 and pl.NO_EXM = 'TÓRAX: P.A.' and er.NO_RX in(select pl.RX_NUM from t_cmo_planilha_leitura pl)
 order by er.id_exm_rea

 open exame_cur
 fetch next from exame_cur into @id_exm_rea

 set @id_oit = (select max(id_oit) as id_oit from t_cmo_oit1980)

 while @@fetch_status = 0
 begin
    set @id_oit = @id_oit + 1

    if @id_exm_rea not in(select distinct oit.id_exm_rea from t_cmo_planilha_leitura pl
    inner join t_cmo_Exame_Realizado er on pl.ID_XFC = er.ID_XFC and pl.RX_NUM = er.NO_RX
    inner join t_cmo_oit1980 oit on er.ID_EXM_REA = oit.ID_EXM_REA
    inner join t_cmo_exame ex on er.ID_EXM = ex.ID_EXM
    inner join t_cmo_oit1980_leitura  ol on oit.ID_OIT = ol.ID_OIT)
    begin
        insert into t_cmo_oit1980_temp1 values
        (@id_oit,
         @id_exm_rea)
    end
    fetch next from exame_cur into @id_exm_rea
 end

 CLOSE exame_cur
 DEALLOCATE exame_cur
    
24.04.2017 / 21:19