1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft SQL Server 2008 R2 Unleashed- P92 docx

10 310 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 213,59 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Any data modification via a view must reference columns from a single base table.. This does not restrict a view to only one table, but the columns referenced in the data modification ca

Trang 1

FROM Sales.CreditCard

UPDATE vw_CreditCard

SET ExpYear = ExpYear + 1

WHERE ExpYear < 2006

In general, updatable views are similar to the previous example The following specific

conditions allow a view to be updatable:

Any data modification via a view must reference columns from a single base table

This does not restrict a view to only one table, but the columns referenced in the

data modification can be for only one of the tables defined in the view

The columns affected by the data modification must directly reference the

underly-ing tables They cannot be derived through an aggregate function (for example, AVG,

COUNT, SUM) and cannot contain computations from an expression that utilizes

columns from another table

The TOP clause cannot be part of the SELECT statement that defines the view when

the WITH CHECK OPTION clause is used

The columns affected by the data modification cannot be affected by GROUP BY,

HAVING, or DISTINCT clauses in the view definition

You can overcome these restrictions by using INSTEAD OF triggers to perform the data

modifications You can create INSTEAD OF triggers on a view, and the logic within the

trig-gers performs the actual database updates INSTEAD OF triggers are discussed in detail in

Chapter 30, “Creating and Managing Triggers.”

Partitioned views are another means for performing data modifications via a view

Partitioned views can be updatable and are not subject to all the restrictions listed for

conventional views However, some additional restrictions apply to partitioned views

These additional restrictions and other details about partitioned views are discussed in the

next section

Partitioned Views

Partitioned views are used to access data that has been horizontally split, or partitioned,

across multiple tables These tables can be in the same or different databases—or even

spread across multiple servers Partitioning of tables is done to spread the I/O and

process-ing load of large tables across multiple disks or servers

You combine the tables in a partitioned view by using a UNION ALL statement that causes

the data from the separate tables to appear as if they were one table These separate tables

are referred to as member tables or base tables The member tables in a SELECT statement of

the view must all be structured in the same way, and the view must adhere to the

follow-ing restrictions:

Trang 2

Columns with the same ordinal position in the SELECT list should have the same

data type

The same column cannot be used multiple times in the SELECT list

A partitioning column that segments the data must be identified and needs to have

the same ordinal position across all the member table SELECT statements

The partitioning column cannot be a computed column, an identity, a default, or a

time stamp

The data values in the partitioning column cannot overlap in the underlying tables

The partitioning column must be part of the primary key of the member table

The member tables in the partitioned view need a CHECK constraint on the

partition-ing column

A table can appear only once as part of the UNION ALL statement

The member tables cannot have indexes created on computed columns in the table

The number of columns in the member table primary key constraints should be the

same

All member tables should have the same ANSI PADDING setting when created

The list of restrictions for creating partitioned views is extensive, but the creation of a

partitioned view is relatively straightforward and intuitive Consider, for example, the

Sales.SalesOrderHeader table in the Adventureworks2008 database This table is relatively

small, but it is the type of table that could have a large number of rows and experience

heavy utilization To balance the workload against this table, you could use a partitioned

view that utilizes base tables that each contain a separate year’s data Listing 27.4 shows

the CREATE TABLE statements to create the base tables for each year The yearly tables are

intended to hold summarized daily numbers, and each contains only a subset of the

columns in the Sales.SalesOrderHeader table

LISTING 27.4 Creating the Base Tables for a Partitioned View

CREATE TABLE Sales.Sales_2001

(

OrderDay datetime NOT NULL

CHECK (OrderDay BETWEEN ‘20010101’ AND ‘20011231’),

SubTotal money NOT NULL ,

TaxAmt money not null,

Freight money not null,

CONSTRAINT PK_Sales_2001_OrderDay PRIMARY KEY CLUSTERED (OrderDay ASC)

)

CREATE TABLE Sales.Sales_2002

