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

Hướng dẫn học Microsoft SQL Server 2008 part 39 doc

10 239 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 1,08 MB

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

Nội dung

The following view will generate a list of tours for the Cape Hatteras base camp: USE CHA2; CREATE VIEW dbo.vCapeHatterasTour AS SELECT TourName, BaseCampID FROM dbo.Tour WHERE BaseCampI

Trang 1

Unchecked data

To understand the need for theWITH CHECK OPTION, it’s important to first understand how views

function without theCHECK OPTION The following view will generate a list of tours for the Cape

Hatteras base camp:

USE CHA2;

CREATE VIEW dbo.vCapeHatterasTour AS

SELECT TourName, BaseCampID FROM dbo.Tour

WHERE BaseCampID = 2;

go SELECT TourName, BaseCampID FROM dbo.vCapeHatterasTour;

- -Outer Banks Lighthouses 2

If the Ashville base camp adds a Blue Ridge Parkway Hike tour and inserts it through the view without

theCHECK OPTION, theINSERTis permitted:

INSERT dbo.vCapeHatterasTour (TourName, BaseCampID)

VALUES (’Blue Ridge Parkway Hike’, 1);

(1 row(s) affected)

TheINSERTworked, and the new row is in the database, but the row is not visible through the view

because theWHEREclause of the view filters out the inserted row This phenomenon is called

disappear-ing rows:

SELECT TourName, BaseCampID FROM dbo.vCapeHatterasTour;

- -Outer Banks Lighthouses 2

If the purpose of the view were to give users at the Cape access to their tours alone, then the view

failed Although they can see only the Cape’s tours, they successfully modified another base camp’s

tours TheWITH CHECK OPTIONwould have prevented this fault

Protecting the data

A view with aWHEREclause and theWITH CHECK OPTIONcan protect the data from undesired inserts

and updates

The following code will back out the previousINSERTand redo the same scenario, but this time the

view will include theWITH CHECK OPTION:

DELETE dbo.vCapeHatterasTour WHERE TourName = ‘Blue Ridge Parkway Hike’;

Trang 2

ALTER VIEW dbo.vCapeHatterasTour

AS

SELECT TourName, BaseCampID

FROM dbo.Tour

WHERE BaseCampID = 2

WITH CHECK OPTION;

go

INSERT dbo.vCapeHatterasTour (TourName, BaseCampID)

VALUES (’Blue Ridge Parkway Hike’, 1);

Server: Msg 550, Level 16, State 1, Line 1

The attempted insert or update failed because the target view either

specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK

OPTION and one or more rows resulting from the operation did not qualify

under the CHECK OPTION constraint

The statement has been terminated

This time theINSERTfailed and the error message attributed the cause to theWITH CHECK OPTIONin

the view, which is exactly the effect desired

Some developers employ views and theWITH CHECK OPTIONas a way of providing row-level

security — a technique called horizontally positioned views As in the base camp view example, they

create a view for each department, or each sales branch, and then give users security permission to

the view that pertains to them While this method does achieve row-level security, it also has a high

maintenance cost

For the application, row-level security can be designed using user-access tables and stored

procedures, as demonstrated in Chapter 52, ‘‘Row-Level Security,’’ but views can help

enforce row-level security for ad hoc queries.

Within Management Studio’s View Designer, theWITH CHECK OPTIONcan be enforced within the View

Properties form There are actually two properties that must be enabled The first is (Update Using View

Rules), which prohibits Management Studio and MDAC from decoding the view and directly accessing

the underlying tables Only when (Update Using View Rules) is enabled can the second option,WITH

CHECK OPTION, be enabled

Protecting the view

Three options protect views from data schema changes and prying eyes These options are simply

added to theCREATEcommand and applied to the view, in much the same way that the WITH CHECK

OPTIONis applied

Database code is fragile and tends to break when the underlying data structure changes Because

views are nothing more than stored SQLSELECTqueries, changes to the referenced tables may break

the view

Creating a view with schema binding locks the underlying tables to the view and prevents changes, as

demonstrated in the following code sample:

Trang 3

go CREATE VIEW dbo.vTest

WITH SCHEMABINDING

AS SELECT [Name] FROM dbo.Test;

go ALTER TABLE Test

ALTER COLUMN [Name] NVARCHAR(100);

Result:

Msg 5074, Level 16, State 1, Line 1 The object ‘vTest’ is dependent on column ‘Name’

Msg 4922, Level 16, State 9, Line 1 ALTER TABLE ALTER COLUMN Name failed because one

or more objects access this column

