Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 91 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
91
Dung lượng
2,53 MB
Nội dung
C0662271X.fm Page 236 Friday, April 29, 2005 7:34 PM 237 Chapter 7 Implementing Views A view is simply a SELECT statement that has a name and is stored in Microsoft SQL Server. Views act as virtual tables to provide several benefits. A view gives developers a standardized way to execute queries, enabling them to write certain common que- ries once as views and then include the views in application code so that all applica- tions use the same version of a query. A view can also provide a level of security by giving users access to just a subset of data contained in the base tables that the view is built over and can give users a more friendly, logical view of data in a database. In addition, a view with indexes created on it can provide dramatic performance improvements, especially for certain types of complex queries. Most views allow only read operations on underlying data, but you can also create updateable views that let users modify data via the view. This chapter shows you how to leverage the power and flexibility of views by creating regular views, updateable views, and indexed views. Exam objectives in this chapter: ■ Implement a view. ❑ Create an indexed view. ❑ Create an updateable view. ❑ Assign permissions to a role or schema for a view. Lessons in this chapter: ■ Lesson 1: Creating a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 ■ Lesson 2: Modifying Data Through Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 ■ Lesson 3: Creating an Indexed View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 Before You Begin To complete the lessons in this chapter, you must have ■ SQL Server 2005 installed. ■ A copy of the AdventureWorks sample database installed in the instance. C0762271X.fm Page 237 Friday, April 29, 2005 7:35 PM 238 Chapter 7 Implementing Views Real World Michael Hotek A couple of years ago, I had a two-week project with a customer who was expe- riencing performance issues. When I started looking into the database, I knew I was in for a big challenge. There were tens of thousands of lines of code spread among almost 2,000 stored procedures, functions, and triggers—along with about 350 tables. What really stood out at first glance were the more than 800 views in the database. Having a large number of views in a database isn’t necessarily a problem. But having more than twice as many views as tables told me that either the tables were poorly designed or the views were not being properly used. Unfortunately, in this case, it was both—but that is a story for a different day. As I investigated, I found views that did nothing more than select a handful of col- umns from a single table by using a simple WHERE clause. After looking at about the 50th view, I discovered that something wasn’t right. Cross-referencing back to the views I already looked at, I found a duplicate. Then I found another and another and another. In one instance, I found 23 views that all did the same thing. It turns out that the developers were in a hurry to create applications and deploy new features. At some point, one of the database administrators (DBAs) dictated that all data access had to be through views because the DBA mistakenly thought that a view gave a performance improvement. So several years later, the company had hundreds of views embedded in the applications. And finding anything was so difficult that developers simply created new views whenever they needed anything, making a bad situation even worse. Fortunately, the applications were not directly accessing tables or views; data access was through stored procedures. So the first step in the process was to wade through the stored procedure, function, and trigger code for references to dupli- cate views. By removing all the duplicates, we could drop more than 400 views. We then took the second step of eliminating anything that really shouldn’t have been a view in the first place. We defined unnecessary views as views that accessed only one table through a simple WHERE clause; views that imple- mented things that did not belong in a view, such as a hard-coded list of states; and views that contained simple logic that any developer should understand. C0762271X.fm Page 238 Friday, April 29, 2005 7:35 PM Before You Begin 239 The end result of this process was a database that contained only 34 views. The only views that survived contained complex calculations or complex joins that needed to be encapsulated either to ensure consistency or to avoid a significant amount of effort in correctly constructing the query in the future. The lesson learned by the developers was that SQL Server gives you a lot of tools to accomplish a task. But just because you can do something doesn’t necessarily mean that you should. Before creating an object in a database, you have to under- stand how it will improve the application and be able to justify why creating the object is the best approach. C0762271X.fm Page 239 Friday, April 29, 2005 7:35 PM 240 Chapter 7 Implementing Views Lesson 1: Creating a View Certain SQL Server objects are necessary or generally recommended. For example, you must have database tables to store data, and you should create certain indexes on your tables to improve performance. However, you should create views only when there is a clear advantage to having them. Views that don’t have demonstrated bene- fits just take up space. Suppose that you need to return the name of a customer who has a credit line in excess of $10,000. A view would provide no advantage in this case because the SELECT statement to generate this result is simple and straightforward. However, if you need to return the name of a customer with the primary address and most recent payment, while keeping in the output all of the customers who have not made a payment, creating a view is probably useful because generating this result requires a combination of inner and outer joins to at least five different tables. In this lesson, you see how to define a view over one or more tables. You also learn why it is important to ensure that you have appropriate permissions assigned for the view and any underlying tables the view is based on. After this lesson, you will be able to: ■ Create a view. ■ Assign permissions to a role or schema for a view. Estimated lesson time: 20 minutes How to Create a View You use the Transact-SQL CREATE VIEW command to create a view over one or more tables. The syntax for the command follows: CREATE VIEW [ schema_name .]view_name [(column [, n ])] [ WITH <view_attribute> [ , n ] ] AS select_statement [;] [ WITH CHECK OPTION ] <view_attribute> ::= { [ ENCRYPTION ] [ SCHEMABINDING ] [ VIEW_METADATA ] } You begin by naming your view. As with all objects, a view must have a name that meets the rules for identifiers. C0762271X.fm Page 240 Friday, April 29, 2005 7:35 PM Lesson 1: Creating a View 241 The command’s first WITH clause lets you apply three different options to the view: ENCRYPTION, SCHEMABINDING, and VIEW_METADATA. ENCRYPTION specifies that SQL Server should encrypt the definition of the view when it is stored in the data- base. The definition of an encrypted view is not visible to anyone, including a member of the sysadmin fixed server role. So when you encrypt a view, you must ensure that you keep the original source code somewhere because you cannot decrypt the definition. When you specify the SCHEMABINDING option, you cannot drop any tables, views, or functions referenced by the view without first dropping the view. BEST PRACTICES Schema binding trick An old trick that many DBAs use in a production environment is to create a view for each table that selects all columns in the table and specifies the SCHEMABINDING option. These views are never used with any application or by any user. The only purpose of the views is to prevent a DBA from accidentally dropping a table or a column within a table. This trick does not prevent a DBA from purposefully dropping a table because the DBA can also drop the view and then drop the table. But dropping an object on purpose that should not be dropped is a security issue. The VIEW_METADATA option returns metadata about a view to client-side data access libraries. You use the command’s AS clause to specify the SELECT statement that defines the view. The SELECT statement can be of any complexity as long as the query is valid and can reference tables, views, user-defined functions (UDFs), and system functions. The only restrictions are that the view’s SELECT statement CANNOT do the following: ■ Use the COMPUTE or COMPUTE BY clause ■ Use the INTO keyword ■ Use the OPTION clause ■ Reference a temporary table or table variable ■ Use the ORDER BY clause unless it also specifies the TOP operator The command’s last option, WITH CHECK OPTION, is something you use to create an updateable view. Lesson 2, “Modifying Data Through Views,” covers this option. After you have created a view, you can use it just like any table in a database. However, a view does NOT contain any data. A view is simply a SELECT statement that has a name associated with it. So when a view is referenced in a SELECT statement, the query optimizer substitutes the reference with the definition of the view in the SELECT statement before generating an execution plan. C0762271X.fm Page 241 Friday, April 29, 2005 7:35 PM 242 Chapter 7 Implementing Views For example, consider the following code: CREATE VIEW v_CustomerAddress AS SELECT a.CustomerID, a.CustomerName, c.AddressLine1, c.AddressLine2, c.AddressLine3, c.City, d.StateProvince, c.PostalCode, e.Country FROM dbo.Customer a INNER JOIN dbo.CustomerToCustomerAddress b ON a.CustomerID = b.CustomerID INNER JOIN dbo.CustomerAddress c ON b.CustomerAddressID = c.CustomerAddressID INNER JOIN dbo.StateProvince d ON c.StateProvinceID = d.StateProvinceID INNER JOIN dbo.Country e ON c.CountryID = e.CountryID; SELECT a.CustomerName, b.CreditLine FROM v_CustomerAddress a INNER JOIN dbo.Customer b ON a.CustomerID = b.CustomerID; The optimizer would locate the reference to the v_CustomerAddress view and substi- tute the view definition, rewriting the submitted query into a query similar to the following: SELECT a.CustomerName, f.CreditLine FROM dbo.Customer a INNER JOIN dbo.CustomerToCustomerAddress b ON a.CustomerID = b.CustomerID INNER JOIN dbo.CustomerAddress c ON b.CustomerAddressID = c.CustomerAddressID INNER JOIN dbo.StateProvince d ON c.StateProvinceID = d.StateProvinceID INNER JOIN dbo.Country e ON c.CountryID = e.CountryID INNER JOIN dbo.Customer f ON a.CustomerID = f.CustomerID; Understanding Ownership Chains Because a view references other objects, there is the potential for permission issues. Consider the objects and object owners that the diagram in Figure 7-1 shows. Figure 7-1 Defining an ownership chain Let’s say that UserA grants SELECT permission to UserD on the v_CustomerAddress view. Even though UserD has permission to execute a SELECT statement against the view, this user would receive an error when he attempts to use the view because the view is defined against the Customer and CustomerAddress tables, which are owned by a different user than either UserA or UserD. When the ownership across a chain of V_CustomerAddress owned by UserA CustomerAddress owned by UserC Customer owned by UserB C0762271X.fm Page 242 Friday, April 29, 2005 7:35 PM Lesson 1: Creating a View 243 dependent objects causes an error due to insufficient permissions, you have a broken ownership chain. For UserD to be able to execute a SELECT statement against the v_CustomerAddress view, the following has to occur: ■ UserA grants UserD SELECT permission to the view. ■ UserB grants UserD SELECT permission to dbo.Customer. ■ UserC grants UserD SELECT permission to dbo.CustomerAddress. MORE INFO Ownership chains For more information about ownership chains, see the SQL Server 2005 Books Online topic “Owner- ship Chains.” SQL Server 2005 Books Online is installed as part of SQL Server 2005. Updates for SQL Server 2005 Books Online are available for download at www.microsoft.com/technet/prodtechnol/sql/ 2005/downloads/books.mspx. Quick Check ■ What are the restrictions on the SELECT statement within a view? Quick Check Answer ■ COMPUTE or COMPUTE BY clauses are not allowed. You cannot use the INTO keyword or OPTION clause. Temporary tables and table variables cannot be referenced. An ORDER BY clause cannot be specified unless the TOP operator is also used. PRACTICE Create a View In this practice, you use the database that contains the tables you created in Chapter 3, “Creating Tables, Constraints, and User-Defined Types,” to create a view to return cus- tomer information for customers who live in Canada. 1. Launch SQL Server Management Studio (SSMS), connect to your instance, open a new query window, and change context to the database containing the tables you created in Chapter 3. 2. Create a view to return information for customers who live in Canada by execut- ing the following statement: CREATE VIEW v_CanadaCustomerAddress AS SELECT a.CustomerID, a.CustomerName, c.AddressLine1, c.AddressLine2, c.AddressLine3, c.City, d.StateProvince, c.PostalCode, e.Country C0762271X.fm Page 243 Friday, April 29, 2005 7:35 PM 244 Chapter 7 Implementing Views FROM dbo.Customer a INNER JOIN dbo.CustomerToCustomerAddress b ON a.CustomerID = b.CustomerID INNER JOIN dbo.CustomerAddress c ON b.CustomerAddressID = c.CustomerAddressID INNER JOIN dbo.StateProvince d ON c.StateProvinceID = d.StateProvinceID INNER JOIN dbo.Country e ON c.CountryID = e.CountryID WHERE e.Country = 'Canada' AND PrimaryAddressFlag = 1; 3. Construct a SELECT statement to verify that the view returns only customers from Canada. Lesson Summary ■ A view is simply a SELECT statement that you name and store in SQL Server as a sort of “virtual table” that lets you give users access to just a subset of data and that lets you improve performance, especially for complex queries. ■ After it’s defined, the view can be referenced in a SELECT statement just like a table, although it does not contain any data. ■ When granting permissions to a view, you must pay careful attention to the own- ership chain to ensure that the user has access to the view as well as all underly- ing objects that the view is built on. Lesson Review The following questions are intended to reinforce key information presented in this lesson. The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE Answers Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. 1. Which of the following options can prevent a table from being dropped? A. CHECK OPTION B. SCHEMABINDING C. UNION D. QUOTED_IDENTIFIER C0762271X.fm Page 244 Friday, April 29, 2005 7:35 PM Lesson 2: Modifying Data Through Views 245 Lesson 2: Modifying Data Through Views As noted previously, a view is just a named SELECT statement. In effect, a view is a pass-through reference to one or more base tables. Although most views provide read access to underlying data, because a view is a pass-through you can also make data modifications through it. A view that enables you to modify data is called an update- able view. This lesson explains how you can perform INSERT, UPDATE, DELETE, BCP, and BULK INSERT operations against a view. After this lesson, you will be able to: ■ Create an updateable view. Estimated lesson time: 20 minutes Creating Updateable Views Although you can define a view based on more than one table, SQL Server restricts any data modifications you execute through the view to a single table. In addition, all changes must directly reference columns and not derivations of a column. Thus, you cannot modify columns that are derived through an aggregate function, such as AVG, COUNT, SUM, MIN, or MAX, or through a computation that involves other columns or operations on a column, such as SUBSTRING. Changes cannot ref- erence columns generated by using operators such as UNION, CROSSJOIN, and INTERSECT. In addition, the view definition cannot contain a GROUP BY, HAVING, or DISTINCT clause. And you cannot use TOP when you specify WITH CHECK OPTION. BEST PRACTICES Using views to modify data Although you can use views to insert, update, and delete data, views are almost never used for that purpose. Stored procedures are always a better option because you can more easily validate changes via stored procedures. Stored procedures are also more flexible. In your view definition, you can include a WHERE clause that limits the range of rows that the view returns. However, the WHERE clause does not restrict the changes that users can make through the view. To restrict the changes that users can make, you use the CREATE VIEW command’s WITH CHECK OPTION clause when defining the view. Let’s look at a brief example to see how the CHECK OPTION clause works. Suppose that you define a view that shows customers who have a credit line greater than $1,000. A user could insert a new customer who has a credit line of $500 and not cause an error. However, doing so could cause confusion because although the insert C0762271X.fm Page 245 Friday, April 29, 2005 7:35 PM [...]... structures, SQL Server supports nested FOR XML queries (explained later in this lesson) MORE INFO Using FOR XML RAW For more information about the settings available to FOR XML RAW, read the topic “Using RAW Mode” in SQL Server 2005 Books Online SQL Server 2005 Books Online is installed as part of SQL Server 2005 Updates for SQL Server 2005 Books Online are available for download at www .microsoft. com/technet/prodtechnol /sql/ 2005/ downloads/books.mspx... data C0862271X.fm Page 269 Friday, April 29, 2005 7:38 PM Lesson 2: Retrieving XML Data by Using SQL Server Server-Side Technologies 269 Lesson 2: Retrieving XML Data by Using SQL Server Server-Side Technologies SQL Server 2005 offers multiple options for retrieving XML data This lesson covers the various techniques for retrieving XML data from SQL Server 2005, regardless of whether the data is stored... 1\CompleteLesson1 .sql file on the CD C0862271X.fm Page 2 64 Friday, April 29, 2005 7:38 PM 2 64 Chapter 8 Managing XML Data Practice 1: Create the TK431Chapter8 Database, UniversalLog Table, and XML Schema In this exercise, you will create the necessary database schema elements to support typed XML data inside a database 1 Open SQL Server Management Studio (SSMS) and open a connection to SQL Server 2005 2 Issue... AddRecordToLog @logRecord SQL Server automatically converts the data types (n)char, (n)varchar, (n)text, varbinary, and image to the XML data type when assigning values to an XML parameter, column, or variable The benefits of storing XML data by using the XML data type in SQL Server 2005 are as follows: ■ The XML data type is fully integrated with the SQL Server query engine and all other SQL Server services... and restrictions for creating an indexed view, see the SQL Server 2005 Books Online topic “Creating Indexed Views.” The purpose of all these restrictions is to ensure that SQL Server can perform a consistent calculation An indexed view, also called a materialized view, causes SQL Server to execute the SELECT statement in the view definition SQL Server then builds a clustered index on the view’s results,... data features in previous versions of SQL Server ■ The SQL Server 2005 AdventureWorks sample database installed ■ Microsoft Visual Studio 2005 or Microsoft Visual C# 2005 Express Edition installed You can download Visual C# 2005 Express Edition from http:// msdn .microsoft. com/vstudio/express/ Real World Adolfo Wiernik As a software architect, I’ve had to create the necessary database schema in an entity-relationship... released Part 14 of the SQL Standard XML-Related Specifications (SQLXML), which specifies how a relational database can natively manage XML data And SQL Server 2005 embraces this specification to give database administrators (DBAs) and developers more flexibility in working with different types of data This lesson focuses on the strategies you can use to store XML data in a SQL Server 2005 relational... representation—either tabular format or XML format Estimated lesson time: 60 minutes Converting Relational Data to XML Both SQL Server 2000 and SQL Server 2005 enable you to compose relational data into an XML representation by using the FOR XML clause in the SELECT statement SQL Server 2005 extends the FOR XML capabilities, making it easier to represent complex hierarchical structures, and adds new keywords... natively as XML ■ SQL Server 2005 provides fine-grained support for selecting, inserting, modifying, or deleting at the node level ■ Performance improves for data-retrieval operations because multiple indexing is possible with the XML data type, so SQL Server reads only relevant nodes ■ Document order and structure are preserved Limitations of storing XML using the XML data type in SQL Server 2005 include... are using the Enterprise or Developer editions of SQL Server 2005 To use an indexed view in any other edition of SQL Server, you must explicitly reference it in the query Quick Check ■ What is the difference between a regular view and an indexed view? Quick Check Answer ■ A regular view is a SELECT statement that is referenced by a name and stored in SQL Server It does not contain any data An indexed . ownership chains, see the SQL Server 2005 Books Online topic “Owner- ship Chains.” SQL Server 2005 Books Online is installed as part of SQL Server 2005. Updates for SQL Server 2005 Books Online are. Friday, April 29, 2005 7:35 PM C0762271X.fm Page 2 54 Friday, April 29, 2005 7:35 PM 255 Chapter 8 Managing XML Data The addition of native XML support in Microsoft SQL Server 2005 represents a. creating an indexed view, see the SQL Server 2005 Books Online topic “Creating Indexed Views.” The purpose of all these restrictions is to ensure that SQL Server can perform a con- sistent calculation.