Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Monday, March 26, 2012

Optimized way of Importing more than 300000 lines of xml data into SQL

Hi,

We have a 120 MB huge relational xml file, that we parse it through xsd file and import it into SQL Server relational tables using .net Dataset class. It takes around 2 hours to validate and import this huge file into sql server.

When the import is happening most of the Server CPU and memory resources are also more than 50%.

We would like to increase the performance of this import and we are ready to redesign the application if we find a better solution.

Any ideas/suggestions sincerely appreciated.

javed.

Hi Javed,

You can use XML Bulk Load component to import your xml data directly into SQL Server.

Refer Books on line SQL Server 2005 :

SQL Server 2005 Books online ->

SQL Server Programming Reference ->

SQL XML 4.0 Programming ->

Performing Bulk Load of XML Data (SQLXML 4.0)

Refer the following links to know more about XmlBulkLoad component:

Performing Bulk Load of XML Data (SQLXML 4.0)

Using SQL Server's XML Support > XML Bulk Load

How to import XML into SQL Server with the XML Bulk Load component

Thanks

Naras.

Wednesday, March 21, 2012

Optimization Rules for XML Bulk Insert

Hello Again,
I was wondering if there were any guide lines to optimize the XML Bulk
Insert component by using different XML formats. I read an article that did
cases, but can't remember where I saw it.
Thank for any help!
-Frank
I found what I was looking for.
http://msdn.microsoft.com/library/de...erformance.asp
If anyone wanted to know also.
"Frank DeLuccia" <fdeluccia-RemoveThisInsert-@.edifice-ims.com> wrote in
message news:OMsHu%239REHA.3984@.TK2MSFTNGP11.phx.gbl...
> Hello Again,
> I was wondering if there were any guide lines to optimize the XML Bulk
> Insert component by using different XML formats. I read an article that
did
> cases, but can't remember where I saw it.
> Thank for any help!
> -Frank
>

Saturday, February 25, 2012

openxml/'for xml' image data problem

