white paper - xml date type in sql server 2005

14
Name of Topic: XML Date type in SLQ Server 2005 N  AME  ACCOUNT / BUSINESS  GROUP  AUTHOR MAHANTESHA G R ES-eEnabling REVIEWED BY Rajeev Kumar HLS ( HILL-ROM) Proprietary and Confidential 1

Upload: amoramadi

Post on 02-Apr-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 1/14

Page 2: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 2/14

Name of Topic: XML Date type in SLQ Server 2005

TABLE OF CONTENTS

XML DATA TYPE .....................................................................................................................................................3

CREATING XML DATA TYPE VARIABLES AND COLUMNS.........................................................................3

ASSIGNING DEFAULTS............................................................................................................................................4

SPECIFYING CONSTRAINTS..................................................................................................................................4

MODIFYING TABLES................................................................................................................................................5

CREATING VIEWS.....................................................................................................................................................5

USING XML IN COMPUTED COLUMNS..............................................................................................................6

XML DML (DATA MANIPULATION LANGUAGE).............................................................................................8

1. I NSERT :..................................................................................................................................................................82. DELETE (XML DML) .........................................................................................................................................11

3. REPLACE VALUE OF (XML DML) .....................................................................................................................12

REFERENCE..............................................................................................................................................................14

 

Proprietary and Confidential 2

Page 3: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 3/14

Name of Topic: XML Date type in SLQ Server 2005

XML Date type in SLQ Server 2005

Xml Data Type

XML data type can store XML documents and fragments in a SQL Serverdatabase. An XML fragment is an XML instance that is missing a single top-level element. We can create columns and variables of the xml type andstore XML instances in them. Note that the stored representation of xml datatype instances cannot exceed 2 GB.

Creating xml Data Type Variables and Columns

 The xml data type is a built-in data type in SQL Server and is somewhatsimilar to other built-in types such as int and varchar. As with other built-intypes, you can use the xml data type as a column type when you create atable as a variable type, a parameter type, a function-return type, or in CASTand CONVERT.

Create an xml type column:

CREATE TABLE T1 (xCol1 int primary key, xCol2 xml)

Create a variable of xml type: DECLARE @x xml  

Pass an xml type parameter to a stored procedure:

Proprietary and Confidential 3

Page 4: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 4/14

Name of Topic: XML Date type in SLQ Server 2005

CREATE PROCEDURE SampleProc(@XmlDoc xml) AS ...

Assigning Defaults

In a table, we can assign a default XML instance to a column of xml type. Wecan provide the default XML in one of two ways.

1. CREATE TABLE T (XmlColumn xml default N'<element1/><element2/>')

2. CREATE TABLE T (XmlColumn xmldefault CAST(N'<element1/><element2/>' AS xml))

Supports NULL and NOT NULLCREATE TABLE T (XmlColumn xml NOT NULL)

Specifying Constraints

When we create columns of xml type, we can define column-level or table-level constraints. However, we cannot use the XML data type methods whenwe specify constraints. An alternative is to create a wrapper, user-definedfunction to wrap the xml data type method and specify user-defined functionin the check constraint as shown in the following example.

In the following example, the constraint on Col2 specifies that each XML

instance stored in this column must have a <ProductDescription> elementthat contains a ProductID attribute. This constraint is enforced by this user-defined function:

CREATE FUNCTION my_udf (@var xml) returns bitAS BEGINRETURN @var.exist ('/ProductDescription/@ProductID')ENDGO

 The exist() method of the xml data type returns 1 if the<ProductDescription> element in the instance contains the ProductID

attribute. Otherwise, it returns 0.

Now, you can create a table with a column-level constraint as follows:

CREATE TABLE T (Col1 int primary key,Col2 xml check(dbo.my_udf(Col2)=1))

GO

Proprietary and Confidential 4

Page 5: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 5/14

Name of Topic: XML Date type in SLQ Server 2005

 The following insert succeeds:INSERT INTO T values(1,'<ProductDescription ProductID="1" />')

Because of the constraint, the following insert fails:INSERT INTO T values(1,'<Product />')

Modifying Tables

 The ALTER TABLE statement supports the xml data type. For example, youcan alter any string type column to the xml data type. Note that in thesecases, the documents contained in the column must be well formed. Also, if you are changing the type of the column from string to typed xml, thedocuments in the column are validated against the specified XSD schemas.

