Home

Uniting, Copying, and/or Merging Records

 

Selecting Different Tables

 

Introduction

In a Query window or the Query Designer, you can show the records of as many tables as you want and those tables don't need to have anything in common. They don't even have to belong to the same database. Consider the following database named Cruise equipped with a table named Cabins:

CREATE DATABASE Cruise;
GO
USE Cruise;
GO

CREATE TABLE Cabins(
    CabinType nvarchar(20) not null,
    Deck nchar(20),
    Size int,
    Rate1Passenger money,
    Rate2Passengers money);
GO
INSERT INTO Cabins -- Size in sq/ft	
VALUES(N'Inside', N'Riviera', 215, 289.00, 578.00),
      (N'Outside', N'Riviera', 185, 319.00, 638.00),
      (N'Outside', N'Riviera', 225, 389.00, 778.00),
      (N'Suite', N'Verandah', 295, 1009.00, 2018.00),
      (N'Inside', N'Upper', 185, 379.00, 758.00),
      (N'Inside', N'Main', 215, 359.00, 718.00),
      (N'Outside', N'Riviera', 185, 349.00, 698.00),
      (N'Suite', N'Main', 300, 885.00, 1680.00)

Here is another database named Video Collection with a table named Videos:

CREATE DATABASE VideoCollection
GO

USE VideoCollection
GO

CREATE TABLE Videos
(
	Title nvarchar(50), 
	Director nvarchar(50),
	WideScreen bit,
	Rating nchar(10),
	YearReleased int
)
GO

INSERT INTO Videos
VALUES(N'War of the Roses (The)', N'Dany de Vito', 0, N'R', 2001),
      (N'Memoirs of a Geisha', N'Rob Marshall', 1, N'PG-13', 2006),
      (N'Last Castle (The)', N'Rod Lurie', 1, N'', 2001),
      (N'Sneakers', N'Phil Alden Robinson', 1, N'PG-13', 2003);
GO

To show the records of more than one table, in a Query window, write a SELECT statement for each table and execute it. If the tables belong to different databases, make sure you indicate this. Here is an example:

USE Cruise;
GO
SELECT CabinType AS [Cabin Type], Deck, Size AS [Size in sq/ft],
       Rate1Passenger AS [Rate for 1 Passenger],
       Rate2Passengers AS [Rate for 2 Passengers]
FROM Cabins;
GO

USE VideoCollection;
GO
SELECT Title, Director, WideScreen As [Has Wide Screen],
       Rating, YearReleased AS [(c) Year]
FROM Videos;
GO

When executed, the lower part of the window displays the records of the tables, each table on its own part:

Showing Records of Various Tables 

Practical LearningPractical Learning: Introducing Unions

  1. Start the computer and log in
  2. Launch Microsoft SQL Server and click Connect
  3. Right-click the name of the server and click New Query
  4. To create a new database, type the following:
    USE master;
    GO
    
    IF  EXISTS(SELECT name 
    	   FROM sys.databases 
     	   WHERE name = N'MusicCollection'
    )
    DROP DATABASE MusicCollection
    GO
    
    CREATE DATABASE MusicCollection
    GO
    
    USE MusicCollection;
    GO
    
    CREATE TABLE AfricanPop (
    	Artist nchar(50),
    	AlbumName nvarchar(50),
    	Releaser nvarchar(50),
    	CopyrightYear int);
    GO
    
    CREATE TABLE Rock (
    	Musician nvarchar(50),
    	Title nvarchar(50) not null,
    	RecordLabel nvarchar(50),
    	YearReleased smallint);
    GO
    
    INSERT INTO AfricanPop
    VALUES(N'Salif Keita', N'Folon... The Past', N'Mango', 1995),
          (N'Vincent Nguini', N'Symphony-Bantu', N'Mesa Records', 1994),
          (N'Tshala Muana', N'Mutuashi', N'Stern''s Music', 1996);
    GO
    
    INSERT INTO Rock
    VALUES(N'Taylor Dayne', N'Can''t Fight Fate', N'Arista Records', 1989),
          (N'Cyndi Lauper', N'She''s So Unusual', N'CBS', 1983),
          (N'Beverly Hills Cop', N'Soundtrack', N'MCA Records', 1984),
          (N'Michael Jackson', N'Dangerous', N'MJJ Productions', 1991),
          (N'Bruce Hornsby and the Range', N'The Way It Is',
           N'Arista/Ariola International', 1986);
    GO
  5. Press F5 to execute
  6. Click inside the Query window and press Ctrl + A to select everything
  7. To see the records from both tables, type the following:
    USE MusicCollection
    GO
    SELECT * FROM AfricanPop;
    GO
    SELECT ALL * FROM Rock;
    GO
  8. Press F5 to see the result

