Login    
 
 
 
 
Text/HTML
  
You are here :: Blogs Saturday, May 19, 2012

Search
Note: This uses the internal blog search engine. The Google search engine is also available at the top of the page.
  
Disclaimer

Please review the site disclaimer before downloading or using content found on this site

  
Categories
  
DEVSHED Blog
As always, I welcome your comments!
Sep 14

Written by: Steve Gray
9/14/2009 12:03 PM  RssIcon

This tip explains how to read an XML attribute from an XML field in sql server. Or, put another way, if we have this data:

<Receivable documentNumber="PYMNT000000000012    " documentDate="12/13/2007">
    <Type>PAYMENT</Type>
    <CashType>CHECK</CashType>
    <Description />
    <CheckNumber />
    <Amount>3.00000</Amount>
    <AppliedAmount>3.00000</AppliedAmount>
    <UnappliedAmount>0.00000</UnappliedAmount>
    <Items />
</Receivable>

We want to use SQL Server 2005 to retrieve the document number (PYMNT000000000012)

The code looks like this:

--create an xml variable, and then read an xml document into it. 
declare @x xml
declare @y as varchar(1000)
select @y ='<Receivable documentNumber="PYMNT12" documentDate="12/13/2007">'
select @y = @y + '  <Type>PAYMENT</Type>'
select @y = @y + '  <CashType>CHECK</CashType>'
select @y = @y + '  <Description />'
select @y = @y + '  <CheckNumber />'
select @y = @y + '  <Amount>3.00000</Amount>'
select @y = @y + '  <AppliedAmount>3.00000</AppliedAmount>'
select @y = @y + '  <UnappliedAmount>0.00000</UnappliedAmount>'
select @y = @y + '  <Items />'
select @y = @y + '</Receivable>'
select @x = @y
 
 
--SQL 2000 CODE
 
 
-- Initialize XML handle
DECLARE @hdoc INT    
EXEC sp_xml_preparedocument @hdoc OUTPUT, @x
 
 -- select the records
SELECT x.documentNumber 
 FROM OPENXML ( @hdoc, '/Receivable', 1 ) WITH (
  documentNumber VARCHAR(20) '@documentNumber'
  ) AS x
 
 -- Release XML handle
 EXEC sp_xml_removedocument @hdoc
 
 
--SQL 2005 CODE
 
 
SELECT 
        x.header.value('@documentNumber[1]', 'varchar(20)') AS OrderNumber,
        x.header.value('Type[1]', 'varchar(20)') AS Typex2
    FROM @x.nodes('//Receivable') AS x(header)

Tags:
Categories:
Location: Blogs Parent Separator DEVSHED Blogs Child Separator SQL
As always, I welcome your comments!
  
 
 
Home | Products | Blogs | Contact Us | Links | God's Plan
Privacy Statement | Terms Of Use
 
Copyright 2011 by Devshed.us