I have the following XML :
<Feed>
<FeedId>10</FeedId>
<Component>
<Date>2011-10-01</Date>
<Date>2011-10-02</Date>
</Component>
</Feed>
Now if possible I would like to parse the XML into sql so it's serialized into the following relational data:
FeedId Component_Date
10 2011-10-01
10 2011-10-02
However using the following SQL:
DECLARE @XML XML;
DECLARE @XMLNodes XML;
SET @XML = '<Feed><FeedId>10</FeedId><Component><Date>2011-10-01</Date><Date>2011-10-02</Date></Component></Feed>';
SELECT t.a.query('FeedId').value('.', 'INT') AS FeedId
,t.a.query('Component/Date').value('.', 'VARCHAR(80)') AS [Component_Date]
FROM @XML.nodes(' /Feed') AS t(a)
The closest I get is :
FeedId Component_Date
10 2011-10-012011-10-02
So the date values appear in the same row, is it possible to achieve what I want using XQuery?
You need a second call to .nodes()
since you have multiple entries inside your XML - try this:
SELECT
t.a.value('(FeedId)[1]', 'INT') AS FeedId,
c.d.value('(.)[1]', 'DATETIME') AS [Component_Date]
FROM
@XML.nodes('/Feed') AS t(a)
CROSS APPLY
t.a.nodes('Component/Date') AS C(D)
Gives me an output of:
FeedId Component_Date
10 2011-10-01 00:00:00.000
10 2011-10-02 00:00:00.000
OK, I can do it using OPENXML method:
eclare @idoc int
DECLARE @XML XML;
DECLARE @XMLNodes XML;
SET @XML = '<Feed><FeedId>10</FeedId><Component><Date>2011-10-01</Date><Date>2011-10-02</Date></Component></Feed>';
exec sp_xml_preparedocument @idoc OUTPUT, @XML
-- SELECT stmt using OPENXML rowset provider
SELECT *
FROM OPENXML (@idoc, '/Feed/Component/Date',1)
WITH (
FeedId Int '../../FeedId',
ComponentDate Date 'text()'
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.