Friday, October 2, 2009

SQL Server 2008, SELECT INTO statement

When we create/write a Select statement containing the INTO Clause, SQL Server creates a new table and inserts the results of the Query into the new table. When we run this Select statement containing the INTO Clause more than once, we get an Error : "There is already an object named 'Table1' in the database."

In order to avoid getting this error and to be able to run this Select statement multiple times by selecting into the same table, we need to add the following code to
1. check for the Existence of this table in the database,
2. drop the table if it already exists
3. Then run the Select statement with the Into Clause

IF EXISTS (SELECT * FROM sys.objects WHERE object_id =OBJECT_ID(N'[dbo].[Table1]') AND type in (N'U'))

BEGIN
Drop table Table1
END

1 comment:

  1. Very good tip. You know, you have updated most of my reports with a similar line and it has proven to be quite useful.

    ReplyDelete