Home

Combining Records

 

Selecting from 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:

Showing Records of Various Tables 

 

Practical LearningPractical Learning: Introducing Unions

  1. Start Microsoft SQL Server and connect to the server
  2. On the Standard toolbar, click the New Query button
  3. 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
  4. Press F5 to execute
  5. To see the records from both tables, replace the code in the Query window with:
     
    USE MusicCollection
    GO
    SELECT * FROM AfricanPop;
    GO
    SELECT ALL * FROM Rock;
    GO
  6. Press F5 to see the result

Music Collection

Uniting the Records

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 What FROM OneTable
UNION
SELECT What 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 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 has 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

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. Of course, 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

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 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
(
	ContractorCode 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', 18.75),
      (N'15007', N'Ralph Sunny', 18.75);
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 Exercise1;
GO

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

Employees

In the same way, you can set a condition to follow when copying the 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 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),
    	Model nvarchar(50),
    	Price money
    );
    GO
    
    INSERT INTO NewCars
    VALUES(N'P2740442', 2010, N'Honda', N'Accord', 24650),
    	  (N'WKL72750', 2009, N'Honda', N'CR-V', 25445),
    	  (N'68471815', 2010, N'Honda', N'Accord', 28245),
    	  (N'974PP392', 2009, N'Honda', N'Civic', 22500),
    	  (N'75854H80', 2009, N'Honda', N'Civic Hybrid', 14675),
    	  (N'26RT8137', 2010, N'Honda', N'Insight', 22080);
    GO
    
    -- =============================================
    -- Database: CarDealer
    -- Table:    UsedVehicles
    -- =============================================
    CREATE TABLE UsedVehicles
    (
    	VehicleNumber nchar(20) not null,
    	YearManufactured int,
    	Make nvarchar(40),
    	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, Make, Model, OriginalPrice)
    VALUES(N'P2740442', N'Honda', N'Accord', 24650),
    	  (N'68471815', N'Honda', N'Accord', 28245),
    	  (N'75854H80', N'Honda', 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 of:

  • Inserting all records from the source to the target
  • Updating the records that meet a criterion
  • Deleting 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 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)

You start with the MERGE operator followed by the table to which the records will be added.

You continue with the USING operator followed by the table from which the records will be retrieved.

You must specify the condition by which the records must correspond. To merge the records, each of 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.

After specifying the tables and the records corresponding conditions, you must indicate what to do if/when a record from the source condition meets a record from the target table.

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 result9s) 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

Common Table Expressions (CTE)

 

Introduction

A common table expression, or CTE, is a temporary selection or other query operation of records from one or more tables. You use it to get an idea of what the query operation would produce if performed on a table. You can create a CTE to create, select, merge, or delete records.

There are two types of common table expressions: recursive and non-recursive.

Practical LearningPractical Learning: Introducing Common Table Expressions

  1. Delete everything in the Query window and replace it with the following:
     
    USE master;
    GO
    
    IF  EXISTS(SELECT name 
    	   FROM sys.databases 
     	   WHERE name = N'CeilInn3'
    )
    DROP DATABASE CeilInn3
    GO
    
    CREATE DATABASE CeilInn3
    GO
    
    USE CeilInn3;
    GO
    
    CREATE TABLE SleepingRooms (
        RoomNumber nchar(10) not null,
        RoomType nvarchar(20) default N'Bedroom',
        BedType nvarchar(40) default N'Queen',
        Rate money default 75.85,
        Available bit default 0
    );
    GO
    
    CREATE TABLE ConferenceRooms (
        RoomNumber nchar(10) not null,
        RoomType nvarchar(20) default N'Conference',
        BedType nvarchar(40),
        Rate money default 75.85,
        Available bit default 0
    );
    GO
    
    INSERT INTO SleepingRooms(RoomNumber, BedType, Rate, Available)
    VALUES(N'104', N'Queen', 80.25, 0),
          (N'105', N'King', 95.50, 1),
          (N'106', N'Queen', 65.95, 1),
          (N'107', N'Queen', 65.95, 1),
          (N'108', N'King', 92.50, 1),
          (N'109', N'Queen', 68.95, 0),
          (N'110', N'Queen', 74.95, 1);
    GO
    INSERT INTO ConferenceRooms(RoomNumber, Rate, Available)
    VALUES(N'C-120', 525.00, 1);
    GO
    INSERT INTO SleepingRooms(RoomNumber, RoomType, BedType, Rate, Available)
    VALUES(N'116', N'Studio', N'King', 112.95, 0);
    GO
    INSERT INTO ConferenceRooms(RoomNumber, Rate, Available)
    VALUES(N'C-122', 450.00, 1);
    GO
    INSERT INTO SleepingRooms(RoomNumber, RoomType, BedType, Rate, Available)
    VALUES(N'202', N'Studio', N'King', 105.95, 1),
          (N'203', N'Studio', N'Queen', 102.50, 1);
    GO
    INSERT INTO SleepingRooms(RoomNumber, BedType, Rate, Available)
    VALUES(N'204', N'Double', 115.95, 1),
          (N'205', N'Queen', 82.95, 0),
          (N'206', N'King', 98.50, 1)
    GO
    INSERT INTO ConferenceRooms(RoomNumber, Rate, Available)
    VALUES(N'C-302', 650.00, 1);
    GO
  2. Press F5 to execute

