22
XQuery XQuery Your gateway to Your gateway to manipulating XML in SQL manipulating XML in SQL Server 2005 Server 2005

XQuery Your gateway to manipulating XML in SQL Server 2005

Embed Size (px)

Citation preview

Page 1: XQuery Your gateway to manipulating XML in SQL Server 2005

XQueryXQuery

Your gateway to manipulating Your gateway to manipulating XML in SQL Server 2005XML in SQL Server 2005

Page 2: XQuery Your gateway to manipulating XML in SQL Server 2005

About the Speaker…About the Speaker…

Hal HayesHal [email protected]@tmaresources.com

Sr. Director, Software EngineeringSr. Director, Software Engineering

TMA Resources, Leader in Member-centric SoftwareTMA Resources, Leader in Member-centric Software

Microsoft MCP (just shy of my MCAD)Microsoft MCP (just shy of my MCAD)

Founder, CAPAREA (formerly CAVBUG)Founder, CAPAREA (formerly CAVBUG)

Learning Tree Instructor (SQL Server)Learning Tree Instructor (SQL Server)

gratuitous aircraft picture

Page 3: XQuery Your gateway to manipulating XML in SQL Server 2005

AgendaAgenda

XQuery DefinedXQuery DefinedWorking with XML in SQL Server 2005Working with XML in SQL Server 2005Advanced UsageAdvanced UsageTopic MapsTopic MapsRecommendationsRecommendationsResourcesResources

Page 4: XQuery Your gateway to manipulating XML in SQL Server 2005

XMLXMLXML SchemasXML SchemasXPath and XSLTXPath and XSLTWorking with XML in .NETWorking with XML in .NETWorking with XML in SQL ServerWorking with XML in SQL Server

What you should know...What you should know...

Page 5: XQuery Your gateway to manipulating XML in SQL Server 2005

What is XQuery???What is XQuery???

XML-based functional, declarative query languageXML-based functional, declarative query language XQuery is SQL-like XQuery is SQL-like Fine-grained querying against native XML Fine-grained querying against native XML

(hierarchical vs. flat table/record format for SQL)(hierarchical vs. flat table/record format for SQL) Syntax is straight-forward making it easy (??) to Syntax is straight-forward making it easy (??) to

queryquery your XML data your XML data Standards Based. Currently a W3C Candidate Standards Based. Currently a W3C Candidate

Recommendation*Recommendation*

