Bader
Bader

Reputation: 3774

How to transfer data from one table to another

I have two tables, I want to transfer all data from the first table to the second table in case of this data is not exits i nthe second table. how to do it using MS-sql server query ?

Upvotes: 0

Views: 2086

Answers (3)

alexm
alexm

Reputation: 6882

it could be something like:

INSERT INTO tableB(FieldA, FieldB, FieldC)
SELECT a.FieldA, a.FieldB, a.FieldC
FROM tableA a 
WHERE NOT EXISTS
 (
    SELECT *
    FROM tableB b

    /* Primary key field(s)*/
    WHERE b.FieldA =a.FieldA 
 )

Upvotes: 1

Andrea Colleoni
Andrea Colleoni

Reputation: 6021

If the table doesn't exixst you can

SELECT * INTO SECOND_TABLE
FROM FIRST_TABLE;

If you want it to run even if table exists you can preceed this query with:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[YOUR_SCHEMA].[SECOND_TABLE]') AND type in (N'U'))
DROP TABLE [YOUR_SCHEMA].[SECOND_TABLE];

Upvotes: 0

Christopher Pelayo
Christopher Pelayo

Reputation: 802

in ms-sql you could do something like this:

INSERT INTO mytable(column1, column2) select value1, value2 from mytable2;

but you must make sure that the column1 and value1 have the same datatype same with column2.

Hope it helps. ;)

Upvotes: 0

Related Questions