Hi @WONG Tony
select * into #TmpTable from TestTable where...
SELECT INTO statement is one of the easy ways to create a new table and then copy the source table data into this newly created table.
The insertion statements for two different conditions in your If statement use the SELECT INTO statement. I am not sure if this is the source of the problem. (There is not enough data to test).
My idea is to create #TmpTable before if condition and use this insertion statement in the if condition.
insert into #TmpTable select * from TestTable where ...
Best regards,
Percy Tang