Skip to content
Advertisement

SQL: Temp tables and script failing on second use, but works on the first

I have a script that makes use of temp tables. When I disconnect from the server, connect, and run the script, it works as expected. If I run the same script twice, it works the first time, and then on the second time, complains that;

Column name or number of supplied values does not match table definition.

I believe I am dropping the table explicitly below. I also have at the start of the script a handful of extra drop table commands for the temp tables as good measure. How can I ensure the temp tables are removed so the procedure is repeatable?

-- create table of differences
drop table if exists #TMP;
select A.*,'table A' TABLE_NAME INTO #TMP from  #compare1 a
full outer join #compare2 b on a.hash = b.hash
where ( a.hash is null or b.hash is null );

INSERT INTO #TMP -- FAILS ON THIS LINE; only one the second try!
select B.*,'table B' from  #compare1 a
full outer join #compare2 b on a.hash = b.hash
where ( a.hash is null or b.hash is null );

Advertisement

Answer

Drop the table at the end of the script not at the beginning.

If you must drop it at the beginning put a GO after the drop table if exists so it runs in its own batch before trying to compile the rest of the script.

Also consider using a more specific name than #TMP – it looks like there must be another instance of that table name created in a parent scope that is visible when compiling the batch and causing the error. (or you are altering the schema of the table in code you have not shown us)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement