Microsoft SQL Server 2008 R2 Unleashed- P194 ppt

10 52 0
Microsoft SQL Server 2008 R2 Unleashed- P194 ppt

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

Thông tin tài liệu

ptg 1924 CHAPTER 47 Using XML in SQL Server 2008 grows proportionally more costly as the number of rows of the table grows. It also prevents the value range scans possible when matching against typed values. When the types of all the nodes are declared in an associated XML schema, the values are stored as the corresponding SQL type (not as strings), and runtime typecasting is not necessary. Following are some other points for performance consideration: . When retrieving an entire XML instance, it is faster to select the xml column by name, without using query() or nodes(), because serialization of the XML up from the shredded Infoset format is costly. . XML indexes are not used during execution of check constraints on xml columns. . You should use the exist() method whenever possible to restrict the range of data being scanned. Full-Text Indexing xml columns can be full-text indexed, just like relational columns. The big difference is that for xml columns, the word boundary is not whitespace but element delimiters (<, >). Element text is indexed; attribute values are ignored. It’s important to use exist() when using a full-text T-SQL function such as CONTAINS to reduce unnecessary scans on the XML columns that don’t contain the text you are looking for. NOTE To generate a full-text index, a unique, non-null, single column index is required. The con- straint name PK_ _SimpleBook_ _2F2FFC0C shown in the following example represents the automatically generated primary key index name for the primary key of SimpleBook. Your instance of SQL Server will likely generate a different name for this index. ptg 1925 Summary 47 Here’s an example of how to generate and utilize a full-text index on an xml column: CREATE FULLTEXT CATALOG FullTextXmlCatalog GO CREATE FULLTEXT INDEX ON SimpleBook(BookXml) KEY INDEX PK_ _SimpleBook_ _2F2FFC0C ON FullTextXmlCatalog GO SELECT ‘End of Chapter’ FROM SimpleBook WHERE CONTAINS(BookXml, ‘Excellent’) AND BookXml.exist(‘(/book/chapter/title[contains(text()[1], “Excellent”)])[1]’)=1 GO End of Chapter Summary Within reason, there’s nothing you can’t do with XML in SQL Server 2008. The Microsoft team has addressed nearly every XML complaint and wish-list item gathered from the days of SQL Server 2000 and 2005. For the beginner and expert alike, SQL Server 2008 offers much to master in the realm of XML processing. The sheer quantity of new features may seem challenging at first. Remember that you need only utilize those features that are appropriate to your current application needs. How your applications develop and grow from there is entirely up to you. In Chapter 48, “SQL Server Web Services,” shows how to expose T-SQL routines to Internet clients using native XML Web services. ptg This page intentionally left blank ptg CHAPTER 48 SQL Server Web Services IN THIS CHAPTER . What’s New in SQL Server Web Services . Web Services Migration Path . Web Services History and Overview . Building Web Services . Examples: A C# Client Application . Using Catalog Views and System Stored Procedures . Controlling Access Permissions Web services address a problem domain that is crucial to business-driven programming: the need for application and platform-independent Remote Procedure Calls (RPC). They also provide one of the few ways in which non-Microsoft clients can consume SQL Server data over the Internet. This chapter provides all the details necessary to get native web services up and running on your instance of SQL Server 2008. It includes examples of both the client- and server- side code needed to make things happen at runtime. What’s New in SQL Server Web Services Microsoft first made it possible to expose T-SQL query batches, stored procedures, and scalar-valued functions as web services with the release of SQLXML 3.0, an add-on package for SQL Server 2000 that allowed for the interchange of relational data as Extensible Markup Language (XML). Over the past few years, the SQLXML packages have addressed the growing dependence of data-driven, distrib- uted applications on XML and have kept SQL Server 2000 current with the explosion of progress in the world of XML. The good news is that we no longer need SQLXML to create SQL Server web services because SQL Server 2008 supports them natively. The bad news is that this feature has been deprecated in SQL Server 2008. Although it is true that sometimes SQL Server features are deprecated for several versions before being removed, it seems more likely ptg 1928 CHAPTER 48 SQL Server Web Services that native web services will be removed from the next version of SQL Server due to secu- rity concerns. Web Services Migration Path Although SQL Server 2008 supports native web services, it’s important to plan your migra- tion path to another web service technology as soon as possible. The first step in moving away from this technology is to identify your web service endpoints. There are several ways to accomplish this. The easiest is to use SQL Server Upgrade Advisor, which includes deprecation warnings in its reports. SQL Server’s installer generates warnings when you upgrade from SQL Server 2005 to 2008. The database engine generates warnings (such as “Avoid using this feature in new development work”) upon service startup and when you create HTTP endpoints using SQL Server Management Studio (SSMS) or a similar tool. You may also view deprecation warnings generated at runtime using SQL Profiler (be sure to include the Deprecation: Warning event in the properties of your trace template). Now that you know how to identify your endpoints, the next step is choosing a replace- ment technology. Microsoft ASP.NET provides comprehensive support for web services, as does Windows Communication Foundation (WCF). There are also a number of related technologies to choose from, such as services developed using Representational State Transfer (a.k.a. RESTful services) and ADO.NET Data Services (formerly known as Astoria). The choice is really about what works for you, your organization, and your applications. Discussion of these technologies is beyond the scope of this book. SQL Server web services generates runtime errors or produces unexpected behaviors if the underlying data trans- mitted by the service is typed as one of the newly introduced SQL Server 2008 data types, such as date, time, hierarchy_id, datetime2, datetimeoffset, geometry, or geography. If you use these data types either in results returned by a stored procedure (exposed via an endpoint), or in its input parameters, SQL Server generates a SOAP fault at runtime. These types also end up commented out of the types section of the WSDL that SQL Server gener- ates for your web services. All data types supported by SQL Server 2005, however, continue to work as expected. In the following sections, we describe how to develop web services using SQL Server 2008 (or SQL Server 2005). Keep in mind that the services you build, while supported today, may not be supported in the near future. Web Services History and Overview Web services are supported on most major software platforms and can be built using Integrated Development Environments (IDEs) that comply with a few key World Wide Web Consortium (W3C) recommendations: . Web Services Description Language (WSDL)—WSDL is the XML grammar used to specify the functions and types (known as its interface) of a web service. . Simple Object Access Protocol (SOAP) 1.2—SOAP is the network transport-layer protocol for web services. ptg 1929 Web Services History and Overview 48 Until now, Open Database Connectivity (ODBC) and Tabular Data Stream (TDS; a propri- etary protocol developed by Sybase) were the only means available for clients to access SQL Server data. But because the web service standards are nonproprietary (although there are proprietary extensions), web service clients don’t need to install Microsoft Data Access Components (MDAC), ODBC, SQL Server Client Tools, or any open source vari- ants of these. NOTE Some of the examples in this chapter assume that you have a rudimentary knowledge of HTTP, a touch of coding savvy (some examples utilize Visual Studio 2008 and the C# .NET programming language), and a general understanding of how XML is used to describe and encapsulate data. The Web Services Pattern Web services follow a stateless request/response model that corresponds directly with the client/server model of Hypertext Transfer Protocol (HTTP). The following summary illus- trates this programming pattern: . A client application discovers that a server application hosts a web service that exposes one or more web methods. This process, known as discovery, is accomplished in one or more of the following ways: . Microsoft’s Universal Description, Discovery, and Integration (UDDI) service, an online catalog for publishing web services, facilitates this process. . More commonly, the developer of the hosted web service provides the network address and web method descriptions to the developer of the client application that will consume it (that is, call its methods). This is still the dominant way web services are exposed because most provide data that is strictly confidential. . The client then asks the discovered web service to describe its methods and their types, parameters, and return values, using the standard WSDL XML vocabulary. This is usually performed via an HTTP request to the web service in the form http[s]://ServerDomainName/WebServiceName?wsdl. . The web service responds by providing the WSDL (an XML document). . The client application (or, in some cases, the IDE of the client, such as Visual Studio) creates a code class based on the server-generated WSDL. This class is known as a stub, or proxy, because it merely contains callable references to the actual remote methods of the web service, wrapped in the formal language semantics of the client’s software platform. (The actual implementation of those methods is held on the server application.) . The client invokes a web service method over some protocol (usually HTTP). This invocation is an HTTP request encoded in the SOAP XML vocabulary. . The web service responds (it is hoped) with a SOAP-encoded response. ptg 1930 CHAPTER 48 SQL Server Web Services NOTE Content and metadata pertaining to these stateless communications are always encoded in XML-tagged documents known as SOAP envelopes. For complete informa- tion on SOAP, visit the SOAP messaging framework specification, available online from the W3C, at www.w3.org. The W3C is the organizational body responsible for creating and maintaining World Wide Web standards, including XML. The W3C website is a great place to get accurate and up-to-date information on Web standards. To recap: UDDI or word-of-mouth provides a discovery mechanism for web services. WSDL provides the web methods, types, and metadata of the web service. Stateless requests and responses are invoked over HTTP (or perhaps TCP) and transmitted in SOAP- encoded format. Before SQL Server 2005, developers had to use the Internet Information Services Virtual Directory Management (IISVDM) for SQL Server utility to create SOAP-typed virtual names to expose their data. (Incidentally, this could also be accomplished using a language such as Visual Basic .NET with the SQLVDir object model that came with IISVDM.) Today, this process is far easier. SQL Server no longer relies on IISVDM or even IIS to publish web services. It ties directly in with operating-system–level (or kernel-mode) HTTP, listening by way of the HTTP API (sometimes referred to as http.sys). This means that under the covers, SQL Server registers the virtual paths (also known as URIs, such as www.myserver.com/urlpath) specified in endpoint creation syntax with http.sys in the same way that IIS registers virtual directories. The operating system then farms out incom- ing HTTP requests to IIS or SQL Server, based on the path of the incoming request. SQL Server also includes the entire SOAP messaging stack in its binaries. You might say that to a certain degree, SQL Server is now a web server with limited applications. NOTE It is possible to create SQL Server endpoints for use with database mirroring schemes, network connectivity, and SQL Server Service Broker. This chapter focuses strictly on web service endpoints. Building Web Services Let’s delve right into the process of building a web service in SQL Server 2008. The first step is to decide which data or T-SQL functionality to expose to the clients who will ultimately call the web methods. For this first example, you should create the stored procedure shown in Listing 48.1, which returns a row of data from the AdventureWorks2008 sample database. The purpose is to reveal a few attributes of an employee, given his or her unique EmployeeId. ptg 1931 Building Web Services 48 LISTING 48.1 A Stored Procedure for Your First Web Service use AdventureWorks2008 GO CREATE PROC dbo.GetEmployeeBasics ( @EmployeeId int ) AS SELECT e.BusinessEntityID, FirstName, LastName, e.JobTitle FROM HumanResources.Employee e JOIN Person.Person p ON e.BusinessEntityID = p. BusinessEntityID WHERE BusinessEntityID = @EmployeeId To expose this procedure as a web method of your web service, you use the CREATE ENDPOINT T-SQL statement, which falls under the formal SQL category of Data Definition Language (DDL). An endpoint can be defined as simply an entity on one end of a connec- tion over a communication protocol, such as HTTP. SOAP endpoints have an additional nickname: nodes. SOAP nodes consist of a SOAP sender and a SOAP receiver, following the request-response model. To create a SOAP-based HTTP endpoint, you use the fairly complex T-SQL syntax shown in Listing 48.2. LISTING 48.2 CREATE ENDPOINT T-SQL Syntax CREATE ENDPOINT EndPointName [ AUTHORIZATION login ] STATE = { STARTED | STOPPED | DISABLED } AS HTTP ( PATH = ’url’ , AUTHENTICATION =( { BASIC | DIGEST | INTEGRATED | NTLM | KERBEROS } [ , n ] ) , PORTS = ( { CLEAR | SSL} [ , n ] ) [ SITE = {‘*’ | ‘+’ | ’webSite’ },] [, CLEAR_PORT = clearPort ] [, SSL_PORT = SSLPort ] [, AUTH_REALM = { ’realm’ | NONE } ] [, DEFAULT_LOGON_DOMAIN = { ’domain’ | NONE } ] [, RESTRICT_IP = { NONE | ALL } ] [, COMPRESSION = { ENABLED | DISABLED } ] ptg 1932 CHAPTER 48 SQL Server Web Services [, EXCEPT_IP = ( { <4-part-ip> | <4-part-ip>:<mask> } [ , n ] ) ) FOR SOAP ( [ { WEBMETHOD [ ’namespace’ .] ’method_alias’ ( NAME = ’database.owner.name’ [ , SCHEMA = { NONE | STANDARD | DEFAULT } ] [ , FORMAT = { ALL_RESULTS | ROWSETS_ONLY } ] ) } [ , n ] ] [ BATCHES = { ENABLED | DISABLED } ] [ , WSDL = { NONE | DEFAULT | ’sp_name’ } ] [ , SESSIONS = { ENABLED | DISABLED } ] [ , LOGIN_TYPE = { MIXED | WINDOWS } ] [ , SESSION_TIMEOUT = timeoutInterval | NEVER ] [ , DATABASE = { ’database_name’ | DEFAULT } [ , NAMESPACE = { ’namespace’ | DEFAULT } ] [ , SCHEMA = { NONE | STANDARD } ] [ , CHARACTER_SET = { SQL | XML }] [ , MAX_SOAP_HEADERS_SIZE = { int | DEFAULT }] ) Before running the examples that follow, you should create a dedicated Windows login to use in the authorization scheme; this user should own and be able to access the database objects you create. In the examples that follow, this user is indicated as MyDomain\SQLWebServicesClient. Replace this name with your own. Listing 48.3 contains the endpoint creation DDL that exposes dbo.GetEmployeeBasics to its web consumers. LISTING 48.3 T-SQL for Creating a SQL Server Web Service Endpoint CREATE ENDPOINT EPT_SQL2008UnleashedExamples AUTHORIZATION [MyDomain\SQLWebServicesClient] STATE = STARTED AS HTTP ( AUTHENTICATION = (INTEGRATED), PATH = ‘/opensql/’, PORTS = (CLEAR, SSL), CLEAR_PORT = 80, SSL_PORT = 443, SITE = ‘*’, COMPRESSION = ENABLED ) FOR SOAP ( ptg 1933 Building Web Services 48 WEBMETHOD ‘urn:www-samspublishing-com:examples’.’WM_GetEmployeeBasics’ ( NAME = ‘AdventureWorks2008.dbo.GetEmployeeBasics’, SCHEMA = STANDARD, FORMAT = ALL_RESULTS ), WSDL = DEFAULT, BATCHES = DISABLED, SCHEMA = STANDARD, LOGIN_TYPE = WINDOWS, SESSION_TIMEOUT = 120, DATABASE = ‘AdventureWorks2008’, NAMESPACE = ‘urn:www-samspublishing-com:examples’, CHARACTER_SET = XML ) In this listing, the name of the endpoint (EPT_SQL2008UnleashedExamples) immediately follows the keywords CREATE ENDPOINT. NOTE Using EPT_ as a prefix is a naming convention chosen to delineate endpoints from other types of user-created objects. Any valid database object name is acceptable here. The endpoint name is also conveniently used to drop the endpoint from the server, as follows: DROP ENDPOINT EPT_SQL2008UnleashedExamples But don’t drop the endpoint until you’ve finished trying out all the examples! One caveat when creating endpoints: if the server name, port, and path you choose are already reserved or in use by another application (such as IIS) on your server, you may need to call the new stored procedure sp_reserve_http_namespace. This procedure explic- itly reserves the URL of your choosing with http.sys so that you may use it for your endpoints. Here’s an example: EXEC sp_reserve_http_namespace N’http://localhost:80/opensql’ Next in the DDL, the AUTHORIZATION keyword is used to specify the name of the login (either of authorization type Windows or SQL Server) that owns the endpoint. You can change the name of the login later by using the ALTER AUTHORIZATION statement, as in the following example: . in SQL Server 2008. The Microsoft team has addressed nearly every XML complaint and wish-list item gathered from the days of SQL Server 2000 and 2005. For the beginner and expert alike, SQL Server. have kept SQL Server 2000 current with the explosion of progress in the world of XML. The good news is that we no longer need SQLXML to create SQL Server web services because SQL Server 2008 supports. deprecated in SQL Server 2008. Although it is true that sometimes SQL Server features are deprecated for several versions before being removed, it seems more likely ptg 1928 CHAPTER 48 SQL Server Web

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

