You are on page 1of 30

Advanced Databases

Course 4
Querying SQL Server Databases

View Objects
View: Virtual representation of one or several tables used to

capture a certain perspective on data, usually associated with


certain database roles.
View = virtual table which display various fields and records from

the source tables, without storing the actual data.


Help manage the complexity of a database and cater for the needs

of particular database users.


Views may be subject to SQL queries, acting as data sources.

User roles

Server
Column T1

Column T2

Column T3

Column T4

ColumnT1
T1
Column T3
T3
ColumnR1
R1 Cmp
ColumnR2
R2 Cmp
Cmp
Cmp

Table 1
View - User 1
Column
Column
Column
Cmp
R1R1 Cmp
R2R2 Cmp
R3R3

Column T2
T2
Column T3
T3
Column R2
R2
Cmp
Cmp
Cmp

Table 2
View - User 2

VIEW object Purposes:


Information distribution for various database roles:
Security mechanism used to restrict access to certain data for certain roles.
Users may only access explicitly defined data considered of interest to the

roles they have been assigned to.


Simplify data manipulation:
Views help assembly data from several source tables.
Querying views is easier than querying the source tables used to define the

views.
Data customization:
Different users may access the same data with a different presentation.

Assembling data from distributed databases:


In case of distributed databases, partitioned tables may be assembled in a

single view that may be queried more easily.

Types of views:
User-defined views: used according to the previously described

scenarios.

Sytem views: queried in order to produce information on the structure of

a database.

Information Schema views


o Example:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
Where TABLE_NAME= 'Student'

Catalog-type of views
o Example:
SELECT * FROM sys.tables
Views on the dynamics of server management data (Data Management View):
o Example:
SELECT session_id, client_net_address
FROM sys.dm_exec_connections

Defining and using views


View definition:
Using the graphical interface SSMS (SQL Server Management Studio):

selected fields, source tables, filters etc. are specified using objects
which provide their visual representation.
Using the SQL syntax:
(CREATE | ALTER | DROP View )
Using views:
Data produced by views may be subjected to the same SQL clauses

used in case of tables (SELECT, UPDATE, DELETE, INSERT)


If views are used as data sources, both view structure (constituent
fields) and record set are DINAMICALLY GENERATED when the
base query is executed.

Creating views using the SSMS interface

Source
tables
selection

Diagram Pane (source tables)

Criteria Pane
(field list, filters, sort order )

SQL Pane

Selection of source fields


to use in view definition

Field names to be displayed in the


record set produced by the view

Sorting options

Computed field, unavailable


in the source tables

Criterion used to filter the


records produced by the query

Managing views using SQL


CREATE VIEW viewName As
sql_SELECT_statement
ALTER VIEW viewName As
sql_SELECT_statement
DROP VIEW viewName

DEFINING VIEWS

EDITING VIEWS

REMOVING VIEWS

Example view creation:


CREATE VIEW vwExaminer As
SELECT * FROM Examiner
WHERE Department=Marketing
Example view modification:
ALTER VIEW vwExaminer As
SELECT * FROM Examiner
WHERE Department=Marketing or Department=Accounting

Managing views using SQL


Selection of data produced by views:
SELECT
FROM
Where
Group by
Having
Order by

fieldName1, fieldName2,
viewName
Filter criteria
Group fields
Filter criteria (Group fields/Aggregate expressions)
Sort fields ASC|DESC

Example view querying:


SELECT Name as Examiner Name
FROM vwExaminer
Where Degree in (lecturer, professor)
Example view querying (another table also used as a data source):
Select Name as Examiner Name
FROM vwExaminer e1 inner join Exam e2
On e1.ExaminerID = e2.ExaminerID
Where Degree in (lecturer, professor)

Indexed Views
INDEX: mechanism for performing fast data searches on

a table or a view.
It is saved as a distinct structure, auxiliary to a table or
view, which helps improving query performance and
response time.
An INDEX consists of keys corresponding to the values
of one or several fields and allow fast identification of
records associated with each key.

