Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » XML .NET » XML in SQL Server Part 2

XML in SQL Server Part 2

This article gives you an overview of working with XML in SQL Server.

Author Rank:
Total page views :  3167
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Please check my previous article @

http://www.c-sharpcorner.com/UploadFile/kadiyalavj/XML_IN_SQL_SERVER02242008110706AM/XML_IN_SQL_SERVER.aspx

The for Section of the select Statement

The for section of the select statement is used to modify the relational structure of an XML document. Compared to the previous version of SQL Server, the capabilities of this option have been greatly expanded.

The general format of using the for option is the following:

[ for { browse | <xml> } ]
<xml> ::=
xml

{
{ raw [ ( 'ElementName' ) ] | auto }
[ <CoirmonDirectives>
[ , { xmldata | xmlschema [ { 'TargetNameSpaceURI' ) ] } ]
[ , elements [ xsinil | absent ]
]
| explicit
[ <ComomonDirectives>
[ , xmldata ]
]
| path [ ( 'ElementName' ) ]
[ <CommonDirectives>
[ , elements [ xsinil | absent ] ]
]
}

<CommonDirectives> :: =

[ , binary base64 ]
[ , type ]
[ , root [ ( 'RootName' ) ] ]

The meaning of each element in the preceding description is as follows:

  • Browse: This option has no relation to XML. It specifies that data can be updated when viewed with applications that use DB-Library.
  • Xml: The query result is to be converted to an XML document.
  • Raw [('ElementName')]: A data set is to be returned, in which each row is an element named <ElementName /> or <row />, if the parentheses are omitted.
  • Auto: An XML document is formed, in which the name of a table or a view is used as the name of the element representing a row of a result data set.
  • Explicit: The structure of the XML document is to be specified explicitly when defining the columns of the result data set.
  • Xml data: An XML-data reduced (XDR) schema is to be joined to the XML document.

Note: An XDR schema describes elements that an XML document may contain and the attributes that can be associated with the elements. It also describes the structure of an XML document, for example, specifying the daughter elements, their order, and number. A schema determines whether an element is empty or contains text. It can also hold the default values of attributes.

  • Xmlschema [ ( 'TargetNameSpaceURI' ) ]: Specifies that an XML schema definition is to be created in the XML document.


    f0_i DB-Library for C is an application programming interface consisting of C functions and macros that allow an application to interact with Microsoft SQL Server 2000. Included are functions that send Transact-SQL statements to SQL Server and functions that process the results of those statements.

  • Elements: The columns should be represented not by attributes but by daughter elements.
    xsinil " A column that can assume NULL value should be represented by an element with the xsi:nil attribute, whose value becomes TRUE if the column value becomes NULL.
    absent " If the column value is NULL, the corresponding element will not be added to the XML document.
    path [ ( 'ElementName' ) ] "The path to the data for XML output.
    binary base64 " The data should be returned in the binary format.
    type " The query result should be returned as XML data (not as text).
    root [ ( 'RootName' ) ] "A root element can be added to an XML document.
    Now consider some examples of using the for option for generating an XML document.

Suppose that there is a table containing information about books in three columns: <id, author, title>. Execute the below query:

select * from dbo.books for xml path ('book')

When executing a query in the SqlQuery window, Microsoft SQL Server Management Studio allows the resulting XML document to be viewed.

The output of the above query is:

<book>

  <id> 1 </id>

  <author> Charles Dickens </author>

  <title> Oliver Twist </title>

</book>

<book>

  <id> 2 </id>

  <author> Stephen King </author>

  <title> The Stand </title>

</book>

<book>

  <id> 3 </id>

  <author> Mark Twain </author>

  <title> The Mysterious Stranger </title>
</book>


It is a legible XML structure, in which each table row corresponds to a book element. The nested elements correspond to table columns.

The Openxml Function

The openxml function provides a rowset view over an XML document. The function is used with the sp_xml_preparedocument stored system procedure.

The format of the function is as follows:

openxml ( idoc int [ in] , rowpattern nvarchar [ in ] ,
[ flags byte [ in ] ] )
[ with ( SchemaDeclaration | TableName ) ]

The meaning of each element in the preceding description is as follows:

" idoc " The handle of the document in the internal (not text) XML format. The text format is converted into the internal XML format using the sp_xml_preperedocument stored system function.

" rowpattern " The pattern used to identify the nodes of an XML document.

" flags " A set of flags indicating how the rowset columns are mapped to the attributes and elements:

" 0 " Defaults to the column/attribute mapping

" 1 " Column/attribute mapping

" 2 " Column/element mapping

" 8 " Used with 1 and 2; indicates that the read data must not be copied into the @mp:xmltext meta property

" SchemaDeclaration " The format of the rowset. This has the following structure: ColNameColType [ColPattern | MetaProperty]
[, ColNameColType [ColPattern | MetaProperty]

" ColName " The name of a rowset column

" CollType " The data type of a rowset column

" ColPattern " An optional pattern specifying how the XML nodes are mapped to the rowset columns

" MetaProperty " Used to obtain metadata about the XML nodes

" TableName " The name of the table containing the schema (instead of SchemaDeclaration).

The below example shows converting of an XML document into a rowset and then adding the rowset to a table.

create table dbo.books ( id int not null, author char(20) not null, title char(20) not null )
declare @hxml int
declare @ xmldata xml
-- forming the text structure of the XML document
set @xmldata = '<Root>

<book>

  <id>

    1/id> <author>Stephen King</author>

    <title>The Stand</title>

  </book>

<book>

  <id>2</id>

  <author>Charles Dickens</author>

  <title>Oliver Twist</title>

</book>

</Root>';

Creating an XML document; @hxml is the document handle

exec sp_xml_preparedocument @hxml output, @ xmldata; 

Inserting data from the XML document into the table insert into dbo.books (id, author, title)

select * from openxml(@hxml, 'Root/book', 10)
with ( id int, author char(20), title char(20) )

An Example of Using the eventdata() Function

The eventdata() function is used with DDL triggers and returns information about the events taking place in the server or a database. The information returned in the XML format. Below shows example shows creation of a table, named log_of_events, into which information about DDL statements will be placed. After the table, a trigger is created that is activated by DDL statements and places information about these statements into the created table.

create table log_of_events (
time datetime,
name char(150),
login char(150),
event char(150),
command char(150) )

create trigger trig1 on database for DDL_DATABASE_LEVEL_EVENTS as
begin
declare @xml1 xml
set @xml1 = eventdata()
insert into log_of_events (time, name, login, event, command)
values ( getdate(), @xml1.value('data(//UserName)[1]', 'nvarchar(max)'), @xml1.value('data(//LoginName)[1]', 'nvarchar(max)'), @xml1.value('data(//EventType)[1]', 'nvarchar(max)'), @xml1.value('data(//CommandText)[1]', 'nvarchar(max)') )
end


Login to add your contents and source code to this article
 About the author
 
Vijaya Kadiyala
I have Quite a few years of experience in Microsoft & Oracle Technologies and i would like to share my knowledge to all. Give some and Get some.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.