SQL query results into a table - sql

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

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

Related

How to insert data from CTE to a Temp Table?

I am trying to create a some logic using CTE and then instead of using DML statement after CTE, I am trying to create a temp table using CTE. This is possible in T-SQL. Is it possible in GBQ?
I know I can create temp table instead of CTE in the below example, but just want to know the possibility!
WITH xyz AS
(SELECT * FROM table1)
CREATE TEMP TABLE temp1 AS (
SELECT * FROM xyz INNER JOIN table2 on ...);
Use below instead
CREATE TEMP TABLE temp1 AS (
WITH xyz AS
(SELECT * FROM table1)
SELECT * FROM xyz INNER JOIN table2 on ...
);
So in 2022 I believe that no longer works without a script or session in GBQ:
You could write your query as follows:
WITH xyz AS (
SELECT
*
FROM table1
)
SELECT
*
FROM xyz
INNER JOIN table2
ON ...
and then click the More Button -> Query Settings as shown below:
After that you can set a destination for your results a a temporary table and here you can define the name of your table etc. in your case it's temp1:
This way you can just save the results of your query into a temporary table. Hope it helps!

SQL: Temp tables and script failing on second use, but works on the first

I have a script that makes use of temp tables. When I disconnect from the server, connect, and run the script, it works as expected. If I run the same script twice, it works the first time, and then on the second time, complains that;
Column name or number of supplied values does not match table definition.
I believe I am dropping the table explicitly below. I also have at the start of the script a handful of extra drop table commands for the temp tables as good measure. How can I ensure the temp tables are removed so the procedure is repeatable?
-- create table of differences
drop table if exists #TMP;
select A.*,'table A' TABLE_NAME INTO #TMP from #compare1 a
full outer join #compare2 b on a.hash = b.hash
where ( a.hash is null or b.hash is null );
INSERT INTO #TMP -- FAILS ON THIS LINE; only one the second try!
select B.*,'table B' from #compare1 a
full outer join #compare2 b on a.hash = b.hash
where ( a.hash is null or b.hash is null );
Drop the table at the end of the script not at the beginning.
If you must drop it at the beginning put a GO after the drop table if exists so it runs in its own batch before trying to compile the rest of the script.
Also consider using a more specific name than #TMP - it looks like there must be another instance of that table name created in a parent scope that is visible when compiling the batch and causing the error. (or you are altering the schema of the table in code you have not shown us)
I normally do the following if I want to run it multiple times in the query window of SQL Server management Studio. This will then always drop the temp table if it exists before running the second one.
IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects O WHERE O.xtype in ('U') AND O.id = object_id(N'tempdb..#MyTempTable'))
BEGIN
PRINT 'Removing temp table #MyTempTable'
DROP TABLE #MyTempTable;
END
CREATE TABLE #MyTempTable(
MyId BIGINT,
SomeOtherId BIGINT
)
Based on the script what I could see is that in the first Query You are using Compare1.* and the 2nd one it's Compare2.*. So looks like both tables are having a different structure. So My suggestion is to give the exact column names and map it to the actual destination than just putting *.
something like this Should Help
IF OBJECT_ID('Tempdb..#TMP;') IS NOT NULL
DROP TABLE #TMP;
select
Destination1 = A.Column1,
Destination2 = A.Column2,
Destination3 = 'table A'
INTO #TMP
from #compare1 a
full outer join #compare2 b
on a.hash = b.hash
where ( a.hash is null or b.hash is null );
INSERT INTO #TMP
(
Destination1,
Destination2,
Destination3
)
select
B.Column1,
B.Column2,
'table B'
from #compare1 a
full outer join #compare2 b
on a.hash = b.hash
where ( a.hash is null or b.hash is null );

Dynamically storing values in SQL table

I'm trying to dynamically create a variable or table in SQL which will store distinct values as a result for another sql query.
declare sample_table table
( values varchar(100))
insert into #sample_table values (select t1.value from my_tablw as t1 group by t1.value);
Supposing the distinct values in column value can change from table query to another table query, I want to store the result of this query in a user defined variable/table which can be used later in another query.
Depending on your definition of can be used later you can use a local temp table or table variable.... you just need to change the syntax a bit to not use the values since you are inserting from the results of a query. I also used DISTINCT below which is clearer than the GROUP BY without an aggregate function.
declare sample_table table ([values] varchar(100))
insert into #sample_table
select distinct t1.value
from my_tablw as t1
--one way to use it
select *
from newTable
where columnVal in (select * from #sample_table)
--another way to use it
select at.*
from anotherTable at
inner join #sample_table t on
t.column = at.column
--and another way...
select f.*
from finalTable f
where exists (select * from #sample_table t where t.column = f.column)
If you need this to be used outside the scope of your current batch, you'll need to use a persisted table or global temporary table.

Select Into error

SELECT
xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
xfqti_virtuemart_product_medias.virtuemart_media_id
INTO #tempTable
FROM xfqti_virtuemart_products_pt_pt
Gives syntax error, I'm about to pull my hair off
Being Virtuemart, I'm guessing this is a MySQL database. If so, the correct syntax for creating a temp table is:
CREATE TEMPORARY TABLE IF NOT EXISTS tempTableName AS
(
SELECT field1, field2
FROM yourtable;
)
That being said, your SELECT statement has two fields from two different tables, but only one of those tables is mentioned in the FROM clause of your statement. They should really both be in there and JOINed. Something like:
CREATE TEMPORARY TABLE IF NOT EXISTS tempTableName AS
(
SELECT
t1.virtuemart_product_id,
t2.virtuemart_media_id
FROM
xfqti_virtuemart_products_pt_pt as t1
INNER JOIN xfqti_virtuemart_product_medias as t2 ON
t1.product_id = t2.product_id
)
Or something.. I can't see your tables and it's been years since I used Virtuemart, so it's just a guess at the table relationship.
Insert Into and Selecthave these sintax
Insert into your_Table (col1,col2)
SELECT
xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
xfqti_virtuemart_product_medias.virtuemart_media_id
FROM xfqti_virtuemart_products_pt_pt
for create table
Create your_Table as
SELECT
xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
xfqti_virtuemart_product_medias.virtuemart_media_id
FROM xfqti_virtuemart_products_pt_pt

drop table and insert records from a new select statement (with the correct records)

I will like to drop an existing table and insert new records from a select statement. Keeping the coulmns the same. Old table (column a, column b) and select statment (select from a,b,c,d with inner joins)
If you need to drop completely you can do this:
Drop table yourtable
SELECT *
INTO yourtable
FROM
(SELECT a , b FROM blah, blah) x
Unless you want to change the schema of your old table, you might try a TRUNCATE TABLE:
TRUNCATE TABLE MyTable
Then you can insert into this table with a SELECT:
INSERT INTO MyTable
(
ColumnA,
ColumnB,
...
)
SELECT
ValueA,
ValueB,
...
FROM
Table1
INNER JOIN Table2
ON Table2.SomeColumn = Table1.SomeColumn
...
On the other hand, if you really want to recreate the table, then you can DROP TABLE and re-create it with a SELECT INTO as Jayvee showed.