User7354632781
User7354632781

Reputation: 2264

SQL query results into a table

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 

Upvotes: 1

Views: 17462

Answers (5)

Eton B.
Eton B.

Reputation: 6281

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

Upvotes: 2

SQLMenace
SQLMenace

Reputation: 134941

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 ......

Upvotes: 2

Brian
Brian

Reputation: 15706

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

Upvotes: 0

Haggai
Haggai

Reputation: 58

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

(make sure you create the table first)

Upvotes: 0

Jagmag
Jagmag

Reputation: 10356

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

Upvotes: 3

Related Questions