I have a stored procedure with a parameter in XML.
My problem is about the format of XML.
This solution its works:
<ROOT><ids><id>2013-01-01</id></ids><ids><id>2013-01-02</id></ids></ROOT>
SELECT * FROM OPENXML(@handle, '/ROOT/id') WITH (idDate Date)
Result: 2013-01-01 .. 2013-01-02
But the second solution not, why?
<ROOT><id>2013-01-01</id><id>2013-01-02</id></ROOT>
SELECT * FROM OPENXML(@handle, '/ROOT') WITH (idDate Date)
Result: Null
The XML is well formed, not?
For reporting uses, XML parameters really shine: You can pass the same XML string to multiple stored procs, yet you won't need to modify all of them, if say, one report's stored procedure requires additional criteria fields at some point in the future (providing of course, existing xml field names and data types haven' ...
Stored Procedure for reading, parsing and inserting XML dataOnce the nodes are fetched we need to extract the attribute and tag Inner Text values. For fetching the Inner Text values between the Tags we need to make use of the values function. The values function can read the Attribute as well as the Inner Text.
Your first query that you claim work does in fact not work with the XML you provided. It should be like this.
declare @handle int
declare @XML xml = '<ROOT><ids><id>2013-01-01</id></ids><ids><id>2013-01-02</id></ids></ROOT>'
exec sp_xml_preparedocument @handle out, @XML
select * from openxml(@handle, '/ROOT/ids', 2) with (id Date)
exec sp_xml_removedocument @handle
The second version should be
declare @handle int
declare @XML xml = '<ROOT><id>2013-01-01</id><id>2013-01-02</id></ROOT>'
exec sp_xml_preparedocument @handle out, @XML
select * from openxml(@handle, '/ROOT/id', 2) with (id Date '.')
exec sp_xml_removedocument @handle
Since you are using SQL Server 2008 or later you could use the XML datatype instead.
declare @XML xml = '<ROOT><id>2013-01-01</id><id>2013-01-02</id></ROOT>'
select T.N.value('text()[1]', 'date') as id
from @XML.nodes('ROOT/id') as T(N)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With