﻿CREATE PROCEDURE [dbo].[RecalcAggregations]
AS

declare @q table(ExchangeId int, CRTD_PairSymbol nvarchar(10), max_LastQuote datetime)
declare  @TableName nvarchar(255)

insert into @q
	select B.ExchangeId, B.CRTD_PairSymbol,max([CRTD_LastQuote]) as max_LastQuote
		from CRT_Data_1Minute B (nolock)							
		where B.CRTD_Period>getdate()-7
		group by B.ExchangeId, B.CRTD_PairSymbol

declare cTasks cursor local static for
	select CRTT_TableName
	from CRT_tasks with (nolock)
	where CRTT_Name <> '1Minute'
	and CRTT_IsActive = 1 and CRTT_Source_TableName <> ''
	order by CRTT_ID

open cTasks
fetch next from cTasks into @TableName
while @@fetch_status = 0
begin
	insert into CRT_LastQuote(ExchangeId, TableName,CRTD_PairSymbol,LAST_CRTD_Period,LastQuote) 
	select t.ExchangeId, @TableName, t.CRTD_PairSymbol, '2015-01-01', '2015-01-01'
	from @q t
	where not exists(select 1 from CRT_LastQuote where TableName = @TableName and CRTD_PairSymbol = t.CRTD_PairSymbol and ExchangeId = t.ExchangeId)
	fetch next from cTasks into  @TableName
end
close cTasks
deallocate cTasks

exec [dbo].[CRT_Agg_All_Except1Minute]
RETURN 0
