tags:

views:

119

answers:

4

I have table A and table B, same schemas.

I want to insert certain rows from table A into table B. For example, insert into table B all rows from table A with column 'abc' > 10.

Couldn't figure out how to do it

+1  A: 

You can use the following notation:

BEGIN TRAN
INSERT INTO ExistingTable (Col1, Col2...)
SELECT Something1, Something2... FROM Table1 WHERE ...
--ROLLBACK/COMMIT
Adamski
+5  A: 

Something like this

INSERT INTO B (supplier_id, supplier_name)
SELECT supplier_id, supplier_name FROM A
WHERE abc > 10;

Make sense?

Chris Harris
The where clause needs the single quotes removed from the column name. Right now you are comparing the string 'abc' to see if it is greater than 10.
Shannon Severance
@Shannon: Fixed, Thanks!
Chris Harris
+1  A: 

At first blush, I'd say something like:

Insert Into B
(Select * from A
Where abc > 10)
AllenG
A: 

I like to do it this way :

create table temp_B
as
select * from A
where abc > 10
union
select * from B;
drop table B;
rename temp_B to B;

If you have to insert millions+ rows, you could win several hours. Don't forget to recreate index & recompile objects.

Scorpi0
That only works if there isn't already data in Table B that you'll need to keep (which isn't also in table A).
AllenG
You keep all the data from Table B because you join with the select * from B, so you are sure to not lose any data.
Scorpi0