Music Collection

Uniting the Records

Consider the following tables:

CREATE TABLE Employees
(
    EmployeeNumber nchar(9),
    FirstName nvarchar(20),
    LastName nvarchar(20),
    HourlySalary money,
    [Status] nvarchar(20) default N'Employee'
);
GO
CREATE TABLE Contractors
(
    ContractorCode nchar(7),
    Name1 nvarchar(20),
    Name2 nvarchar(20),
    Wage decimal(6, 2),
    [Type] nvarchar(20) default N'Contractor'
);
GO

INSERT INTO Employees(EmployeeNumber, FirstName, LastName, HourlySalary)
VALUES(N'2930-4708', N'John', N'Franks', 20.05),
      (N'8274-9571', N'Peter', N'Sonnens', 10.65),
      (N'6359-8079', N'Leslie', N'Aronson', 15.88);
GO
INSERT INTO Contractors(ContractorCode, Name1, Name2, Wage)
VALUES(N'350-809', N'Mary', N'Shamberg', 14.20),
      (N'286-606', N'Chryssa', N'Lurie', 20.26);
GO

Sometimes, either for the sake of comparing records or for preparing to merge them, you may want to display, in one view, the records of more than one table. To support the ability to select records of various tables and show them together, you use the UNION operator. The basic formula to follow is:

SELECT WhatField(s) FROM OneTable
UNION
SELECT WhatField(s) FROM AnotherTable;

 There are rules you must follow:

  • Both tables must have the same number of columns
  • The sequence of data types of the columns in each table must be the same. For example, if the column in one table is string-based, the corresponding column, by order, in the other table must also be string-based
  • The data types in the order of the columns of both tables must be compatible. For example, if the first column of one table uses an integer based data type, the first column of the other table must also have an integer-based data type that can be reconciled with the corresponding column of the other table

The columns don't have to have the same name. Here is an example of getting a union of all records from both tables:

SELECT * FROM Employees
UNION
SELECT * FROM Contractors;
GO

This would produce:

Uniting ALL Records

If you use the above formula, the records of all SELECTed tables would be included in the result. As an alternative, you can set a condition for the table(s) to exclude some records. You can set a condition on only one table, some tables, or all tables, but each table must have its own condition. Here is an exmple that unite some records of the above employees whose name end with s and the contractors who earn more than 20.00:

SELECT * FROM Employees WHERE LastName LIKE N'%s'
UNION
SELECT * FROM Contractors WHERE Wage >= 20.00;
GO

This would produce:

Uniting ALL Records

Practical LearningPractical Learning: Uniting the Records

  1. Replace the code in the Query window with:
    USE MusicCollection;
    GO
    
    SELECT * FROM AfricanPop
    UNION
    SELECT * FROM Rock;
    GO
  2. Press F5 to execute.
    This would produce:
     

    UNION

  3. Notice that, by default, the studio uses the column names of the first table as headers. If you want, you can specify the captions you want, using the AS operator.
    Change the code as follows:
    USE MusicCollection;
    GO
    
    SELECT Artist AS [Musician],
           AlbumName AS [Album Title],
           Releaser AS [Label],
           CopyrightYear AS [(c) Year]
    FROM AfricanPop
    UNION
    SELECT ALL * FROM Rock;
    GO
  4. Press F5 to execute.
    This would produce:
     

    UNION

  5. Select and delete everything in the Query window

