а вот тут:
https://docs.microsoft.com/en-us/sql/t-sql/statements/drop-table-transact-sql?view=sql-server-ver15предупреждение:
! Important
DROP TABLE and CREATE TABLE should not be executed on the same table in the same batch. Otherwise an unexpected error may occur.
drop table #t1
select p.ID as PID,pp.id into #t1 FROM tmp_for_attach t
inner join people p on t.enp=p.enp--t.fam=p.fam and t.IM=p.IM AND t.OT=p.OT AND t.DR=p.DR
inner join POLIS PP ON P.ID=pP.PID
WHERE (stage = 1) AND t.opdoc=3
order by p.id,pp.ID
drop table #t2
select p.ID,MAX(pp.id) as maxpolid into #t2 FROM tmp_for_attach t
inner join people p on t.enp=p.enp--t.fam=p.fam and t.IM=p.IM AND t.OT=p.OT AND t.DR=p.DR
inner join POLIS PP ON P.ID=pP.PID
WHERE (stage = 1) AND t.opdoc=3
group by p.id
order by p.id
delete from #t1 where id in(select #t2.maxpolid from #t2)
drop table #t2
select PID,MAX(id)as id into #t2 from #t1
group by pid
order by pid