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 quer开发者_C百科y 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
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
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 ......
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
use insert - insert into newtbl select x,y,z from tbl
(make sure you create the table first)
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
精彩评论