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


DECLARE @Id AS UNIQUEIDENTIFIER
SET @Id = NEWID()
exec [inv_calculavariacoescusteio] @putilizador = 'upgrade', @pNomeTabelaTmp = NULL, @pPerformanceName = NULL, @pIsFromOriginCost = 0, @pCustoPorArtigo = 0, @AsyncKey = @Id
GO