Merging tables

Last modified: March 28, 2025

When you merge tables in a database schema, it is necessary to create a new table and delete the original table. In this case, the deployment will lead to data loss of the dropped table.

Solution: To prevent data loss, you need to create a migration script to transfer data from the original table to the new table before you delete the original table. The process involves the following steps:

  • Add a column to the sample table Person
  • Generate a migration script to copy data from the original table to the new table and execute it
  • Drop the original table

Note

The comparison engine of the tools doesn’t handle all cases automatically, which is why the cases mentioned above must be resolved manually.

The screenshot displays the Schema Comparison document and the scripts generated by Schema Compare Engine and a migration script, which should be created manually to perform errorless data migration.

Scripts

The table provides source and target table script examples to illustrate the case:

Source table script example Target table script example
CREATE TABLE Person (
  PersonNumber INT PRIMARY KEY,
  PersonName VARCHAR(50) NULL,
  PersonAddress VARCHAR(150) NULL
);
CREATE TABLE Person (
  PersonNumber INT NOT NULL,
  PersonName VARCHAR(50) NULL,
  PRIMARY KEY (PersonNumber)
);

INSERT INTO Person (PersonNumber, PersonName) VALUES (74, 'Alan Dou');
INSERT INTO Person (PersonNumber, PersonName) VALUES (75, 'Jordan Sanders');

CREATE TABLE PersonAddress (
  AddressID INT AUTO_INCREMENT PRIMARY KEY,
  PersonNumber INT NOT NULL,
  AddressLine VARCHAR(50) NULL,
  State VARCHAR(50) NULL,
  Zip VARCHAR(50) NULL
);

ALTER TABLE PersonAddress
  ADD FOREIGN KEY (PersonNumber)
  REFERENCES Person (PersonNumber);

INSERT INTO PersonAddress (PersonNumber, AddressLine, State, Zip)
  VALUES (74, '2590 Main St. Bernalillo, Albuquerque', 'New Mexico', '87102');
INSERT INTO PersonAddress (PersonNumber, AddressLine, State, Zip)
  VALUES (75, '1234 Broadway Street, Apt. 77', 'New York', '10101');

The table provides examples of scripts generated by the Schema Comparison engine and those that should be generated manually for errorless data migration to illustrate the case:

Script generated by the Schema Comparison engine Script that should be generated manually for errorless data migration
DROP TABLE personaddress;

ALTER TABLE person
  ADD COLUMN PersonAddress VARCHAR(150) DEFAULT NULL;
ALTER TABLE person
  ADD COLUMN PersonAddress VARCHAR(150) DEFAULT NULL;

-- migration script:

UPDATE Person
JOIN PersonAddress
ON Person.PersonNumber = PersonAddress.PersonNumber
SET Person.PersonAddress =
  CONCAT(CONCAT(CONCAT(CONCAT(
  PersonAddress.AddressLine, ', ')
  , PersonAddress.State), ', ')
  , PersonAddress.Zip);

-- migration script.

DROP TABLE personaddress;