Some restrictions apply to the creation of schema-bound views TheSELECTstatement must include

the schema name for any referenced objects, andSELECTall columns (*) is not permitted (but that last

requirement shouldn’t bother anyone who follows best practices, says Hugo the Tech Editor)

Within Management Studio’s View Designer, theWITH SCHEMA BINDINGoption can be enabled within

the View Properties page

When the schema underlying a view (that is not schema bound) does change, it will likely break the

view If this happens, to repair the view, either recreate it or run thesp_refreshviewsystem stored

procedure

Encrypting the view’s select statement

TheWITH ENCRYPTIONoption is another security feature When views or stored procedures are

created, the text can be retrieved through thesys.sql_modulesandsys.syscommentssystem

views The code is therefore available for viewing The view may contain aWHEREcondition that

should be kept confidential, or there may be some other reason for encrypting the code TheWITH

ENCRYPTIONoption encrypts the code in the system tables, hides them fromsys.sql_modulesand

sys.syscomments, and prevents anyone from viewing the original code

In the following code example, the text of the view is inspected withinsys.sql_modules, the view is

encrypted, andsys.sql_modulesis again inspected (as expected, theSELECTstatement for the view

is then no longer readable):

SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID(N’dbo.vTest’);

Trang 4

The result is the text of thevTextview:

definition

-CREATE VIEW vTest

WITH SCHEMABINDING

AS

SELECT [Name] FROM dbo.Test;

The followingALTERcommand rebuilds the viewWITH ENCRYPTION:

ALTER VIEW vTest

WITH ENCRYPTION

AS

SELECT [Name] FROM dbo.Test;

Be careful with this option Once the code is encrypted, Management Studio can no longer produce a

script to alter the view, and will instead generate this message:

/****** Encrypted object is not transferable,

and script cannot be generated ******/

In addition, be aware that the encryption affects replication An encrypted view will not be published

Application metadata

The front-end application or data access layer may request schema information, called meta-data, along

with the data when querying SQL Server Typically, SQL Server returns schema information for the

underlying tables, but theWITH VIEW METADATAoption tells SQL Server to return schema information

about the view, rather than the tables referenced by the view This prohibits someone from learning

about the table’s schema and is useful when the view’s purpose is to hide sensitive columns

Using Synonyms

Views are sometimes employed to hide cryptic database schema names Synonyms are similar to views,

but they are more limited Whereas views can project columns, assign column aliases, and build data

using joins and subqueries, synonyms can only assign alternative names to tables, views, and stored

procedures

Synonyms are primarily used to simplify complex object names, particularly with lengthy schema names

A synonym can changeHumanResources.EmployeeDepartmentHistoryintoEmpHist Which

would you rather type 100 times?

Synonyms are part of the SQL standard and are used frequently by Oracle DBAs Note that Oracle

includes both private and public synonyms SQL Server synonyms are only public Even though they

Trang 5

were introduced to SQL Server with version 2005, I’ve seen very little acceptance or use of synonyms in

the SQL community

Schemas enhance security and help prevent SQL injection attacks The hacker needs to guess the schema

