0

Strange thing with sp_xml_preparedocument. Why it not take value from name_x tag ?

declare @pXml nvarchar(max)
set @pXml = '<item>
<name_x>_x</name_x>
<name_1x>_1x</name_1x>
<name_y>_y</name_y>
</item>'

DECLARE @hDoc INT 
EXEC sp_xml_preparedocument @hDoc OUTPUT, @pXml  

SELECT name_x, name_1x, name_y
FROM OPENXML(@hDoc, '/item', 2)
WITH
(
 name_x NVARCHAR(5),
 name_1x NVARCHAR(5),
 name_y NVARCHAR(5)
) xDoc
EXEC sp_xml_removedocument @hDoc
Cœur
  • 37,241
  • 25
  • 195
  • 267
Alex A
  • 141
  • 6

2 Answers2

2

Why don't you just use the native XQuery support in SQL Server?

-- if you're dealing with XML - use the "XML" datatype!
declare @pXml XML = '<item>
                       <name_x>_x</name_x>
                       <name_1x>_1x</name_1x>
                       <name_y>_y</name_y>
                     </item>'


SELECT
    Name_x = @pXml.value('(item/name_x)[1]', 'nvarchar(5)'),
    Name_1x = @pXml.value('(item/name_1x)[1]', 'nvarchar(5)'),
    Name_y = @pXml.value('(item/name_y)[1]', 'nvarchar(5)')

This gives you an output of:

Name_x  Name_1x   Name_y
  _x      _1x       _y
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
2

I don't know quite why it's not working (other than finding a few old threads that do suggest that the MSXML parser can struggle with underscores), but if you add a ColPattern, it's enough to force it to work:

declare @pXml nvarchar(max)
set @pXml = '<item>
<name_x>_x</name_x>
<name_1x>_1x</name_1x>
<name_y>_y</name_y>
</item>'

DECLARE @hDoc INT 
EXEC sp_xml_preparedocument @hDoc OUTPUT, @pXml  

SELECT * --name_x, name_1x, name_y
FROM OPENXML(@hDoc, '/item', 2)
WITH
(
 name_x NVARCHAR(5) 'name_x', --<-- Explicit pattern
 name_1x NVARCHAR(5),
 name_y NVARCHAR(5)
) xDoc
EXEC sp_xml_removedocument @hDoc

Results:

name_x name_1x name_y
------ ------- ------
_x     _1x     _y

I would still recommend marc's solution unless or until you've got a demonstrable issue though

Community
  • 1
  • 1
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448