Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a temporary table exists and delete if it exists before creating a temporary table

I am using the following code to check if the temporary table exists and drop the table if it exists before creating again. It works fine as long as I don't change the columns. If I add a column later, it will give an error saying "invalid column". Please let me know what I am doing wrong.

IF OBJECT_ID('tempdb..#Results') IS NOT NULL     DROP TABLE #Results  CREATE TABLE #Results (     Company                CHAR(3),     StepId                TINYINT,     FieldId                TINYINT, )  select company, stepid, fieldid from #Results  --Works fine to this point  IF OBJECT_ID('tempdb..#Results') IS NOT NULL     DROP TABLE #Results  CREATE TABLE #Results (     Company                CHAR(3),     StepId                TINYINT,     FieldId                TINYINT,     NewColumn            NVARCHAR(50) )  select company, stepid, fieldid, NewColumn from #Results  --Does not work 
like image 841
Sridhar Avatar asked Mar 18 '09 16:03

Sridhar


People also ask

How do I delete a temp table in SQL?

Using the DROP TABLE command on a temporary table, as with any table, will delete the table and remove all data. In an SQL server, when you create a temporary table, you need to use the # in front of the name of the table when dropping it, as this indicates the temporary table.

How do I drop a global temporary table in SQL Server if exists?

After creation, global temporary tables become visible to any user and any connection. They can be manually dropped with DROP TABLE command. Global temporary tables are automatically dropped when the session that create the table completes and there is no active references to that table.


1 Answers

I cannot reproduce the error.

Perhaps I'm not understanding the problem.

The following works fine for me in SQL Server 2005, with the extra "foo" column appearing in the second select result:

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results GO CREATE TABLE #Results ( Company CHAR(3), StepId TINYINT, FieldId TINYINT ) GO select company, stepid, fieldid from #Results GO ALTER TABLE #Results ADD foo VARCHAR(50) NULL GO select company, stepid, fieldid, foo from #Results GO IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results GO 
like image 191
pmac72 Avatar answered Oct 14 '22 11:10

pmac72