Creating a Common Table Expression

The formula to create a common table expression (CTE) is:

[ WITH <common_table_expression> [ ,...n ] ]

<common_table_expression>::=
        expression_name [ ( column_name [ ,...n ] ) ]
    AS
        ( CTE_query_definition )

You start with the WITH keyword followed by a name for the temporary set. The name mus be different from any table that will be used in the CTE's expression. Later we will see the parameters you can add after the name. After the name, type AS followed by parentheses. In the parentheses, create a simple or composite SELECT expression.

After the code that defines the CTE, that is, after the AS(CTE_query_definition) expression, create a SELECT statement that will produce the results.

Practical LearningPractical Learning: Creating a Common Table Expression

  1. Delete everything in the Query window and replace it with:
     
    USE CeilInn3;
    GO
    
    WITH BedRooms AS
    (
        SELECT * FROM SleepingRooms
    )
    
    SELECT * FROM BedRooms;
    GO
  2. Press F5 to execute
     
    WITH
  3. To see the results of both tables, change the statement as follows:
     
    USE CeilInn3;
    GO
    
    WITH BedRooms AS
    (
        SELECT * FROM SleepingRooms
    )
    
    SELECT * FROM BedRooms;
    SELECT * FROM SleepingRooms;
    GO
  4. Press F5 to execute
  5. To see a list of only available rooms from the CTE, change the statement as follows:
     
    USE CeilInn3;
    GO
    
    WITH BedRooms AS
    (
        SELECT * FROM SleepingRooms WHERE Available = 1
    )
    SELECT * FROM BedRooms
    GO
  6. Press F5 to see the result
     
    With

A CTE With Parameters

To make sure you can externally control the results of a CTE, you can pass a type of parameter to it. To do this, after the name of the CTE and before the AS operator, add the parentheses and pass one or more parameters, each represented by a name. The names of parameters must be the exact same names of columns of the table(s) from which the CTE's statement will be based. The number of columns must be the same as the number of columns that will be involved in the final SELECT statement.

In the body of the CTE, use the parameter(s) as you wish. For example, you can involve the parameter(s) in a condition in the CTE.

Practical LearningPractical Learning: Passing Parameters to a CTE

  1. To pass some parameters to the CTE, delete everything in the Query window and replace it with:
     
    USE CeilInn3;
    GO
    
    WITH BedRooms(RoomNumber, RoomType, BedType, Rate, Available)
    AS
    (
    	SELECT RoomNumber, RoomType, BedType, Rate, Available
    	FROM SleepingRooms
    	WHERE BedType = N'Queen'
    )
    SELECT RoomNumber, RoomType, Rate, Available FROM BedRooms
    GO
  2. Press F5 to execute
     
    WITH
  3. To see a list of only available rooms from the CTE, change the statement as follows:
     
    USE CeilInn3;
    GO
    
    WITH BedRooms(RoomNumber, RoomType, BedType, Rate, Available)
    AS
    (
        SELECT RoomNumber, RoomType, BedType, Rate, Available
        FROM SleepingRooms
        WHERE BedType = N'Queen'
    )
    SELECT RoomNumber, RoomType, Rate, Available
    FROM BedRooms
    WHERE Available = 1;
    GO
  4. Press F5 to see the result
     
    With

Recursive Common Table Expressions

A recursive common table expression is a CTE that can contain more than one SELECT statement. In the body of the CTE, you can create as many SELECT statements as you want but those statements must be joined. To join them, you can use a UNION, UNION ALL, or MERGER operator.

Practical LearningPractical Learning: Creating a Recursive CTE

  1. Change the CTE's code as follows:
     
    USE CeilInn3;
    GO
    
    WITH HotelRooms
    AS
    (
        SELECT * FROM SleepingRooms
        UNION
        SELECT * FROM ConferenceRooms
    )
    SELECT * FROM HotelRooms;
    GO
  2. Press F5 to execute
  3. To see a list of all available rooms, change the statement as follows:
     
    USE CeilInn3;
    GO
    
    WITH HotelRooms
    AS
    (
        SELECT * FROM SleepingRooms
        UNION
        SELECT * FROM ConferenceRooms
    )
    SELECT RoomNumber, RoomType, BedType, Rate
    FROM HotelRooms
    WHERE Available = 1;
    GO
  4. Press F5 to execute
     
    WITH

Non-Recursive Common Table Expressions

A non-recursive common table expression is a CTE that can be followed by only one SELECT, INSERT, UPDATE, or DELETE statement that involves a column from inside the CTE's body.

 
 
   
 

Previous Copyright © 2009 FunctionX, Inc. Next