name as well as the table name Little Bobby Tables (a standard DBA joke:http://xkcd.com/327/)

would need to knowmyschema.students Giving the tablemyschema.studentsan easy to guess

synonym would defeat the purpose of using the schema to prevent SQL injection

Synonyms can be managed using Object Explorer, orCREATEandDROPDDL commands

Summary

Views are nothing more than stored SQLSELECTqueries There’s no magic in a view Any valid

SQLSELECTstatement may be saved as a view, including subqueries, complex joins, and aggregate

functions

Views are great for simplifying a complex schema and presenting a more useful picture of the data for

power users writing ad hoc queries and reports Views can simplify complex aggregate queries and hide

nasty joins Any well-planned abstraction layer should include views My only caution is to not push the

view too far Don’t expect to sort data in a view, and don’t make views the pillar of the front-end

appli-cation or website However, for those who detest views, I suggest that a view is infinitely better than an

ad hoc SQL statement that directly hits a table without any abstraction layer

The previous chapters have discussed retrieving data using the powerfulSELECTstatement Views

store theSELECTstatement for ad hoc queries The next chapter continues the discussion ofSELECT,

extending its power by adding data modification verbs

Trang 6

Modifying Data

IN THIS CHAPTER

Inserting data from expressions, other result sets, and stored procedures Updating and deleting data Mastering the new merge command

Exposing inserted and deleted tables to the DML

Things change Life moves on Because the purpose of a database is to

accurately represent reality, the data must change along with reality

For SQL programmers, that means inserting, updating, and deleting

rows — using the basic data manipulation language (DML) commands However,

these operations aren’t limited to writing single rows of data Working with SQL

means thinking in terms of data sets The process of modifying data with SQL

draws on the entire range of SQL Server data-retrieval capabilities — the powerful

SELECT, joins, full-text searches, subqueries, and views

This chapter is all about modifying data within SQL Server using theINSERT,

UPDATE,DELETE, andMERGESQL commands Modifying data raises issues

that need to be addressed, or at least considered Inserting surrogate primary

keys requires special methods Table constraints may interfere with the data

modification Referential integrity demands that someDELETEoperations cascade

to other related tables This chapter will help you understand these concerns

and offer some ways to deal with them Because these potential obstacles affect

INSERT,UPDATE,MERGE, and, to some degree,DELETE, they are addressed in

their own sections after the sections devoted to the individual commands

The ACID database properties (atomic, consistent, isolated, and durable) are critical to the modification of data.

For many databases, SQL Server’s default transactional control is sufficient.

However, misapplied transaction locking and blocking represents one of the

top four causes of poor performance Chapter 66, ‘‘Managing Transactions,

Locking, and Blocking,’’ digs into SQL Server’s architecture and explains how data

modifications occur within transactions to meet the ACID requirements, and how

SQL Server manages data locks.

Trang 7

Best Practice

The SQL INSERT, UPDATE, DELETE, and MERGE commands are really verb extensions of the basic

SELECT command The full potential of the SELECT command lies within each data-modification

operation Even when modifying data, you should think in terms of sets, rather than single rows

Data-modification commands may be submitted to SQL Server from any one of several interfaces This

chapter is concerned more with the strategy and use of theINSERT,UPDATE,DELETE, andMERGE

commands than with the interface used to submit a given command to SQL Server

What’s New in Data Modification?

This is an area in which SQL Server 2008 has a few significant new T-SQL features:

Row constructors: Insert multiple rows with a single INSERT VALUES statement

Merge: Set-based command that can insert, update, or delete for matching or

non-matching rows

Composable SQL: Builds on SQL Server 2005’s OUTPUT clause and can pass the result

of the OUTPUT clause to an outer query Composable SQL is covered in Chapter 11,

‘‘Including Data with Subqueries and CTEs.’’

SQL Server Management Studio offers two interfaces for submitting SQL commands: Query Designer

and Query Editor If you love a visual UI, then Query Designer may work for a while, but you should

migrate to Query Editor to enjoy the richness of T-SQL I do all my development work exclusively in

Query Editor

For more details on using Management Studio’s Query Designer and Query Editor, see Chapter 6, ‘‘Using Management Studio.’’

Inserting Data

SQL offers six forms ofINSERTandSELECT/INTOas the primary methods of inserting data (as shown

in Table 15-1) The most basic method simply inserts a row of data, while the most complex builds a

data set from a complexSELECTstatement and creates a table from the result

Each of theseINSERTforms is useful for a unique task, often depending on the source of the data

being inserted

Trang 8

TABLE 15-1

Insert Forms

Insert Form Description

INSERT/VALUES Inserts one or more rows of values; commonly used to insert

data from a user interface INSERT/SELECT Inserts a result set; commonly used to manipulate sets of data

INSERT/EXEC Inserts the results of a stored procedure; used for complex data

manipulation INSERT/DEFAULT VALUES Creates a new row with all defaults; used for pre-populating

pigeonhole data rows SELECT/INTO Creates a new table from the result set of a SELECT statement

MERGE Combines inserting, updating, and deleting data in a single

statement

SQL Server complements the SQL INSERT commands with other tools to aid in

moving large amounts of data or performing complex data conversions The venerable

Bulk Copy Wizard and the Copy Database Wizard are introduced in Chapter 44, ‘‘Transferring

Databases.’’ The Copy Database Wizard actually creates a simple Integration Services package.

Chapter 37, ‘‘Performing ETL with Integration Services,’’ details Integration Services, a very

powerful tool that can move and manipulate large sets of data between/among nearly any

data sources.

When inserting new data, if the table has surrogate keys, then primary key values must be generated

to identify the new rows While identity columns and GUIDs both make excellent primary keys,

each requires special handling during the insertion of rows This section describes how to create

identity-column values and GUIDs

Inserting simple rows of values

The simplest and most direct method of inserting data is theINSERT/VALUESmethod Until SQL

Server 2008,INSERT .VALUESwas limited to inserting a single row, but SQL Server is now compliant

with the ANSI standard and can include row constructors — inserting multiple rows in a single

INSERT .VALUESstatement:

INSERT [INTO] schema.table [(columns, )]

VALUES (value, ), (value, ), ;

Building anINSERT .VALUESstatement is mostly straightforward, although you do have a few

options TheINTOkeyword is optional and is commonly ignored The key to building anINSERT

Trang 9

When the values are inserted into a new row, each value corresponds to an insert column The insert

columns may be in any order — the order of the columns within the table is irrelevant — as long as

the insert columns and the value columns in the SQLINSERTcommand are in the same order

As with every chapter that includes code, the file Ch 15 - Modifying Data.sql on

www.SQLServerBible.com contains all the sample code for this chapter Additional examples of data-modification statements may be found in any of the sample database ‘‘populate’’

scripts, or in the stored procedures of the OBXKites sample database.

The followingINSERTcommands reference the columns in varying order, inserting one row and then

multiple rows:

USE CHA2

INSERT INTO dbo.Guide (FirstName, LastName) VALUES (’Tammie’, ‘Commer’);

INSERT INTO dbo.Guide (LastName, FirstName, Qualifications) VALUES

(’Smith’, ‘Dan’, ‘Diver, Whitewater Rafting’),

(’Jeff’, ‘Davis’, ‘Marine Biologist, Diver’);

The followingSELECTcommand verifies the insert:

SELECT GuideID, LastName, FirstName, Qualifications FROM dbo.Guide;

Result (your result may differ depending on the data loaded into the database):

GuideID LastName FirstName Qualifications - - -

-1 Smith Dan Diver, Whitewater Rafting

2 Davis Jeff Marine Biologist, Diver

Not every column in the table has to be listed, but if a column appears, then a value has to be

avail-able for theINSERTcommand The firstINSERTstatement in the previous sample code omitted the

Qualificationscolumn TheINSERToperation worked nonetheless and inserted aNULLinto the

omitted column

If theQualificationscolumn had a default constraint, then the default value would have been

inserted instead of theNULL When a column has both no default and aNOT NULLconstraint, and

no value is provided in theINSERTstatement, theINSERToperation will fail (For more information

about inserting defaults and nulls, see the section ‘‘Potential Data-Modification Obstacles’’ later in this

chapter.)

It’s possible to explicitly force theINSERTof a default without knowing the default value If the

key-wordDEFAULTis provided in the value-column list, then SQL Server will store the default value for the

column This is a good practice because it documents the intention of the code, rather than leaving the

code blank and assuming the default The insert-column list is required when using row constructors to

insert multiple rows

Trang 10

Explicitly listing the columns is a good idea It prevents an error if the table schema changes, and it

helps document the insert However, the insert-column list is optional In this case, the values are

inserted into the table according to the order of the columns in the table (ignoring an identity column)

It’s critical that every table column receive valid data from the value list Omitting a column in the value

list causes theINSERToperation to fail

You learned earlier that when the columns are explicitly listed within theINSERT/VALUEScommand,

an identity column can’t receive a value Similarly, the identity column is also ignored in the value list

when the columns are assumed The rest of the values are in the same order as the columns of the

Guidetable, as follows:

INSERT Guide

VALUES (‘Jones’, ‘Lauren’,

‘First Aid, Rescue/Extraction’,‘19590625’,‘200104415’);

To view the inserted data, the followingSELECTcommand pulls data from theGuidetable:

SELECT GuideID, LastName, FirstName, Qualifications

FROM dbo.Guide;

Result:

GuideID LastName FirstName Qualifications

- - -

-1 Smith Dan Diver, Whitewater Rafting

2 Davis Jeff Marine Biologist, Diver

4 Jones Lauren First Aid, Rescue/Extraction

So far in the sample code, values have been hard-coded string literals Alternately, the value could be

returned from an expression This is useful when a data type requires conversion, or when data need to

be altered, calculated, or concatenated:

INSERT dbo.Guide (FirstName, LastName, Qualifications)

VALUES (‘Greg’, ‘Wilson’,

‘Rock Climbing’ + ‘, ’ + ‘First Aid’);

The nextSELECTstatement verifies Greg’s insert:

SELECT GuideID, LastName, FirstName, Qualifications

FROM dbo.Guide;

Result:

GuideID LastName FirstName Qualifications

- - -

-1 Smith Dan Diver, Whitewater Rafting

2 Davis Jeff Marine Biologist, Diver

Ngày đăng: 04/07/2014, 09:20

TỪ KHÓA LIÊN QUAN