This is my xml
<root>
<children>
<child id = "1">
<description>This is child 1</description>
</child>
<child id = "2">
<description>This is child 2</description>
</child>
<child id = "3">
<description>This is child 3</description>
</child>
</children>
</root>
I am trying to update a table named Child which has columns “ID” and “Description”. The table already has the ID column values in it but the description is blank. I need to update this description against the ID from the above given xml file.
I tried doing a OPENXML with flag value as 2 (element-centric) and was able to retrieve all the descriptions.
But am unaware as in how to retrieve descriptions based on the ID values, using a where clause in OPENXML.
The database I am using is SQL Server 2008.
(Also will OPENXML work for SQL Server 2005?)
This is wat I tried to do:
DECLARE @idoc int DECLARE @doc xml
select @doc= c from openrowset(bulk 'C:\Test.xml',single_blob) as temp(c)
exec sp_xml_preparedocument @idoc output, @doc
SELECT * FROM OPENXML (@idoc, '/root/children/child', 2)
WITH (summary varchar(1000)) descr
EXEC sp_xml_removedocument @idoc
Thanks in advance
Nick
p.s: The structure of the xml cannot be changed. I need to work around with this constraint.
Assuming you’re on SQL Server 2005 or up and you’re XML is stored in a variable called
@input, you could try this:The
GrabXMLcommon table expression (CTE) parses and flattens the XML into rows and columns, and the followingUPDATEstatement uses those rows/columns to update the existing table.Update: there are two possible problem points if your strings are longer than you expect:
first off, you might need to increase the length on the conversion from XML:
and secondly, you need to check what length your column in the table
dbo.Childis and truncate the length of the string extracted from the XML to not exceed the length of the database column:Here, you need to extract at most as many characters from the
g.Descriptionstring as your database columndbo.Child.descriptionallows.