I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
(SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);
I tried but get a syntax error message.
What would you do if you want to do this?
No "VALUES", no parenthesis:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
You have two syntax options:
Option 1
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
CREATE TABLE Table2 (
id int identity(1, 1) not null,
LongIntColumn2 int,
CurrencyColumn2 money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1
Option 2
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1
Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).
Remove both VALUES and the parenthesis.
INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1
I believe your problem in this instance is the "values" keyword. You use the "values" keyword when you are inserting only one row of data. For inserting the results of a select, you don't need it.
Also, you really don't need the parentheses around the select statement.
From msdn:
Multiple-record append query:
INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase]
SELECT [source.]field1[, field2[, …]
FROM tableexpression
Single-record append query:
INSERT INTO target [(field1[, field2[, …]])]
VALUES (value1[, value2[, …])
Remove VALUES from your SQL.
Remove "values" when you're appending a group of rows, and remove the extra parentheses. You can avoid the circular reference by using an alias for avg(CurrencyColumn) (as you did in your example) or by not using an alias at all.
If the column names are the same in both tables, your query would be like this:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn) as CurrencyColumn1
FROM Table1
GROUP BY LongIntColumn;
And it would work without an alias:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn)
FROM Table1
GROUP BY LongIntColumn;
Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables.
Open both recordsets
Extract the data from the first table (SELECT blablabla)
Update 2nd recordset with data available in the first recordset (either by adding new records or updating existing records
Close both recordsets
This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)
inserting data form one table to another table in different DATABASE
insert into DocTypeGroup
Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType
from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup
Do you want to insert extraction in an existing table?
If it does not matter then you can try the below query:
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 INTO T1 FROM Table1
GROUP BY LongIntColumn1);
It will create a new table -> T1 with the extracted information
How can I check in table_1 if value_a of column_a (and where value_b of column_b = 'x') already exists in column_a of table_2? If it's not present insert it and create a new row for the missing value_a in table_2?
Update: (What seems to work is this:)
INSERT INTO products
(key, category)
SELECT key, category
FROM accounts
WHERE category = 'vegan'
AND NOT EXISTS (SELECT *
FROM products
WHERE accounts.key = products.key);
Why don't you transform the column into a primary key ? You'll just have to handle the duplicate entry error code
EDIT :
The solution here is to use SELECT instead of WHERE (thanks to degr)
INSERT INTO tableA(`id`,`column1`)
SELECT 44,'Value of Column1' -- The values you want to insert
WHERE NOT EXISTS(SELECT * FROM table2 WHERE id=40) -- check that there is no matching with the request
AND 1=1 --additional conditions
AND NOT EXISTS(SELECT * FROM Table3 WHERE id=44); --additional conditions
I want to query one table to see whether there exist any rows with 'A' type.
so I use this sql:
SELECT EXISTS(select * from %T where type = 'A');
then I need to update another table's column value to the above result. In order to prevent an insert with 'A' type happen during update, I am thinking to use a lock. but lock is very expensive, is there other alternative way to do this without locking?
If we have to use lock, I am thinking if table has already had type A, there is no need to lock insert during update because the result will still be 1. only prevent insert when there is no row with type A. How to do that?
Thanks!
Since you want to update a table when there is a type 'A', normally I would suggest you do the update or check every time right after inserting or deleting a row.
Or you could do something like this:
UPDATE table1 t1
LEFT JOIN table2 t2 ON t1.type = t2.type
SET t1.column1 = 1
WHERE t2.type IS NOT NULL
or
UPDATE table1 t1
SET t1.column1 = 1
WHERE EXISTS (
SELECT ...
FROM table2
WHERE type = 'A'
);
Please give me more details such as what is your table like and what exactly you want to do so we can discuss further.
I have to run two insert statements in two different tables.
The sqls are as under :
INSERT INTO Table1 ('t1_name', 't1_class') VALUES ('Joe','8');
Table1 has an autoincremental ti_id column
INSERT INTO Table2 ('t2_ti_id','t2_course') VALUES(< 'ti_id' from Table1 call >,
'English'),(< 'ti_id' from Table1 call >, 'Math').
So end result should have been, such that the autoincremental id set for table1 query is used in the table2 query
Table1
t1_id ti_name t1_class
1 Joe 8
Table2
t2_id t2_t1_id t1_course
1 1 English
2 1 Math
t1_id and t2_t1_id have a foreign key setup
Please tell me how to make thecalls from the same sql, so that i dont have to make a seperate perl script for this
Thanks in advance
Use last_insert_id()
Try this:
INSERT INTO Table1 (t1_name, t1_class) VALUES ('Joe','8');
SET #t1id = SELECT LAST_INSERT_ID();
INSERT INTO Table2 (t2_ti_id, t2_course)
VALUES (#t1id,'English')
I have two tables t1 and t2. t1 has duplicated values. I need to insert all records from t1 to t2, but I don't want duplicates to occur in t2. I tried the following command which seems to me correct and no syntax error when I run it but the problem, it has 0 effect. No records from t1 inserted in t2.
insert into test.t2 (name2)
select name1 from test.t1 where NOT EXISTS (select name2 from test.t2);
Can anybody help ?
insert into test.t2(name2)
select distinct name1 from test.t1 where name1 NOT IN(select name2 from test.t2);
OR
insert into test.t2(name2)
select distinct name1 from test.t1 t1 where NOT EXISTS(select name2 from test.t2 t2 where t1.name1=t2.name2);
You can create a unique index (of one or more columns) and then use the MySQL replace command.
CREATE UNIQUE INDEX unique_name2 ON t2 (name2);
REPLACE INTO t2 (name2) values ($name1);
...
You've go two options here, one involves not duplicating the data on your insert, the second being to ignore duplicates when inserting.
To de-duplicate from the SELECT call you'd use `DISTINCT:
INSERT INTO test.t2 (name2) SELECT name1 FROM test.t1 WHERE name1 NOT IN (SELECT name2 FROM test.t2)
You can also add a UNIQUE index to avoid this problem in the first place:
ALTER TABLE t2 ADD UNIQUE INDEX index_name2 (name2)
Note that you will get an error if there is already duplicate data in t2, so you may have to clean it up beforehand.
Then you can add data with the IGNORE option:
INSERT IGNORE INTO test.t2 (name2) SELECT name1 FROM TEST.t1
The unique index approach will guarantee uniqueness.
I need to insert data from user to another user and when write this statement
.....
insert into trep12.jobhead
select
*
from
wsfin04.jobhead
where
wsfin04.jobhead.job_no not in (select job_no from trep12.jobhead)
and wsfin04.jobhead.CHASS_NO not in (select CHASS_NO from trep12.jobhead)
and rdate between '01-jul-15'
and '01-oct-15'
and job_type = 1;
.....
the result is 0 rows created.
this should do it:
INSERT IGNORE INTO test.t2 SELECT name2 FROM test.t1
Selects from one table and inserts into another.