Dirt, Spit, and Happy FLWOR

Slides:



Advertisements
Similar presentations
XML Data Management 8. XQuery Werner Nutt. Requirements for an XML Query Language David Maier, W3C XML Query Requirements: Closedness: output must be.
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
XQuery John Annechino Steven Pow. Agenda What is XQuery? Uses of XQuery XQuery vs. XSLT Syntax –Built-In Functions –FLWOR –if-then-else –User-Defined.
1 XQuery Web and Database Management System. 2 XQuery XQuery is to XML what SQL is to database tables XQuery is designed to query XML data What is XQuery?
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 13-1 COS 346 Day 25.
NaLIX: A Generic Natural Language Search Environment for XML Data Presented by: Erik Mathisen 02/12/2008.
1 COS 425: Database and Information Management Systems XML and information exchange.
The XML data type in Microsoft SQL Server. The XML Type Microsoft SQL Server offers a special data type – XML – Used in tables, etc. – Basically a (long)
Database Systems More SQL Database Design -- More SQL1.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Module 9 Designing an XML Strategy. Module 9: Designing an XML Strategy Designing XML Storage Designing a Data Conversion Strategy Designing an XML Query.
1 Advanced Topics XML and Databases. 2 XML u Overview u Structure of XML Data –XML Document Type Definition DTD –Namespaces –XML Schema u Query and Transformation.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Overview of XPath Author: Dan McCreary Date: October, 2008 Version: 0.2 with TEI Examples M D.
Introduction to XPath Bun Yue Professor, CS/CIS UHCL.
XMLII XSchema XSchema XQuery XQuery. XML Schema XML Schema is a more sophisticated schema language which addresses the drawbacks of DTDs. Supports XML.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
2.2 SQL Server 2005 的 XML 支援功能. Overview XML Enhancements in SQL Server 2005 The xml Data Type Using XQuery.
Integrating XML with Microsoft SQL Server ©NIITeXtensible Markup Language/Lesson 9/Slide 1 of 31 Objectives In this lesson, you will learn to: * Generate.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
2005rel-xml-iii1  View forests and query composition The composition algorithm works for a (large) subset of XQuery, excluding : (see paper for details)
Lecture 21 XML querying. 2 XSL (eXtensible Stylesheet Language) In HTML, default styling is built into browsers as tag set for HTML is predefined and.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui SWEN 432 Advanced Database Design and Implementation An Introduction to XQuery.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui SWEN 432 Advanced Database Design and Implementation An Introduction to XQuery.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Sofia, Bulgaria | 9-10 October Using XQuery to Query and Manipulate XML Data Stephen Forte CTO, Corzen Inc Microsoft Regional Director NY/NJ (USA) Stephen.
What is XML?  XML stands for EXtensible Markup Language  XML is a markup language much like HTML  XML was designed to carry data, not to display data.
Company LOGO OODB and XML Database Management Systems – Fall 2012 Matthew Moccaro.
 XML is designed to describe data and to focus on what data is. HTML is designed to display data and to focus on how data looks.  XML is created to structure,
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Processing of structured documents Spring 2002, Part 2 Helena Ahonen-Myka.
Oracle Database Administration Lecture 3  Transactions  SQL Language: Additional information  SQL Language: Analytic Functions.
@CRMUG Technical Academy Fetch Xml Were can Fetch Xml be used Basic Fetch Xml and using advanced find to build your own Fetch Query Creating Fetch Xml.
5/24/01 Leveraging SQL Server 2000 in ColdFusion Applications December 9, 2003 Chris Lomvardias SRA International
Module 18 Querying XML Data in SQL Server® 2008 R2.
Copyright© 2005 Oracle Corp.1 SQL/XML Jim Melton USA: Oracle Corp. JTC1 SC32N1632.
SQL LANGUAGE and Relational Data Model TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
XML Query: xQuery Reference: Xquery By Priscilla Walmsley, Published by O’Reilly.
SQL Server 2005: Extending the Type System with XML.
XPath --XML Path Language Motivation of XPath Data Model and Data Types Node Types Location Steps Functions XPath 2.0 Additional Functionality and its.
Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type.
SEMI-STRUCTURED DATA (XML) 1. SEMI-STRUCTURED DATA ER, Relational, ODL data models are all based on schema Structure of data is rigid and known is advance.
XML and SQL Server Better friends than you thought Matt Hartman.
Create Stored Procedures and Functions Database Management Fundamentals LESSON 2.4.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Introduction to Database Programming with Python Gary Stewart
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Creating Database Objects
You Got XML In My Database? What’s Up With That?
XML: Extensible Markup Language
SQL – Python and Databases
Using XML in SQL Server and Azure SQL Database
Querying and Transforming XML Data
PL/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-1
XML QUESTIONS AND ANSWERS
SQL Server 2016 JSON Support FOR Data Warehousing
Paul Jacobs The iSchool University of Maryland Thursday, Oct. 6, 2016
SQL FUNDAMENTALS CDSE Days 2018.
XML Path Language Andy Clark 17 Apr 2002.
NULLs and Other SQL Gotchas
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL DATA CONSTRAINTS.
NULLs and Other SQL Gotchas
Paul Jacobs The iSchool University of Maryland Thursday, Oct. 5, 2017
Trainer: Bach Ngoc Toan– TEDU Website:
Creating Database Objects
Introduction to SQL Server and the Structure Query Language
XML? What’s this doing in my database? Adam Koehler
Presentation transcript:

