Skip to content
Advertisement

Parse text and special characters from SQL Server

I have an issue with parsing text with special characters from XML in SQL Server.

Let’s say I have a XML file Sample.xml which has the following data:

I prepared the following SQL script which can parse everything except two sentences in the <TextType> attribute:

  • First sentence to retrieve
  • Second sentence to retrieve

Could you please help me to add the column with the sentences mentioned above?

Advertisement

Answer

OPENXML is old and basically deprecated, it has numerous issues.

You should use the newer XQuery functions .nodes and .value to retrieve your data.

Your primary issue is that you have XML stored as string inside another XML. You need to retrieve it as nvarchar(max), then cast it using TRY_CONVERT.

db<>fiddle

Note the way there are two calls to .nodes, and one feeds into the next.

You can even feed this in straight from OPENROWSET

I recommend you fix whatever is generating this XML, ideally you would pass through the inner XML without stringifying it.

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