*W3 standardized language (http://www.w3.org/XML/Query)*W3 standardized language (http://www.w3.org/XML/Query)

Page 6: XQuery Your gateway to manipulating XML in SQL Server 2005

XQuery in SQL Server 2005XQuery in SQL Server 2005

A subset of full languageA subset of full language Namespace awareNamespace aware Can work with or without a Schema (strong Can work with or without a Schema (strong

vs. weak-typed)vs. weak-typed)

One major difference…no “let” statement!One major difference…no “let” statement!

Page 7: XQuery Your gateway to manipulating XML in SQL Server 2005

XQuery BasicsXQuery Basics

FLOWRFLOWRXPathXPathCommentsComments

Page 8: XQuery Your gateway to manipulating XML in SQL Server 2005

FLOWRFLOWR

Main construct of XQuery is Main construct of XQuery is the the FLOWRFLOWR expression expression

For-Let-Where-Order-ReturnFor-Let-Where-Order-Return

equivalence to SELECT-equivalence to SELECT-FROM-HAVING-WHERE in FROM-HAVING-WHERE in SQLSQL

Use the Use the ReturnReturn construct to construct to shape your resultsshape your results

<bib>

{

for $b in doc("bib.xml")/bib/book

where $b/publisher = “Microsft" and

$b/@year gt 1991

return

<book year="{ $b/@year }">

{ $b/title }

</book>

}

</bib>

Page 9: XQuery Your gateway to manipulating XML in SQL Server 2005

FLOWR (continued)FLOWR (continued) forfor clauseclause provides a definition of a variable and binding of provides a definition of a variable and binding of

iterations across a range of sequence values (SQL-SELECT)iterations across a range of sequence values (SQL-SELECT)

letlet clause clause allows association of a variable to a further ordered list allows association of a variable to a further ordered list of tuples (SQL-SET)of tuples (SQL-SET)

where clausewhere clause is a filter of the current sequence or tuples from is a filter of the current sequence or tuples from for/let (SQL-WHERE)for/let (SQL-WHERE)

order clauseorder clause sorts current results based on a given criteria sorts current results based on a given criteria (SQL-ORDER)(SQL-ORDER)

return clausereturn clause is used to create output that can be XML or not is used to create output that can be XML or not XML (SQL-RETURN)XML (SQL-RETURN)

Page 10: XQuery Your gateway to manipulating XML in SQL Server 2005

Two ExamplesTwo Examples

Standard Recommendation XQueryStandard Recommendation XQuery(using XMLSpy)(using XMLSpy)

SQL Server 2005 VersionSQL Server 2005 Version

Page 11: XQuery Your gateway to manipulating XML in SQL Server 2005

Additional XML Data Type Methods Additional XML Data Type Methods In SQL 2005In SQL 2005

Column.query()Column.query()

Column.value()Column.value()

Column.modify()Column.modify()

Column.nodes()Column.nodes()

Column.exists()Column.exists()

Page 12: XQuery Your gateway to manipulating XML in SQL Server 2005

XQuery DMLXQuery DML

Column.query(‘Column.query(‘statementstatement’)’) Use XQuery statement, orUse XQuery statement, or XPathXPath Declaration of a namespaceDeclaration of a namespace Can return XMLCan return XML

Column.value(‘Column.value(‘statementstatement’, ‘’, ‘typetype’)’) Returns a valueReturns a value Use SQL types (i.e. ‘varchar(255)’)Use SQL types (i.e. ‘varchar(255)’)

Page 13: XQuery Your gateway to manipulating XML in SQL Server 2005

XQuery DMLXQuery DML

Column.nodes()Column.nodes() Useful for “shredding” an XML document into its constituent Useful for “shredding” an XML document into its constituent

parts. parts. If used in the WHERE clause, can be used in conjunction If used in the WHERE clause, can be used in conjunction

with .query(), .exist(), .value(), and .nodes() (but with .query(), .exist(), .value(), and .nodes() (but not not .modify().modify()))

Column.exist()Column.exist() Returns a 1 (representing True) if the XQuery expression in Returns a 1 (representing True) if the XQuery expression in

a query returns a nonempty result (meaning it returns at least a query returns a nonempty result (meaning it returns at least one XML node).one XML node).

Returns a 0 (representing False) if the XQuery returns and Returns a 0 (representing False) if the XQuery returns and empty result.empty result.

Page 14: XQuery Your gateway to manipulating XML in SQL Server 2005

XQuery DMLXQuery DML

Column.modify()Column.modify()Used for XML DML operations (non-query)Used for XML DML operations (non-query)‘‘update’, ‘delete’, ‘replace value of ’update’, ‘delete’, ‘replace value of ’Executed as part of the DML “Update” statementExecuted as part of the DML “Update” statement

UPDATE customerDataSET customerDocs.modify('

insert <history>no history available</history> as firstinto (//customer)[1]')

Page 15: XQuery Your gateway to manipulating XML in SQL Server 2005

DemosDemos

With some basic stuffWith some basic stuffMaybe some advanced stuff, too!Maybe some advanced stuff, too!

Page 16: XQuery Your gateway to manipulating XML in SQL Server 2005

Quick Introduction to Topic MapsQuick Introduction to Topic Maps

Constructs for creating a meta-model of Constructs for creating a meta-model of data and informationdata and information

Topic Maps are XML basedTopic Maps are XML basedCurrent (pending) standard is XTM 2.0 Current (pending) standard is XTM 2.0

(ISO)(ISO)

Page 17: XQuery Your gateway to manipulating XML in SQL Server 2005

Topic Map FundamentalsTopic Map Fundamentals

“An Introduction to Topic Maps”, Kal Ahmed and Graham Moore, The Architectural Journal, http://www.architecturejournal.net/2005/issue5/Jour5Intro/

Page 18: XQuery Your gateway to manipulating XML in SQL Server 2005

Topic Map DemoTopic Map Demo

Page 19: XQuery Your gateway to manipulating XML in SQL Server 2005

RecommendationsRecommendations For getting at detail in your XML documents stored in the For getting at detail in your XML documents stored in the

database, XQuery is a great tool.database, XQuery is a great tool.

Don’t rely on the XQuery Where clause…you could Don’t rely on the XQuery Where clause…you could retrieve empty records!retrieve empty records!

Strong-typed (mapped to Schema) XML Data Columns Strong-typed (mapped to Schema) XML Data Columns will have better performance than weak-typed.will have better performance than weak-typed.

DML is limited. You have better choices for manipulation DML is limited. You have better choices for manipulation (i.e. .NET XML, XLinq)(i.e. .NET XML, XLinq)

Dynamic Parameterized XQueries are problematic, but Dynamic Parameterized XQueries are problematic, but can be done. Best bet is to encase them in StoredProcs.can be done. Best bet is to encase them in StoredProcs.

Page 20: XQuery Your gateway to manipulating XML in SQL Server 2005

ResourcesResources

W3C XQuery Working GroupW3C XQuery Working Grouphttp://www.w3.org/XML/Queryhttp://www.w3.org/XML/Query

Topic Map ISO Topic Map ISO http://www.isotopicmaps.org/sam/sam-xtmhttp://www.isotopicmaps.org/sam/sam-xtm//

Topic Map ConsortiumTopic Map Consortiumhttp://www.topicmaps.orghttp://www.topicmaps.org

Page 21: XQuery Your gateway to manipulating XML in SQL Server 2005

BooksBooks A Developer's Guide to SQL Server 2005 , Beauchemin, A Developer's Guide to SQL Server 2005 , Beauchemin,

Berglund, Sullivan; Addison-WesleyBerglund, Sullivan; Addison-Wesley

XQuery Kick Start, James McGovern, et al.; SAMSXQuery Kick Start, James McGovern, et al.; SAMS

XQuery, The XML Query Language, Michael Brundage, XQuery, The XML Query Language, Michael Brundage, Addison-WesleyAddison-Wesley

XQuery from the Experts, Don Chamberlin, et al., XQuery from the Experts, Don Chamberlin, et al., Addison-WesleyAddison-Wesley

Page 22: XQuery Your gateway to manipulating XML in SQL Server 2005

Blogs of NoteBlogs of NoteMichael Rys, Program Manager for SQL Server's XML Technologies and member of W3 Michael Rys, Program Manager for SQL Server's XML Technologies and member of W3 XML Query Working GroupXML Query Working Grouphttp://sqljunkies.com/WebLog/mryshttp://sqljunkies.com/WebLog/mrys

Kent Tegels, DevelopMentor, MVPKent Tegels, DevelopMentor, MVPhttp://sqljunkies.com/WebLog/ktegelshttp://sqljunkies.com/WebLog/ktegels

Mike Champion, Program Manager for XML Standards XML WebData team at MicrosoftMike Champion, Program Manager for XML Standards XML WebData team at Microsofthttp://blogs.msdn.com/mikechampionhttp://blogs.msdn.com/mikechampion

Shankar Pal, XML SQL Program Manager, Microsoft CorporationShankar Pal, XML SQL Program Manager, Microsoft Corporationhttp://blogs.msdn.com/spalhttp://blogs.msdn.com/spal

Microsoft Corporation XML Team WeblogMicrosoft Corporation XML Team Webloghttp://blogs.msdn.com/xmlteam/default.aspxhttp://blogs.msdn.com/xmlteam/default.aspx

Bob Beauchemin's Blog, Author of A First Look at SQL Server 2005 for DevelopersBob Beauchemin's Blog, Author of A First Look at SQL Server 2005 for Developershttp://staff.develop.com/bobb/weblog/default.aspxhttp://staff.develop.com/bobb/weblog/default.aspx