Free Newsletters:
DatabaseJournal  
DBANews
Search Database Journal:
 
HOME News MS SQL Oracle DB2 Access MySQL PostgreSQL PHP SQL Etc Scripts Links Discussion
internet.com

» HOME
» NEWS
» FEATURES
» SERIES
MS SQL
Oracle
MS Access
MySQL
DB2
» RESOURCES
Products
Scripts
Links
» DISCUSSION
» TECH JOBS

Marketplace Partners
Be a Marketplace Partner




internet.commerce
Be a Commerce Partner
Online Education
Logo Design
Boat Donations
Server Racks
Promotional Pens
Web Hosting Directory
Disney World Tickets
Home Improvement
Promos and Premiums
Calling Cards
Holiday Gift Ideas
Online Universities
Shop
KVM Switch over IP




Google Display Ads in Your Pocket

Ballmer Ready to Move on Yahoo?

Acer Strong in Q1 With Aggressive Growth

internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Linked Data Planet Conference & Expo

CA ERwin® Data Modeler Proven database design and modeling. Efficiently analyze, design and deploy effective database solutions. Whitepaper: Manage SQL Server Deployments
Try it free: CA ERwin® Data Modeler

Access FREE HP High-Availability Solutions for Exchange 2007 Tools:
Access FREE HP Server Solutions Tools:
Whitepaper:
Backup and Recovery Best Practices for Microsoft Exchange Server 2007 with HP

Whitepaper:
Best Practices for HP Servers and HP Enterprise Virtual Array in a Microsoft Exchange

Whitepaper:
Optimizing HP Servers with Microsoft SQL Server 2008

Whitepaper:
Backup and Recovery Best Practices for SQL Server 2005

Whitepaper:
Configuration Best Practices for Microsoft SQL Server 2005 with HP EVA4000 and HP Blade Servers

Solaris 8 Migration Assistant
Rapidly move your Solaris 8 application environments to new systems running Solaris 10 with the Solaris 8 Migration Assistant. Reduce migration risk while taking advantage of increased performance, reliability and security of the latest SPARC hardware platforms and Solaris 10 OS. »

 
Sun Eco Innovation: Good for Business, Good for the Environment
A complete solution to help you optimize and refresh your datacenter while properly recycling equipment and eliminating eWaste, including money-saving promotions to lower hardware acquisition costs. »

 
Sun Eco Innovation: Power Calculators
Power consumption has increasingly become a priority in customer's minds when purchasing new systems or storage. Sun's Power Calculators provide data on power consumption of Sun products allowing IT managers to better plan the power requirements in the datacenter to achieve better energy and cost savings. »

 
Optimize the Web Tier: Consolidate to Get More Performance in Less Space and Lower Power Consumption
Expansion in the Web tier is generally accomplished by adding more servers whenever extra capacity is needed. As the pool of servers grows larger, however, the complexity of the environment can grow exponentially. »

Production Manager (hands on)
Aquent
US-MA-Cambridge

Justtechjobs.com Post A Job | Post A Resume
MS SQL
May 2, 2007
Query XML data from a table with XML data type
By Muthusamy Anantha Kumar aka The MAK

The objective of this article is to guide Microsoft SQL Server Database Administrators on how to:

  • Create XML Schema
  • Create a table with XML data type
  • Import XML file to the table with XML data type
  • Query the XML file
  • Query the XML file and produce results, similar to results produced by Transact SQL Statements

Step1

Let us create a C:\XML\Customer1.XML File as shown below. This XML file contains data related to one customer.

<?xml version="1.0" standalone="yes"?>
<Customer>
  <CustomerLogInfo>
    <Date>2007-03-31T06:40:38.0000000-05:00</Date>
    <user>james.brewer</user>
    <Userid>1AE</Userid>
    <ls>A-Accessible</ls>
    <eqtid>761</eqtid>
    <es>Stopped</es>
    <tp>30</tp>
  </CustomerLogInfo>
  <CustomerLogInfo>
    <Date>2007-03-31T06:40:38.0000000-05:00</Date>
    <user>james.brewer</user>
    <Userid>1AE</Userid>
    <ls>Not-Accessible</ls>
    <eqtid>870</eqtid>
    <es>Stopped</es>
    <tp>30</tp>
  </CustomerLogInfo>
  <CustomerLogInfo>
    <Date>2007-03-31T06:40:38.0000000-05:00</Date>
    <user>james.brewer</user>
    <Userid>1AE</Userid>
    <ls>A-Accessible</ls>
    <eqtid>97F</eqtid>
    <es>Started</es>
    <tp>30</tp>
  </CustomerLogInfo>
