Home

Microsoft SQL Server - Transact-SQL Example: UNION

   

Description

This sample code shows how to use the UNION keyword to get a common list of more than one table:

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
SELECT * FROM Employees
UNION
SELECT * FROM Contractors;
GO

Here is an example where each table has a condition:

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

Home Copyright © 2011 FunctionX.com