DECLARE
	@EntityId BIGINT =4761,
	@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 * 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] = @EntityId AND
		 [FiscalYear] = @FiscalYear
		AND [StartDate] >= @StartDate
	) IB ON
		IB.[ItemID] = IQ.[ItemID]
	AND IB.[N] = 1
	WHERE
		IQ.[EntityID] = @EntityId	AND 
IQ.[fOnHand_qty] <> IB.[Inventory_qty]

order by EntityID
	


	--mxls dwarf

	--select * from tbItem with (nolock)
	--where itemid = 621