Assign a cursor value to a table column

1

I have a cursor. I need in an insert to insert the value of each cursor position to a table. How do I do this? I need to insert the value of the exame_cur cursor. My code below:

set nocount on
declare 
@id_xfc int,
@id_exm_rea int,
@id_oit 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

 select max(id_oit) as id_oit into t_id_oit_1 from t_cmo_oit1980

 --insert into t_cmo_oit1980_temp1(id_oit) select id_oit from t_id_oit_1

 while @@fetch_status = 0
 begin
    insert into t_cmo_oit1980_temp1
    select
    (select id_oit + 1 from t_cmo_oit1980_temp1),
    (@id_exm_rea)

 end

 CLOSE exame_cur
 DEALLOCATE exame_cur

select * from t_cmo_oit1980_temp1
go

Is my code above correct?

I updated the code for the above, and running is taking a long time. I've posted these lines and it's not over yet.

    
asked by anonymous 24.04.2017 / 17:44

1 answer

0

You just needed to use the variable that fetch loaded with the value in insert and make fetch back into loop while :

while @@fetch_status = 0
begin
    -- aqui, verificar se o insert está correto usando @id_exm_rea
    insert into t_cmo_oit1980_temp1 values (@id_exm_rea)

    -- aqui pega o próximo valor do cursor
    fetch next from exame_cur into @id_exm_rea
end
    
25.04.2017 / 13:07