Creating Indexed Views in SQL


CREATE VIEW viewName WITH SCHEMABINDING As
sql_SELECT_statement

CREATE UNIQUE CLUSTERED INDEX indexName ON


viewName(fieldName)

Example:

CREATE VIEW vwIDXSubject WITH SCHEMABINDING


As
SELECT * FROM dbo.Subject
WHERE Department=marketing

CREATE UNIQUE CLUSTERED INDEX subjectIDX ON


vwIDXSubject (SubjectName)

Partitioned Views
Enable access to identically structured record

sets in distributed environments (multiple


servers);
Used to implement federative databases;
Example:
List of subjects in the realm of marketing available in two

databases (Curriculum2012 and Curriculum2011) only


unique values in fields SubjectID and SubjectName should
be displayed.

Partitioned Views - Example


Create view testPartitionedView
AS
SELECT SubjectID, SubjectName
FROM Curriculum2012.dbo.Subject
WHERE Department=marketing
UNION
SELECT SubjectID, SubjectName
FROM Curriculum2011.dbo.Subject
WHERE Department=marketing

Frequently Used
SQL System Functions

CONVERT Function
converts the result produced by an expression to a specified data type

The syntax:

CONVERT (result_data_type [(length)], expression [, date_style])


result_data_type destination data type for converting expression
length the length of the data type (only for data types that support this property)
expression any valid SQL expression, that produces a result to be converted to
result_data_type
date_style predefined code used to specify a certain SQL pattern as a data format.

Usual codes for data_style argument -> specify input/output date/time formats:

Date style

Corresponding
Date/Time format

101

mm/dd/yyyy

103

dd/mm/yyyy

108

hh:mi:sec

113

dd mon yyyy hh:mi:ss:mmm

CONVERT Function (example)

Note: 103 indicates the format


(dd/mm/yyyy) used to specify the string
to be converted to a date. If the code is
left out (as it is optional) the default date
format of the server will be used and it
may lead to errors; for instance, the
example presented here produces an
error if the default format is mm/dd/yyyy
(23 is invalid as a month).

CONVERT Function (example)

GETDATE() Function
Example: server date and time
returns the current system date and time

Example: server date

Example: server time

NEWID() Function
returns an uniqueidentifier value

DAY, MONTH, YEAR Functions


Syntax:

DAY (date_expression)
MONTH(date_expression)
YEAR(date_expression)

DATEPART Function
Syntax:
DATEPART (date_part, date/time_expression)
Returns the specified date part of a particular date/time value.
date_part
(predefined and
frequently used values)
year
month
day

Returns day of month (1-31)

dayofyear

Returns day of year (1-365/366)

quarter

Returns quarter number in year

week

Returns week number in year

hour
minute
second

DATEPART Function (example)

DATEDIFF Function
Syntax:
DATEDIFF (date_part, starting date/time , ending date/time)
Returns the difference between two dates (starting date ending date);
the result is represented by a certain number of date_part intervals.

DATEADD Function
Syntax:

DATEADD (date_part, n, start_date/time)


Returns a date/time value by adding n intervals of the specified type (date_part) to
another date (start_date/time).

LTRIM, RTRIM Functions


LTRIM(string_expression) removes leading spaces in the
given text string
RTRIM(string_expression) removes trailing spaces in the
given text string

LEN, LOWER, UPPER Functions

LEN(string_expression) returns the number of characters in


the given text string
LOWER(string_expression) returns the specified text string
converted to lowercase
UPPER (string_expression) returns the specified text string
converted to uppercase

LEFT, RIGHT, SUBSTRING Functions

LEFT(string_expression, n) returns the leading n characters


in the given text string
RIGHT(string_expression, n) returns the trailing n
characters in the given text string
SUBSTRING (string_expression, start, n) returns n
characters from the specified text string, starting with the
character in start position

You might also like