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

Microsoft SQL Server 2008 R2 Unleashed- P91 docx

10 279 0

Đ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 421,22 KB

Nội dung

ptg 844 CHAPTER 27 Creating and Managing Views in SQL Server adventure-works\rachel0 1965-08-09 F 2003-07-01 1 Only the rows in the Employee table with a HireDate value greater than March 1, 2003, are returned when you select everything from the view. Separate views can be created based on geography, demographics, or any other data element that requires a different set of security. Keep in mind that additional conditions can be applied when selecting from a view. You can utilize another WHERE clause in the SELECT statement that uses a view. This is demon- strated in the following example: select * from EmpViewHorizontal where HireDate >= ‘7/1/03’ and BirthDate > ‘1/1/65’ LoginID BirthDate Gender HireDate SalariedFlag adventure-works\rachel0 1965-08-09 F 2003-07-01 1 As you can see, a view with horizontal security restricts your initial result set but does not prevent you from applying additional conditions to obtain the desired result. Creating Views You can create several different types of views in SQL Server 2008, including standard views, indexed views, and partitioned views. Standard views are like those that have been discussed thus far in this chapter; they let you achieve most of the benefits associated with views. An indexed view has a unique clustered index defined on it that causes the view to be materialized. In other words, the creation of the index causes physical storage of the data related to the view’s index. Partitioned views join horizontally partitioned data from a set of distinct tables. They can be locally partitioned, meaning that the tables are on the same server; or they can be distributed, meaning that some of the tables exist on other servers. Partitioned views and indexed views are discussed in detail later in this chapter. All types of views share a common set of restrictions: . Every column (including derived columns) must have a name. . The SELECT statement used in the view cannot include the COMPUTE BY clause or the INTO keyword. . The SELECT statement used in the view cannot include the ORDER BY clause. . The SELECT statement used in the view cannot contain temporary tables. . You cannot associate AFTER triggers with views, but you can associate INSTEAD OF triggers. . You cannot associate rules or default definitions with a view. . You cannot define a full-text index on a view. Download from www.wowebook.com ptg 845 Creating Views 27 A view can have a maximum of 1,024 columns. You can select all the columns for a view by using a SELECT * statement, but you need to use some caution when doing so. In particular, you must keep in mind that the view will not display columns that have been added to the view’s underlying tables after the view has been created. The fact that the new columns are not displayed can be a good thing but is sometimes overlooked. You can prevent changes to the underlying objects (for example, tables) by creating the view with SCHEMABINDING. SCHEMABINDING is discussed in the next section. If you want the changes to the underlying objects to be reflected in the views, you can use the sp_refreshview stored procedure. This stored procedure updates the metadata for the specified non-schema-bound view. TIP SQL Server Books Online lists a handy script that can be used to update any view that has a dependency on an object. The script is shown in the sp_refreshview examples. The script, listed here, is coded such that it will generate output that can be run to generate the sp_refreshview statements for the Person.Person table in the Adventureworks2008 database: SELECT DISTINCT ‘EXEC sp_refreshview ‘’’ + name + ‘’’’ FROM sys.objects so INNER JOIN sys.sql_dependencies sd ON so.object_id = sd.object_id WHERE type = ‘V’ AND sd.referenced_major_id = object_id(‘Person.Person’) To ge nerate the executions for another object, you simply change the name of the object (that is, Person.Person) found at the end of the script to the name of the object you want to investigate. With these guidelines in mind, you are now ready to create your view. Views can be created in SQL Server 2008 using T-SQL or SQL Server Management Studio (SSMS). Creating Views Using T-SQL The CREATE VIEW statement is used to create views with T-SQL. The syntax for the CREATE VIEW statement follows: CREATE VIEW [ schema_name . ] view_name [ (column [ , n ] ) ] [ WITH <view_attribute> [ , n ] ] AS select_statement [ ; ] [ WITH CHECK OPTION ] Download from www.wowebook.com ptg 846 CHAPTER 27 Creating and Managing Views in SQL Server <view_attribute> ::= { [ ENCRYPTION ] [ SCHEMABINDING ] [ VIEW_METADATA ] } This statement and the related options are essentially the same in SQL Server 2008 as they were in SQL Server 2005 and SQL Server 2000. We first look at a simple example for creat- ing a view with T-SQL and then delve into several other examples that utilize the view attributes. Listing 27.2 shows a sample T-SQL statement for creating a simple view. LISTING 27.2 Creating a Simple View with T-SQL CREATE VIEW Sales.vw_OrderSummary as select datepart(yy, orderdate) as ‘OrderYear’, datepart(mm, orderdate) as ‘OrderMonth’, sum(TotalDue) as ‘OrderTotal’ from Sales.SalesOrderHeader group by datepart(yy, orderdate), datepart(mm, orderdate) There are several important aspects to notice in the example in Listing 27.2. First, all the columns in the SELECT statement are derived columns and do not simply reference a column in a table. You do not need to have a derived column in your view, but if you do, the derived column(s) must have a name or an alias assigned to it to be able to create the view. The column name allows you to reference the derived column when selecting from the view. If the derived columns in the SELECT statement are not named, the CREATE VIEW statement will fail. Another notable characteristic of the simple view example is that an aggregate is used in the SELECT statement. Aggregates are allowed in views and are common implementations of views. Views with aggregates can be used instead of summary tables that denormalize data and use additional disk space. Keep in mind that the results of any view (including those with aggregates) are not returned in any particular order. Views cannot be created with the ORDER BY clause, but the ORDER BY clause can be utilized in a SELECT statement that references the view. The following example shows the first five rows of the vw_OrderSummary view created in Listing 27.2: select top 5 * from Sales.vw_OrderSummary OrderYear OrderMonth OrderTotal —————- —————- ——————————- 2003 5 4449886.2315 2001 11 3690018.6652 Download from www.wowebook.com ptg 847 Creating Views 27 2003 8 6775857.0745 2002 7 3781879.0708 2003 11 5961182.6761 You can see from the results of the SELECT that the summarized order information is not returned in any particular order. If you want to sort the results, you can treat the view like a table in a SELECT statement and use the ORDER BY clause to produce the desired results. The following example shows a SELECT statement from the vw_OrderSummary view and the ordered results: select top 5 * from Sales.vw_OrderSummary where OrderYear >= 2004 order by OrderYear, OrderMonth OrderYear OrderMonth OrderTotal —————- —————- ——————————- 2004 1 3691013.2227 2004 2 5207182.5122 2004 3 5272786.8106 2004 4 4722890.7352 2004 5 6518825.2262 TIP In many cases, it is best to create views that include the primary key columns from the underlying tables. This allows the views to be joined to other tables. Consider, for example, a view created on the Employee table in the Adventureworks2008 database. If you want to join that view to another table (such as EmployeeAddress), you need the primary key of the table (that is, Employee.EmployeeID) in the view. Views can also be created with the following special view attributes: ENCRYPTION, SCHEMABINDING, and VIEW_METADATA. Each of these attributes and some other specialized views are discussed in the following sections. ENCRYPTION The ENCRYPTION attribute causes the view definition to be stored as encrypted text in sys.syscomments. This feature is also available for stored procedures and other database code that you may want to protect. One issue to consider when you create a view using the ENCRYPTION option is that this option prevents the view from being published as part of SQL Server replication. Download from www.wowebook.com ptg 848 CHAPTER 27 Creating and Managing Views in SQL Server The following example shows the creation of one of the prior views with the ENCRYPTION attribute: IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N’[Sales].[vw_OrderSummary]’)) DROP VIEW [Sales].[vw_OrderSummary] GO CREATE VIEW Sales.vw_OrderSummary WITH ENCRYPTION AS select datepart(yy, orderdate) as ‘OrderYear’, datepart(mm, orderdate) as ‘OrderMonth’, sum(TotalDue) as ‘OrderTotal’ from Sales.SalesOrderHeader group by datepart(yy, orderdate), datepart(mm, orderdate) go The following SELECT statement from sys.syscomments retrieves the text related to the encrypted view and shows that the view definition is not visible in the Text column: SELECT id, OBJECT_NAME(ID) ‘ViewName’, text FROM SYS.sysCOMMENTS WHERE OBJECT_NAME(ID) LIKE ‘%vw_OrderSummary%’ id ViewName text —————— ——————————— ——————————— 919674324 vw_OrderSummary NULL SCHEMABINDING The SCHEMABINDING attribute binds a view to the schema of the underlying table(s) refer- enced in the view’s SELECT statement. This binding action prevents any changes to the underlying tables that would affect the view definition. For example, if you have a view that includes the Employee.Title column, this column cannot be altered or dropped in the Employee table. If schema changes are attempted on the underlying tables, an error message is returned, and the change is not allowed. The only way to make the change is to drop the view or alter the view to remove the SCHEMABINDING attribute. TIP Views created with SCHEMABINDING have been used in the past to simply prevent changes to the underlying schema. Any table for which you wanted to prevent schema changes was included in a view, and this essentially locked the definition of the table. This approach is no longer needed because you can accomplish the same thing using DDL triggers, which can react to schema changes and prevent them if desired. Download from www.wowebook.com ptg 849 Creating Views 27 VIEW_METADATA When the VIEW_METADATA option is specified, SQL Server returns information about the view, as opposed to the base tables. This happens when browse-mode metadata is requested for a query that references the view via a database API. Browse-mode metadata is additional information returned by SQL Server to client-side DBLIB, ODBC, and OLE DB APIs, which allows them to implement client-side updatable cursors. WITH CHECK OPTION WITH CHECK OPTION forces all data modifications made through a view to adhere to the conditions in the view. The example shown in Listing 27.3 shows a view created using WITH CHECK OPTION. LISTING 27.3 View using a WITH CHECK OPTION CREATE VIEW HumanResources.vw_MaleEmployees AS SELECT LoginID, Gender FROM HumanResources.Employee WHERE Gender = 'M' WITH CHECK OPTION The following UPDATE statement fails when executed against the view created in Listing 27.3 because the Gender change would cause it to no longer be seen by the view: UPDATE HumanResources.vw_MaleEmployees SET Gender = ‘F’ WHERE LoginId = ‘adventure-works\taylor0’ Updates and other modifications made though a view are discussed further in the “Data Modifications and Views” section, later in this chapter. Creating Views Using the View Designer SQL Server 2008 provides a graphical tool, called the View Designer, you can use to create views. This tool can be an invaluable aid when you are creating or modifying a view. The View Designer is equipped with four panes that provide the information relative to the view. Figure 27.1 shows the View Designer display for the Person. vStateProvinceCountryRegion view installed in the Adventureworks2008 database. To view an existing view in the View Designer, right-click on the view listed in the Object Explorer and select Design. To create a new view via the View Designer, right-click the Views node in the Object Explorer and select New View. An empty View Designer is displayed. Download from www.wowebook.com ptg 850 CHAPTER 27 Creating and Managing Views in SQL Server The View Designer has these four panes: . Diagram pane—Gives a graphical view of the tables that are part of the view. This includes the columns in the tables and relationships between the tables contained in the view. . Criteria pane—Displays all the columns selected in the view and allows for sorting, filtering, and other related column-oriented criteria. . SQL pane—Renders the T-SQL associated with the view. . Results pane—Shows the results of that view’s SELECT statement. The panes in the View Designer are dependent on each other. If you add a WHERE clause in the SQL pane, the corresponding Filter value is added in the Criteria pane. Similarly, if you right-click in the Diagram pane and add a table to the view, the Criteria and SQL panes are updated to reflect this change. TIP One of the most amazing features of the View Designer is the capability to render a SQL statement into its graphical form. You can copy T-SQL into the SQL pane, and the View Designer reverse-engineers the tables into the Diagram pane, giving you a graphi- cal display of the query. Some complex SQL statements cannot be rendered, but many of them can. Give it a try; you will be impressed. FIGURE 27.1 The View Designer window. Download from www.wowebook.com ptg 851 Creating Views 27 FIGURE 27.2 The view’s Properties window. You can control the View Designer via the Quer y Designer menu option as well. Adding a new table, verifying the T-SQL, and changing the panes displayed are just some of the options available on this menu. NOTE The View Designer does not allow you to set every attribute of a view. It is a great starting point for creating a view, but you need to set some attributes using T-SQL after creating the view. For example, you cannot specify WITH CHECK OPTION in the View Designer, but you can set it by altering the view after it has been created. There is also no option to script a view from the View Designer. You must close the View Designer first, and then you are asked whether you want to save the view. If you click Yes, a prompt allows you to specify a name. The Properties window displays information about the view and also allows you to enter additional view properties. If this window is not visible, you can select the Properties window from the View menu or simply press F4. The properties you can set on the view include (but are not limited to) a description, the schema that owns the view, and whether to bind the view to the schema. Figure 27.2 shows the Properties window for the Person.vStateProvinceCountryRegion view that we looked at earlier. After defining a view using the panes in the View Designer and setting its properties, you can choose to save the view. You are prompted to give it a name. After you save the view, it appears in the Object Explorer tree. Download from www.wowebook.com ptg 852 CHAPTER 27 Creating and Managing Views in SQL Server Managing Views After creating your view, you can manage the view via T-SQL or the View Designer. The T- SQL commands for managing views are the ALTER VIEW and DROP VIEW statements. The ALTER VIEW statement is used to modify the properties or definition of the view, and the DROP VIEW statement is used to remove the view from the database. Altering Views with T-SQL The ALTER VIEW syntax follows: ALTER VIEW [ schema_name . ] view_name [ ( column [ , n ] ) ] [ WITH <view_attribute> [ , n ] ] AS select_statement [ ; ] [ WITH CHECK OPTION ] <view_attribute> ::= { [ ENCRYPTION ] [ SCHEMABINDING ] [ VIEW_METADATA ] } The ALTER VIEW statement utilizes the same set of options and parameters as the CREATE VIEW statement. You should consider using the ALTER VIEW statement when making changes to your view instead of dropping and re-creating the view. Altered views retain their associated permissions and do not affect dependent stored procedures or triggers. An example of the ALTER VIEW statement follows: ALTER VIEW [dbo].[vw_employee] with SCHEMABINDING AS SELECT TITLE, GENDER FROM HumanResources.Employee WITH CHECK OPTION The entire definition of the view, including any attributes or options, must be listed in the ALTER VIEW statement. This behavior is similar to that of the ALTER PROCEDURE statement and some of the other ALTER statements. You can generate the ALTER VIEW statement from the Object Explorer by right-clicking the view and selecting Script View As and then choosing Alter To. This allows you to script the ALTER statement to a new query editor window, a file, or the Clipboard. Download from www.wowebook.com ptg 853 Data Modifications and Views 27 Dropping Views with T-SQL You can drop views from a database by using the DROP VIEW statement. The syntax for DROP VIEW follows: DROP VIEW [ schema_name . ] view_name [ ,n ] [ ; ] You can drop more than one view by using one DROP VIEW statement and listing all the targeted views, separated by commas. You should consider running the sp_depends stored procedure against the targeted views before dropping them. This procedure lists the objects dependent on the view you are dropping. TIP You c an also drop more than one view v ia SSMS. Simply select the Views node in Object Explorer and then activate the Object Explorer Details window. The Object Explorer Details window displays all the views and allows you to select multiple views that are displayed. After selecting the views you want to delete, you can right-click a selection and choose Delete to remove all the views selected. Managing Views with SSMS You can use the Object Explorer in SQL Server Management Studio to alter or drop views as well. To do so, you right-click a view in the Object Explorer and choose Design to launch the View Designer. The View Designer allows you to modify a view in an easy-to- use graphical interface. Refer to the “Creating Views Using the View Designer” section, earlier in this chapter, for a detailed review of the View Designer. To drop a view, you right-click the view in the Object Explorer and choose Delete. You can drop the view by clicking OK on the Delete Object screen, or you can script the drop state- ment for later execution. Data Modifications and Views Data modifications are allowed through a view under certain circumstances. Views that meet these criteria are sometimes called updatable views. Updatable views can be refer- enced in an INSERT, UPDATE,or DELETE statement, and these statements ultimately affect the underlying table(s) in the view. The following example contains a SQL statement to create an updatable view, followed by an UPDATE statement that performs a data modification using the view: CREATE VIEW vw_CreditCard AS SELECT CreditCardID, CardType, CardNumber, ExpMonth, ExpYear Download from www.wowebook.com . can be created in SQL Server 2008 using T -SQL or SQL Server Management Studio (SSMS). Creating Views Using T -SQL The CREATE VIEW statement is used to create views with T -SQL. The syntax for. Views in SQL Server <view_attribute> ::= { [ ENCRYPTION ] [ SCHEMABINDING ] [ VIEW_METADATA ] } This statement and the related options are essentially the same in SQL Server 2008 as they. the same in SQL Server 2008 as they were in SQL Server 2005 and SQL Server 2000. We first look at a simple example for creat- ing a view with T -SQL and then delve into several other examples

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

TỪ KHÓA LIÊN QUAN