Dirt, Spit, and Happy FLWOR Hands on with XQuery Dirt, Spit, and Happy FLWOR

Presentation Rating: ADVANCED INTERMEDIATE BEGINNER

Presentation Rating:

Purpose Introduce the basic syntax of FLWOR, the XQuery language. Interfaces with T-SQL Basic functions We won’t be covering conversion of SQL to XML (FOR XML…) No tricks or tips

Why Me? Data Architect working in the field of financial information security Prior experience as DBA and a reporting/database developer AtlantaMDF Chapter Leader Tutor, not a teacher

Assumptions About You Database professional (DBA, database developer, BI specialist) Some experience with XML

Let’s Review “Gentlemen, this is a football.” – Vince Lombardi

Basic XML Structure <root> <tag>This is an element</tag> <tag att=“attribute”> Another element</tag> </root> Elements and Attributes are both nodes.

Basic XML Structure XML can be Typed or Untyped Untyped = xml fragments; WYSIWYG Typed = validation of datatypes, relationships Typed XML requires a Schema SQL Server supports Schema SQL Server supports inline DTD Namespaces Used for providing uniquely named elements and attributes in an XML document

XML in SQL Server 2000+ Generation: Translation: FOR XML OPENXML RAW, AUTO, EXPLICIT Translation: OPENXML sp_xml_preparedocument sp_xml_removedocument

XML in SQL Server 2005+ Generation: Translation: FOR XML xml datatype PATH TYPE Translation: xml datatype XQuery

XML Translation xml datatype Well-formed fragments (no root required) 2 GB maximum Cannot be compared or sorted Supports conversion to (n)varchar(max) Required for XQuery

XML Translation XQuery Complete query language outside of SQL Server SQL Server 2005+ implements limited subset xml methods exist() value() query() nodes() modify() (beyond scope of presentation)

XML Translation SQL engine interfaces with XML engine

XML Translation XML method Syntax Returns .exist() .exist(XQuery) bit: 1 if True, 0 if False, NULL if xml is NULL .value() .value(XQuery, SQLtype) SQL data type: specified as a parameter in method .query() .query(XQuery) XML: 1 fragment per row .nodes() .nodes(XQuery) as Table(column) XML: each node becomes a new row Primary purpose of XQuery in SQL Server is to convert XML data to a tuple in a dataset. For robust handling of XML, use another tool.

FLWOR “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler

FLWOR For Let Where Order By Return Context switches ({}) Primary Language Other Components For Let Where Order By Return Context switches ({}) Functions (data(), position()) Positional References ([ ]) SQL Server’s implementation of XQuery is a limited subset; it improved between 2005 and 2008, but several functions are still not available.

Positional References [] DECLARE @x XML = '<Families> <Family name="Ainsworth"> <Parent name="Stuart"> <Child name="Isabel"/> <Child name="Grace"/> </Parent> </Family> <Family name="Smith"> <Parent name="Aaron"> <Child name="John"/> </Families>' SELECT @x.query('//Family').value('(Family/@name)[1]', 'varchar(100)'), @x.query('//Family').value('(Family/@name)[2]', 'varchar(100)')

Context switches {} DECLARE @x XML = '<Families> <Family name="Ainsworth"> <Parent name="Stuart"> <Child name="Isabel"/> <Child name="Grace"/> </Parent> </Family> <Family name="Smith"> <Parent name="Aaron"> <Child name="John"/> </Families>' SELECT @x.query('<New>{/Families/Family[1]}</New>')