</Customer>

Step 2

Let us create a database and create an XML Schema collection as shown below.

USE [master]
GO
/****** Object:  Database [XMLTest]    Script Date: 04/17/2007 01:49:43 ******/
IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'XMLTest')
DROP DATABASE [XMLTest]
go
create database XMLTest
go
use XMLTest
go
Create XML Schema Collection XMLTrack
as
N'<xs:schema
attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Customer">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="CustomerLogInfo">
<xs:complexType>
<xs:sequence>
<xs:element name="Date" type="xs:string" />
<xs:element name="user" type="xs:string" />
<xs:element name="Userid" type="xs:string" />
<xs:element name="ls" type="xs:string" />
<xs:element name="eqtid" type="xs:string" />
<xs:element name="es" type="xs:string" />
<xs:element name="tp" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>'
go

Note: Update the Schema collection based on your data in your XML file.

Step 3

Let us create a table with XML data type:

USE [XMLTest]
GO
/****** Object:  Table [dbo].[XMLFiles]    Script Date: 04/17/2007 02:07:52 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[XMLFiles]') AND type in (N'U'))
DROP TABLE [dbo].[XMLFiles]
 
create table XMLFiles(Fileid int identity(1,1),
ImportedDate datetime constraint xmldatestamp default getdate(),
Filename varchar(500),
data xml (XMLTrack))

Step 4

Let us import the XML file we created, C:\XML\Customer1.XML, using the openrowset function as shown below.

USE [XMLTest]
go
INSERT INTO XMLFiles(Filename,DATA)
 SELECT 'Customer1' a,* 
FROM OPENROWSET( BULK 'C:\XML\Customer1.xml' ,SINGLE_CLOB)
as mytable
go

Note: The SINGLE_BLOB keyword imports the entire XML file to the XML data type column.

Step 5

Let us query the XMLFiles table using the transact SQL below.

USE [XMLTest]
go
select * from XMLFiles where FileId=1
go

This statement would produce the following results: [refer Fig 1.0].


Fig 1.0

When you click on the data, it also shows the XML data. [refer fig 1.1]

<Customer>
  <CustomerLogInfo>
    <Date>2007-03-31T06:40:38.0000000-05:00</Date>
    <user>james.brewer</user>
    <Userid>1AE</Userid>
    <ls>A-Accessible</ls>
    <eqtid>761</eqtid>
    <es>Stopped</es>
    <tp>30</tp>
  </CustomerLogInfo>
  <CustomerLogInfo>
    <Date>2007-03-31T06:40:38.0000000-05:00</Date>
    <user>james.brewer</user>
    <Userid>1AE</Userid>
    <ls>Not-Accessible</ls>
    <eqtid>870</eqtid>
    <es>Stopped</es>
    <tp>30</tp>
  </CustomerLogInfo>
  <CustomerLogInfo>
    <Date>2007-03-31T06:40:38.0000000-05:00</Date>
    <user>james.brewer</user>
    <Userid>1AE</Userid>
    <ls>A-Accessible</ls>
    <eqtid>97F</eqtid>
    <es>Started</es>
    <tp>30</tp>
  </CustomerLogInfo>
</Customer>


Fig 1.1

Step 6

Now let us query the XML data from the table to produce a transact SQL like result set. Execute the below XQuery as shown below.

SELECT 
ref.value ('Date', 'nvarchar(364)') as [Date],
ref.value ('user', 'nvarchar(364)') as [User],
ref.value ('Userid', 'nvarchar(364)') as [Userid],
ref.value ('ls', 'nvarchar(364)') as [ls],
ref.value ('eqtid', 'nvarchar(364)') as [eqtid],
ref.value ('es', 'nvarchar(364)') as [es],
ref.value ('tp', 'nvarchar(364)') as [tp]
FROM   XMLFiles CROSS APPLY Data.nodes ('//Customer/CustomerLogInfo') R(ref)
where Fileid=1

This would produce the results shown below [refer Fg 1.2]

Date,User,Userid,ls,eqtid,es,tp
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,A-Accessible,761,Stopped,30
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,Not-Accessible,870,Stopped,30
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,A-Accessible,97F,Started,30


Fig 1.2

Step 7

Now let us repeat step 4 and import the data again.

USE [XMLTest]
go
INSERT INTO XMLFiles(Filename,DATA)
 SELECT 'Customer1' a,* 
FROM OPENROWSET( BULK 'C:\XML\Customer1.xml' ,SINGLE_CLOB)
as mytable
go

Step 8

Now let us query the table as shown below.

USE [XMLTest]
go
select * from XMLFiles
go

This would produce the following result.


Fig 1.3

Step 9

In order to show all the data from both rows, we could write the query shown below.

SELECT 
ref.value ('Date', 'nvarchar(364)') as [Date],
ref.value ('user', 'nvarchar(364)') as [User],
ref.value ('Userid', 'nvarchar(364)') as [Userid],
ref.value ('ls', 'nvarchar(364)') as [ls],
ref.value ('eqtid', 'nvarchar(364)') as [eqtid],
ref.value ('es', 'nvarchar(364)') as [es],
ref.value ('tp', 'nvarchar(364)') as [tp]
FROM   XMLFiles CROSS APPLY Data.nodes ('//Customer/CustomerLogInfo') R(ref)
where Fileid=1
union all
SELECT 
ref.value ('Date', 'nvarchar(364)') as [Date],
ref.value ('user', 'nvarchar(364)') as [User],
ref.value ('Userid', 'nvarchar(364)') as [Userid],
ref.value ('ls', 'nvarchar(364)') as [ls],
ref.value ('eqtid', 'nvarchar(364)') as [eqtid],
ref.value ('es', 'nvarchar(364)') as [es],
ref.value ('tp', 'nvarchar(364)') as [tp]
FROM   XMLFiles CROSS APPLY Data.nodes ('//Customer/CustomerLogInfo') R(ref)
where Fileid=2

This would produce the following result. Refer fig 1.4

Date,User,Userid,ls,eqtid,es,tp
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,A-Accessible,761,Stopped,30
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,Not-Accessible,870,Stopped,30
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,A-Accessible,97F,Started,30
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,A-Accessible,761,Stopped,30
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,Not-Accessible,870,Stopped,30
2007-03-31T06:40:38.0000000-05:00,james.brewer,1AE,A-Accessible,97F,Started,30

Note: If you are planning to display all of the data from each row from the XML data type, you could create a stored procedure with temp table or cursor etc.


Fig 1.4

Conclusion

This article has illustrated how to create an XML Schema, create a table with XML data type, import the XML file to the table with XML data type, query the XML file and Query the XML file and produce results similar to results produced by the Transact SQL Statements result set.

» See All Articles by Columnist MAK

Tools:
Add databasejournal.com to your favorites
Add databasejournal.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

MS SQL Archives

Download: SQL Backup & DBA Best Practices eBook
Download: SQL Compare Pro 6--The fastest, easiest way to compare and synchronize two databases.
Download: SQL Backup & DBA Best Practices eBook.
Webcast: Five Virtualization Trends to Watch. Produced for HP, Citrix, and Intel.
Download: Solaris 8 Migration Assistant. Run Solaris 8 apps on the latest SPARC systems and Solaris 10.


Latest Forum Threads
MS SQL Forum
Topic By Replies Updated
"SELECT rowguidcol" vs. "SELECT <actual name>" rgarrison 9 April 16th, 03:46 PM
Database experience with Sharepoint? DarkCloudInc 2 April 15th, 01:49 PM
MsSql 2000 question ?? arul 3 April 14th, 11:26 AM
mdx/analysis/reporting service for date calculation j-in-nz 0 April 8th, 06:46 PM







JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES