Tải bản đầy đủ (.pdf) (10 trang)

Hướng dẫn học Microsoft SQL Server 2008 part 38 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (744.34 KB, 10 trang )

Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 332
Part II Manipulating Data with Select
Creating views using the Query Designer
Because a view is nothing more than a saved SQL SELECT statement, the creation of a view begins with
aworking
SELECT statement. Any SQL SELECT statement, as long as it’s a valid SQL SELECT 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,
332
www.getcoolebook.com
Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 333
Projecting Data Through Views 14
available 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 the
from clause 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 SQL
SELECT statement.
To test the view’s SQL


SELECT statement within Query Designer, use the Execute SQL button or F5.
This will run the
SELECT statement 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 SQL
SELECT statement 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’s
SELECT statement.
■ Selecttopnrows:Opens the Query Editor with a
SELECT statement 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 a
SELECT statement referencing the view,
with only the results pane visible, and executes the view.
■ Script the view: Management Studio can script the DDL statements to
CREATE, ALTER,or
DROP the 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.
333
www.getcoolebook.com
Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 334
Part II Manipulating Data with Select
Creating 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 view vEmployeeList in 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, the create command 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.
Aquery(
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 saved
SELECT statement.
The following
SELECT statement references the vEmployeeList view:
SELECT BusinessEntityID, LastName, FirstName, JobTitle
FROM dbo.vEmployeeList
334
www.getcoolebook.com
Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 335
Projecting Data Through Views 14
FIGURE 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’s
select statement.
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

1S
´
anchez Ken Chief Executive Officer
2 Duffy Terri Vice President of Engineering
3 Tamburello Roberto Engineering Manager
4 Walters Rob Senior Tool Designer
When views are referenced from ad hoc queries, a WHERE condition is typically added to filter the data
from the view:
SELECT BusinessEntityID, LastName, FirstName, JobTitle
FROM dbo.vEmployeeList
WHERE JobTitle = ‘Database Administrator’;
335
www.getcoolebook.com

Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 336
Part II Manipulating Data with Select
Result:
BusinessEntityID LastName FirstName JobTitle

270 Ajenstat Fran
¸
coi Database Administrator
271 Wilson Dan Database Administrator
Altering and dropping a view
It’s likely that the view’s SELECT statement will need to be changed at some point in time. Once a view
has been created, the SQL
SELECT statement may be easily edited by using the ALTER command. Alter-
ing the view changes the saved
SELECT statement 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.
The
ALTER command supplies a new SQL SELECT statement for the view:
ALTER SchemaName.ViewName
AS
SQL Select Statement;
Management Studio can automatically generate an ALTER statement 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 the
DROP
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
The basic mechanics of creating a view and selecting data from the view are pretty straightforward, but
views have their own particular nuances — topics such as sorting data, updating data through a view,
and nesting views several levels deep. This section examines views from a broader point of view.
336
www.getcoolebook.com
Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 337
Projecting Data Through Views 14
Column 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 the
SELECT statement. The view’s column list names override any column names or column
aliases in the view’s
SELECT statement.
The following query alters the
vEmployeeList view so that the result columns become ID, 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):
ID Last First Job

1S
´
anchez Ken Chief Executive Officer
2 Duffy Terri Vice President of Engineering
3 Tamburello Roberto Engineering Manager
4 Walters Rob Senior Tool Designer
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 the
ORDER BY clause in the query referencing the view. For example, the fol-
lowing code selects data from the
vEmployeeList view and orders it by LastName, FirstName.The
ORDER BY clause 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

285 Abbas Syed Pacific Sales Manager
38 Abercrombie Kim Production Technician - WC60
211 Abolrous Hazem Quality Assurance Manager
121 Ackerman Pilar Shipping and Receiving
Supervisor
337
www.getcoolebook.com
Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 338
Part II Manipulating Data with Select
If the view includes a TOP predicate, then the view is allowed to include an ORDER BY — without the
ORDER BY,thetop would be meaningless. However, this ORDER BY clause serves only to define which
rows qualify for the
TOP predicate. The only way to logically guarantee sorted results is to define the
ORDER BY clause 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 valid SELECT statement, a few basic restrictions do apply:
■ Views may not include the

SELECT INTO option that creates a new table from the selected
columns.
SELECT INTO fails 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.
■ The
OPTION clause, which gives table or query hints for the entire query, is not allowed.
■ The
tablesample table option, which can randomly select pages, is not allowed within
aview.
■ Views may not contain
compute or compute by columns. Instead, use standard aggregate
functions and groupings. (
Compute and compute by are obsolete and are included for
backward compatibility only.)
Nesting views
Because a view is nothing more than a SQL SELECT statement, and a SQL SELECT statement may ref-
erence any data source, views may reference other views. Views referred to by other views are sometimes
called nested views.
The following view uses
vEmployeeList and adds a WHERE clause to restrict the results to the
smartest and best-looking employees:
CREATE VIEW dbo.vEmployeeListDBA
AS
SELECT BusinessEntityID, LastName, FirstName, JobTitle
FROM dbo.vEmployeeList AS vE
WHERE JobTitle = ‘Database Administrator’;

338
www.getcoolebook.com
Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 339
Projecting Data Through Views 14
In this example, the view vEmployeeList is nested within vEmployeeListDBA.Anotherwayto
express the relationship is to say that
vEmployeeListDBA depends on vEmployeeList.
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,
the
vEmployeeListDBA includes the nested view vEmployeeList, which in turn is based on the
Employee table, and so on.
From code dependencies may be seen using the sys.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’)
339
www.getcoolebook.com
Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 340
Part II Manipulating Data with Select
Best Practice
W
hile 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
I
don’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 the
UPDATE statement that
references the view must change columns in only one table.
■ Aggregate functions or
GROUP 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 the
WITH CHECK OPTION,theINSERT or UPDATE operation must meet
the view’s
WHERE-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.
One way to work around non-updatable views is to build an INSTEAD OF trigger that

inspects the modified data and then performs a legal
UPDATE operation based on that data.
Chapter 26, ‘‘Creating DML Triggers,’’ explains how to create an
INSTEAD OF trigger.
340
www.getcoolebook.com
Nielsen c14.tex V4 - 07/21/2009 12:49pm Page 341
Projecting Data Through Views 14
Views 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
B
esides 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.
The
WITH CHECK OPTION causes the WHERE clause 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 the
WHERE clause
a two-way restriction.
The
WITH CHECK OPTION is useful when the view should limit inserts and updates with the same
restrictions applied to the
WHERE clause.
341
www.getcoolebook.com

×