Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML as parameter in stored procedure (sql server)

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?

like image 574
user2024475 Avatar asked Feb 15 '13 10:02

user2024475


People also ask

Can we pass XML to stored procedure in SQL Server?

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' ...

How do I read an XML stored procedure in SQL?

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.


1 Answers

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)
like image 63
Mikael Eriksson Avatar answered Dec 04 '22 13:12

Mikael Eriksson