SELECT ISNULL(MAX(c.ID), 0) + 1 AS MinID
FROM (SELECT (SELECT COUNT(*)
FROM aaa b
WHERE a.id >= b.id) AS ID, Name
FROM AAA a) c INNER JOIN
AAA d ON c.ID = d.id AND c.Name = d.Name
select c.new_id+1 as min_id from (
select isnull(min(a.id),max(a.id)) as new_id from (select id from 表) as a
left join (select min(id) as id2 from 表 union all select max(id) as id2 from test2) as b on a.id=b.id2
where b.id2 is null and not exists (select * from #test where id=a.id+1)) as c