Skip to content
Advertisement

Parse a varchar column containing XML like data into row wise

i have a column in table which contain data like XML,i would like to get data in rows.

My table data as-

It returns value-

but i want to use this information in another way like that

any help is appreciable.

Advertisement

Answer

Besides the fact, that it always is a good idea to use the appropriate type to store your data, you can use a cast on the fly to use your xml-like-data with XML methods:

In this case I use CROSS APPLY to add a column A.Casted to the result set, which is a row-wise casted XML.

This will break, in cases of invalid XML (of course). You might try TRY_CAST instead. This would return NULL, but will hide data errors…

Some more background
The cast to XML is a rather expensive operation. Doing this whenever you want to read out of your data is some heavy load for your server. Furthermore, using VARCHAR is prone to two major errors:

  • If there are foreign characters you might get question marks
  • If the XML is not valid, you will not see it – until you use it.

If possible, try to change the table’s design to use native XML.

And one more hint
It is a bad approach to name-number elements (same for columns). Instead of <Line1><Line2><Line3> better use <Line nr="1"><Line nr="2"><Line nr="3">

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement