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

Microsoft SQL Server 2005 Developer’s Guide- P13 ppsx

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

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 594,04 KB

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

Nội dung

You can see an example of using the FOR XML clause with the XML Type directive here: SELECT DocID, MyXMLDoc FROM MyXMLDocs WHERE DocID=1 FOR XML AUTO, TYPE NOTE This listing uses the ex

Trang 1

<Name>

<Last_Name>Brown</Last_Name>

<First_Name>Kevin</First_Name>

</Name>

</Employee>

<Employee Employee_ID="3">

<Name>

<Last_Name>Tamburello</Last_Name>

<First_Name>Roberto</First_Name>

</Name>

</Employee>

For more information about using the XML Explicit mode, see the SQL Server

2005 BOL

Type Mode

When XML data types are returned using the FOR XML clause’s Type mode, they

are returned as XML data types You can see an example of using the FOR XML

clause with the XML Type directive here:

SELECT DocID, MyXMLDoc FROM MyXMLDocs

WHERE DocID=1 FOR XML AUTO, TYPE

NOTE

This listing uses the example MyXMLDocs table that was created earlier in this chapter.

This query returns the relational DocID column along with the MyXMLDoc XML

data type column It uses the FOR XML AUTO clause to return the results as XML

The TYPE directive specifies that the results will be returned as an XML data type

You can see the results of using the Type directive here:

-<MyXMLDocs DocID="1">

<MyXMLDoc>

<MyXMLDoc xmlns="http://MyXMLDocSchema">

<DocumentID>1</DocumentID>

<DocumentBody>Modified Body</DocumentBody>

</MyXMLDoc>

</MyXMLDoc>

</MyXMLDocs>

Trang 2

The preceding listing was reformatted to make it more readable in the published page width.

FOR XML Path

The new FOR XML PATH mode provides increased power to shape XML results than either the FOR XML AUTO or FOR XML RAW mode but without the

complexity of the FOR XML EXCLICIT mode The new PATH mode allows

users to specify the path in the XML tree where an element or attribute can be added Essentially, the new PATH mode is a simpler alternative to the FOR XML EXCPLICIT mode It can accomplish most of the things the developers need with the use of universal tables and complex unions However, it is more limited than the FOR XML EXPLICIT mode You can see an example of using the FOR XML PATH mode in the following listing:

SELECT Top 3 title, FirstName, LastName from Person.Contact FOR XML PATH

This query uses the same Person.Contact table from the AdventureWorks database that the earlier FOR XML RAW and AUTO modes did, but with quite different results, which you can see here:

<row>

<title>Mr.</title>

<FirstName>Gustavo</FirstName>

<LastName>Achong</LastName>

</row>

<row>

<title>Ms.</title>

<FirstName>Catherine</FirstName>

<LastName>Abel</LastName>

</row>

<row>

<title>Ms.</title>

<FirstName>Kim</FirstName>

<LastName>Abercrombie</LastName>

</row>

By default each of the results is enclosed in the set of <row> </row> tags The output is close to the output that can be produced using FROM XML EXPLICIT

Trang 3

However, the FOR XML PATH statement provides additional flexibility by making

it possible to insert attributes and elements, enhancing the structure of the output

The following list shows how you can add the <Employee> element to this output

using the For XML PATH mode:

SELECT Top 3

title "Employee/Title",

FirstName "Employee/First_Name",

LastName "Employee/Last_Name"

from Person.Contact FOR XML PATH

Much as when you use a standard SQL AS clause, you can add parent tags and

rename the XML output elements by using the quoted string that you can see following

each column in this FOR XML PATH example The Employee tag, which you can see

to the left of the / symbol, will be created when the result set is output The name to

the right of the / symbol will be used as a new name for the element The output from

this version of the FOR XML PATH mode can be seen in the following listing Notice

where the <Employee></Employee> tag has been added to the XML output:

<row>

<Employee>

<Title>Mr.</Title>

<First_Name>Gustavo</First_Name>

<Last_Name>Achong</Last_Name>

</Employee>

</row>

<row>

<Employee>

<Title>Ms.</Title>

<First_Name>Catherine</First_Name>

<Last_Name>Abel</Last_Name>

</Employee>

</row>

<row>

<Employee>

<Title>Ms.</Title>

<First_Name>Kim</First_Name>

<Last_Name>Abercrombie</Last_Name>

</Employee>

</row>

Trang 4

Nested FOR XML Queries

SQL Server 2000 was limited to using the FOR XML clause in the top level of

a query Subqueries couldn’t make use of the FOR XML clause SQL Server 2005 adds the ability to use nested FOR XML queries, which are useful for returning multiple items where there is a parent-child relationship One example of this type

of relationship might be order header and order details records; another might be product categories and subcategories You can see an example of using a nested FOR XML clause in the following listing:

SELECT (SELECT title, FirstName, LastName

FROM Person.Contact

FOR XML RAW, TYPE,ROOT('root')).query('/root[1]/row[1]')

Notice that the inner SELECT statement uses the TYPE mode to return a XML result This result is then processed using a simple XQuery executed with the XML data type’s query method In this case the XQuery extracts the values from the first row in the result set, as is shown here:

<row title="Mr." FirstName="Gustavo" LastName="Achong" />

Inline XSD Schema Generation

SQL Server 2005’s FOR XML support also has the ability to generate an XSD schema by adding the XMLSCHEMA directive to the FOR XML clause You can see an example of using the new XMLSCHEMA directive in the following listing:

SELECT MyXMLDoc FROM MyXMLDocs WHERE DocID=1 FOR XML AUTO, XMLSCHEMA

In this case, because the XMLSCHEMA directive has been added to the FOR XML clause, the query will generate and return the schema that defines the specific XML column along with the XML result from the selected column

The XMLSCHEMA directive works only with the FOR XML AUTO and FOR XML RAW modes It cannot be used with the FOR XML EXPLICIT or FOR XML PATH mode If the XMLSCHEMA directive is used with a nested query, it can be used only at the top level of the query The XSD schema that’s generated from this query is shown in the following listing:

<xsd:schema targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet2" xmlns:schema="urn:schemas-microsoft-com:sql:SqlRowSet2"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:sqltypes="http://schemas.microsoft.com/sqlserver/2004/sqltypes"

Trang 5

<xsd:import namespace="http://schemas.microsoft.com

/sqlserver/2004/sqltypes"

schemaLocation="http://schemas.microsoft.com

/sqlserver/2004/sqltypes/sqltypes.xsd" />

<xsd:import namespace="http://MyXMLDocSchema" />

<xsd:element name="MyXMLDocs">

<xsd:complexType>

<xsd:sequence>

<xsd:element name="MyXMLDoc" minOccurs="0">

<xsd:complexType sqltypes:xmlSchemaCollection=

"[tecadb].[dbo].[MyXMLDocSchema]">

<xsd:complexContent>

<xsd:restriction base="sqltypes:xml">

<xsd:sequence>

<xsd:any processContents="strict" minOccurs="0"

maxOccurs="unbounded"

namespace="http://MyXMLDocSchema">

</xsd:sequence>

</xsd:restriction>

</xsd:complexContent>

</xsd:complexType>

</xsd:element>

</xsd:sequence>

</xsd:complexType>

</xsd:element>

</xsd:schema>

<MyXMLDocs xmlns="urn:schemas-microsoft-com:sql:SqlRowSet2">

<MyXMLDoc>

<MyXMLDoc xmlns="http://MyXMLDocSchema">

<DocumentID>1</DocumentID>

<DocumentBody>Modified Body</DocumentBody>

</MyXMLDoc>

</MyXMLDoc>

</MyXMLDocs>

The XMLSCHEMA directive can return multiple schemas, but it always returns

at least two: one schema is returned for the SqlTypes namespace, and a second

schema is returned that describes the results of the FOR XML query results In the

preceding listing you can see the schema description of the XML data type column

beginning at: <xsd:element name="MyXMLDocs"> Next, the XML results can be

seen at the line starting with <MyXMLDocs xmlns="urn:schemas-microsoft-com:

sql:SqlRowSet2">

Trang 6

You can also generate an XDR (XML Data Reduced) schema by using the XMLDATA directive in combination with the FOR XML clause However, the XDR schema has been deprecated in favor of XSD schema.

OPENXML

While the FOR XML clause essentially creates an XML document from relational data, the OPENXML keyword does the reverse The OPENXML function provides

a relational rowset over an XML document To use SQL Server’s OPENXML functionality, you must first call the sp_xml_preparedocument stored procedure, which parses the XML document using the XML Document Object Model (DOM) and returns a handle to OPENXML OPENXML then provides a rowset view of the parsed XML document When you are finished working with the document, you then call the sp_xml_removedocument stored procedure to release the system resources consumed by OPENXML and the XML DOM

With SQL Server 2005 the OPENXML support has been extended to include support for the new XML data type and the new user-defined data type The

following example shows how you can use OPENXML in conjunction with a WITH clause and the new XML data type:

DECLARE @hdocument int

DECLARE @doc varchar(1000)

SET @doc ='<MyXMLDoc>

<DocumentID>1</DocumentID>

<DocumentBody>"OPENXML Example"</DocumentBody>

</MyXMLDoc>'

EXEC sp_xml_preparedocument @hdocument OUTPUT, @doc

SELECT * FROM OPENXML (@hdocument, '/MyXMLDoc', 10)

WITH (DocumentID varchar(4),

DocumentBody varchar(50))

EXEC sp_xml_removedocument @hdocument

At the top of this listing you can see where two variables are declared The

@hdocument variable will be used to store the XML document handle returned by the sp_xml_preparedocument stored procedure, while the @doc variable will contain the sample XML document itself Next, the sp_xml_preparedocument stored procedure

is executed and passed the two variables This stored procedure uses XML DOM

Trang 7

to parse the XML document and then returns a handle to the parsed document in

the @hdocument variable That document handle is then passed to the OPENXML

keyword used in the SELECT statement

The first parameter used by OPENXML is the document handle contained in

the @hdocument variable The second parameter is an XQuery that specifies the

nodes in the XML document that will construct the relational rowset The third

parameter specifies the type of XML-to-relational mapping that will be performed

The value of 2 indicates that element-centric mapping will be used (A value of

1 would indicate that attribute-centric mapping would be performed.) The WITH

clause provides the format of the rowset that’s returned In this example, the WITH

clause specifies that the returned rowset will consist of two varchar columns

named DocumentID and DocumentBody While this example shows the rowset

names matching the XML elements, that’s not a requirement Finally, the sp_xml

_removedocument stored procedure is executed to release the system resources

This SELECT statement using the OPENXML feature will return a rowset that

consists of the element values from the XML document You can see the results of

using OPENXML in the following listing:

DocumentID DocumentBody

-

-1 "OPENXML Example"

(1 row(s) affected)

XML Bulk Load

There are several ways to bulk-load XML documents from disk You can use the

Bulk Copy Program (BCP) or SQL Server Integration Services You can also do this

programmatically by using the COM-based SQLXML object library from NET or

by using the bulk load functionality that Microsoft has added to the OPENROWSET

function You can see an example of using OPENROWSET to bulk-load an XML

document in the following listing:

INSERT into MyXMLDocs(DocID, MyXMLDoc)

Select 3 AS DocID, * FROM OPENROWSET

(Bulk 'c:\temp\MyXMLDoc3.xml', SINGLE_CLOB) as DocumentID

In this example the INSERT statement is used to insert the results of the SELECT

statement into the MyXMLDocs table Here the value for the DocID column is

supplied as a literal, but you could also use a variable for this value The XML

Trang 8

document is loaded into the MyXMLDoc column in the MyXMLDocs table using the * FROM OPENROWSET statement The OPENROWSET function uses the bulk rowset provider to read data in from the file ‘C:\temp\MyXMLDoc3.xml’ The SINGLE_CLOB argument specifies that the data from the file will be inserted into

a single row If you omit the SINGLE_CLOB argument, then the data from the file can be inserted into multiple rows By default, the Bulk provider for the OPENROWSET function will split the rows on the Carriage Return character, which is the default row delimiter Alternatively, you can specify the field and row delimiters using the optional FIELDTERMINATOR and ROWTERMINATOR arguments of the OPENROWSET function You can see the contents of the