(

Trang 3

OrderDay datetime NOT NULL,

CHECK (OrderDay BETWEEN ‘20020101’ AND ‘20021231’),

SubTotal money NOT NULL ,

TaxAmt money not null,

Freight money not null,

CONSTRAINT PK_Sales_2002_OrderDay PRIMARY KEY CLUSTERED (OrderDay ASC)

)

CREATE TABLE Sales.Sales_2003

(

OrderDay datetime NOT NULL

CHECK (OrderDay BETWEEN ‘20030101’ AND ‘20031231’),

SubTotal money NOT NULL ,

TaxAmt money not null,

Freight money not null,

CONSTRAINT PK_Sales_2003_OrderDay PRIMARY KEY CLUSTERED (OrderDay ASC)

)

CREATE TABLE Sales.Sales_2004

(

OrderDay datetime NOT NULL

CHECK (OrderDay BETWEEN ‘20040101’ AND ‘20041231’),

SubTotal money NOT NULL ,

TaxAmt money not null,

Freight money not null,

CONSTRAINT PK_Sales_2004_OrderDay PRIMARY KEY CLUSTERED (OrderDay ASC)

)

Notice that each table has a primary key on OrderDay, the partitioning column Also

notice that a CHECK constraint is defined for each table; it ensures that only orders for the

given year can be stored in the table

To demonstrate the power of a partitioned view, it is best to populate the base tables that

will be used by the view Listing 27.5 contains a series of INSERT statements that select

from the Sales.SalesOrderHeader table and populate the base tables The SELECT

state-ments summarize several key columns by day and contain a WHERE clause that limits the

result to orders for the respective years

LISTING 27.5 Populating the Base Tables for a Partitioned View

INSERT Sales.Sales_2001

SELECT CONVERT(VARCHAR(8),OrderDate,112),

SUM(SubTotal), SUM(TaxAmt), SUM(Freight)

FROM Sales.SalesOrderHeader

WHERE OrderDate between ‘20010101’ AND ‘20011231’

GROUP BY CONVERT(VARCHAR(8),OrderDate,112)

Trang 4

INSERT Sales.Sales_2002

SELECT CONVERT(VARCHAR(8),OrderDate,112),

SUM(SubTotal), SUM(TaxAmt), SUM(Freight)

FROM Sales.SalesOrderHeader

WHERE OrderDate between ‘20020102’ AND ‘20021231’

GROUP BY CONVERT(VARCHAR(8),OrderDate,112)

INSERT Sales.Sales_2003

SELECT CONVERT(VARCHAR(8),OrderDate,112),

SUM(SubTotal), SUM(TaxAmt), SUM(Freight)

FROM Sales.SalesOrderHeader

WHERE OrderDate between ‘20030101’ AND ‘20031231’

GROUP BY CONVERT(VARCHAR(8),OrderDate,112)

INSERT Sales.Sales_2004

SELECT CONVERT(VARCHAR(8),OrderDate,112),

SUM(SubTotal), SUM(TaxAmt), SUM(Freight)

FROM Sales.SalesOrderHeader

WHERE OrderDate between ‘20040102’ AND ‘20041231’

GROUP BY CONVERT(VARCHAR(8),OrderDate,112)

Now that you have the populated base table, you can create a partitioned view and ensure

that the view is selecting only from the base tables that it needs

Two types of partitioned views are discussed in this chapter: local and distributed A local

partitioned view utilizes base tables found on the same server A distributed partitioned

view contains at least one base table that resides on a different (remote) server The focus

in the section is on local partitioned views; distributed partitioned views are discussed

later in this chapter The T-SQL for creating a local partitioned view named

Sales.vw_Sales_Daily is shown in Listing 27.6

LISTING 27.6 Creating a Local Partitioned View

Create View Sales.vw_Sales_Daily

as

SELECT * FROM Sales.Sales_2001

UNION ALL

SELECT * FROM Sales.Sales_2002

