/****** Object:  StoredProcedure [dbo].[CombineDocsByDate]    Script Date: 6/10/2024 12:45:40 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER  PROCEDURE [dbo].[CombineDocsByDate]
	(
		@DateInto DateTime,
		@DateUntil DateTime
	)

AS
	SET NOCOUNT ON 

	DECLARE @N as int
	SET @N=0

	if  @DateInto = @DateUntil
	BEGIN
		select @N
		return 
	END

	DECLARE @IDTo as bigint
	DECLARE @IDFrom as bigint

	--select * from AccDocHeader where Flags <> 1

	SELECT top 1 @IDTo=ID from AccDocHeader where Flags = 1 AND id > 0 AND [DocDate]>=@DateInto and [DocDate]<@DateUntil  order by DocDate desc
	if @IDTo is null
	BEGIN
		print 'not found'
		select @N
		return 
	END

	DECLARE myCursor CURSOR FOR select ID from AccDocHeader where Flags = 1 and id > 0 and  ID<>@IDTo AND [DocDate]>=@DateInto and [DocDate]<@DateUntil Order by DocDate
	OPEN myCursor

	FETCH NEXT FROM myCursor INTO @IDFrom
	print @IDFrom
	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE @RC int
		EXECUTE @RC = [dbo].[CombineDocs] 
		 @IDFrom ,@IDTo, 1
		Print '@RC=' + Str(@RC)
		SET @N=@N+@RC
		print @N
		FETCH NEXT FROM myCursor INTO @IDFrom
		print @IDFrom
	END

	CLOSE myCursor
	DEALLOCATE myCursor

	select @N
	return 