exec std_droptemptable '#tempregistoscalcvariacoes' GO select a.* into #tempregistoscalcvariacoes from ( select artigo = m.artigo, grupocustos = m.grupocustos, m.lote, data = min(m.[data]) ,actquantidades = 1 , idcusteio = convert(uniqueidentifier, null) ,apenascalculocusto = convert(bit,0) from inv_custeio m inner join ( select distinct artigo from inv_custeio where dataref is not null ) a on a.artigo = m.artigo group by m.artigo, m.grupocustos, m.lote union all select artigo = m.artigo, grupocustos = m.grupocustos, m.lote, data = min(m.[data]) ,actquantidades = 1 , idcusteio = convert(uniqueidentifier, null) ,apenascalculocusto = convert(bit,1) from inv_custeio m inner join ( select distinct artigo from inv_custeio where dataref is null ) a on a.artigo = m.artigo where a.Artigo in (select c.Artigo from INV_Origens o inner join inv_custeio c on o.id = c.IdOrigem ) group by m.artigo, m.grupocustos, m.lote ) a where a.artigo in ('colocar aqui o codigo do artigo') and a.data > 'colocar aqui a data de inicio' --para definir a data de inicio exec [inv_calculavariacoescusteio] @putilizador = 'upgrade', @pperformancename = '' GO