+ All Categories
Home > Documents > SQL Server 2005: Extending the Type System with XML.

SQL Server 2005: Extending the Type System with XML.

Date post: 19-Jan-2016
Category:
Upload: diane-snow
View: 224 times
Download: 1 times
Share this document with a friend
28
SQL Server 2005: Extending the Type System with XML
Transcript
Page 1: SQL Server 2005: Extending the Type System with XML.

SQL Server 2005: Extending the Type System with

XML

SQL Server 2005: Extending the Type System with

XML

Page 2: SQL Server 2005: Extending the Type System with XML.

Who I AmWho I Am

Shawn Wildermuth ([email protected])

C# MVP INETA Speaker Author of “Pragmatic ADO.NET”; Editor of http://ONDotnet.com This Presentation can be found at:– http://adoguy.com/presentations

Shawn Wildermuth ([email protected])

C# MVP INETA Speaker Author of “Pragmatic ADO.NET”; Editor of http://ONDotnet.com This Presentation can be found at:– http://adoguy.com/presentations

Page 3: SQL Server 2005: Extending the Type System with XML.

AgendaAgenda

The XML Datatype Using the XML Type Methods What is the Type System Can’t I use CLR Types? Typed XML Extending the Typed System with XML XML Indexes

The XML Datatype Using the XML Type Methods What is the Type System Can’t I use CLR Types? Typed XML Extending the Typed System with XML XML Indexes

Page 4: SQL Server 2005: Extending the Type System with XML.

The XML DataTypeThe XML DataType

New to SQL Server 2005– Native support for XML data– Not stored as text blobs– XML treated as first-class type– Has some limitations– Support in-place editing

New to SQL Server 2005– Native support for XML data– Not stored as text blobs– XML treated as first-class type– Has some limitations– Support in-place editing

Page 5: SQL Server 2005: Extending the Type System with XML.

The XML DataType (2)The XML DataType (2)

Using the XML datatype– Can be used in procedural code:

– Can be gathered from Old Style XML Syntax:

– Can be used in Table/View Declarations:

Using the XML datatype– Can be used in procedural code:

– Can be gathered from Old Style XML Syntax:

– Can be used in Table/View Declarations:

DECLARE @doc xmlSELECT @doc = '<Team name="Braves" />'

SELECT @doc = (SELECT * FROM Person.Contact FOR XML AUTO)

CREATE TABLE Team ( TeamID int identity not null, TeamDoc xml DEFAULT '<Team />' NOT NULL)

Page 6: SQL Server 2005: Extending the Type System with XML.

The XML DataType (3)The XML DataType (3)

Using the XML datatype:– Inserting/updating XML with Strings:

Using the XML datatype:– Inserting/updating XML with Strings:

-- Insert a couple of recordsINSERT INTO Team (TeamDoc)VALUES ('<Team name="Braves"> <Players> <Pitcher name="John Smoltz" role="Closer"/> <Pitcher name="Russ Ortiz" role="Starter" /> <ThirdBase name="Chipper Jones" role="Starter" bats="switch"/> </Players></Team>');

Page 7: SQL Server 2005: Extending the Type System with XML.

The XML DataType (4)The XML DataType (4)

Limitations– No conversion to and from text/ntext– Only strings can cast to XML type– Cannot be used in GROUP BY’s– Cannot be in Distributed or Materialized

Views– Cannot used primary or foreign keys– Cannot be uniquely constrained– Only 32 XML Columns per Table– Only 128 Levels of Hierarchy supported

Limitations– No conversion to and from text/ntext– Only strings can cast to XML type– Cannot be used in GROUP BY’s– Cannot be in Distributed or Materialized

Views– Cannot used primary or foreign keys– Cannot be uniquely constrained– Only 32 XML Columns per Table– Only 128 Levels of Hierarchy supported

Page 8: SQL Server 2005: Extending the Type System with XML.

The XML DataType The XML DataType

The XML Type has five methods:– Query: Used to find subresults

– Exist: Used to find matches

The XML Type has five methods:– Query: Used to find subresults

– Exist: Used to find matches

SELECT TeamDoc.query('/Team/Players/Pitcher') FROM Team

<Pitcher name="John Smoltz" role="Closer" /><Pitcher name="Russ Ortiz" role="Starter" />

SELECT Count(*) FROM TeamWHERE TeamDoc.exist('/Team/Players/Pitcher[@role="Starter"]') = 1

Page 9: SQL Server 2005: Extending the Type System with XML.

The XML DataType Methods (2)The XML DataType Methods (2)

– Value: Used to find a value of a result

– Nodes: Used to return nodes collections (We won’t be covering this in the interest of

the schedule)

– Value: Used to find a value of a result

– Nodes: Used to return nodes collections (We won’t be covering this in the interest of

the schedule)

SELECT TeamDoc.value('(/Team/Players/Pitcher/@name)[1]', 'nvarchar(max)') as FirstPitcherFROM Team FirstPitcher

-----------------John Smoltz

Page 10: SQL Server 2005: Extending the Type System with XML.

