tags:

views:

66

answers:

5

I wanna put the results from sql query into a table but if i do SELECT columns names INTO NEWTABLE(which is not created), its good for one time but when i run that query again, it says table already exists. All i am doing is results from that query into the newtable and i am gonna run it every week so it should not give me the error: table already exists.

For Example : i wanna put Following query results into a Newtable EmployeeDetails and i am gonna run it every week.

select a.Name, b.Id 
from Database1 a left join  
     Database2 b 
ON a.Id = b.Id 
+1  A: 

Use INSERT INTO instead.

But make sure that the table is already created before you call insert into the first time,

INSERT INTO table1 (column1, column2, ...)
SELECT column3, column4, ...
FROM table2
InSane
A: 

use insert - insert into newtbl select x,y,z from tbl

(make sure you create the table first)

Haggai
i tried that but table name is gonna be the same so it gives me the same error : table already exists
CombatCaptain
A: 

If you only need the generated table for the duration of the current SQL connection, create a temporary table:

CREATE TEMPORARY TABLE newtable SELECT the_rest_of_your_query

Or, if you want to keep the table around for a week, but replace it completely each week, make sure it's gone first:

DROP TABLE IF EXISTS newtable

Brian
+1  A: 

Check with IF EXISTS

example for sql server

IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[YOurTableName]') 
AND type in (N'U'))
BEGIN
      DROP TABLE [dbo].[YOurTableName
END

select * into [dbo].[YOurTableName]
from ......
SQLMenace
Only good if you want to completely replace the data.
HLGEM
I understood he want to use select into....
SQLMenace
+1  A: 
IF  EXISTS (SELECT * FROM sys.objects 
    WHERE object_id = OBJECT_ID(N'[dbo].[YOurTableName]') AND type in (N'U')) 
      //INSERT INTO STATEMENT
ELSE
     //SELECT INTO STATEMENT THAT U ALREADY HAVE
Eton B.