SQL XQuery/Xpath to values in an xmlcolumn.value

In the following example, ExceptionLog table has an xml column called TMXML. This contains a canonical xml message. The SQL can “peer” into the xml column, and pull out selected fields.

  'varchar(24)') AS RequestType,
  'varchar(24)') AS CurrentStepName,
  'varchar(24)') AS CurrentProcessCode
FROM ExceptionLog


A nifty idea is to put the above SQL in a view, and hide the xquery statements from the common user. Then the user can simply do

Select * from ViewExceptionLog

NOTE 1: The xpath must return a single value, else you will get an error something like this:

XQuery [TMXML.value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'

This is why each element in the hierarchy has the [1] after it, to return only the first nonoccurence. Even if you data doesn’t have multiple of them, T-SQL doesn’t know, you have to be explicit.

NOTE 2: if you are copying your xpath from C#, it’s probably easier to replace the single quotes with double quotes, as C# and SQL use the opposite quotes delimiters by default.

NOTE 3: Use a tool like http://www.xpathtester.com/xpath to test your xpath outside of SQL. You can paste your xml text message there, and play with different xpath statements. Then when you have one that works, go back and plug it into your T-SQL query.

For further info: http://msdn.microsoft.com/en-us/library/ms178030.aspx

Leave a Reply

Recent Posts




All Rights Reserved Theme by 404 THEME.