Uniting ALL Records

By default, when UNION is used, the database engine arranges the records based on the first column. This means that if the first column is number-based, the records would be sorted in increment based on that column. If the first column is character-based, the list would be given with that column in alphabetical order. As an alternative, you can ask the database engine to include the records as they are made available, that is, the records of the first table, followed by those of the second table, and so on. To give this instruction, add the ALL keyword after UNION. The formula to follow is:

SELECT WhatField(s) FROM OneTable
UNION ALL
SELECT WhatField(s) FROM AnotherTable;

 Here is an example:

SELECT * FROM Employees
UNION ALL
SELECT * FROM Contractors;
GO

This would produce:

Uniting ALL Records

Copying Records

 

Introduction

Imagine you have two tables that are supposed to hold the same values. Maybe the tables were created by different people for the same goal. Maybe there is an old table that holds the records from previous business transactions and there is a new table with the new records. At one time, you may want to merge these records. You have various options.

Consider the following tables:

USE Exercise;
GO

CREATE TABLE Seasonals
(
	ContractorCode nchar(10),
	FirstName nvarchar(20),
	LastName nvarchar(20),
	Wage money
);

INSERT INTO Seasonals
VALUES(N'86824', N'Julie', N'Chance', 12.84),
      (N'84005', N'Ayinda', N'Kaihibu', 9.52);
GO

CREATE TABLE Employees
(
	EmplNbr nchar(10),
	FirstName nvarchar(20),
	LastName nvarchar(20),
	HourlySalary money
);

INSERT INTO Employees
VALUES(N'22684', N'Ann', N'Keans', 20.52),
      (N'48157', N'Godwin', N'Harrison', 18.75),
      (N'82476', N'Timothy', N'Journ', 28.04),
      (N'15007', N'Ralph', N'Sunny', 22.64);
GO

Copying From a Table

Copying the records consists of transferring them from one table, the source, to another table, the target. You can copy all records from the source to the target. You can select what columns to copy. Or you can specify under what conditions some records would be copied.

To copy all records from one table to another, the source and the target must have the same number of columns and the same sequence of columns with regards to their data types. To copy the records, Start an INSERT or INSERT INTO statement. Instead of the VALUES keyword, create a SELECT statement that involves the source table. Here is an example:

USE Exercise;
GO

INSERT INTO Employees SELECT * FROM Seasonals;
GO

Once this statement has been executed, all records from the source table are copied to the target table:

Employees

If you use the above formula, the records of a column from the source table would be copied to the corresponding column of the target table. Sometimes, you will want to merge tables that neither share the same sequence of columns nor have the same number of columns. Consider the following tables:

USE Exercise;
GO

CREATE TABLE Seasonals
(
	SeasonalCode nchar(10),
	Wage money,
	LastName nvarchar(20),
	FirstName nvarchar(20)
);

INSERT INTO Seasonals
VALUES(N'86824', 12.84, N'Chance', N'Julie'),
      (N'84005', 9.52, N'Kaihibu', N'Ayinda');
GO

CREATE TABLE Employees
(
	EmplNbr nchar(10),
	EmployeeName nvarchar(50),
	HourlySalary money
);

INSERT INTO Employees
VALUES(N'22684', N'Ann Keans', 20.52),
      (N'48157', N'Godwin Harrison', 18.75),
      (N'82476', N'Timothy Journ', 21.05),
      (N'15007', N'Ralph Sunny', 15.55);
GO

In such a case, before copying the records, you must analyze the table to figure out a way to converge the records. Here is an example:

USE Exercise;
GO

INSERT INTO Employees
SELECT SeasonalCode, FirstName + N' ' + Lastname, Wage FROM Seasonals;
GO 

Employees

In the same way, you can set a condition to follow when copying the records. Here is an example:

