
DECLARE
	@EntityCode BIGINT = 1810,
	@Now DATETIME = SYSDATETIME(),
	@FiscalYear VARCHAR(10),
	@StartDate DATETIME

SELECT
	@FiscalYear = [sFiscalYear],
	@StartDate = [iPeriodBegin_dt]
FROM [dbo].[tbPeriodDetail] WITH(NOLOCK)
WHERE
	@Now >= [iPeriodBegin_dt]
AND @Now < [iPeriodEnd_dt]

IF @FiscalYear IS NULL
	RAISERROR('Fiscal year not found', 10, 1)

--DECLARE CURS CURSOR FAST_FORWARD FOR (
--	SELECT
--		[EntityID] 
--	FROM [dbo].[tbEntity] WITH(NOLOCK)
--	WHERE
--		[EntityTypeID] = 4
--		and entityid = @EntityCode
--)

--OPEN CURS

--FETCH NEXT FROM CURS INTO @EntityId

--WHILE @@FETCH_STATUS = 0
BEGIN
	UPDATE IQ SET
		[fOnHand_qty] = IB.[Inventory_qty]
	FROM [dbo].[tbItemQty] IQ WITH(NOLOCK)
	INNER JOIN (
		SELECT
			[ItemID],
			[Inventory_qty],
			[N] = ROW_NUMBER() OVER(PARTITION BY [ItemID] ORDER BY [FiscalYear] DESC, [StartDate] DESC)
		FROM [dbo].[tbItemBalance] IB WITH(NOLOCK)
		WHERE
			[EntityID] = @EntityCode
		AND [FiscalYear] = @FiscalYear
		AND [StartDate] >= @StartDate
	) IB ON
		IB.[ItemID] = IQ.[ItemID]
	AND IB.[N] = 1
	WHERE
		IQ.[EntityID] = @EntityCode
	AND IQ.[fOnHand_qty] <> IB.[Inventory_qty]

	--FETCH NEXT FROM CURS INTO @EntityId
END

--CLOSE CURS
--DEALLOCATE CURS