The XML DataType Methods (3)The XML DataType Methods (3)

– Modify: Used to do in-place changes MS Specific XQuery Extensions for

Modification– insert

– delete

– Modify: Used to do in-place changes MS Specific XQuery Extensions for

Modification– insert

– delete

UPDATE TeamSET TeamDoc.modify(' insert <Pitcher name="Jaret Wright"/> as last into (/Team/Players)[1]')WHERE TeamDoc.exist('/Team[@name="Braves"]') = 1

UPDATE TeamSET TeamDoc.modify(' delete /Team/Players[@name="Jaret Wright"]')WHERE TeamDoc.exist('/Team[@name="Braves"]') = 1

Page 11: SQL Server 2005: Extending the Type System with XML.

The XML DataType Methods (4)The XML DataType Methods (4)

– Modify: Used to do in-place changes replace with (like update)

Can use full XQuery syntax as needed

– Modify: Used to do in-place changes replace with (like update)

Can use full XQuery syntax as needed

UPDATE TeamSET TeamDoc.modify (' replace value of (/Team/Players/Pitcher[@name="John Smoltz"]/@role)[1] with "Starter"')

UPDATE TeamSET TeamDoc.modify (' replace value of (/Team/Players/Pitcher[@name="John Smoltz"]/@role)[1] with ( if (/Team/Players/Pitcher[@name="John Smoltz"]/@role = "Closer") then "Starter" else "Closer")')

Page 12: SQL Server 2005: Extending the Type System with XML.

SQL Server Type SystemSQL Server Type System

Type system has been static– varchar, int, bit, datetime, etc.– Could only create types by reduction

Type system has been static– varchar, int, bit, datetime, etc.– Could only create types by reduction

EXEC sp_addtype N'age', N'tinyint', N'not null'GO

CREATE RULE age_rangeAS@age >= 0 AND @age <=140GO

EXEC sp_bindrule N'age_range', N'age'GO

Page 13: SQL Server 2005: Extending the Type System with XML.

SQL Server Type System (2)SQL Server Type System (2)

SQL Server 2005 Supports two extensions– Managed Types

Limited to 8000 bytes in size Good for including behavior Must deal with security issues of managed

code No Good Inter Object Searching Story No Good Indexing Story

SQL Server 2005 Supports two extensions– Managed Types

Limited to 8000 bytes in size Good for including behavior Must deal with security issues of managed

code No Good Inter Object Searching Story No Good Indexing Story

Page 14: SQL Server 2005: Extending the Type System with XML.

SQK Server Type System (3)SQK Server Type System (3)

SQL Server 2005 Supports two extensions– Typed XML

Size not an issue No behavior can be added Just data limits security issues XQuery/XPath for sub-searching Supports XML Indexing

SQL Server 2005 Supports two extensions– Typed XML

Size not an issue No behavior can be added Just data limits security issues XQuery/XPath for sub-searching Supports XML Indexing

Page 15: SQL Server 2005: Extending the Type System with XML.

Using Typed XMLUsing Typed XML

Uses Schema Collections for different Types– Uses new DDL syntax to add XML Type

Uses Schema Collections for different Types– Uses new DDL syntax to add XML TypeCREATE XML SCHEMA COLLECTION BaseballSchema AS '<?xml

version="1.0"?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="Team"> <xsd:complexType> <xsd:sequence> <xsd:element name="Pitcher"> <xsd:complexType> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element></xsd:schema>'

Page 16: SQL Server 2005: Extending the Type System with XML.

Using Typed XML (2)Using Typed XML (2)

Once registered, can use as XML type: Once registered, can use as XML type:DECLARE @team xml(BaseballSchema)

SET @team = '<Team name="Braves"> <Pitcher name="John Smoltz" /> </Team>'

SELECT @team<Team name="Braves"><Pitcher name="John Smoltz" /></Team>

(1 row(s) affected)

Page 17: SQL Server 2005: Extending the Type System with XML.

Using Typed XML (3)Using Typed XML (3)

Validation Happens at Assignment Validation Happens at AssignmentDECLARE @team xml(BaseballSchema)

-- Won’t work as role isn’t definedSET @team = '<Team name="Braves"> <Pitcher name="John Smoltz" role="Closer" /> </Team>'

