DECLARE @FNumber INT,@fstartnumber INT ;
SET @fstartnumber=900
SELECT ROW_NUMBER() OVER (ORDER BY FNumber)+@fstartnumber-1 AS FIndex, a.FNumber
INTO #tmp
FROM(SELECT FNumber
FROM t_Voucher
WHERE FYear=2020 AND FPeriod=7 AND FGroupID=1
UNION
SELECT FNumber
FROM t_VoucherBlankOut
WHERE FYear=2020 AND FPeriod=7 AND FGroupID=1) a WHERE a.FNumber>=@fstartnumber;
IF NOT EXISTS (SELECT * FROM #tmp AS t WHERE t.FIndex<t.fnumber)
</t.fnumber)
SELECT @FNumber=ISNULL(MAX(FIndex), 0)+1 FROM #tmp;
ELSE
SELECT @FNumber=ISNULL(MIN(t.FIndex), 0)
FROM #tmp AS t
WHERE t.FIndex<t.fnumber;
</t.fnumber;
DROP TABLE #tmp;
SELECT @FNumber;