I'm having problems with image fields when trying to insert XML into a table
using 'for xml' and openxml.
The code below demonstrates my problem. I have a table, tblAttachment that
contains a field named 'file' that contains image data.
prsXML is a simple proc that takes an xml document, extracts rows using
openxml and updates the row.
--prsXML
create proc dbo.prsXML2 @.XMLDoc text as begin
declare @.iDoc int
EXEC sp_xml_preparedocument @.idoc OUTPUT, @.XMLDoc
select * into #tblAttachment
from openxml (@.idoc, '/NewDataSet/tblAttachment', 2) with tblAttachment
update tblAttachment set [ID] = t.[ID], [FileName] = t.[FileName],
[File] = t.[File]
from #tblAttachment t inner join tblAttachment f on f.ID = t.ID
drop table #tblAttachment
exec sp_xml_removedocument @.idoc
end
If I call prsXML passing it a simple xml document as shown below it updates
the row in the database.
prsXML '<?xml version="1.0" ?>
<NewDataSet>
<tblAttachment>
<ID>49AA5490-DD38-4A7D-87E7-0525E07930AF</ID>
<FileName>test.jpg</FileName>
<File>QUJDREVGRw==</File>
</tblAttachment>
</NewDataSet>'
However, when I then select this updated row using:
select [file] from tblAttachment where ID =
'49AA5490-DD38-4A7D-87E7-0525E07930AF'
for xml auto, elements, binary base64
it returns:
<tblAttachment>
<file>UQBVAEoARABSAEUAVgBHAFIAdwA9AD0A</file>
</tblAttachment>
The element <File>QUJDREVGRw==</File>
does not match the element: <file>UQBVAEoARABSAEUAVgBHAFIAdwA9AD0A</file>
returned by the last query.
It appears that encoding/decoding is messing up the image data. What is
going on and how can I fix it?
Thanks for your help.
Jay
The issue is that FOR XML binary base64 does encode the content of your
image column using base64 encoding, but the OpenXML with clause does not
perform a decoding (let's say it is a design quirk :-)).
So you have the following workarounds:
1. Extract the encoded image and run a base64-decoder on it before doing the
insertion. The algorithm is well-described in the literature and can be
implemented using T-SQL or an extended stored proc.
2. You are waiting for SQL Server 2005, where the nodes() method will
provide you automatic decoding in the same scenario.
Sorry and best regards
Michael
"jamccormick" <jamccormick@.discussions.microsoft.com> wrote in message
news:17A4CDE2-90C8-46B0-A17E-493E2A6AF23E@.microsoft.com...
> I'm having problems with image fields when trying to insert XML into a
> table
> using 'for xml' and openxml.
> The code below demonstrates my problem. I have a table, tblAttachment
> that
> contains a field named 'file' that contains image data.
> prsXML is a simple proc that takes an xml document, extracts rows using
> openxml and updates the row.
> --prsXML
> create proc dbo.prsXML2 @.XMLDoc text as begin
> declare @.iDoc int
> EXEC sp_xml_preparedocument @.idoc OUTPUT, @.XMLDoc
> select * into #tblAttachment
> from openxml (@.idoc, '/NewDataSet/tblAttachment', 2) with tblAttachment
> update tblAttachment set [ID] = t.[ID], [FileName] = t.[FileName],
> [File] = t.[File]
> from #tblAttachment t inner join tblAttachment f on f.ID = t.ID
> drop table #tblAttachment
> exec sp_xml_removedocument @.idoc
> end
> If I call prsXML passing it a simple xml document as shown below it
> updates
> the row in the database.
> prsXML '<?xml version="1.0" ?>
> <NewDataSet>
> <tblAttachment>
> <ID>49AA5490-DD38-4A7D-87E7-0525E07930AF</ID>
> <FileName>test.jpg</FileName>
> <File>QUJDREVGRw==</File>
> </tblAttachment>
> </NewDataSet>'
> However, when I then select this updated row using:
> select [file] from tblAttachment where ID =
> '49AA5490-DD38-4A7D-87E7-0525E07930AF'
> for xml auto, elements, binary base64
> it returns:
> <tblAttachment>
> <file>UQBVAEoARABSAEUAVgBHAFIAdwA9AD0A</file>
> </tblAttachment>
> The element <File>QUJDREVGRw==</File>
> does not match the element: <file>UQBVAEoARABSAEUAVgBHAFIAdwA9AD0A</file>
> returned by the last query.
> It appears that encoding/decoding is messing up the image data. What is
> going on and how can I fix it?
> Thanks for your help.
> --
> Jay

OpenXML XPath question

I've included the xml and my OpenXML statement below. Using XPath in the
WITH portion of the OpenXML statement I can retrieve most values I need, but
I am trying to retrieve the values 'Last Name of Client' and 'First Name of
Client' from the xml and am not having any luck. I tried using '..' as the
xpath query but that returns text in the Question node and all child nodes.
<Section Value="AA"> Name and Identification Numbers
<Question Value="1.A"> Last Name of Client
<Question_Text>Last</Question_Text>
<Answer_Text>ROSSI1</Answer_Text>
<Answer_Value>ROSSI2</Answer_Value>
</Question>
<Question Value="2.A"> First Name of Client
<Question_Text>First Name</Question_Text>
<Answer_Text>TestA1</Answer_Text>
<Answer_Value>TestA2</Answer_Value>
</Question>
</Section>
OpenXML(@.idoc, '/ns0:GoldCare_Assessment/Section/Question')
WITH ([SectionValue] varchar(50) '../@.Value',
[QuestionValue] varchar(50) '@.Value',
[Question_Text] varchar(50) './Question_Text',
[Answer_Text] varchar(50) './Answer_Text',
[Answer_Value] varchar(50) './Answer_Value')Look at the bottom of this article where the stored procedure is shown:
http://www.eggheadcafe.com/articles...er_bulkload.asp
2005 Microsoft MVP C#
Robbe Morris
http://www.robbemorris.com
http://www.mastervb.net/home/ng/for...st10017013.aspx
http://www.eggheadcafe.com/articles...e_generator.asp
"Jeremy Chapman" <NoSpam@.Please.com> wrote in message
news:e1us7sSGFHA.2756@.TK2MSFTNGP15.phx.gbl...
> I've included the xml and my OpenXML statement below. Using XPath in the
> WITH portion of the OpenXML statement I can retrieve most values I need,
> but
> I am trying to retrieve the values 'Last Name of Client' and 'First Name
> of
> Client' from the xml and am not having any luck. I tried using '..' as
> the
> xpath query but that returns text in the Question node and all child
> nodes.
> <Section Value="AA"> Name and Identification Numbers
> <Question Value="1.A"> Last Name of Client
> <Question_Text>Last</Question_Text>
> <Answer_Text>ROSSI1</Answer_Text>
> <Answer_Value>ROSSI2</Answer_Value>
> </Question>
> <Question Value="2.A"> First Name of Client
> <Question_Text>First Name</Question_Text>
> <Answer_Text>TestA1</Answer_Text>
> <Answer_Value>TestA2</Answer_Value>
> </Question>
> </Section>
> OpenXML(@.idoc, '/ns0:GoldCare_Assessment/Section/Question')
> WITH ([SectionValue] varchar(50) '../@.Value',
> [QuestionValue] varchar(50) '@.Value',
> [Question_Text] varchar(50) './Question_Text',
> [Answer_Text] varchar(50) './Answer_Text',
> [Answer_Value] varchar(50) './Answer_Value')
>
>

OPENXML won't return rows

I am trying to insert a row from an XML document into a table. Here is
the table structure:
CREATE TABLE dbo.Customer(
CustomerGUID uniqueidentifier NOT NULL,
CustomerName varchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Version int NULL,
ActivatedDate smalldatetime NULL,
ActivatedByWS uniqueidentifier NULL,
DeactivatedDate smalldatetime NULL,
DeactivatedByWS varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
UpdatedByWS uniqueidentifier NULL,
CustomerType char(2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
SalesOfficeName varchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL,
PRIMARY KEY CLUSTERED
(
CustomerGUID ASC
)WITH (IGNORE_DUP_KEY = OFF) ON PRIMARY,
UNIQUE NONCLUSTERED
(
CustomerName ASC
)WITH (IGNORE_DUP_KEY = OFF) ON PRIMARY
) ON PRIMARY
GO
Here is the code to get the data from the document and insert it:
DECLARE @.docHandle int
declare @.xmlDocument xml
set @.xmlDocument = N'<ROOT>
<Customer>
<CustomerGUID>05062E6D-453B-4CAE-9EA4-BAF7D00E4235</CustomerGUID>
<CustomerType>CU</CustomerType>
<SalesOfficeName>Roadway Main</SalesOfficeName>
<UpdatedByWS>D7DA4883-656D-4923-9C5C-FD83EBE6F1BE</UpdatedByWS>
<ActivatedDate>2005-11-20T00:00:00</ActivatedDate>
</Customer>
</ROOT>'
EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.xmlDocument
-- comment out the actual INSERT
--INSERT INTO Customer (CustomerGUID, CustomerType, SalesOfficeName,
UpdatedByWS, ActivatedDate)
SELECT CustomerGUID, CustomerType, SalesOfficeName, UpdatedByWS,
ActivatedDate
FROM OPENXML(@.docHandle, N'/ROOT/Customer')
WITH Customer
EXEC sp_xml_removedocument @.docHandle
GO
I get this result:
CustomerGUID CustomerType SalesOfficeName UpdatedByWS ActivatedDate
-- -- -- -- --
NULL NULL NULL NULL NULL
I think that I am not describing the XML correctly to the XML variable,
but I don't know what to do next. Any ideas? Thanks.
You need to specify the flags parameter to tell OPENXML to look for elements
instead of attributes. The default Flags value is 1, which is attributes -
use 2 for elements, or 3 for both (or better yet use colpatterns in a table
def in the WITH clause).
DECLARE @.docHandle int
declare @.xmlDocument xml
set @.xmlDocument = N'<ROOT>
<Customer>
<CustomerGUID>05062E6D-453B-4CAE-9EA4-BAF7D00E4235</CustomerGUID>
<CustomerType>CU</CustomerType>
<SalesOfficeName>Roadway Main</SalesOfficeName>
<UpdatedByWS>D7DA4883-656D-4923-9C5C-FD83EBE6F1BE</UpdatedByWS>
<ActivatedDate>2005-11-20T00:00:00</ActivatedDate>
</Customer>
</ROOT>'
EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.xmlDocument
-- comment out the actual INSERT
--INSERT INTO Customer (CustomerGUID, CustomerType, SalesOfficeName,
UpdatedByWS, ActivatedDate)
SELECT CustomerGUID, CustomerType, SalesOfficeName,
UpdatedByWS,ActivatedDate
FROM OPENXML(@.docHandle, N'/ROOT/Customer', 2)
WITH Customer
Cheers,
Graeme
_____________________
Graeme Malcolm
Principal Technologist
Content Master
- a member of CM Group
www.contentmaster.com
<googleThis@.nadolna.net> wrote in message
news:1132684803.666917.108890@.g47g2000cwa.googlegr oups.com...
>I am trying to insert a row from an XML document into a table. Here is
> the table structure:
> CREATE TABLE dbo.Customer(
> CustomerGUID uniqueidentifier NOT NULL,
> CustomerName varchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
> Version int NULL,
> ActivatedDate smalldatetime NULL,
> ActivatedByWS uniqueidentifier NULL,
> DeactivatedDate smalldatetime NULL,
> DeactivatedByWS varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
> UpdatedByWS uniqueidentifier NULL,
> CustomerType char(2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
> SalesOfficeName varchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL,
> PRIMARY KEY CLUSTERED
> (
> CustomerGUID ASC
> )WITH (IGNORE_DUP_KEY = OFF) ON PRIMARY,
> UNIQUE NONCLUSTERED
> (
> CustomerName ASC
> )WITH (IGNORE_DUP_KEY = OFF) ON PRIMARY
> ) ON PRIMARY
> GO
>
> Here is the code to get the data from the document and insert it:
> DECLARE @.docHandle int
> declare @.xmlDocument xml
> set @.xmlDocument = N'<ROOT>
> <Customer>
> <CustomerGUID>05062E6D-453B-4CAE-9EA4-BAF7D00E4235</CustomerGUID>
> <CustomerType>CU</CustomerType>
> <SalesOfficeName>Roadway Main</SalesOfficeName>
> <UpdatedByWS>D7DA4883-656D-4923-9C5C-FD83EBE6F1BE</UpdatedByWS>
> <ActivatedDate>2005-11-20T00:00:00</ActivatedDate>
> </Customer>
> </ROOT>'
> EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.xmlDocument
> -- comment out the actual INSERT
> --INSERT INTO Customer (CustomerGUID, CustomerType, SalesOfficeName,
> UpdatedByWS, ActivatedDate)
> SELECT CustomerGUID, CustomerType, SalesOfficeName, UpdatedByWS,
> ActivatedDate
> FROM OPENXML(@.docHandle, N'/ROOT/Customer')
> WITH Customer
> EXEC sp_xml_removedocument @.docHandle
> GO
> I get this result:
> CustomerGUID CustomerType SalesOfficeName UpdatedByWS ActivatedDate
> -- -- -- -- --
> NULL NULL NULL NULL NULL
> I think that I am not describing the XML correctly to the XML variable,
> but I don't know what to do next. Any ideas? Thanks.
>
|||That was it! Thanks very much, Graeme.

OPENXML won't return rows

I am trying to insert a row from an XML document into a table. Here is
the table structure:
CREATE TABLE dbo.Customer(
CustomerGUID uniqueidentifier NOT NULL,
CustomerName varchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Version int NULL,
ActivatedDate smalldatetime NULL,
ActivatedByWS uniqueidentifier NULL,
DeactivatedDate smalldatetime NULL,
DeactivatedByWS varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
UpdatedByWS uniqueidentifier NULL,
CustomerType char(2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
SalesOfficeName varchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL,
PRIMARY KEY CLUSTERED
(
CustomerGUID ASC
)WITH (IGNORE_DUP_KEY = OFF) ON PRIMARY,
UNIQUE NONCLUSTERED
(
CustomerName ASC
)WITH (IGNORE_DUP_KEY = OFF) ON PRIMARY
) ON PRIMARY
GO
---
Here is the code to get the data from the document and insert it:
---
DECLARE @.docHandle int
declare @.xmlDocument xml
set @.xmlDocument = N'<ROOT>
<Customer>
<CustomerGUID>05062E6D-453B-4CAE-9EA4-BAF7D00E4235</CustomerGUID>
<CustomerType>CU</CustomerType>
<SalesOfficeName>Roadway Main</SalesOfficeName>
<UpdatedByWS>D7DA4883-656D-4923-9C5C-FD83EBE6F1BE</UpdatedByWS>
<ActivatedDate>2005-11-20T00:00:00</ActivatedDate>
</Customer>
</ROOT>'
EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.xmlDocument
-- comment out the actual INSERT
--INSERT INTO Customer (CustomerGUID, CustomerType, SalesOfficeName,
UpdatedByWS, ActivatedDate)
SELECT CustomerGUID, CustomerType, SalesOfficeName, UpdatedByWS,
ActivatedDate
FROM OPENXML(@.docHandle, N'/ROOT/Customer')
WITH Customer
EXEC sp_xml_removedocument @.docHandle
GO
I get this result:
CustomerGUID CustomerType SalesOfficeName UpdatedByWS ActivatedDate
-- -- -- -- --
NULL NULL NULL NULL NULL
I think that I am not describing the XML correctly to the XML variable,
but I don't know what to do next. Any ideas? Thanks.You need to specify the flags parameter to tell OPENXML to look for elements
instead of attributes. The default Flags value is 1, which is attributes -
use 2 for elements, or 3 for both (or better yet use colpatterns in a table
def in the WITH clause).
DECLARE @.docHandle int
declare @.xmlDocument xml
set @.xmlDocument = N'<ROOT>
<Customer>
<CustomerGUID>05062E6D-453B-4CAE-9EA4-BAF7D00E4235</CustomerGUID>
<CustomerType>CU</CustomerType>
<SalesOfficeName>Roadway Main</SalesOfficeName>
<UpdatedByWS>D7DA4883-656D-4923-9C5C-FD83EBE6F1BE</UpdatedByWS>
<ActivatedDate>2005-11-20T00:00:00</ActivatedDate>
</Customer>
</ROOT>'
EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.xmlDocument
-- comment out the actual INSERT
--INSERT INTO Customer (CustomerGUID, CustomerType, SalesOfficeName,
UpdatedByWS, ActivatedDate)
SELECT CustomerGUID, CustomerType, SalesOfficeName,
UpdatedByWS,ActivatedDate
FROM OPENXML(@.docHandle, N'/ROOT/Customer', 2)
WITH Customer
Cheers,
Graeme
_____________________
Graeme Malcolm
Principal Technologist
Content Master
- a member of CM Group
www.contentmaster.com
<googleThis@.nadolna.net> wrote in message
news:1132684803.666917.108890@.g47g2000cwa.googlegroups.com...
>I am trying to insert a row from an XML document into a table. Here is
> the table structure:
> CREATE TABLE dbo.Customer(
> CustomerGUID uniqueidentifier NOT NULL,
> CustomerName varchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
> Version int NULL,
> ActivatedDate smalldatetime NULL,
> ActivatedByWS uniqueidentifier NULL,
> DeactivatedDate smalldatetime NULL,
> DeactivatedByWS varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
> UpdatedByWS uniqueidentifier NULL,
> CustomerType char(2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
> SalesOfficeName varchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL,
> PRIMARY KEY CLUSTERED
> (
> CustomerGUID ASC
> )WITH (IGNORE_DUP_KEY = OFF) ON PRIMARY,
> UNIQUE NONCLUSTERED
> (
> CustomerName ASC
> )WITH (IGNORE_DUP_KEY = OFF) ON PRIMARY
> ) ON PRIMARY
> GO
>
> ---
> Here is the code to get the data from the document and insert it:
> ---
> DECLARE @.docHandle int
> declare @.xmlDocument xml
> set @.xmlDocument = N'<ROOT>
> <Customer>
> <CustomerGUID>05062E6D-453B-4CAE-9EA4-BAF7D00E4235</CustomerGUID>
> <CustomerType>CU</CustomerType>
> <SalesOfficeName>Roadway Main</SalesOfficeName>
> <UpdatedByWS>D7DA4883-656D-4923-9C5C-FD83EBE6F1BE</UpdatedByWS>
> <ActivatedDate>2005-11-20T00:00:00</ActivatedDate>
> </Customer>
> </ROOT>'
> EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.xmlDocument
> -- comment out the actual INSERT
> --INSERT INTO Customer (CustomerGUID, CustomerType, SalesOfficeName,
> UpdatedByWS, ActivatedDate)
> SELECT CustomerGUID, CustomerType, SalesOfficeName, UpdatedByWS,
> ActivatedDate
> FROM OPENXML(@.docHandle, N'/ROOT/Customer')
> WITH Customer
> EXEC sp_xml_removedocument @.docHandle
> GO
> I get this result:
> CustomerGUID CustomerType SalesOfficeName UpdatedByWS ActivatedDate
> -- -- -- -- --
> NULL NULL NULL NULL NULL
> I think that I am not describing the XML correctly to the XML variable,
> but I don't know what to do next. Any ideas? Thanks.
>|||That was it! Thanks very much, Graeme.

OpenXML with namespace and no prefix

I'm trying to run a query on some xml using openxml. The xml has a
namespace withough a prefix, and I'm having trouble. Below is a sample of
the xml and my openxml query. It runs but doesn't give back the expected
resultset. Any hints?
SELECT @.strIDXml = '<?xml version="1.0"?><IDs
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.interiorhealth.ca/DevSupport"><ID>3</ID><ID>2</ID></IDs>'
DECLARE @.idoc int
EXECUTE sp_xml_preparedocument @.idoc OUTPUT, @.strIDXml, '<IDs
xmlns="http://www.interiorhealth.ca/DevSupport"/>'
SELECT
2,[ID]
FROM
OpenXML(@.idoc, '/IDs/ID')
WITH (
[ID] int '.'
)
EXECUTE sp_xml_removedocument @.iDocJeremy wrote:
> I'm trying to run a query on some xml using openxml. The xml has a
> namespace withough a prefix, and I'm having trouble. Below is a sample of
> the xml and my openxml query. It runs but doesn't give back the expected
> resultset. Any hints?
For your query you need to bind a prefix to the default namespace and
use that prefix as in the following example:
EXECUTE sp_xml_preparedocument @.idoc OUTPUT, @.strIDXml, '<IDs
xmlns:pf="http://www.interiorhealth.ca/DevSupport"/>'
SELECT
2,[ID]
FROM
OpenXML(@.idoc, '/pf:IDs/pf:ID')
WITH (
[ID] int '.'
)
You are free to choose any valid prefix you like, just make sure it is
bound to the namespace URI defined in the original XML.
Martin Honnen -- MVP XML
http://JavaScript.FAQTs.com/|||thanks!
"Martin Honnen" <mahotrash@.yahoo.de> wrote in message
news:ux0UArHxHHA.736@.TK2MSFTNGP06.phx.gbl...
> Jeremy wrote:
> For your query you need to bind a prefix to the default namespace and use
> that prefix as in the following example:
> EXECUTE sp_xml_preparedocument @.idoc OUTPUT, @.strIDXml, '<IDs
> xmlns:pf="http://www.interiorhealth.ca/DevSupport"/>'
> SELECT
> 2,[ID]
> FROM
> OpenXML(@.idoc, '/pf:IDs/pf:ID')
> WITH (
> [ID] int '.'
> )
> You are free to choose any valid prefix you like, just make sure it is
> bound to the namespace URI defined in the original XML.
> --
> Martin Honnen -- MVP XML
> http://JavaScript.FAQTs.com/

OpenXML with namespace and no prefix

I'm trying to run a query on some xml using openxml. The xml has a
namespace withough a prefix, and I'm having trouble. Below is a sample of
the xml and my openxml query. It runs but doesn't give back the expected
resultset. Any hints?
SELECT @.strIDXml = '<?xml version="1.0"?><IDs
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.interiorhealth.ca/DevSupport"><ID>3</ID><ID>2</ID></IDs>'
DECLARE @.idoc int
EXECUTE sp_xml_preparedocument @.idoc OUTPUT, @.strIDXml, '<IDs
xmlns="http://www.interiorhealth.ca/DevSupport"/>'
SELECT
2,[ID]
FROM
OpenXML(@.idoc, '/IDs/ID')
WITH (
[ID] int '.'
)
EXECUTE sp_xml_removedocument @.iDoc
Jeremy wrote:
> I'm trying to run a query on some xml using openxml. The xml has a
> namespace withough a prefix, and I'm having trouble. Below is a sample of
> the xml and my openxml query. It runs but doesn't give back the expected
> resultset. Any hints?
For your query you need to bind a prefix to the default namespace and
use that prefix as in the following example:
EXECUTE sp_xml_preparedocument @.idoc OUTPUT, @.strIDXml, '<IDs
xmlns:pf="http://www.interiorhealth.ca/DevSupport"/>'
SELECT
2,[ID]
FROM
OpenXML(@.idoc, '/pf:IDs/pf:ID')
WITH (
[ID] int '.'
)
You are free to choose any valid prefix you like, just make sure it is
bound to the namespace URI defined in the original XML.
Martin Honnen -- MVP XML
http://JavaScript.FAQTs.com/
|||thanks!
"Martin Honnen" <mahotrash@.yahoo.de> wrote in message
news:ux0UArHxHHA.736@.TK2MSFTNGP06.phx.gbl...
> Jeremy wrote:
> For your query you need to bind a prefix to the default namespace and use
> that prefix as in the following example:
> EXECUTE sp_xml_preparedocument @.idoc OUTPUT, @.strIDXml, '<IDs
> xmlns:pf="http://www.interiorhealth.ca/DevSupport"/>'
> SELECT
> 2,[ID]
> FROM
> OpenXML(@.idoc, '/pf:IDs/pf:ID')
> WITH (
> [ID] int '.'
> )
> You are free to choose any valid prefix you like, just make sure it is
> bound to the namespace URI defined in the original XML.
> --
> Martin Honnen -- MVP XML
> http://JavaScript.FAQTs.com/

OpenXML with a schema

Why doesn't this work?
DECLARE @.xml VARCHAR(8000)
DECLARE @.iDoc INT
DECLARE @.Status INT
SELECT @.xml = '
<xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema">
<s:Schema id="RowsetSchema">
<s:ElementType name="row" content="eltOnly" rs:updatable="true">
<s:AttributeType name="DocumentKey1" rs:number="1" rs:nullable="true"
rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="DocumentKey1">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:AttributeType name="DocumentKey2" rs:number="2" rs:nullable="true"
rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="DocumentKey2">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:AttributeType name="DocumentType" rs:number="3" rs:nullable="true"
rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="DocumentType">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:AttributeType name="SourceCompanyCode" rs:number="4" rs:nullable="true"
rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="SourceCompanyCode">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:AttributeType name="StarShipCompanyCode" rs:number="5"
rs:nullable="true" rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="StarShipCompanyCode">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:extends type="rs:rowbase"/>
</s:ElementType>
</s:Schema>
<rs:data>
<rs:insert>
<z:row DocumentKey1="172" SourceCompanyCode="SOA"/>
</rs:insert>
</rs:data>
</xml>
'
EXEC @.Status = sp_xml_preparedocument @.idoc OUTPUT, @.xml
SELECT 'sp_xml_preparedocument status=',@.Status
--SELECT * FROM OPENXML (@.idoc, '/xml',2)
select *
FROM OPENXML (@.idoc, '/xml/data/insert/row',4)
WITH(
DocumentKey1 varchar(30)'@.DocumentKey1'
,DocumentKey2 varchar(30)'@.DocumentKey2'
,DocumentType varchar(30)'DocumentType'
,SourceCompanyCodevarchar(30) '@.SourceCompanyCode'
,StarShipCompanyCodevarchar(30) '@.StarShipCompanyCode'
)
You need to declare the namespaces in sp_xml_preparedocument, and use their
prefixes in the XPath used in the OPENXML function:
EXEC @.Status = sp_xml_preparedocument @.idoc OUTPUT, @.xml, '<root
xmlns:z="#RowsetSchema" xmlns:rs="urn:schemas-microsoft-com:rowset"/>'
SELECT 'sp_xml_preparedocument status=',@.Status
--SELECT * FROM OPENXML (@.idoc, '/xml',2)
select *
FROM OPENXML (@.idoc, '/xml/rs:data/rs:insert/z:row',2)
WITH (
DocumentKey1 varchar(30) '@.DocumentKey1'
,DocumentKey2 varchar(30) '@.DocumentKey2'
,DocumentType varchar(30) 'DocumentType'
,SourceCompanyCode varchar(30) '@.SourceCompanyCode'
,StarShipCompanyCode varchar(30) '@.StarShipCompanyCode'
)
Hope that helps,
Graeme
--
Graeme Malcolm
Principal Technologist
Content Master Ltd.
www.contentmaster.com
"John Grant" <johnwendell@.hotmail.com> wrote in message
news:B0134ADC-8D97-480C-A952-BA4862A7F75A@.microsoft.com...
Why doesn't this work?
DECLARE @.xml VARCHAR(8000)
DECLARE @.iDoc INT
DECLARE @.Status INT
SELECT @.xml = '
<xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema">
<s:Schema id="RowsetSchema">
<s:ElementType name="row" content="eltOnly" rs:updatable="true">
<s:AttributeType name="DocumentKey1" rs:number="1" rs:nullable="true"
rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="DocumentKey1">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:AttributeType name="DocumentKey2" rs:number="2" rs:nullable="true"
rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="DocumentKey2">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:AttributeType name="DocumentType" rs:number="3" rs:nullable="true"
rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="DocumentType">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:AttributeType name="SourceCompanyCode" rs:number="4" rs:nullable="true"
rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="SourceCompanyCode">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:AttributeType name="StarShipCompanyCode" rs:number="5"
rs:nullable="true" rs:writeunknown="true" rs:basecatalog="StarShipServer"
rs:basetable="ShipmentKey" rs:basecolumn="StarShipCompanyCode">
<s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="30"/>
</s:AttributeType>
<s:extends type="rs:rowbase"/>
</s:ElementType>
</s:Schema>
<rs:data>
<rs:insert>
<z:row DocumentKey1="172" SourceCompanyCode="SOA"/>
</rs:insert>
</rs:data>
</xml>
'
EXEC @.Status = sp_xml_preparedocument @.idoc OUTPUT, @.xml
SELECT 'sp_xml_preparedocument status=',@.Status
--SELECT * FROM OPENXML (@.idoc, '/xml',2)
select *
FROM OPENXML (@.idoc, '/xml/data/insert/row',4)
WITH (
DocumentKey1 varchar(30) '@.DocumentKey1'
,DocumentKey2 varchar(30) '@.DocumentKey2'
,DocumentType varchar(30) 'DocumentType'
,SourceCompanyCode varchar(30) '@.SourceCompanyCode'
,StarShipCompanyCode varchar(30) '@.StarShipCompanyCode'
)

OPENXML with a namespace

Sorry, I've tried to search to find my answer, but I just can't quite figure
it out... I'm new to querying XML in a stored proc...
I have an XML file that looks like:
<Members xmlns="http://tempuri.org/template.xsd">
<Member>
<OperationType>Insert</OperationType>
</Member>
<Member>
<OperationType>Update</OperationType>
</Member>
</Members>
there's more to it, but I've simplified it down.
and in my stored proc, I'm trying this: (assume that @.idoc is already
declared and @.FileContents contains the contents of the xml file I'm
reading)
EXEC sp_xml_preparedocument @.idoc OUTPUT, @.FileContents, '<Members
xmlns="http://tempuri.org/template.xsd"/>'
SELECT *
FROM OPENXML(@.idoc, '/Members/Member',2)
WITH (OperationType varchar(30))
EXEC sp_xml_removedocument @.idoc
I get no results...
If I take the xmlns declaration out of the <Members> element in the source
file, it works fine and I get a list of the OperationType elements.
What am I missing?
Thanks much,
SherylHi SL,
Welcome to the MSDN newsgroup.
Regarding on the OPENXML with namespace problem, based on my research, we
can use the third parameter of the sp_xml_prparedocument procedure to
specify namespace info. Also, in our sequental xpath, we need to explicitly
identify namespace through a namespace prefix. For detailed info, you can
refer to the following MSDN document and web article:
#How To: Use OpenXML on an Xml document with a default namespace
http://www.sqlxml.org/faqs.aspx?faq=101
#sp_xml_preparedocument
http://msdn.microsoft.com/library/e...o.asp?frame=tru
e
Hope this helps.
Regards,
Steven Cheng
Microsoft Online Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)|||That was perfect, thanks!
"Steven Cheng[MSFT]" <stcheng@.online.microsoft.com> wrote in message
news:GubgkovKGHA.3680@.TK2MSFTNGXA02.phx.gbl...
> Hi SL,
> Welcome to the MSDN newsgroup.
> Regarding on the OPENXML with namespace problem, based on my research, we
> can use the third parameter of the sp_xml_prparedocument procedure to
> specify namespace info. Also, in our sequental xpath, we need to
> explicitly
> identify namespace through a namespace prefix. For detailed info, you can
> refer to the following MSDN document and web article:
>
> #How To: Use OpenXML on an Xml document with a default namespace
> http://www.sqlxml.org/faqs.aspx?faq=101
> #sp_xml_preparedocument
> http://msdn.microsoft.com/library/e...ft.com/security
> (This posting is provided "AS IS", with no warranties, and confers no
> rights.)
>
>|||You're welcome SL,
Regards,
Steven Cheng
Microsoft Online Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

OPENXML with a namespace

Sorry, I've tried to search to find my answer, but I just can't quite figure
it out... I'm new to querying XML in a stored proc...
I have an XML file that looks like:
<Members xmlns="http://tempuri.org/template.xsd">
<Member>
<OperationType>Insert</OperationType>
</Member>
<Member>
<OperationType>Update</OperationType>
</Member>
</Members>
there's more to it, but I've simplified it down.
and in my stored proc, I'm trying this: (assume that @.idoc is already
declared and @.FileContents contains the contents of the xml file I'm
reading)
EXEC sp_xml_preparedocument @.idoc OUTPUT, @.FileContents, '<Members
xmlns="http://tempuri.org/template.xsd"/>'
SELECT *
FROM OPENXML(@.idoc, '/Members/Member',2)
WITH (OperationType varchar(30))
EXEC sp_xml_removedocument @.idoc
I get no results...
If I take the xmlns declaration out of the <Members> element in the source
file, it works fine and I get a list of the OperationType elements.
What am I missing?
Thanks much,
Sheryl
Hi SL,
Welcome to the MSDN newsgroup.
Regarding on the OPENXML with namespace problem, based on my research, we
can use the third parameter of the sp_xml_prparedocument procedure to
specify namespace info. Also, in our sequental xpath, we need to explicitly
identify namespace through a namespace prefix. For detailed info, you can
refer to the following MSDN document and web article:
#How To: Use OpenXML on an Xml document with a default namespace
http://www.sqlxml.org/faqs.aspx?faq=101
#sp_xml_preparedocument
http://msdn.microsoft.com/library/en...asp?frame=tru
e
Hope this helps.
Regards,
Steven Cheng
Microsoft Online Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
|||That was perfect, thanks!
"Steven Cheng[MSFT]" <stcheng@.online.microsoft.com> wrote in message
news:GubgkovKGHA.3680@.TK2MSFTNGXA02.phx.gbl...
> Hi SL,
> Welcome to the MSDN newsgroup.
> Regarding on the OPENXML with namespace problem, based on my research, we
> can use the third parameter of the sp_xml_prparedocument procedure to
> specify namespace info. Also, in our sequental xpath, we need to
> explicitly
> identify namespace through a namespace prefix. For detailed info, you can
> refer to the following MSDN document and web article:
>
> #How To: Use OpenXML on an Xml document with a default namespace
> http://www.sqlxml.org/faqs.aspx?faq=101
> #sp_xml_preparedocument
> http://msdn.microsoft.com/library/en...asp?frame=tru
> e
> Hope this helps.
> Regards,
> Steven Cheng
> Microsoft Online Support
> Get Secure! www.microsoft.com/security
> (This posting is provided "AS IS", with no warranties, and confers no
> rights.)
>
>
|||You're welcome SL,
Regards,
Steven Cheng
Microsoft Online Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

openxml vs xquery behind the scenes ?

Also, with regards the changes from Sql 2000 to Sql 2005.

When dealing with parsing/querying xml within a stored procedure, what is the difference (internally to sql server) between using OPENXML and xquery statements within a stored procedure ? With openxml, you need to call sp_xml_preparedocument, which will load a special version of the msxml parser called msxmlsql and loads the entire document into memory.

One thing that I like about XQUERY is that you can use the CROSS APPLY join to process database XML data on a row by row basis. I am new to using XML so I am also interested in hering the answer.

OPENXML vs BCP

Hi,
My application writes data into sql server.

Currently it converts data into XML (an in memory XML string) and write
using OPENXML.

I want to know if i write it to a csv file and use BCP, then will it be
faster then OPENXML. (i feel, writing to a csv will create IO operation that
will slow down the process).

ThanksIf you have many records, I would expect BCP to be much faster. The fastest
way to import large amounts of data into SQL Server is using a bulk insert
technique like BCP.

If your data originates as XML, you might also check out XML Bulk Load. See
http://msdn.microsoft.com/library/d...lkload_7pv0.asp

--
Hope this helps.

Dan Guzman
SQL Server MVP

"Sandy" <a@.a.com> wrote in message news:dhr9v4$15v@.netnews.net.lucent.com...
> Hi,
> My application writes data into sql server.
> Currently it converts data into XML (an in memory XML string) and write
> using OPENXML.
> I want to know if i write it to a csv file and use BCP, then will it be
> faster then OPENXML. (i feel, writing to a csv will create IO operation
> that
> will slow down the process).
> Thanks

OPENXML to return actual raw XML

Hello there,
I have the following Transact-SQL code. I want to return the raw <Features>
node and its content (tags included), but the OPENXML will always return
text values only.
Any suggestions or ideas are welcome... (you can paste this code into the
Query Analyzer to see what i mean).
Thanks!
DECLARE @.h int
EXEC sp_xml_preparedocument @.h OUTPUT,
N'
<?xml version="1.0"?>
<MovexOrder xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Items>
<MovexItem>
<Features>
<FechaEntrada>28/09/2004 15:04:11</FechaEntrada>
<FechaSalida>16/10/2004 15:04:11</FechaSalida>
<Modelo>A00600</Modelo>
<TallaAmericana>897</TallaAmericana>
<TallaPantalon>77</TallaPantalon>
<RefTejido>oiljgkkk</RefTejido>
<Observaciones>texto</Observaciones>
<LargoPrenda />
<LargoManga />
</Features>
<ID>1</ID>
<ITDS />
<ITNO>A00600HH9005148 </ITNO>
<ORTP />
<JDCD>001</JDCD>
<ORQT>2</ORQT>
<SAPR>0</SAPR>
<PONR>0</PONR>
<MODEL6>A00600</MODEL6>
<MODEL2>HH</MODEL2>
<SERIES>900</SERIES>
<TYPE>H</TYPE>
<COLOR>51</COLOR>
<SIZE>T48 </SIZE>
<Text />
</MovexItem>
<MovexItem>
<ID>2</ID>
<ITDS />
<ITNO>A00600HH9005154 </ITNO>
<ORTP />
<JDCD>001</JDCD>
<ORQT>1</ORQT>
<SAPR>0</SAPR>
<PONR>0</PONR>
<MODEL6>A00600</MODEL6>
<MODEL2>HH</MODEL2>
<SERIES>900</SERIES>
<TYPE>H</TYPE>
<COLOR>51</COLOR>
<SIZE>T54 </SIZE>
<Text />
</MovexItem>
</Items>
<ORNO />
<CONO>400</CONO>
<WHLO />
<CUNO>H0600001 </CUNO>
<CUNM />
<CMPN>05PV</CMPN>
<ORTP>NOR</ORTP>
<FACI>A01</FACI>
<CUOR />
<ORDT>28/09/2004</ORDT>
<RLDT>14/01/2005</RLDT>
<OFNO>ENE</OFNO>
<ORST>0</ORST>
<STAT />
<ADID />
<ADDR />
<ID>-1</ID>
<Text />
</MovexOrder>'
SELECT ID, Features
FROM OpenXML(@.h,'/MovexOrder/Items/MovexItem', 2)
WITH (ID INT, Features ntext )
WHERE Features IS NOT NULL
Change the SELECT statement to:
SELECT ID, Features
FROM OpenXML(@.h,'/MovexOrder/Items/MovexItem/Features', 2)
WITH
(ID INT '../ID',
Features ntext '@.mp:xmltext' )
WHERE Features IS NOT NULL
Cheerrs,
Graeme
--
Graeme Malcolm
Principal Technologist
Content Master Ltd.
www.contentmaster.com
"Ariel" <Ariel@.discussions.microsoft.com> wrote in message
news:8CC6DA6E-C06E-4499-BE40-42F5CFEC2FFC@.microsoft.com...
Hello there,
I have the following Transact-SQL code. I want to return the raw <Features>
node and its content (tags included), but the OPENXML will always return
text values only.
Any suggestions or ideas are welcome... (you can paste this code into the
Query Analyzer to see what i mean).
Thanks!
DECLARE @.h int
EXEC sp_xml_preparedocument @.h OUTPUT,
N'
<?xml version="1.0"?>
<MovexOrder xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Items>
<MovexItem>
<Features>
<FechaEntrada>28/09/2004 15:04:11</FechaEntrada>
<FechaSalida>16/10/2004 15:04:11</FechaSalida>
<Modelo>A00600</Modelo>
<TallaAmericana>897</TallaAmericana>
<TallaPantalon>77</TallaPantalon>
<RefTejido>oiljgkkk</RefTejido>
<Observaciones>texto</Observaciones>
<LargoPrenda />
<LargoManga />
</Features>
<ID>1</ID>
<ITDS />
<ITNO>A00600HH9005148 </ITNO>
<ORTP />
<JDCD>001</JDCD>
<ORQT>2</ORQT>
<SAPR>0</SAPR>
<PONR>0</PONR>
<MODEL6>A00600</MODEL6>
<MODEL2>HH</MODEL2>
<SERIES>900</SERIES>
<TYPE>H</TYPE>
<COLOR>51</COLOR>
<SIZE>T48 </SIZE>
<Text />
</MovexItem>
<MovexItem>
<ID>2</ID>
<ITDS />
<ITNO>A00600HH9005154 </ITNO>
<ORTP />
<JDCD>001</JDCD>
<ORQT>1</ORQT>
<SAPR>0</SAPR>
<PONR>0</PONR>
<MODEL6>A00600</MODEL6>
<MODEL2>HH</MODEL2>
<SERIES>900</SERIES>
<TYPE>H</TYPE>
<COLOR>51</COLOR>
<SIZE>T54 </SIZE>
<Text />
</MovexItem>
</Items>
<ORNO />
<CONO>400</CONO>
<WHLO />
<CUNO>H0600001 </CUNO>
<CUNM />
<CMPN>05PV</CMPN>
<ORTP>NOR</ORTP>
<FACI>A01</FACI>
<CUOR />
<ORDT>28/09/2004</ORDT>
<RLDT>14/01/2005</RLDT>
<OFNO>ENE</OFNO>
<ORST>0</ORST>
<STAT />
<ADID />
<ADDR />
<ID>-1</ID>
<Text />
</MovexOrder>'
SELECT ID, Features
FROM OpenXML(@.h,'/MovexOrder/Items/MovexItem', 2)
WITH (ID INT, Features ntext )
WHERE Features IS NOT NULL
|||Thanks a lot Graeme! It's working now.
"Graeme Malcolm" wrote:

> Change the SELECT statement to:
> SELECT ID, Features
> FROM OpenXML(@.h,'/MovexOrder/Items/MovexItem/Features', 2)
> WITH
> (ID INT '../ID',
> Features ntext '@.mp:xmltext' )
> WHERE Features IS NOT NULL
> Cheerrs,
> Graeme
> --
> --
> Graeme Malcolm
> Principal Technologist
> Content Master Ltd.
> www.contentmaster.com
>
> "Ariel" <Ariel@.discussions.microsoft.com> wrote in message
> news:8CC6DA6E-C06E-4499-BE40-42F5CFEC2FFC@.microsoft.com...
> Hello there,
> I have the following Transact-SQL code. I want to return the raw <Features>
> node and its content (tags included), but the OPENXML will always return
> text values only.
> Any suggestions or ideas are welcome... (you can paste this code into the
> Query Analyzer to see what i mean).
> Thanks!
>
> DECLARE @.h int
> EXEC sp_xml_preparedocument @.h OUTPUT,
> N'
> <?xml version="1.0"?>
> <MovexOrder xmlns:xsd="http://www.w3.org/2001/XMLSchema"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
> <Items>
> <MovexItem>
> <Features>
> <FechaEntrada>28/09/2004 15:04:11</FechaEntrada>
> <FechaSalida>16/10/2004 15:04:11</FechaSalida>
> <Modelo>A00600</Modelo>
> <TallaAmericana>897</TallaAmericana>
> <TallaPantalon>77</TallaPantalon>
> <RefTejido>oiljgkkk</RefTejido>
> <Observaciones>texto</Observaciones>
> <LargoPrenda />
> <LargoManga />
> </Features>
> <ID>1</ID>
> <ITDS />
> <ITNO>A00600HH9005148 </ITNO>
> <ORTP />
> <JDCD>001</JDCD>
> <ORQT>2</ORQT>
> <SAPR>0</SAPR>
> <PONR>0</PONR>
> <MODEL6>A00600</MODEL6>
> <MODEL2>HH</MODEL2>
> <SERIES>900</SERIES>
> <TYPE>H</TYPE>
> <COLOR>51</COLOR>
> <SIZE>T48 </SIZE>
> <Text />
> </MovexItem>
> <MovexItem>
> <ID>2</ID>
> <ITDS />
> <ITNO>A00600HH9005154 </ITNO>
> <ORTP />
> <JDCD>001</JDCD>
> <ORQT>1</ORQT>
> <SAPR>0</SAPR>
> <PONR>0</PONR>
> <MODEL6>A00600</MODEL6>
> <MODEL2>HH</MODEL2>
> <SERIES>900</SERIES>
> <TYPE>H</TYPE>
> <COLOR>51</COLOR>
> <SIZE>T54 </SIZE>
> <Text />
> </MovexItem>
> </Items>
> <ORNO />
> <CONO>400</CONO>
> <WHLO />
> <CUNO>H0600001 </CUNO>
> <CUNM />
> <CMPN>05PV</CMPN>
> <ORTP>NOR</ORTP>
> <FACI>A01</FACI>
> <CUOR />
> <ORDT>28/09/2004</ORDT>
> <RLDT>14/01/2005</RLDT>
> <OFNO>ENE</OFNO>
> <ORST>0</ORST>
> <STAT />
> <ADID />
> <ADDR />
> <ID>-1</ID>
> <Text />
> </MovexOrder>'
> SELECT ID, Features
> FROM OpenXML(@.h,'/MovexOrder/Items/MovexItem', 2)
> WITH (ID INT, Features ntext )
> WHERE Features IS NOT NULL
>
>

openxml to build a report

Trying to build a report for XML data stored in a table... Employee.EmployeeUDF has six fields...I need to be able to report on all the data for the table....any way to do this?

So far, I have found a plethora of information that will easily allow me to return one row of the table...like below...but can't get more than that...

DECLARE @.idoc int
DECLARE @.doc varchar(1000)

--The line remarked line below will select the udf xml values from the Employee table
SELECT @.doc = EmployeeUDF FROM Employee

--The following is an example of the getting the udf_date_tamex info from the xml
--SELECT @.doc = ' <udf>
<udf_text_tam>595297022</udf_text_tam>
<udf_date_tamex>2009-12-20</udf_date_tamex>
<udf_text_sher>2547793</udf_text_sher>
<udf_date_sherex>2010-02-15</udf_date_sherex>
<udf_text_helth> 772469 </udf_text_helth>
<udf_date_expriration>2008-04-28</udf_date_expriration>
</udf>'

-- Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @.idoc OUTPUT, @.doc
-- Execute a SELECT statement using OPENXML rowset provider.
SELECT *
FROM OPENXML (@.idoc, '/udf',2)
--specify the fields you wish to return by specifying the tag and datatype
WITH (udf_date_tamex datetime)

EXEC sp_xml_removedocument @.idoc

Thanks....
Jason

If you are using SQL Server 2000, you will have to wrap the above into a cursor that loops over every row.

If you are using SQL Server 2005, you should use the nodes() method in the following way:

select n.value('f_text_tam[1]', 'bigint'), n.value('udf_date_tamex[1]','datetime'), ....
from Employee cross apply EmployeeUDF.nodes('/udf') as E(n)

Best regards
Michael

|||

Thanks Michael. The cursor solution is the one. Should have specified 2000. It also reminds me to request 2005 install tomorrow...

J.

Monday, February 20, 2012

OpenXml sub elements

Hi All,
I,m shredding this xml to view the data and ultimate goal is to insert
the data at a later stage but when I shred it with the syntax
mentioned below then I recieve only one record instead of 3 records
with different AnsOptions (last sub element).
Help!
DECLARE @.doc xml
SET @.doc =
'<DivisionName>
<QuestInfo />
<DVName>Home</DVName>
<DvcodeNo>1</DvcodeNo>
<ClaimGroup>
<CustSurveyNo>4</CustSurveyNo>
<Questions>
<QuestionID>34</QuestionID>
<QuestionDesc>Q1.?</QuestionDesc>
<Answer>
<AnswerID>13</AnswerID>
<Answer>No</Answer>
<Ansoption>
<Options>Unhelpful</Options>
</Ansoption>
<Ansoption>
<Options>Time Waiting</Options>
</Ansoption>
<Ansoption>
<Options>Rude/Abrupt</Options>
</Ansoption>
</Answer>
</Questions>
</ClaimGroup>
</DivisionName>'
DECLARE @.docHandle int
-- Call stored procedure to create the memory tree
EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.doc
--split --
SELECT *
FROM
-- Add OPENXML statement for ResponseDetail table
OPENXML(@.docHandle, '/DivisionName/ClaimGroup/Questions/Answer', 2)
WITH
(DVName varchar (20) '../../../DVName',
DvcodeNo int '../../../DvcodeNo',
CustSurveyNo int '../../CustSurveyNo',
QuestionID int '../QuestionID',
QuestionDesc varchar(50) '../QuestionDesc',
AnswerID int,
Ansoption varchar (30))
EXEC sp_xml_removedocument @.docHandle
Results
Home 1 4 34 Q1.? 13 Unhelpful
Any Ideas ?, I need to finish this procedure as quick as possible,
Please adviseSELECT *
FROM
-- Add OPENXML statement for ResponseDetail table
OPENXML(@.docHandle, '/DivisionName/ClaimGroup/Questions/Answer/
Ansoption', 2)
WITH
(DVName varchar (20) '../../../../DVName',
DvcodeNo int '../../../../DvcodeNo',
CustSurveyNo int '../../../CustSurveyNo',
QuestionID int '../../QuestionID',
QuestionDesc varchar(50) '../../QuestionDesc',
AnswerID int '../AnswerID',
Ansoption varchar (30) 'Options')|||Thanks all sorted!
markc...@.hotmail.com wrote:
> SELECT *
> FROM
> -- Add OPENXML statement for ResponseDetail table
> OPENXML(@.docHandle, '/DivisionName/ClaimGroup/Questions/Answer/
> Ansoption', 2)
> WITH
> (DVName varchar (20) '../../../../DVName',
> DvcodeNo int '../../../../DvcodeNo',
> CustSurveyNo int '../../../CustSurveyNo',
> QuestionID int '../../QuestionID',
> QuestionDesc varchar(50) '../../QuestionDesc',
> AnswerID int '../AnswerID',
> Ansoption varchar (30) 'Options')|||It Doesn't work again if I add more data to the XML :
DECLARE @.doc xml
SET @.doc =
'<DivisionName>
<QuestInfo Custref="18759" SubDate="2006-01-01T00:00:00"
Polref="30018759" AgentID="4189" ClaimRef="14024-5647-890"/>
<DVName>Ho</DVName>
<DvcodeNo>1</DvcodeNo>
<ClaimGroup>
<CustSurveyNo>4</CustSurveyNo>
<ClaimGroupType>Water</ClaimGroupType>
<Questions>
<QuestionID>45</QuestionID>
<Answer>
<AnswerID>43</AnswerID>
<Ansoption />
</Answer>
</Questions>
<Questions>
<QuestionID>34</QuestionID>
<QuestionDesc>Q1. Was your call answered prompt and
courteously?</QuestionDesc>
<Answer>
<AnswerID>13</AnswerID>
<Ansoption>
<Options>Unhelpful</Options>
</Ansoption>
</Answer>
</Questions>
</ClaimGroup>
</DivisionName>'
DECLARE @.docHandle int
-- Call stored procedure to create the memory tree
EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.doc
SELECT *
FROM
-- Add OPENXML statement for SalesOrderDetail table INSERT
OPENXML(@.docHandle, '/DivisionName/ClaimGroup/Questions/Answer/
Ansoption', 2)
WITH
(DVName varchar (20) '../../../../DVName',
DvcodeNo int '../../../../DvcodeNo',
CustSurveyNo int '../../../CustSurveyNo',
ClaimGroupType varchar (20) '../../../ClaimGroupType',
QuestionID int '../../QuestionID',
QuestionDesc varchar(50) '../../QuestionDesc',
AnswerID int '../AnswerID',
Ansoption varchar (30)'Options')
EXEC sp_xml_removedocument @.docHandle

OpenXml sub elements

Hi All,
I,m shredding this xml to view the data and ultimate goal is to insert
the data at a later stage but when I shred it with the syntax
mentioned below then I recieve only one record instead of 3 records
with different AnsOptions (last sub element).
Help!
DECLARE @.doc xml
SET @.doc =
'<DivisionName>
<QuestInfo />
<DVName>Home</DVName>
<DvcodeNo>1</DvcodeNo>
<ClaimGroup>
<CustSurveyNo>4</CustSurveyNo>
<Questions>
<QuestionID>34</QuestionID>
<QuestionDesc>Q1.?</QuestionDesc>
<Answer>
<AnswerID>13</AnswerID>
<Answer>No</Answer>
<Ansoption>
<Options>Unhelpful</Options>
</Ansoption>
<Ansoption>
<Options>Time Waiting</Options>
</Ansoption>
<Ansoption>
<Options>Rude/Abrupt</Options>
</Ansoption>
</Answer>
</Questions>
</ClaimGroup>
</DivisionName>'
DECLARE @.docHandle int
-- Call stored procedure to create the memory tree
EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.doc
--split --
SELECT *
FROM
-- Add OPENXML statement for ResponseDetail table
OPENXML(@.docHandle, '/DivisionName/ClaimGroup/Questions/Answer', 2)
WITH
(DVName varchar (20) '../../../DVName',
DvcodeNo int '../../../DvcodeNo',
CustSurveyNo int '../../CustSurveyNo',
QuestionID int '../QuestionID',
QuestionDesc varchar(50) '../QuestionDesc',
AnswerID int,
Ansoption varchar (30))
EXEC sp_xml_removedocument @.docHandle
Results
Home1434Q1.?13Unhelpful
Any Ideas ?, I need to finish this procedure as quick as possible,
Please advise
SELECT *
FROM
-- Add OPENXML statement for ResponseDetail table
OPENXML(@.docHandle, '/DivisionName/ClaimGroup/Questions/Answer/
Ansoption', 2)
WITH
(DVName varchar (20) '../../../../DVName',
DvcodeNo int '../../../../DvcodeNo',
CustSurveyNo int '../../../CustSurveyNo',
QuestionID int '../../QuestionID',
QuestionDesc varchar(50) '../../QuestionDesc',
AnswerID int '../AnswerID',
Ansoption varchar (30) 'Options')
|||Thanks all sorted!
markc...@.hotmail.com wrote:
> SELECT *
> FROM
> -- Add OPENXML statement for ResponseDetail table
> OPENXML(@.docHandle, '/DivisionName/ClaimGroup/Questions/Answer/
> Ansoption', 2)
> WITH
> (DVName varchar (20) '../../../../DVName',
> DvcodeNo int '../../../../DvcodeNo',
> CustSurveyNo int '../../../CustSurveyNo',
> QuestionID int '../../QuestionID',
> QuestionDesc varchar(50) '../../QuestionDesc',
> AnswerID int '../AnswerID',
> Ansoption varchar (30) 'Options')
|||It Doesn't work again if I add more data to the XML :
DECLARE @.doc xml
SET @.doc =
'<DivisionName>
<QuestInfo Custref="18759" SubDate="2006-01-01T00:00:00"
Polref="30018759" AgentID="4189" ClaimRef="14024-5647-890"/>
<DVName>Ho</DVName>
<DvcodeNo>1</DvcodeNo>
<ClaimGroup>
<CustSurveyNo>4</CustSurveyNo>
<ClaimGroupType>Water</ClaimGroupType>
<Questions>
<QuestionID>45</QuestionID>
<Answer>
<AnswerID>43</AnswerID>
<Ansoption />
</Answer>
</Questions>
<Questions>
<QuestionID>34</QuestionID>
<QuestionDesc>Q1. Was your call answered prompt and
courteously?</QuestionDesc>
<Answer>
<AnswerID>13</AnswerID>
<Ansoption>
<Options>Unhelpful</Options>
</Ansoption>
</Answer>
</Questions>
</ClaimGroup>
</DivisionName>'
DECLARE @.docHandle int
-- Call stored procedure to create the memory tree
EXEC sp_xml_preparedocument @.docHandle OUTPUT, @.doc
SELECT *
FROM
-- Add OPENXML statement for SalesOrderDetail table INSERT
OPENXML(@.docHandle, '/DivisionName/ClaimGroup/Questions/Answer/
Ansoption', 2)
WITH
(DVName varchar (20) '../../../../DVName',
DvcodeNo int '../../../../DvcodeNo',
CustSurveyNo int '../../../CustSurveyNo',
ClaimGroupType varchar (20) '../../../ClaimGroupType',
QuestionID int '../../QuestionID',
QuestionDesc varchar(50) '../../QuestionDesc',
AnswerID int '../AnswerID',
Ansoption varchar (30)'Options')
EXEC sp_xml_removedocument @.docHandle

OPENXML SELECT does not work with one of the definitions

Problem with XML
Apparently there seems to be 2 different XML definitions of a string;
The first one is like this:
'<people><person name="John Doe" age="30"/></people>'
The second version is like this:
'<?xml version ="1.0"?><BarcodeTTP><BerichtIndicator>0</BerichtIndicator><Channel>GJN
</Channel><PartyCode>gjn</PartyCode><PUIC>gjn0000114</PUIC><Resultaat>0</Resultaat>
<ResultaatTekst>houdoe</ResultaatTekst></BarcodeTTP>'
After preparing the output and so I wish to SELECT the DATA in one ROW.
The first structure I can get output with.
SELECT [name], [age]
FROM OPENXML(@.id, '/people/person')
WITH
( name varchar(20) ,
age varchar(20) )
The Second Structure
SELECT BerichtIndicator, Channel, PartyCode, PUIC, Resultaat,
ResultaatTekst
FROM OPENXML(@.id, '/BarcodeTTP')
WITH
(BerichtIndicator int '@.BerichtIndicator',
Channel varchar(10) '@.Channel',
PartyCode varchar(20) '@.PartyCode',
PUIC varchar(20) '@.PUIC',
Resultaat int '@.Resultaat',
ResultaatTekst varchar(100) '@.ResultaatTekst')
Gives me one row with alll columns filled with NULL values.
What do I wrong ? Or do I have to do something with the structure ?
Arno de Jong, The Netherlands.
declare @.id int
exec sp_xml_preparedocument @.id OUTPUT, N'<?xml version="1.0"?>
<BarcodeTTP>
<BerichtIndicator>0</BerichtIndicator>
<Channel>GJN</Channel>
<PartyCode>gjn</PartyCode>
<PUIC>gjn0000114</PUIC>
<Resultaat>0</Resultaat>
<ResultaatTekst>houdoe</ResultaatTekst>
</BarcodeTTP>
'
SELECT BerichtIndicator, Channel, PartyCode, PUIC, Resultaat, ResultaatTekst
FROM OPENXML(@.id, '/BarcodeTTP', 2)
WITH (BerichtIndicator int,
Channel varchar(10),
PartyCode varchar(20),
PUIC varchar(20),
Resultaat int,
ResultaatTekst varchar(100))
exec sp_xml_removedocument @.id
Martin
"A.M. de Jong" <arnojo@.wxs.nl> wrote in message
news:ct0fjc$nfo$1@.reader13.wxs.nl...
> Problem with XML
>
> Apparently there seems to be 2 different XML definitions of a string;
>
> The first one is like this:
> '<people><person name="John Doe" age="30"/></people>'
>
> The second version is like this:
> '<?xml version
="1.0"?><BarcodeTTP><BerichtIndicator>0</BerichtIndicator><Channel>GJN
>
</Channel><PartyCode>gjn</PartyCode><PUIC>gjn0000114</PUIC><Resultaat>0</Res
ultaat>
> <ResultaatTekst>houdoe</ResultaatTekst></BarcodeTTP>'
>
>
> After preparing the output and so I wish to SELECT the DATA in one ROW.
>
> The first structure I can get output with.
>
> SELECT [name], [age]
> FROM OPENXML(@.id, '/people/person')
> WITH
> ( name varchar(20) ,
> age varchar(20) )
>
> The Second Structure
>
> SELECT BerichtIndicator, Channel, PartyCode, PUIC, Resultaat,
> ResultaatTekst
> FROM OPENXML(@.id, '/BarcodeTTP')
> WITH
> (BerichtIndicator int '@.BerichtIndicator',
> Channel varchar(10) '@.Channel',
> PartyCode varchar(20) '@.PartyCode',
> PUIC varchar(20) '@.PUIC',
> Resultaat int '@.Resultaat',
> ResultaatTekst varchar(100) '@.ResultaatTekst')
>
> Gives me one row with alll columns filled with NULL values.
> What do I wrong ? Or do I have to do something with the structure ?
> Arno de Jong, The Netherlands.
>
>

OPENXML SELECT does not work with one of the definitions

Problem with XML
Apparently there seems to be 2 different XML definitions of a string;
The first one is like this:
'<people><person name="John Doe" age="30"/></people>'
The second version is like this:
'<?xml version ="1.0"?><BarcodeTTP><BerichtIndicator>0</BerichtIndicator><Ch
annel>GJN
</Channel><PartyCode>gjn</PartyCode><PUIC>gjn0000114</PUIC><Resultaat>0</Res
ultaat>
<ResultaatTekst>houdoe</ResultaatTekst></BarcodeTTP>'
After preparing the output and so I wish to SELECT the DATA in one ROW.
The first structure I can get output with.
SELECT [name], [age]
FROM OPENXML(@.id, '/people/person')
WITH
( name varchar(20) ,
age varchar(20) )
The Second Structure
SELECT BerichtIndicator, Channel, PartyCode, PUIC, Resultaat,
ResultaatTekst
FROM OPENXML(@.id, '/BarcodeTTP')
WITH
(BerichtIndicator int '@.BerichtIndicator',
Channel varchar(10) '@.Channel',
PartyCode varchar(20) '@.PartyCode',
PUIC varchar(20) '@.PUIC',
Resultaat int '@.Resultaat',
ResultaatTekst varchar(100) '@.ResultaatTekst')
Gives me one row with alll columns filled with NULL values.
What do I wrong ? Or do I have to do something with the structure ?
Arno de Jong, The Netherlands.declare @.id int
exec sp_xml_preparedocument @.id OUTPUT, N'<?xml version="1.0"?>
<BarcodeTTP>
<BerichtIndicator>0</BerichtIndicator>
<Channel>GJN</Channel>
<PartyCode>gjn</PartyCode>
<PUIC>gjn0000114</PUIC>
<Resultaat>0</Resultaat>
<ResultaatTekst>houdoe</ResultaatTekst>
</BarcodeTTP>
'
SELECT BerichtIndicator, Channel, PartyCode, PUIC, Resultaat, ResultaatTekst
FROM OPENXML(@.id, '/BarcodeTTP', 2)
WITH (BerichtIndicator int,
Channel varchar(10),
PartyCode varchar(20),
PUIC varchar(20),
Resultaat int,
ResultaatTekst varchar(100))
exec sp_xml_removedocument @.id
Martin
"A.M. de Jong" <arnojo@.wxs.nl> wrote in message
news:ct0fjc$nfo$1@.reader13.wxs.nl...
> Problem with XML
>
> Apparently there seems to be 2 different XML definitions of a string;
>
> The first one is like this:
> '<people><person name="John Doe" age="30"/></people>'
>
> The second version is like this:
> '<?xml version
="1.0"?><BarcodeTTP><BerichtIndicator>0</BerichtIndicator><Channel>GJN
>
</Channel><PartyCode>gjn</PartyCode><PUIC>gjn0000114</PUIC><Resultaat>0</Res
ultaat>
> <ResultaatTekst>houdoe</ResultaatTekst></BarcodeTTP>'
>
>
> After preparing the output and so I wish to SELECT the DATA in one ROW.
>
> The first structure I can get output with.
>
> SELECT [name], [age]
> FROM OPENXML(@.id, '/people/person')
> WITH
> ( name varchar(20) ,
> age varchar(20) )
>
> The Second Structure
>
> SELECT BerichtIndicator, Channel, PartyCode, PUIC, Resultaat,
> ResultaatTekst
> FROM OPENXML(@.id, '/BarcodeTTP')
> WITH
> (BerichtIndicator int '@.BerichtIndicator',
> Channel varchar(10) '@.Channel',
> PartyCode varchar(20) '@.PartyCode',
> PUIC varchar(20) '@.PUIC',
> Resultaat int '@.Resultaat',
> ResultaatTekst varchar(100) '@.ResultaatTekst')
>
> Gives me one row with alll columns filled with NULL values.
> What do I wrong ? Or do I have to do something with the structure ?
> Arno de Jong, The Netherlands.
>
>

openxml seemingly fails to process external entity

I am having a problem getting OPENXML to process some xml that contains an
"external entity" in SQL Server 2000.
Background, which you probably already know:
--
Xml uses "external entities" the way the C language uses "#include": when
an xml processor finds the directive, it refers to an external file whose
contents are to be processed at that point.
I have created a minimal example that illustrates the problem.
1. First, here is some SQL that correctly processes some XML that does
*not* use external entities. The XML is stored in a variable (@.testXml), an
d
a select statement reads this XML and reports some basic facts about the onl
y
data in it, namely, that there is a tag called "DatastreamDownload ":
-- demonstrate validity of simple xml
declare @.testXml varchar(8000)
set @.testXml ='
<?xml version="1.0" ?>
<DatastreamDownload />
'
declare @.idoc int
exec sp_xml_preparedocument @.idoc output, @.testXml
select *
from openxml( @.idoc, '/DatastreamDownload', 0)
exec sp_xml_removedocument @.idoc
Here are the beginnings of the lines I see in SQL Query Analyzer:
id parentid nodetype localname
-- -- -- --
0 NULL 1 DatastreamDownload
(1 row(s) affected)
2. I then stored the XML from @.testXml in a file, simple.xml. The
following 2 lines show the contents of the file, except that I've added 4
spaces to the beginning of each of the lines in this listing (that is, the
prefixed spaces are not in the file):
<?xml version="1.0" ?>
<DatastreamDownload />
3. I created a second file of XML, simpleEntity.xml, that includes
simple.xml by using a external entity. The following 11 lines show the
contents of the file, except that I've added 4 spaces to the beginning of
each of the lines in this listing (that is, the prefixed spaces are not in
the file):
<?xml version="1.0" ?>
<!DOCTYPE just4ExternalEntity
[
<!ENTITY externalEntity SYSTEM "simple.xml">
]
>
<just4ExternalEntity>
<workingTag />
&externalEntity;
</just4ExternalEntity>
You can verify that this external entity stuff is done properly by opening
this second file in Internet Explorer. I see something like this, except
with better colors:
<?xml version="1.0" ?>
<!DOCTYPE just4ExternalEntity (View Source for full doctype...)>
- <just4ExternalEntity>
<workingTag />
<DatastreamDownload />
</just4ExternalEntity>
4. Finally, I copied the working xml from simpleEntity.xml into a SQL
variable, @.xmlDoc. I had to prefix a network path to "simple.xml", to give
the SQL Server a chance of locating simple.xml. I've represented this
network path by "\\unc..." below, although in my actual test I used a valid
(and triple-tested) unc.
Openxml can partially process this code. The first select statement below
reports on the "workingTag" tag, which is defined in the @.xmlDoc variable ,
but fails to report on the sibling "DatastreamDownload" tag, which is define
d
in the external entity.
-- attempt to read the same xml from a disk file using an external entity
declare @.xmlDoc varchar(1000)
set @.xmlDoc = -- code from simpleEntity.xml
'
<?xml version="1.0" ?>
<!DOCTYPE just4ExternalEntity
[
<!ENTITY externalEntity SYSTEM "\\unc...\simple.xml">
]
>
<just4ExternalEntity>
<workingTag />
&externalEntity;
</just4ExternalEntity>
'
declare @.jdoc int
declare @.rc int
exec @.rc = sp_xml_preparedocument @.jdoc output, @.xmlDoc
select @.rc as resultCode
-- lists row, as expected
select *
from openxml( @.jdoc, '/just4ExternalEntity/workingTag', 0)
-- fails to list row
select *
from openxml( @.jdoc, '/just4ExternalEntity/DatastreamDownload', 0)
exec sp_xml_removedocument @.jdoc
Here are the beginnings of the lines I see in SQL Query Analyzer:
resultCode
--
0
(1 row(s) affected)
id parentid nodetype localname
-- -- -- --
7 0 1 workingTag
(1 row(s) affected)
id parentid nodetype localname
-- -- -- --
(0 row(s) affected)
I was expecting to see 1 row in the last result set above, with
"DatastreamDownload" in the "localname" column.
So openxml is failing to process something that Internet Explorer has no
trouble with. As far as I know (and I'm no expert) external entities are a
standard part of XML, and a standards-conforming XML processor should handle
them. So it seems very likely that the processor used by openxml does handl
e
them. It's even possible that openxml and IE are using the same processor,
although that would quite a feat of coordination for a company the size of
Microsoft.
Since external entities are standard, and since IE issues a security warning
when I use one via a network unc, I'm suspecting that there is a privilege
problem in getting openxml to read the external entity.
Thanks for any help.External entities are not supported with OpenXML for a variety of security
related reasons.
Best is to resolve them on the client/midtier side before sending the XML to
the server.
Best regards
Michael
"HolmesDM" <HolmesDM@.discussions.microsoft.com> wrote in message
news:8AF86E16-03D4-49A7-9A20-8133C2B0E109@.microsoft.com...
>I am having a problem getting OPENXML to process some xml that contains an
> "external entity" in SQL Server 2000.
> Background, which you probably already know:
> --
> Xml uses "external entities" the way the C language uses "#include": when
> an xml processor finds the directive, it refers to an external file whose
> contents are to be processed at that point.
>
> I have created a minimal example that illustrates the problem.
> 1. First, here is some SQL that correctly processes some XML that does
> *not* use external entities. The XML is stored in a variable (@.testXml),
> and
> a select statement reads this XML and reports some basic facts about the
> only
> data in it, namely, that there is a tag called "DatastreamDownload ":
> -- demonstrate validity of simple xml
> declare @.testXml varchar(8000)
> set @.testXml ='
> <?xml version="1.0" ?>
> <DatastreamDownload />
> '
> declare @.idoc int
> exec sp_xml_preparedocument @.idoc output, @.testXml
> select *
> from openxml( @.idoc, '/DatastreamDownload', 0)
> exec sp_xml_removedocument @.idoc
>
> Here are the beginnings of the lines I see in SQL Query Analyzer:
> id parentid nodetype localname
> -- -- -- --
--
> 0 NULL 1
> DatastreamDownload
> (1 row(s) affected)
>
> 2. I then stored the XML from @.testXml in a file, simple.xml. The
> following 2 lines show the contents of the file, except that I've added 4
> spaces to the beginning of each of the lines in this listing (that is, the
> prefixed spaces are not in the file):
> <?xml version="1.0" ?>
> <DatastreamDownload />
>
> 3. I created a second file of XML, simpleEntity.xml, that includes
> simple.xml by using a external entity. The following 11 lines show the
> contents of the file, except that I've added 4 spaces to the beginning of
> each of the lines in this listing (that is, the prefixed spaces are not in
> the file):
> <?xml version="1.0" ?>
> <!DOCTYPE just4ExternalEntity
> [
> <!ENTITY externalEntity SYSTEM "simple.xml">
> ]
> <just4ExternalEntity>
> <workingTag />
> &externalEntity;
> </just4ExternalEntity>
> You can verify that this external entity stuff is done properly by opening
> this second file in Internet Explorer. I see something like this, except
> with better colors:
> <?xml version="1.0" ?>
> <!DOCTYPE just4ExternalEntity (View Source for full doctype...)>
> - <just4ExternalEntity>
> <workingTag />
> <DatastreamDownload />
> </just4ExternalEntity>
> 4. Finally, I copied the working xml from simpleEntity.xml into a SQL
> variable, @.xmlDoc. I had to prefix a network path to "simple.xml", to
> give
> the SQL Server a chance of locating simple.xml. I've represented this
> network path by "\\unc..." below, although in my actual test I used a
> valid
> (and triple-tested) unc.
> Openxml can partially process this code. The first select statement below
> reports on the "workingTag" tag, which is defined in the @.xmlDoc variable
> ,
> but fails to report on the sibling "DatastreamDownload" tag, which is
> defined
> in the external entity.
> -- attempt to read the same xml from a disk file using an external
> entity
> declare @.xmlDoc varchar(1000)
> set @.xmlDoc = -- code from simpleEntity.xml
> '
> <?xml version="1.0" ?>
> <!DOCTYPE just4ExternalEntity
> [
> <!ENTITY externalEntity SYSTEM "\\unc...\simple.xml">
> ]
> <just4ExternalEntity>
> <workingTag />
> &externalEntity;
> </just4ExternalEntity>
> '
> declare @.jdoc int
> declare @.rc int
> exec @.rc = sp_xml_preparedocument @.jdoc output, @.xmlDoc
> select @.rc as resultCode
> -- lists row, as expected
> select *
> from openxml( @.jdoc, '/just4ExternalEntity/workingTag', 0)
> -- fails to list row
> select *
> from openxml( @.jdoc, '/just4ExternalEntity/DatastreamDownload',
> 0)
> exec sp_xml_removedocument @.jdoc
>
> Here are the beginnings of the lines I see in SQL Query Analyzer:
> resultCode
> --
> 0
> (1 row(s) affected)
> id parentid nodetype localname
> -- -- -- --
> 7 0 1 workingTag
> (1 row(s) affected)
> id parentid nodetype localname
> -- -- -- --
> (0 row(s) affected)
> I was expecting to see 1 row in the last result set above, with
> "DatastreamDownload" in the "localname" column.
> So openxml is failing to process something that Internet Explorer has no
> trouble with. As far as I know (and I'm no expert) external entities are
> a
> standard part of XML, and a standards-conforming XML processor should
> handle
> them. So it seems very likely that the processor used by openxml does
> handle
> them. It's even possible that openxml and IE are using the same
> processor,
> although that would quite a feat of coordination for a company the size of
> Microsoft.
> Since external entities are standard, and since IE issues a security
> warning
> when I use one via a network unc, I'm suspecting that there is a privilege
> problem in getting openxml to read the external entity.
> Thanks for any help.|||Thanks for the definitive answer, even if it's not exactly the one I'd hoped
for.
"Michael Rys [MSFT]" wrote:

> External entities are not supported with OpenXML for a variety of security
> related reasons.
> Best is to resolve them on the client/midtier side before sending the XML
to
> the server.
> Best regards
> Michael
> "HolmesDM" <HolmesDM@.discussions.microsoft.com> wrote in message
> news:8AF86E16-03D4-49A7-9A20-8133C2B0E109@.microsoft.com...
>
>