CREATE TABLE Employees
(
	EmployeeNumber nchar(9),
	FirstName nvarchar(20),
	LastName nvarchar(20),
	HourlySalary money,
	[Status] nvarchar(20) null
);
GO
CREATE TABLE ConsideredForPromotion
(
	Number nchar(9),
	FName nvarchar(20),
	LName nvarchar(20),
	Wate money,
	[Type] nvarchar(20)
);
GO
INSERT INTO Employees
VALUES(N'2860-1824', N'Julie', N'Chance', 12.84, N'Full Time'),
      (N'6842-8005', N'Ayinda', N'Kaihibu', 9.52, N'Part Time'),
      (N'9226-2084', N'Ann', N'Keans', 20.52, N'Full Time'),
      (N'2480-8157', N'Godwin', N'Harrison', 18.75, N'Full Time'),
      (N'6824-7006', N'Timothy', N'Journ', 21.05, NULL),
      (N'4150-9075', N'Ralph', N'Sunny', 15.55, N'Part Time');
GO

INSERT INTO ConsideredForPromotion
SELECT EmployeeNumber,
       FirstName,
       LastName,
       HourlySalary,
       [Status]
FROM Employees
WHERE [Status] = N'Full Time';
GO

Copying From Many Tables

You can use the ability to copy records to get records from two or more tables and add them to a another table.

The formula to follow is:

INSERT INTO TableName
SELECT WhatField(s) FROM OneTable
UNION [ALL]
SELECT WhatField(s) FROM AnotherTable;

Copying a Set of Records

Imagine you have an existing table filled with records. Instead of copying all records from that table into another table, you may want to copy only a specific number of records. To do this, use the following formula:

INSERT TOP (Number) [INTO] TargetTable
SELECT WhatObject(s) FROM WhatObject

After the INSERT keyword, add TOP followed by parentheses. In the parentheses, enter the desired number of records. The rest of the formula follows the techniques we hase used so far. Here is an example:

USE Exercise;
GO

CREATE TABLE Interns
(
	InternNumber nchar(10),
	LastName nvarchar(20),
	FirstName nvarchar(20),
	Salary money
);
GO

INSERT INTO Interns
VALUES(N'30848', N'Politanoff', N'Jeannette', 22.04),
      (N'81094', N'Bragg', N'Salomon', 15.50),
      (N'20938', N'Verne', N'Daniel', 21.24),
      (N'11055', N'Beal', N'Sidonie', 12.85),
      (N'88813', N'Jensen', N'Nicholas', 20.46);
GO

INSERT TOP (3) INTO Employees
SELECT InternNumber, FirstName + ' ' + Lastname, Salary FROM Interns;
GO

SELECT * FROM Employees;
GO

This would produce:

Employees

Notice that only 3 records from the source table were copied.

 
 
 

Copying a Percentage of Records

 Instead of copying a fixed number of records, you can specify a portion as a percentage. In this case, use the following formula:

INSERT TOP (Number) PERCENT [INTO] TargetTable
SELECT WhatObject(s) FROM WhatObject

The new keyword in this formula is PERCENT. You must use it to indicate that the number in the parentheses represents a percentage value. That number must be between 0.00 and 100.00 included. Here is an example:

USE Exercise;
GO
INSERT INTO Interns
VALUES(N'28440', N'Avery', N'Herbert', 13.74),
      (N'60040', N'Lynnette', N'Douglas', 17.75),
      (N'25558', N'Washington', N'Jacob', 20.15),
      (N'97531', N'Colson', N'Lois', 17.05),
      (N'24680', N'Meister', N'Victoria', 11.60);
GO
INSERT TOP (30) PERCENT INTO Employees
SELECT InternNumber, FirstName + ' ' + Lastname, Salary FROM Interns;
GO

This would produce:

Employees

Notice that the source table (the Interns table) has nine records but only three (9 / (100/30) = 9 / 3.33 = 2.7 ≈ 3 (the closest higher integer to 2.7 is 3)) record from that table were copied into the Employees table.