Mục lục

  • Part I: Welcome to Microsoft SQL Server

    • 1 SQL Server 2008 Overview

      • SQL Server Components and Features

      • SQL Server 2008 R2 Editions

      • SQL Server Licensing Models

      • 2 What’s New in SQL Server 2008

        • New SQL Server 2008 Features

        • 3 Examples of SQL Server Implementations

          • Application Terms

          • Part II: SQL Server Tools and Utilities

            • 4 SQL Server Management Studio

              • What’s New in SSMS

              • 5 SQL Server Command-Line Utilities

                • What’s New in SQL Server Command-Line Utilities

                • The sqlcmd Command-Line Utility

                • The dta Command-Line Utility

                • The tablediff Command-Line Utility

                • The bcp Command-Line Utility

                • The sqldiag Command-Line Utility

                • The sqlservr Command-Line Utility

                • 6 SQL Server Profiler

                  • What’s New with SQL Server Profiler

                  • SQL Server Profiler Architecture

                  • Executing Traces and Working with Trace Output

                  • Saving and Exporting Traces

                  • Part III: SQL Server Administration

                    • 7 SQL Server System and Database Administration

                      • What’s New in SQL Server System and Database Administration

                      • 8 Installing SQL Server 2008

                        • What’s New in Installing SQL Server 2008

                        • Installing SQL Server Using a Configuration File

Tài liệu cùng người dùng

Tài liệu liên quan