-- Schema: C6Mart
-- Stored Procedure: PreCheckIDX

CREATE procedure C6Mart.PreCheckIDX

as
begin
	declare @Rete varchar(1)
	declare @CodiceFiscale varchar(20)
	declare @idReport int

	declare @Riga varchar(2000)
	declare @id int

	declare @flagRigaOk int

	declare @dataGenerazione datetime
	declare @dataVenerdi datetime

	declare @giorniDietro int

	set @Riga = ''
	set @id = 0

	set @dataVenerdi =  getdate()

	set @giorniDietro =
		case DATEPART(dw, @dataVenerdi)
			when 2 then 0
			when 3 then 1
			when 4 then 2
			when 5 then 3
			when 6 then 4
			when 7 then 5
			when 1 then 6
		end

	set @dataVenerdi = convert(varchar(4), year(@dataVenerdi)) + right('0' + convert(varchar(2), month(@dataVenerdi)), 2) + right('0' + convert(varchar(2), day(@dataVenerdi)), 2)

	set @dataGenerazione = dateadd(d, -@giorniDietro, @dataVenerdi)

	create table #tIdx (id int, Riga varchar(2000), flagOk int)

	declare cur cursor for
		select Rete, CodiceFiscale, idReport from c6mart.gestione_pdf_ftp where datagenerazione >= @dataGenerazione
		--and id_Fk_zip = -1

	open cur

	fetch next from cur into @Rete, @CodiceFiscale, @idReport

	while @@fetch_status = 0
	begin
		set @id = @id + 1
		set @Riga = C6Mart.Concatena_Check(@Rete, @CodiceFiscale, @idReport)
	
		if isnull(@Riga, '') = ''
			set @flagRigaOk = 0
		else
			set @flagRigaOk = 1

		insert into #tIdx (id, Riga, flagOk) values (@id, @Riga, @flagRigaOk)

		fetch next from cur into @Rete, @CodiceFiscale, @idReport
	
	end

	close cur
	deallocate cur

	select * from #tIdx

	drop table #tIdx
end