Moving Records

Consider the following two tables:

USE Exercise;
GO
CREATE TABLE Contractors
(
	ContractorCode nchar(10), Salary money,
	LastName nvarchar(20), FirstName nvarchar(20)
);
INSERT INTO Contractors
VALUES(N'86824', 12.84, N'Chance', N'Julie'),
      (N'84005', 9.52, N'Kaihibu', N'Ayinda'),
      (N'27084', 14.26, N'Gorman', N'Alex');
GO
CREATE TABLE Employees
(
	FirstName nvarchar(50),	LastName nvarchar(20),
	EmplNbr nchar(10), HourlySalary money
);
INSERT INTO Employees
VALUES(N'Ann', N'Keans', N'22684', 20.52),
      (N'Godwin', N'Harrison', N'48157', 18.75),
      (N'Timothy', N'Journ', N'82476', 21.05),
      (N'Ralph', N'Sunny', N'15007', 15.55);
GO
SELECT ALL * FROM Contractors;
GO
SELECT ALL * FROM Employees;
GO

Moving Records

Moving records consists of transferring them from one table, the source, to another table, the target. Neither SQL nor Transact-SQL directly supports this operation, which happens to be extremely easy. You have many options. Probably the easiest way to do this consists of copying the records from the source to the target, then deleting the same records from the source. Here is an example:

USE Exercise;
GO

INSERT INTO Employees
SELECT FirstName, LastName, ContractorCode, Salary
FROM Contractors
WHERE Contractors.Salary >= 10.00;
GO

DELETE FROM Contractors
WHERE Contractors.Salary >= 10.00;
GO

SELECT ALL * FROM Contractors;
GO
SELECT ALL * FROM Employees;
GO

Moving Records

Merging Records

 

Introduction

Imagine you have two tables created at different times, or by different people, or for different reasons. You may have two tables that have duplicate records (the same record(s) in more than one table, for example the same employee number and same name in two tables). You may have records in different tables but some of those records share a field's value (you may have an employee A in one table and another employee B in another table but both have the same employee number with different names, perhaps when two companies merge). As an assignment, you may be asked to combine the records of those tables into one.

Practical LearningPractical Learning: Introducing Merging

  1. In the Query window, type the following:
    -- =============================================
    -- Database:	 CarDealer
    -- Date Created: Monday 07 September 2009
    -- Author:	 FunctionX
    -- =============================================
    USE master
    GO
    
    -- Drop the database if it already exists
    IF  EXISTS (
    	SELECT name 
    		FROM sys.databases 
    		WHERE name = N'CarDealer'
    )
    DROP DATABASE CarDealer
    GO
    
    CREATE DATABASE CarDealer
    GO
    
    USE CarDealer;
    GO
    
    -- =============================================
    -- Database: CarDealer
    -- Table:    NewCars
    -- =============================================
    CREATE TABLE NewCars
    (
    	CarCode nchar(20) not null,
    	CarYear int,
    	Make nvarchar(40) default N'Honda',
    	Model nvarchar(50),
    	Price money
    );
    GO
    
    INSERT INTO NewCars(CarCode, CarYear, Model, Price)
    VALUES(N'P2740442', 2010, N'Accord', 24650),
          (N'WKL72750', 2009, N'CR-V', 25445),
          (N'68471815', 2010, N'Accord', 28245),
          (N'974PP392', 2009, N'Civic', 22500),
          (N'75854H80', 2009, N'Civic Hybrid', 14675),
          (N'26RT8137', 2010, N'Insight', 22080);
    GO
    
    -- =============================================
    -- Database: CarDealer
    -- Table:    UsedVehicles
    -- =============================================
    CREATE TABLE UsedVehicles
    (
    	VehicleNumber nchar(20) not null,
    	YearManufactured int,
    	Make nvarchar(40) default N'Honda',
    	Model nvarchar(50),
    	Mileage int,
    	OriginalPrice money,
    	CurrentValue money
    );
    GO
    
    INSERT INTO UsedVehicles
    VALUES(N'984795MM', 1998, N'Ford', N'Escort', 112683, 12420, 3250),
          (N'96304807', 2006, N'Toyota', N'Corolla', 64286, 18855, 12500);
    GO
    INSERT INTO UsedVehicles(VehicleNumber, Model, OriginalPrice)
    VALUES(N'P2740442', N'Accord', 24650),
          (N'68471815', N'Accord', 28245),
          (N'75854H80', N'Civic Hybrid', 14675);
    GO
  2. Press F5 to execute
  3. To see the records of each table, replace the code in the Query window with:
    USE CarDealer;
    GO
    SELECT CarCode AS [Car Code], CarYear AS [Year],
           Make, Model, Price AS [Market Value] FROM NewCars;
    GO
    SELECT VehicleNumber AS [Vehicle #], YearManufactured AS [Year],
           Make, Model, Mileage, OriginalPrice AS [Original Value],
           CurrentValue AS [Market Value] FROM UsedVehicles;
    GO
  4. Press F5 to execute

Car Dealer

Merging the Records

Record merging consists of inserting the records of one table, referred to as the source, into another table, referred to as the target. When performing this operation, you will have the option to:

  • Insert all records from the source to the target
  • Update the records that meet a criterion
  • Delete some records based on a condition

 The primary formula to merge two tables is:

MERGE Table1 AS Target
USING Table2 AS Source
ON Table1.CommonField = Table2.CommonField
WHEN MATCHED Matched Options
    THEN Match Operation(s)
WHEN NOT MATCHED BY TARGET
    THEN Not Matched By Target Operation(s)
WHEN NOT MATCHED BY SOURCE
    THEN Not Matched By Source Operation(s)

You start with the MERGE operator followed by the table to which the records will be added. Here is an example:

MERGE Contractors AS Workers

You continue with the USING operator followed by the table from which the records will be retrieved. Here is an example:

MERGE Contractors AS Workers
USING Employees AS Teachers

You must specify the condition by which the records must correspond.

To merge the records, the tables must have a common column. The columns don't have to have the same name but they should be of the same type (and size). To provide this information, type ON followed by the condition. Here is an example:

MERGE Contractors AS Workers
USING Employees AS Teachers
ON Workers.ContractorCode = Teachers.EmployeeNumber

To make the statement easier to read, you can include it in parentheses.

After specifying the tables and the records corresponding conditions, you must indicate what to do if/when a record from the source table meets a record from the target table. These conditions are set in the last part of the statement.

Consider the following tables:

CREATE TABLE Contractors
(
    ContractorCode nchar(10),
    FName nvarchar(20),
    LName nvarchar(20),
    Wage decimal(6, 2)
);
GO
CREATE TABLE Employees
(
    EmployeeNumber nchar(10),
    DateHired date,
    FirstName nvarchar(20),
    LastName nvarchar(20),
    HourlySalary money,
    EmploymentStatus nvarchar(20) null
);
GO
INSERT INTO Contractors
VALUES(N'350809', N'Mary', N'Shamberg', 14.20),
      (N'286606', N'Chryssa', N'Lurie', 20.26),
      (N'415905', N'Ralph', N'Sunny', 15.55);
GO
INSERT INTO Employees
VALUES(N'286018', N'20020426', N'Julie', N'Chance', 12.84, N'Full Time'),
      (N'286606', N'19981008', N'Ayinda', N'Kaihibu', 9.52, N'Part Time'),
      (N'922620', N'20100815', N'Ann', N'Keans', 20.52, N'Full Time'),
      (N'415905', N'20061222', N'Godwin', N'Harrison', 18.75, N'Full Time'),
      (N'682470', N'20080430', N'Timothy', N'Journ', 21.05, NULL);
GO

This would produce:

Merging Records

When merging records, the first conditional operation is to decide what to do if two records match. To start, you would add a WHEN MATCHED statement:

MERGE Contractors AS Workers
USING Employees AS Teachers
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN MATCHED

If two records of the tables match, one thing you can do is to delete the matching record. To do this, after the WHEN MATCHED expression, add a THEN DELETE statement. Here is an example:

MERGE Contractors AS Workers
USING Employees AS Teachers
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN MATCHED
    THEN DELETE;
GO

SELECT ALL * FROM Employees;
GO
SELECT ALL * FROM Contractors;
GO

Merging Records

Imagine that you want to merge the records of both tables by inserting the employees in the Contractors table. Instead of deleting matching records, another option is to update the matched records. Notice that there are two employees who have the same employee number as two contractors. In this case, a simple solution we will use is to precede those employee numbers by 00. We can write the same statement as follows:

MERGE Contractors AS Workers
USING Employees AS Teachers
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN MATCHED
    THEN UPDATE SET ContractorCode = N'00' + ContractorCode

The other operation is to specify what to do if the records don't match: Simple, we will simply merge them (the employees) with the others (the contractors). This can be done as follows:

MERGE Contractors AS Workers
USING Employees AS Teachers
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN MATCHED
    THEN UPDATE SET ContractorCode = N'00' + ContractorCode
WHEN NOT MATCHED
    THEN INSERT(ContractorCode, FName, LName, Wage)
    VALUES(EmployeeNumber, FirstName, LastName, HourlySalary);
GO

We can them see the contents of both tables again to see what records each contains now:

SELECT ALL * FROM Employees;
GO
SELECT ALL * FROM Contractors;
GO

Merging Records

Of course, in the same way, you can merge the records of any table to those of the other table, as long as you follow the rules. For example, based on the above tables, if you want to merge the contractors with the employees, you can specify the Employees table as the target, the Contractors table as source, and their numbers as the common column to match. Then, when the numbers match, you can specify what to do. For us, once more we can simply ask the database engine to start the number with 00. For the records that don't match, we can simply add the records from the source to the targe. Here is an example:

MERGE Employees AS Teachers
USING Contractors AS Workers
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN MATCHED
    THEN UPDATE SET EmployeeNumber = N'00' + ContractorCode
WHEN NOT MATCHED
    THEN INSERT(EmployeeNumber, FirstName, LastName, HourlySalary)
    VALUES(ContractorCode, FName, LName, Wage);
GO

Merging Records

When you write WHEN NOT MATCHED, it is assumed that you want the cases where a record of the target matches a record of the source. As a result, you can also write the expression as WHEN NOT MATCHED BY TARGET:

MERGE Employees AS Teachers
USING Contractors AS Workers
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN MATCHED
    THEN UPDATE SET EmployeeNumber = N'00' + ContractorCode
WHEN NOT MATCHED BY TARGET
    THEN INSERT(EmployeeNumber, FirstName, LastName, HourlySalary)
    VALUES(ContractorCode, FName, LName, Wage);
GO

To specify what to do if a record of the source matches one from the target, add a WHEN NOT MATCHED BY SOURCE statement. In this case, you must use either a DELETE or an UPDATE statment.

Practical LearningPractical Learning: Merging the Records

  • Delete the whole code in the Query window and replace it with:
    USE CarDealer;
    GO
    
    MERGE UsedVehicles AS Target
    USING NewCars AS Source
    ON (Target.VehicleNumber = Source.CarCode)
    WHEN NOT MATCHED BY Target
        THEN INSERT(VehicleNumber, YearManufactured,
    	        Make, Model, OriginalPrice)
    	 VALUES(CarCode, CarYear, Make, Model, Price)
    WHEN MATCHED
        THEN UPDATE SET Target.YearManufactured = Source.CarYear,
    		    Target.Make = Source.Make,
    		    Target.Model = Source.Model,
    		    Target.OriginalPrice = Source.Price
    GO

Outputting the Results of a Merge

If you do a merge using the above formula, after the merge has been performed, you would not know the results) unless you run a new query on the target table. Fortunately, you can ask the database engine to immediately display a summary of what happened. To do this, after the last THEN statement, create an OUTPUT expression. The formula to follow is:

MERGE Table1 AS Target
USING Table2 AS Source
ON Table1.CommonField = Table2.CommonField
WHEN MATCHED Matched Options
    THEN Match Operation(s)
WHEN NOT MATCHED BY TARGET Not Matched By Target Options
	THEN Not Matched By Target Operation(s)
WHEN NOT MATCHED BY SOURCE Not Matched By Source Options
	THEN Not Matched By Source Operation(s)
OUTPUT $action, DELETED | INSERTED | from_table_name.*

To get a summary of the merging operation(s):

  • If you are performing only one type of operation, type OUTPUT, followed by either inserted.* or deleted.*
  • If you are performing different types of operations, type OUTPUT, followed by $action, followed by either inserted.* or deleted.* or both

Practical LearningPractical Learning: Outputting the Results of a Merge

  1. To see the records of each table, add the following last line:
    USE CarDealer;
    GO
    
    MERGE UsedVehicles AS Target
    USING NewCars AS Source
    ON (Target.VehicleNumber = Source.CarCode)
    WHEN NOT MATCHED BY Target
    	THEN INSERT(VehicleNumber, YearManufactured,
    		    Make, Model, OriginalPrice)
    	     VALUES(CarCode, CarYear, Make, Model, Price)
    WHEN MATCHED
    	THEN UPDATE SET Target.YearManufactured = Source.CarYear,
    			Target.Make = Source.Make,
    			Target.Model = Source.Model,
    			Target.OriginalPrice = Source.Price
    OUTPUT $action, inserted.*, deleted.*;
    GO
  2. Press F5 to execute
  3. To see the results on the target table, change the statement as follows:
    USE CarDealer;
    GO
    
    SELECT ALL * FROM UsedVehicles;
    GO
  4. Press F5 to execute
     
    Car Dealer
  5. Click inside the Query window and press Ctrl + A to select everything
  6. To delete the database in this lesson, type the following:
    USE master;
    GO
    DROP DATABASE MusicCollection;
    GO
    DROP DATABASE CarDealer;
    GO
  7. Close the Query window
  8. When asked whether you want to save, click No
  9. Close Microsoft SQL Server