XML Validation: Attribute 'role' is not permitted in this context. Location: /*:Team[1]/*:Pitcher[1]/@*:role

Page 18: SQL Server 2005: Extending the Type System with XML.

Using Typed XML (4)Using Typed XML (4)

Works just as well as columns in Tables

Works just as well as columns in TablesCREATE TABLE Team ( TeamID int identity not null, TeamDoc xml(BaseballSchema))

INSERT INTO Team (TeamDoc) VALUES ('<Team name="Braves"> <Pitcher name="John Smoltz" /> </Team>')

Page 19: SQL Server 2005: Extending the Type System with XML.

Using Typed XML (5)Using Typed XML (5)

Searching can then include XML searches– Just like non-typed XML, but faster

Searching can then include XML searches– Just like non-typed XML, but fasterSELECT TeamDoc.query('/Team/Pitcher[@name="John Smoltz"]') FROM Team

Page 20: SQL Server 2005: Extending the Type System with XML.

Managing Typed XML SchemasManaging Typed XML Schemas

Schema Collections– Can contain more than one XSD– Include new schema with ADD:

Schema Collections– Can contain more than one XSD– Include new schema with ADD:

ALTER XML SCHEMA COLLECTION BaseballSchema ADD '<?xml version="1.0"?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" > <xsd:element name="Score"> <xsd:complexType> <xsd:attribute name="HomeTeam" type="xsd:string" /> <xsd:attribute name="AwayTeam" type="xsd:string" /> <xsd:attribute name="HomeScore" type="xsd:int" /> <xsd:attribute name="AwayScore" type="xsd:int" /> </xsd:complexType> </xsd:element></xsd:schema>'

Page 21: SQL Server 2005: Extending the Type System with XML.

Managing Typed XML Schemas (2)Managing Typed XML Schemas (2)

Both XSD’s can now be used Both XSD’s can now be usedINSERT INTO Team (TeamDoc) VALUES ('<Team name="Braves"> <Pitcher name="John Smoltz" /> </Team>')

INSERT INTO Team (TeamDoc) VALUES ('<Score HomeTeam="Braves" AwayTeam="RedSox" HomeScore="5" AwayScore="4" />')

Page 22: SQL Server 2005: Extending the Type System with XML.

Managing Typed XML Schemas (3)Managing Typed XML Schemas (3)

Cannot drop schemas if used– ALTER does not let you drop an XSD– Cannot drop entire collection until not in

use

Cannot drop schemas if used– ALTER does not let you drop an XSD– Cannot drop entire collection until not in

useALTER TABLE Team DROP COLUMN TeamDocGO

DROP XML SCHEMA COLLECTION BaseballSchemaGO

CREATE XML SCHEMA COLLECTION BaseballSchema AS '...'GO

ALTER TABLE Team ADD TeamDoc xml (BaseballSchema)

Page 23: SQL Server 2005: Extending the Type System with XML.

Managing Typed XML Schemas (4)Managing Typed XML Schemas (4)

Caveats– May need to workout versioning

Can do this with Convert(xml(sometype), oldtype)

Only works if the new schema is superset May need to do xslt to do real conversions Or; support both versions

Caveats– May need to workout versioning

Can do this with Convert(xml(sometype), oldtype)

Only works if the new schema is superset May need to do xslt to do real conversions Or; support both versions

Page 24: SQL Server 2005: Extending the Type System with XML.

XML IndexingXML Indexing

XML Columns can have Indexes– Can have Primary and secondary indexes– Primary improves simple node searches

XML Columns can have Indexes– Can have Primary and secondary indexes– Primary improves simple node searches

CREATE PRIMARY XML INDEX IXML_Teams ON Team (TeamDoc)

SELECT * FROM TEAM WHERE TeamDoc.exist("\Team\Pitcher")

Page 25: SQL Server 2005: Extending the Type System with XML.

XML Indexing (2)XML Indexing (2)

Secondary Indexes – Add for specific types of searches

PATH– On the path and value columns of the primary

index to make path-specific exist() method calls more efficient

PROPERTY– Builds an index on the PK, path and value columns

of the primary index to make value() method calls more efficient

Secondary Indexes – Add for specific types of searches

PATH– On the path and value columns of the primary

index to make path-specific exist() method calls more efficient

PROPERTY– Builds an index on the PK, path and value columns

of the primary index to make value() method calls more efficient

TeamDoc.exist('/ /Pitcher[@name = "John Smoltz"]')

TeamDoc.value('(/Team/@name)[1]’)

Page 26: SQL Server 2005: Extending the Type System with XML.

XML Indexing (3)XML Indexing (3)

Secondary Indexes – Add for specific types of searches

VALUE– Builds an index on the value and path of the

primary index to make node based exist() method calls more efficient

Secondary Indexes – Add for specific types of searches

VALUE– Builds an index on the value and path of the

primary index to make node based exist() method calls more efficientTeamDoc.exist('//Pitcher[@role="Closer"]')

Page 27: SQL Server 2005: Extending the Type System with XML.

XML Indexing (4)XML Indexing (4)

Creating Secondary Indexes– Use CREATE XML INDEX syntax

Add USING to specify primary index

Creating Secondary Indexes– Use CREATE XML INDEX syntax

Add USING to specify primary indexCREATE XML INDEX IXML_Team_Path ON Team (TeamDoc) USING XML INDEX IXML_Teams FOR PATH

CREATE XML INDEX IXML_Team_Prop ON Team (TeamDoc) USING XML INDEX IXML_Teams FOR PROPERTY

CREATE XML INDEX IXML_Team_Value ON Team (TeamDoc) USING XML INDEX IXML_Teams FOR VALUE

Page 28: SQL Server 2005: Extending the Type System with XML.

Questions?Questions?


Recommended