Monday, December 10, 2012
TSql Manipulating XML (XQUERY)
--TSQL SELECT FROM XML FIELD
DECLARE @xmlData XML
set @xmlData='<?xml version="1.0"?>
<ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ITEM>
<FilterID>1219</FilterID>
<Name>Fred</Name>
<Code>510</Code>
<Department>N</Department>
<Number>305327</Number>
</ITEM>
<ITEM>
<FilterID>3578</FilterID>
<Name>Gary</Name>
<Code>001</Code>
<Department>B</Department>
<Number>0692690</Number>
</ITEM>
<ITEM>
<FilterID>3579</FilterID>
<Name>George</Name>
<Code>001</Code>
<Department>X</Department>
<Number>35933</Number>
</ITEM>
</ROOT>'
SELECT
ref.value('FilterID[1]', 'int') AS FilterID ,
ref.value('Name[1]', 'NVARCHAR (10)') AS Name ,
ref.value('Code[1]', 'NVARCHAR (10)') AS Code ,
ref.value('Department[1]', 'NVARCHAR (3)') AS Department,
ref.value('Number[1]', 'int') AS Number
FROM @xmlData.nodes('/ROOT/ITEM')
xmlData( ref )
--TSQL SELECT TO XML FIELD
select * from dbo.TBLFOO
FOR XML PATH('ITEM'), root('ROOT')
Subscribe to:
Post Comments (Atom)
for xml auto,elements , root('main')
ReplyDeleteI have a table, T1, with a XML column, EventXML, on SQL Server 2008. I want to query all
ReplyDeletethe rows where certain node contains a particular value. Better, I'd like to retrieve the
value in a different node. The table T1
GDP
2.0
2012-01-01
SELECT
EventID, EventTime,
AnnouncementValue = t1.EventXML.value('(/Event/Announcement/Value)[1]',
'decimal(10,2)'),
AnnouncementDate = t1.EventXML.value('(/Event/Announcement/Date)[1]',
'date')
FROM
dbo.T1
WHERE
t1.EventXML.exist('/Event/Indicator/Name[text() = "GDP"]') = 1
It will find all rows where the /Event/Indicator/Name equals GDP and then it will display
the / and / for those rows.