Creating views using the Query DesignerBecause a view is nothing more than a saved SQLSELECTstatement, the creation of a view begins with a workingSELECTstatement.. For more details on u
Trang 1Creating views using the Query Designer
Because a view is nothing more than a saved SQLSELECTstatement, the creation of a view begins with
a workingSELECTstatement Any SQLSELECTstatement, as long as it’s a valid SQLSELECT
state-ment (with a few minor exceptions), can be cut and pasted from nearly any other tool into a view
Within SQL Server Management Studio, views are listed in their own node under each database
The New View command in the context menu launches the Query Designer in a mode that creates
views, as shown in Figure 14-1
FIGURE 14-1
Creating a view in Management Studio’s Query Designer
The View Designer mode functions within Management Studio’s Query Designer, which is also used to
query tables The actual SQL code for the view is displayed or edited in the SQL pane Columns may be
added to the view by using the Diagram pane, the Grid pane, or the SQL pane The Add Table feature,
Trang 2available in the context menu or toolbar, can add tables, other views, synonyms, and table-valued
functions
Tables or other views can be added to the new view by dragging them to the Diagram pane from the
Object Explorer or using the Add Table context menu option
There’s a toolbar button and a context menu item to add a derived table to the view, but all it does is
slightly modify thefromclause to create a placeholder for the subquery The SQL for the subquery is
then manually entered in the SQL pane
The Verify SQL Syntax button in the toolbar verifies only the SQL syntax; it does not verify the names
of tables, views, or columns in the SQLSELECTstatement
To test the view’s SQLSELECTstatement within Query Designer, use the Execute SQL button or F5
This will run theSELECTstatement by itself, without creating the view
The Save toolbar button actually runs the script to create the view in the database Note that the view
must be a valid, error-free SQLSELECTstatement in order to be saved
For more details on using the Query Designer, refer to Chapter 6, ‘‘Using Management
Studio.’’
Once the view is created, several tasks may be performed on the view using Object Explorer’s view
con-text menu:
■ Redesign the view: Opens the Query Designer tool with the view’sSELECTstatement
■ Select top n rows: Opens the Query Editor with aSELECTstatement referencing the view
The number of rows selected can be modified in Management Studio’s options
■ Edit top n rows: Opens the Query Designer with aSELECTstatement referencing the view,
with only the results pane visible, and executes the view
■ Script the view: Management Studio can script the DDL statements toCREATE,ALTER, or
DROPthe view, as well as sample DML statements referencing the view
■ View dependencies: This option can be very important because views, by definition, reference
other data sources, and are often referenced themselves
■ Full-text indexes: A full-text index (covered in Chapter 19, ‘‘Using Integrated Full-Text
Search’’) can be created and managed based on data selected by the view
■ Policies: Apply and manage policy-based management policies for the view
■ Rename/Delete the view: The view may also be renamed or dropped by selecting it and
pressing Rename or Delete, respectively
■ Properties: Opens the properties dialog with pages for security permissions and extended
properties
Double-clicking the view opens its subnodes: columns, triggers (instead of tasks), indexes (indexed
views), and statistics
Trang 3Creating views with DDL code
Views may be managed using the Query Editor by executing SQL scripts with the data definition language
(DDL) commands:CREATE,ALTER, andDROP The basic syntax for creating a view is as follows:
CREATE VIEW schemaname.ViewName [(Column aliases)]
AS SQL Select Statement;
For example, to create the viewvEmployeeListin code, the following command would be executed
in a query window:
USE AdventureWorks2008 Go
CREATE VIEW dbo.vEmployeeList AS
SELECT P.BusinessEntityID, P.Title, P.LastName, P.FirstName, E.JobTitle
FROM Person.Person P INNER JOIN HumanResources.Employee E
ON P.BusinessEntityID = E.BusinessEntityID
As with creating any object, thecreatecommand must be the only command in the batch
Although I’m generally opposed to Hungarian notation (tblTablename, intIntegerColumn, etc.) for database objects, I prefer to preface views with a lowercase v , simply to keep them separate in data source listings, but, to be honest, most database developers do not preface views
with a v
The view name must be unique in the database Attempting to create a view with a name shared by any
other object will generate an error
Executing views
Technically, a view by itself cannot be executed A view can only patiently wait to be referenced by a
SQL query
A query (SELECT,INSERT,UPDATE,DELETE, orMERGE) can include the view as a data source, and
that query can be executed As illustrated in Figure 14-2, a view is useful only as a data source within a
query You can think of a view as nothing more than a placeholder for a savedSELECTstatement
The followingSELECTstatement references thevEmployeeListview:
SELECT BusinessEntityID, LastName, FirstName, JobTitle
FROM dbo.vEmployeeList
Trang 4FIGURE 14-2
When the query that references a view is submitted to SQL Server, the query parser picks the query
apart and replaces the name of the view with the view’sselectstatement
ad hoc Query
VIEW dbo.vEmployeeList
SELECT BusinessEntityID, LastName,
FirstName, JobTitle
FROM dbo.vEmployeeList;
SELECT P.BusinessEntityID, P.LastName, P.FirstName, E.JobTitle
FROM Person.Person P INNERJOIN HumanResources.Employee E
ON P.BusinessEntityID = E.BusinessEntityID
Query Parser
includes the view
into the submitted
query
Executed Query SELECT BusinessEntityID, LastName,
FirstName, JobTitle
FROM (SELECT P.BusinessEntityID, P.LastName, P.FirstName, E.JobTitle
FROM Person.Person P
INNER JOIN HumanResources.Employee E
ON P.BusinessEntityID = E.BusinessEntityID);
Result (abbreviated):
BusinessEntityID LastName FirstName JobTitle
- - -
3 Tamburello Roberto Engineering Manager
When views are referenced from ad hoc queries, aWHEREcondition is typically added to filter the data
from the view:
SELECT BusinessEntityID, LastName, FirstName, JobTitle
FROM dbo.vEmployeeList
WHERE JobTitle = ‘Database Administrator’;
Trang 5BusinessEntityID LastName FirstName JobTitle - - -
-270 Ajenstat Fran¸coi Database Administrator
Altering and dropping a view
It’s likely that the view’sSELECTstatement will need to be changed at some point in time Once a view
has been created, the SQLSELECTstatement may be easily edited by using theALTERcommand
Alter-ing the view changes the savedSELECTstatement while keeping any properties and security settings in
place This is preferable to dropping the view, losing all the security settings and properties, and then
recreating the view
TheALTERcommand supplies a new SQLSELECTstatement for the view:
ALTER SchemaName.ViewName AS
SQL Select Statement;
Management Studio can automatically generate anALTERstatement from an existing view In Object
Explorer, select the view and then choose Script View as➪ Alter to ➪ New Query Editor Window from
the context menu
If the view is no longer needed, it can be completely erased from the database using theDROP
command:
DROP VIEW SchemaName.ViewName;
Within a script that is intended to be executed several times, the following code can drop and recreate
the view:
IF OBJECT_ID(’vEmployeeList’) IS NOT NULL
DROP VIEW dbo.vEmployeeList
Go
CREATE VIEW SchemaName.ViewName
AS SQL Select Statement;
Just to reiterate, views don’t contain any data, so there’s no danger that dropping a view will cause any
data loss However, applications, reports, and other objects might depend on the view, and dropping
the view might break something else For more about viewing dependencies within SQL Server, see the
section ‘‘Nesting Views’’ later in this chapter
A Broader Point of View
Trang 6Column aliases
The column aliases option is rarely used With syntax similar to the column list for a common table
expression, the view’s column list renames every output column just as if every column had those alias
names in theSELECTstatement The view’s column list names override any column names or column
aliases in the view’sSELECTstatement
The following query alters thevEmployeeListview so that the result columns becomeID,Last,
First, andJob:
ALTER VIEW dbo.vEmployeeList (ID, Last, First, Job)
AS
SELECT P.BusinessEntityID,
P.LastName, P.FirstName, E.JobTitle
FROM Person.Person P
INNER JOIN HumanResources.Employee E
ON P.BusinessEntityID = E.BusinessEntityID
GO
SELECT *
FROM dbo.vEmployeeList
Result (abbreviated):
- -
-1 S´anchez Ken Chief Executive Officer
2 Duffy Terri Vice President of Engineering
3 Tamburello Roberto Engineering Manager
Order by and views
Views serve as data sources for other queries and don’t support sorting the data within the view To sort
data from a view, include theORDER BYclause in the query referencing the view For example, the
fol-lowing code selects data from thevEmployeeListview and orders it byLastName,FirstName The
ORDER BYclause is not a part of vEmployeeList, but it is applied to the view by the executing SQL
statement:
SELECT *
FROM dbo.vEmployeeList
ORDER BY LastName, FirstName
Result:
BusinessEntityID LastName FirstName JobTitle
- - -
38 Abercrombie Kim Production Technician - WC60
211 Abolrous Hazem Quality Assurance Manager
121 Ackerman Pilar Shipping and Receiving
Supervisor
Trang 7If the view includes aTOPpredicate, then the view is allowed to include anORDER BY— without the
ORDER BY, thetopwould be meaningless However, thisORDER BYclause serves only to define which
rows qualify for theTOPpredicate The only way to logically guarantee sorted results is to define the
ORDER BYclause in the executing query
SQL Server 2000, and some service packs of SQL Server 2005, had a bug (yes, I call
it a bug) in the Query Optimizer that would allow an ORDER BY in a view using a top
100 percent predicate This behavior was never documented or officially supported However, in SQL
Server 2008, this error was corrected and the top 100 percent with an ORDER BY trick will not sort the
result.
A source of confusion is that Management Studio’s Query Designer allows views to have sorted columns,
and it adds the top 100 percent trick to the view That is a SQL Server 2008 bug.
View restrictions
Although a view can contain nearly any validSELECTstatement, a few basic restrictions do apply:
■ Views may not include theSELECT INTOoption that creates a new table from the selected columns.SELECT INTOfails if the table already exists and it does not return any data, so it’s not a valid view:
SELECT * INTO Table
■ Views may not refer to a temporary table (one with a#in the name) or a table variable (preceded with an@), because these types of tables are very transient
■ TheOPTIONclause, which gives table or query hints for the entire query, is not allowed
■ Thetablesampletable option, which can randomly select pages, is not allowed within
a view
■ Views may not containcomputeorcompute bycolumns Instead, use standard aggregate functions and groupings (Computeandcompute byare obsolete and are included for backward compatibility only.)
Nesting views
Because a view is nothing more than a SQLSELECTstatement, and a SQLSELECTstatement may
ref-erence any data source, views may refref-erence other views Views referred to by other views are sometimes
called nested views.
The following view usesvEmployeeListand adds aWHEREclause to restrict the results to the
smartest and best-looking employees:
CREATE VIEW dbo.vEmployeeListDBA AS
SELECT BusinessEntityID, LastName, FirstName, JobTitle
Trang 8In this example, the viewvEmployeeListis nested withinvEmployeeListDBA Another way to
express the relationship is to say thatvEmployeeListDBAdepends onvEmployeeList
Dependencies from other objects in SQL Server can be easily viewed using Object Explorer’s view
con-text menu➪ View Dependencies Figure 14-3 shows the Object Dependencies dialog for a nested view
FIGURE 14-3
The dependency chain for nested views is easily seen in the Object Dependencies dialog Here,
thevEmployeeListDBAincludes the nested viewvEmployeeList, which in turn is based on the
Employeetable, and so on
Fromcode dependencies may be seen using thesys.dm_sql_referencing_entities()function
For example, the following query would indicate whether any other SQL Server object referenced
vEmployeeList:
SELECT *
FROM sys.dm_sql_referencing_entities
(’dbo.vEmployeeList, ‘Object’)
Trang 9Best Practice
While there may be a good reason for nesting views to support power users who build ad hoc queries,
I don’t recommend nesting views as a general practice They’re just too difficult to diagnose and
maintain I’ve seen development shops that build their production abstraction layer with nested views several
layers deep It performs poorly and is very difficult to modify
For other options to nesting subselects within outer queries, see Chapter 11, ‘‘Including Data with Subqueries and CTEs.’’
Updating through views
One of the main complaints concerning views is that unless the view is a simple single table view, it’s
difficult to update the underlying data through the view While the SQL Server Query Optimizer can
update through some complex views, there are some hard-and-fast limitations
Best Practice
Idon’t recommend designing an application around updatable views Views are best used as an abstraction
layer for ad hoc queries and reports, not for power users to update data, and certainly not for forms,
websites, or client applications to update the database
Any of the following factors may cause a view to be non-updatable:
■ Only one table may be updated If the view includes joins, then theUPDATEstatement that references the view must change columns in only one table
■ Aggregate functions orGROUP BYs in the view will cause the view to be non-updatable SQL Server couldn’t possibly determine which of the summarized rows should be updated
■ If the view includes a subquery as a derived table, and any columns from the subquery are exposed as output from the view, then the view is not updateable However, aggregates are permitted in a subquery that is being used as a derived table, so long as any columns from the aggregate subquery are not in the output columns of the view
■ If the view includes theWITH CHECK OPTION, theINSERTorUPDATEoperation must meet the view’sWHERE-clause conditions
Of course, the other standard potential difficulties with updating and inserting data still apply Chapter 16, ‘‘Modification Obstacles,’’ discusses in more detail potential troubles with modifying data.
Trang 10Views and performance
Views have an undeserved reputation for poor performance I think the reason for this belief is based on
several factors:
■ Views are often used by power users who submit ad hoc SQL In earlier versions of SQL
Server, ad hoc SQL didn’t perform as well as stored procedures
■ Views are often used by power users who use front-end UI applications to select and browse
data Some of these applications opened the connections and held locks, causing all sorts of
performance problems
■ Views are often used by power users who find useful data in a view and then build new views
on top of views These nested views might contain a horribly complex view several layers deep
that kills performance, while the top-level view appears to be a simple, easy view
Let me put the myth to rest: Well-written views will perform well The reason to limit views to ad hoc
queries and reports isn’t for performance, but for extensibility and control
Alternatives to Views
Besides views, SQL Server offers several technologies to build an abstraction layer around the data Stored
procedures are generally my first choice when exposing any data to the outside world User-defined
functions offer several benefits, and inline table-valued user-defined functions are very similar to views but
with parameters Chapter 21 discuss T-SQL, stored procedures, and functions
If you are using views to support ad hoc queries, as I suggest you do, you may also want to explore providing
Analysis Services cubes for those users who need to perform complex explorations of the data Cubes
pre-aggregate, or summarize, the data along multiple dimensions The user may then browse the cube and
compare the different data dimensions For the developer, providing one cube can often eliminate several
queries or reports
Chapter 71, ‘‘Building Multidimensional Cubes with Analysis Services,’’ explains how to create cubes
Locking Down the View
Views are designed to control access to data There are several options that protect the data or the view
TheWITH CHECK OPTIONcauses theWHEREclause of the view to check the data being inserted or
updated through the view in addition to the data being retrieved In a sense, it makes theWHEREclause
a two-way restriction
TheWITH CHECK OPTIONis useful when the view should limit inserts and updates with the same
restrictions applied to theWHEREclause