MyXMLDoc.xml file in the following listing:

<MyXMLDoc xmlns="http://MyXMLDocSchema">

<DocumentID>3</DocumentID>

<DocumentBody>"The Third Body"</DocumentBody>

</MyXMLDoc>

If you execute this command from the SQL Server Management Studio, you need

to remember that this will be executed on the SQL Server system, and therefore the file and path references must be found on the local server system The following query shows the contents of the MyXMLDocs file after performing the bulk load:

select * from MyXMLDocs

These are the updated contents of the MyXMLDocs file:

DocID MyXmlDoc

-

-1 <MyXMLDoc xmlns="http://MyXMLDocSchema"><DocumentID> -1</DocumentID> <DocumentBody>Modified Body</DocumentBody></MyXMLDoc>

2 <MyXMLDoc xmlns="http://MyXMLDocSchema"><DocumentID>2</DocumentID> <DocumentBody>"My text2"</DocumentBody></MyXMLDoc>

3 <MyXMLDoc xmlns="http://MyXMLDocSchema"><DocumentID>3</DocumentID> <DocumentBody>"The Third Body"</DocumentBody></MyXMLDoc>

(3 row(s) affected)

NOTE

The preceding listing was reformatted to make it more readable in the published page width.

Trang 9

Native HTTP SOAP Access

Another new XML-related feature found in SQL Server 2005 is native HTTP SOAP

support This new feature enables SQL Server to directly respond to the HTTP/

SOAP requests that are issued by Web services without requiring an IIS system to

act as an intermediary Using the native HTTP SOAP support, you can create Web

services that are capable of executing T-SQL batches, stored procedures, and

user-defined scalar functions To ensure a high level of default security, native HTTP

access is turned off by default However, you can enable HTTP support by simply

creating an HTTP endpoint and specify that it be started

Creating SOAP Endpoints

SOAP endpoints essentially enable programmatic access via Web services to SQL

Server objects like stored procedures and functions In the following example you’ll

see how to create a SOAP endpoint that exposes the uspGetEmployeeManagers

stored procedure in the sample AdventureWorks database You can see the

uspGetEmployeeManagers stored procedure in Figure 7-1

Creating a new SOAP endpoint will create a Web services wrapper for that

uspGetEmployeeManagers stored procedure, enabling it to be called by external

processes To create an SOAP endpoint, you need to use the CREATE ENDPOINT

statement like the one shown in the following listing:

CREATE ENDPOINT MyAdWWebService

STATE = STARTED

AS HTTP(

PATH = '/AdWWS',

AUTHENTICATION = (INTEGRATED ),

PORTS = ( CLEAR ),

SITE = 'SQL2005-2'

)

FOR SOAP (

WEBMETHOD 'GetManagers'

(name='AdventureWorks.dbo.uspGetEmployeeManagers',

FORMAT = ROWSETS_ONLY),

WSDL = DEFAULT,

SCHEMA = STANDARD,

DATABASE = 'adventureworks',

NAMESPACE = 'http://AdWWS.com'

Trang 10

This example illustrates creating a SOAP endpoint named MyAdWWebService for the stored procedure named GetProductName in the sample AdventureWorks database The STATE keyword that you see in the beginning indicates that this endpoint will be started and available immediately after it is created Other supported values include STOPPED and DISABLED

There are basically two sections to the CREATE ENDPOINT command The first half of the statement, beginning with the AS HTTP clause, describes the network access to the Web service The second part, beginning with the FOR SOAP clause, describes the Web service itself In the first part the PATH keyword specifies the URL for the Web service endpoint This value will be appended to the local server name (e.g., http://server/AdWWS) The AUTHENTICATION keyword specifies the type of authentication to be used to access the Web service This example

uses INTEGRATED security, but values of BASIC, NTLM, and KERBEROS are

Figure 7-1 AdventureWorks uspGetEmployeeManagers stored procedure

Ngày đăng: 03/07/2014, 01:20

TỪ KHÓA LIÊN QUAN