Views (Transact‑SQL)
What is a view?
A view is a virtual table defined by a T‑SQL query. It can encapsulate complex joins, filter logic, or calculations, presenting a simplified, reusable result set to users and applications.
Creating a view
CREATE VIEW dbo.EmployeeInfo
AS
SELECT e.EmployeeID,
e.FirstName,
e.LastName,
d.DepartmentName,
e.HireDate
FROM dbo.Employees AS e
JOIN dbo.Departments AS d
ON e.DepartmentID = d.DepartmentID;
Altering a view
ALTER VIEW dbo.EmployeeInfo
AS
SELECT e.EmployeeID,
e.FirstName,
e.LastName,
d.DepartmentName,
e.HireDate,
e.Salary
FROM dbo.Employees AS e
JOIN dbo.Departments AS d
ON e.DepartmentID = d.DepartmentID;
Dropping a view
DROP VIEW dbo.EmployeeInfo;
Schema‑bound views
Use WITH SCHEMABINDING
to prevent underlying objects from being altered in a way that would affect the view.
CREATE VIEW dbo.SecureEmployeeInfo
WITH SCHEMABINDING
AS
SELECT EmployeeID, FirstName, LastName
FROM dbo.Employees;