SQL Server query xml attribute for an element value

Divvet picture Divvet · Oct 16, 2012 · Viewed 25.5k times · Source

Sorry if this is somewhere else, I have found a lot of similar examples but I have been unable to get it working with my data. 2 days later and I need an answer :(

Basically have a SQL Server table with a column containing XML data. This data contains values I need to extract.

Here is my XML.

  <CustomFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.kaseya.com/vsa/2007/12/ServiceDeskDefinition.xsd">
    <Field fieldName="AutoCategory">Event Log</Field>
    <Field fieldName="SType">Event Log</Field>
    <Field fieldName="STag1">AgentGuid</Field>
    <Field fieldName="STag2">AlertRegistrationId</Field>
    <Field fieldName="STag3">LogType</Field>
    <Field fieldName="SValue1">619764177412541</Field>
    <Field fieldName="SValue2">104</Field>
    <Field fieldName="SValue3">1380569194</Field>
    <Field fieldName="SdTicketId">RPSv1006330</Field>
    <Field fieldName="AgentName">bla bla</Field>
    <Field fieldName="MachineGroupGuid">86115414719112271316891312</Field>
    <Field fieldName="OrgFk">59165166782128125214185317</Field>
    <Field fieldName="GuidAgent">619764177412541</Field>
    <Field fieldName="AlertCount">0</Field>
    <Field fieldName="TicketTitle">bla bla</Field>
    <Field fieldName="LegacyId">152262</Field>
    <Field fieldName="LegacyRef">152262</Field>
    <Field fieldName="CwStatus">2</Field>
    <Field fieldName="CwTicketId">89495</Field>
</CustomFields>

I need to be able to pull out the value associated to the CwTicketId field name.

So in essence, I want to look through the XML to find the node with fieldName = "CwTicketId" and to return 89495 or equivalent value.

Below is the code I have come up with myself, which pulls values out, but the problem is sometimes the XML is ordered differently, so the values are not always on the line that I have specified, hence it returns in accurate data.

;WITH XMLNAMESPACES(DEFAULT N'http://www.kaseya.com/vsa/2007/12/ServiceDeskDefinition.xsd')
SELECT 
    ref as ServiceDeskID, 
    sdSummary as ServiceDeskSummary,
    customFields.value('(/CustomFields/Field/node())[17]', 'varchar(100)') as LegacyIDTicketing,
    customFields.value('(/CustomFields/Field/node())[19]', 'varchar(100)') as CWIDTicketing
FROM 
    [ksubscribers].[kasadmin].[SDIncident]

The second value I also need, but if i can figure out how to pull one value out, I can duplicate for the other.

Hope someone can help as I have started ripping my hair out!

Thanks for the help!!

Answer

Roman Pekar picture Roman Pekar · Oct 16, 2012
;WITH XMLNAMESPACES(DEFAULT N'http://www.kaseya.com/vsa/2007/12/ServiceDeskDefinition.xsd')
select
    T.C.value('data(.)', 'nvarchar(128)')
from [YOUR_TABLE] as Y
    outer apply Y.[YOUR_XML_COLUMN].nodes('/CustomFields/Field[@fieldName="CwTicketId"]') as T(C)