UNION ALL

SELECT * FROM Sales.Sales_2003

UNION ALL

SELECT * FROM Sales.Sales_2004

Trang 5

The best way to validate that a partitioned view is working properly is to run a conditional

SELECT against the view and display the execution plan If the partitioned view is

func-tioning properly, it should be accessing only the base tables it needs to satisfy the SELECT

and should not access all the tables in the view unless it needs to The following example

shows a sample SELECT against the new partitioned view:

SELECT * FROM Sales.vw_Sales_Daily

WHERE OrderDay > ‘20040701’

and SubTotal > 2000

If you execute this statement and review the actual execution plan, you see that an index

seek is performed against the Sales.Sales_2004 table This is the correct result, given that

the SELECT statement is targeting order data from 2004

NOTE

SQL Server Books Online states that the recommended method for partitioning data on

a local server in SQL Server 2008 is through the use of partitioned tables and

index-es Partitioned tables and indexes are discussed in Chapter 24, “Creating and

Managing Tables.”

Modifying Data Through a Partitioned View

You can modify data via a partitioned view if the SQL statement performing the

modifica-tion meets certain condimodifica-tions, as described here:

All columns in the partitioned view must be specified in the INSERT statement

Columns that include a DEFAULT constraint or allow nulls are also subject to this

requirement

The DEFAULT keyword cannot be used on inserts to partitioned views or on updates

to partitioned views

UPDATE statements cannot modify PRIMARY KEY columns if the member tables have

text, ntext, or image columns

Inserts and updates to a partitioned view are not allowed if the view contains a

time stamp

Identity columns in a partitioned view cannot be modified by an INSERT or UPDATE

statement

INSERT, UPDATE, and DELETE statements are not allowed against a partitioned view if

there is a self-join with the same view or with any of the member tables in the

statement

NOTE

Data can be modified through partitioned views only in the Enterprise and Developer

Editions of SQL Server 2008

Trang 6

In addition to the conditions shown in this list, you must also satisfy any restrictions that

apply to the member tables Check constraints, foreign key constraints, and any other

table-level restrictions must be accounted for in the modification statement The user

executing the modification against the partitioned view must have the appropriate

INSERT, UPDATE, or DELETE permissions on the member tables for the update to succeed

Distributed Partitioned Views

Microsoft provides distributed partitioned views (DPVs) as a primary means to scale out a

database server Scalability allows an application or a database to utilize additional

resources, which allows it to perform more work There are two kinds of scalability:

scaleup and scaleout A scaleup solution focuses on a single server scaled to provide more

processing power than its predecessor An example of scaleup would be migrating from a

server with a single dual-core processor to a machine with 4-quad-core processor Scaleout

solutions include the addition of servers to augment the overall processing power

DPVs are similar to local partitioned views, but they utilize one or more tables located on

a remote server The placement of partitioned data on remote servers allows the processing

power of more than one server to be utilized The partitioning is intended to be

transpar-ent to the application and allow for additional partitions and servers as the application’s

needs scale

The following list outlines the basic requirements for creating a DPV:

A linked server definition is added to each member server that will contain the

parti-tioned data The linked server contains the connection information required to run

distributed queries on another member server

The lazy schema validation option is set to true on each of the member servers,

using sp_serveroption This option is set for performance reasons and allows the

query processor to skip schema checking of remote tables if the query can be

satis-fied on a single member server

A DPV is created on each member server This DPV references the local tables in

addition to the tables found on the other member servers

Listing 27.7 shows SQL commands that can be used to satisfy the requirements in the

preceding list The DPV created in the last portion of the script is similar to the local

parti-tioned view created in the previous section The key difference in this DPV example is the

inclusion of a distributed query that retrieves records for Sales.Sales_2002 from a remote

server The remote server in this example is named DbSvrXP

LISTING 27.7 Creating a Distributed Partitioned View

Exec sp_addlinkedserver @server=’dbsvrxp’,

@srvproduct=’’,

@provider=’MSDASQL’,

@provstr=’DRIVER={SQL Server};

SERVER=dbsvrxp;UID=linklogin;PWD=pw;Initial Catalog=Adventureworks2008’

Trang 7

—Set the server option for improved DPV performance

exec sp_serveroption dbsvrxp, ‘lazy schema validation’, true

Create View Sales.vw_Sales_Daily

as

SELECT * FROM Sales.Sales_2001

UNION ALL

SELECT * FROM dbsvrxp.Adventureworks2008.Sales.Sales_2002

UNION ALL

SELECT * FROM Sales.Sales_2003

UNION ALL

SELECT * FROM Sales.Sales_2004

The DPV created in Listing 27.7 contains only one remote table The example could be

further expanded to have each table in the UNION clause on a different remote server

Keep in mind that the DPV CREATE statement needs to be adjusted when run on the

remote server(s) The tables that are local on one server are now remote on the other

server, and those that are remote can now be local

If the DPVs are properly defined, SQL Server 2008 attempts to optimize their performance

by minimizing the amount of data transferred between member servers The query

proces-sor retrieves the CHECK constraint definitions from each member table This allows the

query processor to map the specified search arguments to the appropriate table(s) The

query execution plan then accesses only the necessary tables and retrieves only the remote

rows needed to complete the SQL statement

Data can be modified through a DPV as well Updatable DPVs, which were introduced in

SQL Server 2000, are still available in SQL Server 2008 Data modifications are performed

against a view, allowing true transparency The view is accessed as if it were a base table,

and the user or application is unaware of the actual location of the data If it is configured

properly, SQL Server determines via the WHERE clause specified in the update query which

partition defined in the view must be updated rather than updating all tables in the join

NOTE

Data can be modified through distributed partitioned views only in the Enterprise and

Developer Editions of SQL Server 2008

Indexed Views

You establish indexed views by creating a unique clustered index on the view itself,

inde-pendent of the member tables that it references The creation of this unique index

trans-forms a view from an object that is virtual in nature to one that has physical storage

Trang 8

requires maintenance, and, most importantly, can provide performance benefits that

justify its creation

Creating Indexed Views

Indexed views were first available for creation in SQL Server 2000 and continue to be a

viable means for improving query performance in SQL Server 2008 An index can be

created on a view in all versions of SQL Server 2008, but there are limitations on some of

the versions The Developer and Enterprise Editions of SQL Server 2008 are the only

editions that support the use of indexed views for queries that don’t specifically reference

the views Other editions of SQL Server must reference the view by name in the SQL

state-ments and must also use the NOEXPAND keyword in the query The details of NOEXPAND are

discussed in the section “To Expand or Not to Expand,” later in this chapter

Regardless of the edition of SQL Server you are running, some basic requirements must be

satisfied for you to create an indexed view These requirements, which follow, are detailed

in SQL Server 2008 Books Online:

The ANSI_NULLS and QUOTED_IDENTIFIER options must be set to ON when the CREATE

VIEW statement is executed

The ANSI_NULLS option must be set to ON for the execution of all CREATE TABLE

state-ments that create tables referenced by the view

The view must not reference any other views, only base tables

All base tables referenced by the view must be in the same database as the view and

have the same owner as the view

The view must be created with the SCHEMABINDING option Schema binding binds the

view to the schema of the underlying base tables

User-defined functions referenced in the view must be created with the

SCHEMABINDING option

Tables and user-defined functions must be referenced via two-part names in the

view One-part, three-part, and four-part names are not allowed

All functions referenced by expressions in the view must be deterministic

If the view definition uses an aggregate function, the SELECT list must also include

COUNT_BIG (*)

The DATA ACCESS property of a user-defined function must be NO SQL, and the

EXTERNAL ACCESS property must be NO

CLR functions can appear only in the SELECT list of the view and can reference only