Context switches {} <New> <Family name="Ainsworth"> <Parent name="Stuart"> <Child name="Isabel" /> <Child name="Grace" /> </Parent> </Family> </New>

(for)(let)… return FLWOR requires either for or let and a return statement return returns the actual dataset SELECT @x.query('<root> {for $f in /Families return "Hello World!"} </root> ') <root>Hello World!</root>

for for is an iterative operator Used to assign elements into a variable Step through that variable SELECT @x.query('<root> {for $f in /Family return "Hello World!"} </root> ') <root>Hello World! Hello World!</root>

let let assigns a value to a variable Introduced in SQL 2008 SELECT @x.query('<root>{for $f in //Family let $n:=data($f/@name) return $n} </root> ') <root>Ainsworth Smith</root>

Pop Quiz! <Families> <Family name="Ainsworth"> <Parent name="Stuart" /> </Family> <Family name="Smith"> <Parent name="Aaron" /> </Families> SELECT @x.query('<root>{for $f in //Family let $n:=data($f/@name) for $p in $f/Parent return <Person>{concat($p/@name, " ", $n)}</Person>} </root>')

Pop Quiz! <root> <Person>Stuart Ainsworth</Person> <Person>Aaron Smith</Person> </root>

where Similar to WHERE clause in SQL DECLARE @x XML = '<Families> <Family name="Ainsworth"> <Parent name="Stuart"> <Child name="Isabel"/> <Child name="Grace"/> </Parent> </Family> <Family name="Smith"> <Parent name="Aaron"> <Child name="John"/> </Families>'

where <root> <Person>Isabel Ainsworth</Person> SELECT @x.query('<root>{for $f in //Family let $n:=data($f/@name) for $c in $f/Parent/Child where $n="Ainsworth" return <Person>{concat($c/@name, " ", $n)}</Person>} </root>') <root> <Person>Isabel Ainsworth</Person> <Person>Grace Ainsworth</Person> </root>

order by SELECT @x.query('<root>{for $f in //Family let $n:=data($f/@name) for $c in $f/Parent/Child where $n="Ainsworth“ order by $c/@name return <Person>{concat($c/@name, " ", $n)}</Person>} </root>') <root> <Person>Grace Ainsworth</Person> <Person>Isabel Ainsworth</Person> </root>

More stuff to learn “A child of five would understand this. Send someone to fetch a child of five.” - Groucho Marx

Functions ceiling, floor, round concat, contains, substring lower-case Function (XQuery) string-length upper-case Function (XQuery) not number local-name Function (XQuery) namespace-uri Function (XQuery) last position empty distinct-values id Function (XQuery) count avg, min, max, sum string, data true Function (XQuery) false Function (XQuery) expanded-QName (XQuery) local-name-from-QName (XQuery) namespace-uri-from-QName (XQuery) sql:column() function (XQuery) sql:variable() function (XQuery)

sql:variable() DECLARE @x XML = '<Loc id="1">Atlanta</Loc> <Loc id="2">Washington</Loc>', @id INTEGER = 1 SELECT @x.query('<root>{for $l in /Loc where $l/@id="2" return data($l)}</root>') , @x.query('<root>{for $l in /Loc where $l/@id=sql:variable("@id") <root>Washington</root> <root>Atlanta</root>

sql:column() DECLARE @x XML = '<Loc id="1">Atlanta</Loc> <Loc id="2">Washington</Loc>' DECLARE @T TABLE (ID INTEGER) INSERT INTO @T (ID) VALUES(1), (2) SELECT @x.query('<root>{for $l in /Loc where $l/@id=sql:column("T.ID") return data($l)}</root>') FROM @T T _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <root>Atlanta</root> <root>Washington</root>

Pop Quiz! DECLARE @x XML = '<row>A</row> <row>B</row> <row>C</row> <row>D</row> <row>E</row> ' DECLARE @T TABLE (ID INT) INSERT INTO @T (ID) SELECT ROW_NUMBER() OVER (ORDER BY c.column_id ) FROM sys.columns c SELECT @x.query('/row [position()=sql:column("T.ID")]') FROM @T t WHERE t.ID <= @x.query('<r> {count(/row)} </r>').value('.', 'int')

Pop Quiz! <row>A</row> <row>B</row> <row>C</row> <row>D</row> <row>E</row>

Questions? “It’s a miracle that curiosity survives formal education.” – Albert Einstein

Contact Information Stuart R Ainsworth stuart@codegumbo.com http://www.codegumbo.com http://www.twitter.com/codegumbo