4

I have two SQL Server databases, and I need to write a script to migrate data from database A to database B. Both databases have the same schema.

I must loop through the tables and for each table I must follow those rules:

  1. If the item I'm migrating does not exist in the target table (for example, the comparison is made on a column Name) then I insert it directly.
  2. If the item I'm migrating exists in the target table then I need to only update certain columns (for example, only update Age and Address but do not touch other columns)

Can anyone help me with that script? Any example would suffice. Thanks a lot

EDIT:

I just need an example for one table. No need to loop, I can handle each table separately (because each table has its own comparison column and update columns)

2 Answers 2

8

The MERGE statement looks like it can help you here. An Example:

MERGE StudentTotalMarks AS stm
USING (SELECT StudentID,StudentName FROM StudentDetails) AS sd
ON stm.StudentID = sd.StudentID
WHEN MATCHED AND stm.StudentMarks > 250 THEN DELETE
WHEN MATCHED THEN UPDATE SET stm.StudentMarks = stm.StudentMarks + 25
WHEN NOT MATCHED THEN
INSERT(StudentID,StudentMarks)
VALUES(sd.StudentID,25);

The merge statement is available as of SQL Server 2008 so you are in luck

Sign up to request clarification or add additional context in comments.

2 Comments

What if the Tables are in different databases?
Hi Youssef. Merging across different databases is supported, just use the fully qualified database name. More info: mikebosch.net/2010/08/…
0

Instead of creating a script why don't you copy the source table under a different name into the target server (update needs to take place).

Then just do a simple insert where name does not exist.

Here is the SQL for step 1 only.

INSERT INTO [TableA]
SELECT Name,
       XX,
       XXXX
FROM   TableB
WHERE  NOT NAME IN(SELECT NAME
                   FROM   TableA) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.