DECLARE
	@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]


select IQ.ItemID, IQ.EntityID, IQ.fOnHand_qty, IB.Inventory_qty FROM [dbo].[tbItemQty] IQ WITH (NOLOCK)
	INNER JOIN (
		SELECT
			[ItemID],
			[EntityID],
			[Inventory_qty],
			[N] = ROW_NUMBER() OVER(PARTITION BY [ItemID], [Entityid] ORDER BY [FiscalYear] DESC, [StartDate] DESC)
		FROM [dbo].[tbItemBalance] IB WITH (NOLOCK)
		WHERE
			[EntityID] in (select EntityID from tbentity with (nolock) where entitytypeid = 4 and status = 'open') AND
		 [FiscalYear] = @FiscalYear
		AND [StartDate] >= @StartDate
	) IB ON
		IB.[ItemID] = IQ.[ItemID] AND
		IB.[EntityID] = IQ.[EntityID]
	AND IB.[N] = 1
	WHERE
		IQ.[EntityID] in (select EntityID from tbentity with (nolock) where entitytypeid = 4 and status = 'open')	AND 
IQ.[fOnHand_qty] <> IB.[Inventory_qty]

order by IQ.EntityID