Exercises

   

Lesson Summary Questions

  1. What are the two rules to create a union of tables (Select 2)?
    1. There must be a maximum of 6 tables
    2. The number and the order of the columns must be the same
    3. The names of the tables must be the same
    4. The data types must be compatible
    5. The database must have a clustered index
  2. What is the basic formula to create a union of two tables?
    1. SELECT WhatField(s) FROM OneTable
      UNION
      SELECT WhatField(s) FROM AnotherTable;
    2. WITH UNION
      SELECT WhatField(s) FROM OneTable
      ADD
      SELECT WhatField(s) FROM AnotherTable;
    3. SET UNION ON
      SELECT WhatField(s) FROM OneTable
      JOIN
      SELECT WhatField(s) FROM AnotherTable;
    4. SELECT WhatField(s) FROM OneTable
      UNION WITH
      SELECT WhatField(s) FROM AnotherTable;
    5. ON SELECT WhatField(s) FROM OneTable
      JOIN SELECT WhatField(s) FROM AnotherTable;
      UNION ALL
      
  3. What types of DML operations can be performed in a MERGE statement (Select 3)?
    1. CREATE
    2. SELECT
    3. INSERT
    4. UPDATE
    5. DELETE

Answers

  1. Answers
    1. Wrong Answer
    2. Right Answer
    3. Wrong Answer
    4. Right Answer
    5. Wrong Answer
  2. Answers
    1. Right Answer
    2. Wrong Answer
    3. Wrong Answer
    4. Wrong Answer
    5. Wrong Answer
  3. Answers
    1. Wrong Answer
    2. Wrong Answer
    3. Right Answer
    4. Right Answer
    5. Right Answer
 
 
   
 

Previous Copyright © 2009-2011 FunctionX.com Next