You are on page 1of 15

OBJECTIVES:

• UNDERSTANDING,
CREATING & MANAGING VIEWS
VIEWS

View can be considered as a virtual representation of a table


or multiple tables
VIEW V1
Col 1 Col 2 Col 3

TABLE T1
Col 1 Col 2 Col 3 Col 4 Col 5 Col 6
VIEWS
CREATE VIEW vwDepartment
AS
SELECT [DepartmentID]
,[Name]
,[GroupName]
CREATE

,[ModifiedDate]
FROM [dbo].[Department]
GO

SELECT [DepartmentID]
,[Name]
EXECUTE

,[GroupName]
,[ModifiedDate]
FROM vwDepartment
GO
VIEWS

Advantages:

• Security
Users can be restricted direct access to a table and only allowed
to access a subset of data via views.

Ex: Users are only allowed to access customer name, phone, email via
a view but restricted from accessing the bank account and other
sensitive information.
VIEWS

Advantages (Cont...):

• Simplicity
A relational database may have many tables with complex
relationships, e.g., one-to-one and one-to-many that make it
difficult to navigate.

However, one can simplify the complex queries with joins and
conditions using a set of views.
VIEWS

Advantages (Cont...):

• Consistency
Sometimes, there is a need to write complex formulae or logic
in every query.

To make it consistent, one can put the complex queries’ logic


and calculations in views and use them where the calculation is
required rather than rewriting the query in each and every
instance.
VIEWS

Disadvantages:

• Performance
Complex, multi-table views may take considerable time due to
translation which actually are referred to the underlying source
tables.
VIEWS

Disadvantages (Cont...):

• Update Restrictions
Multi-table views are often required to be restricted to
read-only.
VIEWS

Limitations:

• Cannot pass parameters to SQL Server views


• Cannot use an ORDER BY clause in views
(Workaround: Use TOP or FOR XML)
• Views cannot be created on Temporary Tables
• Cannot associate rules and defaults with views
VIEWS

ALTER VIEW vwDepartment


MODIFYING DEFN

AS
SELECT [DepartmentID]
,[Name]
,[GroupName]
,[ModifiedDate]
FROM [dbo].[Department]
GO

From SQL Server 2016, Microsoft added “CREATE OR ALTER” for creating/modifying
procedural object definition
VIEWS
DROPPING

DROP VIEW vwDepartment


GO
RENAMING

EXECUTE sp_rename ‘vwDepartment’, ‘vwDepartmentNew’


GO
VIEWS

More…
VIEWS

Data Modification:

• Insertion/Update can be done to one underlying table at-a-time


• Insertion requires the underlying table to have NULLABLE or
DEFAULT valued columns which are not part of the view
• Deletion is not allowed in case of multi-table view
VIEWS

Data Modification (Cont…):


UPDATE vwDepartment
UPDATE

SET [Name] = [Name] + '_UPD'


WHERE [DepartmentID] = 2
GO
DELETION

DELETE FROM vwDepartment


WHERE [DepartmentID] = 2
GO

You might also like