CREATE TABLE T (Col1 int primary key, Col2 nvarchar(max))GO

INSERT INTO T

VALUES (1, '<Root><Product ProductID="1"/></Root>')GO

ALTER TABLE TALTER COLUMN Col2 xmlGO

We can change an xml type column from untyped XML to typed XML. Forexample:

CREATE TABLE T (Col1 int primary key, Col2 xml)GO

INSERT INTO Tvalues (1, '<p1:ProductDescription ProductModelID="1"xmlns:p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription">

</p1:ProductDescription>')GO

ALTER TABLE TALTER COLUMN Col2 xml (Production.ProductDescriptionSchemaCollection)

GO

Creating Views

We can use an xml type column to create views. The following examplecreates a view in which the value from an xml type column is retrieved usingthe value() method of the xml data type.

Proprietary and Confidential 5

Page 6: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 6/14

Name of Topic: XML Date type in SLQ Server 2005

CREATE TABLE T ( ProductID int primary key, CatalogDescription xml)

-- Insert sample data.INSERT INTO T values(1,'<ProductDescription ProductID="1"ProductName="SomeName" />')GO

INSERT INTO T values(2,'<ProductDescription ProductID="2"ProductName="SomeName2" />')GO

-- Create viewCREATE VIEW MyView AS

SELECT ProductID,CatalogDescription.value('(/ProductDescription/@ProductName)[1]',

'varchar(40)') AS PNameFROM T

GO 

-- Execute the following query against the view:

SELECT * FROM MyView

-- This is the result: ProductID PName----------- ---------------------

1 SomeName2 SomeName2

Using XML in Computed ColumnsWe can create a computed column by extracting a value from an xml typecolumn as shown in the following example. Because the xml data typemethods cannot be used directly in creating computed columns, the examplefirst defines a function (my_udf) that returns a value from an XML instance. The function wraps the value() method of the xml type. The function name isthen specified in the CREATE TABLE statement for the computed column.

CREATE FUNCTION my_udf(@var xml) returns intAS BEGINRETURN @var.value('(/ProductDescription/@ProductModelID)[1]' , 'int')ENDGO

-- Use the function in CREATE TABLE.CREATE TABLE T (col1 xml, col2 as dbo.my_udf(col1) )GO

-- Try adding a row.

Proprietary and Confidential 6

Page 7: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 7/14

Name of Topic: XML Date type in SLQ Server 2005

INSERT INTO T values('<ProductDescription ProductModelID="2" />')GOINSERT INTO T values('<ProductDescription ProductModelID="3" />')GO

-- Verify results.

SELECT col2, col1 FROM T

Result:Col2 Col1

--------------------------------------------------------------2 <ProductDescription ProductModelID="2"/>3 <ProductDescription ProductModelID="3"/>

As in the previous example, the following example defines a function toreturn an xml type instance for a computed column. Inside the function, thequery() method of the xml data type retrieves a value from an xml type

parameter.

CREATE FUNCTION my_udf(@var xml)RETURNS xml AS

BEGINRETURN @var.query('ProductDescription/Features')

END

In the following CREATE TABLE statement, Col2 is a computed column thatuses the XML data (<Features> element) that is returned by the function:

CREATE TABLE T (Col1 xml, Col2 as dbo.my_udf(Col1) )

-- Insert a row in table T.INSERT INTO T VALUES('<ProductDescription ProductModelID="1" >

<Features><Feature1>description</Feature1><Feature2>description</Feature2>

</Features></ProductDescription>')

-- Verify the results.SELECT * FROM T

Proprietary and Confidential 7

Page 8: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 8/14

Name of Topic: XML Date type in SLQ Server 2005

XML DML (Data Manipulation Language)We can use XQuery to query XML instances stored in columns, parameters,or variables. We can also use the XML Data Manipulation Language (XMLDML) to apply updates to the XML instances. Because the XQuery standarddid not define XQuery DML at the time of development, SQL Serverintroduces XML Data Modification Language extensions to XQuery. These

extensions allow us to perform insert, update, and delete operations.

1. Insert :a. Inserting element nodes into the document

 The following example illustrates how to insert elements into a document.First, an XML document is assigned to a variable of xml type. Then, throughseveral insert XML DML statements, the example illustrates how elementnodes are inserted in the document. After each insert, the SELECT statement

displays the result.

Ex:DECLARE @myDoc xmlSET @myDoc =

'<Root><ProductDescription ProductID="1" ProductName="Road Bike"><Features> </Features></ProductDescription>

</Root>'

SELECT @myDoc 

-- insert first feature child (no need to specify as first or as last)

SET @myDoc.modify('insert <Maintenance>3 year parts and labor extended maintenance isavailable</Maintenance>into (/Root/ProductDescription/Features)[1]')

SELECT @myDoc

-- insert second feature. We want this to be the first in sequence so use 'asfirst'

set @myDoc.modify('insert <Warranty>1 year parts and labor</Warranty>as firstinto (/Root/ProductDescription/Features)[1]

Proprietary and Confidential 8

Page 9: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 9/14

Name of Topic: XML Date type in SLQ Server 2005

')

SELECT @myDoc

-- insert third feature child. This one is the last child of <Features> so use 'aslast'SELECT @myDoc

SET @myDoc.modify('insert <Material>Aluminium</Material>as lastinto (/Root/ProductDescription/Features)[1]')

SELECT @myDoc 

-- Add fourth feature - this time as a sibling (and not a child)-- 'after' keyword is used (instead of as first or as last child)

SELECT @myDocset @myDoc.modify('insert <BikeFrame>Strong long lasting</BikeFrame>after (/Root/ProductDescription/Features/Material)[1]')SELECT @myDoc;GO

B. Inserting multiple elements into the document

In the following example, a document is first assigned to a variable of xmltype. Then, a sequence of two elements, product features, is inserted into it.

DECLARE @myDoc xmlSET @myDoc = '<Root>

<ProductDescription ProductID="1" ProductName="Road Bike"><Features> </Features>

</ProductDescription></Root>'

SELECT @myDoc 

-- insert first feature children (no need to specify as first or last)SET @myDoc.modify('insert (

<Warranty>1 year parts and labor</Warranty>,<Maintenance>3 year parts and labor extended maintenance is

available</Maintenance>)

into (/Root/ProductDescription/Features)[1] ')

SELECT @myDoc;

C. Inserting attributes into a document

Proprietary and Confidential 9

Page 10: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 10/14

Name of Topic: XML Date type in SLQ Server 2005

 The following example illustrates how attributes are inserted in adocument.First, a document is assigned to an xml type variable. Then, aseries of insert XML DML statements is used to insert attributes into thedocument. After each attribute insertion, the SELECT statement displays theresult.

DECLARE @myDoc xml

SET @myDoc ='<Root>

<Location LocationID="10" ><step>Manufacturing step 1 at this work center</step><step>Manufacturing step 2 at this work center</step>

</Location></Root>'

SELECT @myDoc

-- insert LaborHours attributeSET @myDoc.modify('insert attribute LaborHours {".5" }

into (/Root/Location[@LocationID=10])[1] ')

SELECT @myDoc

-- insert MachineHours attribute but its value is retrived from a sql variable @HrsDECLARE @Hrs floatSET @Hrs =.2SET @myDoc.modify('insert attribute MachineHours {sql:variable("@Hrs") }into (/Root/Location[@LocationID=10])[1] ')

SELECT @myDoc

-- insert sequence of attribute nodes (note the use of ',' and ()-- around the attributes.SET @myDoc.modify('insert (

attribute SetupHours {".5" },attribute SomeOtherAtt {".2"}

)into (/Root/Location[@LocationID=10])[1] ')

SELECT @myDoc;

D. Inserting text node

In this query, an XML document is first assigned to a variable of xml type. Then, XML DML is used to insert a text node as the first child of the <Root>element. The text constructor is used to specify the text.

DECLARE @myDoc xmlSET @myDoc = '<Root>

<ProductDescription ProductID="1" ProductName="RoadBike">

Proprietary and Confidential 10

Page 11: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 11/14

Name of Topic: XML Date type in SLQ Server 2005

<Features></Features></ProductDescription>

</Root>'

SELECT @myDoc

set @myDoc.modify('

insert text{"Product Catalog Description"}as first into (/Root)[1]

')

SELECT @myDoc

2. Delete (XML DML)

A. Deleting nodes from a document stored in an untyped xml variable

 The following example illustrates how to delete various nodes from a

document. First, an XML instance is assigned to variable of xml type. Then,subsequent delete XML DML statements delete various nodes from thedocument.

DECLARE @myDoc xmlSET @myDoc = '<?Instructions for=TheWC.exe ?><Root><!-- instructions for the 1st work center -->

<Location LocationID="10"LaborHours="1.1"MachineHours=".2" >Some text 1

<step>Manufacturing step 1 at this work center</step>

<step>Manufacturing step 2 at this work center</step></Location></Root>'SELECT @myDoc

-- delete an attributeSET @myDoc.modify('

delete /Root/Location/@MachineHours')SELECT @myDoc

-- delete an element

SET @myDoc.modify('delete /Root/Location/step[2]')SELECT @myDoc

-- delete text node (in <Location>SET @myDoc.modify('

delete /Root/Location/text()')

Proprietary and Confidential 11

Page 12: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 12/14

Name of Topic: XML Date type in SLQ Server 2005

SELECT @myDoc

-- delete all processing instructionsSET @myDoc.modify('

delete //processing-instruction()')SELECT @myDoc

B. Deleting nodes from a document stored in an untyped xml columnIn the following example, a delete XML DML statement removes the second child element of <Features> from the document stored in the column.

CREATE TABLE T (i int, x xml)Go

INSERT INTO T VALUES(1,'<Root>

<ProductDescription ProductID="1"ProductName="Road Bike">

<Features><Warranty>1 year parts and 

labor</Warranty><Maintenance>3 year parts and labor 

extended maintenance isavailable</Maintenance>

</Features></ProductDescription>

</Root>')

-- verify the contents before deleteSELECT x.query(' //ProductDescription/Features')FROM T 

-- delete the second featureUPDATE TSET x.modify('delete /Root/ProductDescription/Features/*[2]')

-- verify the deletionSELECT x.query(' //ProductDescription/Features')FROM T

3. replace value of (XML DML)

A. Replacing values in an XML instanceIn the following example, a document instance is first assigned to a variable of xml type.

 Then, replace value of XML DML statements update values in the document.

DECLARE @myDoc xml

Proprietary and Confidential 12

Page 13: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 13/14

Name of Topic: XML Date type in SLQ Server 2005

SET @myDoc = '<Root><Location LocationID="10" LaborHours="1.1"

MachineHours=".2" >Manufacturing steps are described here.<step>Manufacturing step 1 at this work center</step><step>Manufacturing step 2 at this work center</step></Location>

</Root>'

SELECT @myDoc

-- update text in the first manufacturing stepSET @myDoc.modify('

replace value of (/Root/Location/step[1]/text())[1]with "new text describing the manu step"

')SELECT @myDoc-- update attribute valueSET @myDoc.modify('

replace value of (/Root/Location/@LaborHours)[1]with "100.0"

')

SELECT @myDoc

B. Using the if expression to determine replacement value You can specify the if expression in Expression2 of the replace value of XML DML statement,as shown in the following example. Expression1 identifies that the LaborHours attribute fromthe first work center is to be updated. Expression2 uses an if expression to determine thenew value of the LaborHours attribute.

DECLARE @myDoc xml

SET @myDoc = '<Root><Location LocationID="10"

LaborHours=".1"MachineHours=".2" >Manu steps are described here.

<step>Manufacturing step 1 at this work center</step><step>Manufacturing step 2 at this work center</step></Location></Root>'

SELECT @myDoc

SET @myDoc.modify('replace value of (/Root/Location[1]/@LaborHours)[1]

with (if (count(/Root/Location[1]/step) > 3) then

"3.0"else

"1.0")

')SELECT @myDoc

Proprietary and Confidential 13

Page 14: White Paper - XML Date Type in SQL Server 2005

7/27/2019 White Paper - XML Date Type in SQL Server 2005

http://slidepdf.com/reader/full/white-paper-xml-date-type-in-sql-server-2005 14/14

Name of Topic: XML Date type in SLQ Server 2005

Referenceurl: http://msdn2.microsoft.com

 

Proprietary and Confidential 14