fields that are not part of the clustered index key They cannot appear in the WHERE

clause of the view or the ON clause of a JOIN operation in the view

CLR functions and methods of CLR user-defined types used in the view definition

must have the properties set as DETERMINISTIC = TRUE, PRECISE = TRUE, DATA

ACCESS = NO SQL, and EXTERNAL ACCESS = NO

Trang 9

If GROUP BY is specified, the view SELECT list must contain a COUNT_BIG(*)

expres-sion, and the view definition cannot specify HAVING, CUBE, or ROLLUP

The view cannot contain any of the T-SQL elements shown in the following list:

You can see from this list that the number of requirements is extensive It can therefore be

difficult to determine whether all the requirements have been met for a particular view To

simplify this determination, you can query the IsIndexable property, using the

OBJECTPROPERTY function The following example demonstrates the use of the

IsIndexable property against the sys.views catalog view:

SELECT name AS ViewName

,SCHEMA_NAME(schema_id) AS SchemaName

,OBJECTPROPERTYEX(object_id,’IsIndexed’) AS IsIndexed

,OBJECTPROPERTYEX(object_id,’IsIndexable’) AS IsIndexable

,create_date

,modify_date

FROM sys.views;

The IsIndexable property returns a 1 (or TRUE) if an index can be created on the view

and a 0 if it is not indexable Most of the views in the Adventureworks2008 database are

not indexable, but the database does contain a couple of examples of views that have

been indexed The following example shows the CREATE statement for an index on the

vProductAndDescription view The SET options required when creating the index are

included in the example as well:

SET ARITHABORT ON — for 80 compatibility or earlier

GO

SET CONCAT_NULL_YIELDS_NULL ON

* or tablename.* An expression on a column found in

the GROUP BY clause

A derived table

A common table expression

(CTE)

A rowset function The UNION, EXCEPT, or

INTERSECT operators Subqueries Outer joins or self-joins The TOP clause

The ORDER BY clause The DISTINCT keyword COUNT (COUNT_BIG is

allowed)

AVG, MAX, MIN, STDEV,

STDEVP, VAR, or VARP

A SUM function that references a nullable expression

A CLR user-defined aggre-gate function

The full text predicate COMPUTE or COMPUTE BY CONTAINS

or FREETEXT

CROSS APPLY or OUTER APPLY operators Table hints Join hints

Trang 10

SET QUOTED_IDENTIFIER ON

GO

SET ANSI_NULLS ON

GO

SET ANSI_PADDING ON

GO

SET ANSI_WARNINGS ON

GO

SET NUMERIC_ROUNDABORT OFF

GO

CREATE UNIQUE CLUSTERED INDEX [IX_vProductAndDescription]

ON [Production].[vProductAndDescription]

(

[CultureID] ASC,

[ProductID] ASC

)

The following example shows the Production.vProductAndDescript view that the index

was created on:

CREATE VIEW [Production].[vProductAndDescription]

WITH SCHEMABINDING

AS

View (indexed or standard) to display products

—and product descriptions by language

SELECT

p.[ProductID]

,p.[Name]

,pm.[Name] AS [ProductModel]

,pmx.[CultureID]

,pd.[Description]

FROM [Production].[Product] p

INNER JOIN [Production].[ProductModel] pm

ON p.[ProductModelID] = pm.[ProductModelID]

INNER JOIN [Production].[ProductModelProductDescriptionCulture] pmx

ON pm.[ProductModelID] = pmx.[ProductModelID]

INNER JOIN [Production].[ProductDescription] pd

ON pmx.[ProductDescriptionID] = pd.[ProductDescriptionID];

Indexed Views and Performance

Adding indexes to tables is a generally accepted means for improving database

perfor-mance Indexes provide a keyed lookup to rows of data that can improve database access

and avoid the performance nightmare of a table scan where the entire contents of a table

Ngày đăng: 05/07/2014, 02:20

TỪ KHÓA LIÊN QUAN