Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast TEXT to XML in SQL Server

Basically I have a column named XML that is of type TEXT; this cannot be changed for other reason, but I was wondering how I could cast it to XML.

It gives me an error

XML parsing: line 1, character 39, unable to switch the encoding

when trying to do this. Is there anyways around it to still get it formatted to XML? I'm really stuck at this point.

Data within column:

<?xml version="1.0" encoding="utf-16"?>
<Record>
     <UserGuid>c624a356-9f18-403c-b404-790e79034c7d</UserGuid>
</Record>

Here is the cast SQL code:

SELECT CAST(XML AS XML).value('(/Record/UserGuid)[1]', 'NVARCHAR(max)')
FROM tbl_Module_RequestForms_Items
like image 342
the sandman Avatar asked Dec 01 '11 00:12

the sandman


People also ask

Can you type CAST in SQL?

You can cast to many SQL Server types such as binary , char , varchar , date , datetime , time , decimal , bigint , and float .

What is XML Auto in SQL Server?

FOR XML AUTO in SQL SERVER The FOR XML AUTO clause converts each column in the SQL table into an attribute in the corresponding XML document.


2 Answers

Your problem is: you have XML with an encoding="utf-16", but your column is a non-Unicode column......

Assuming that you cannot change it to NTEXT either, you have to do two nested CAST to achieve what you're looking for:

SELECT 
    CAST(CAST(XML AS NTEXT) AS XML).value('(/Record/UserGuid)[1]', 'NVARCHAR(max)')
FROM 
    tbl_Module_RequestForms_Items

First, you need to cast to NTEXT (or NVARCHAR(MAX)), and then you have to cast that result to XML, before you can use it.

Tip: remove those "other reasons" and convert this to XML datatype if you really need to use it as XML .....

like image 179
marc_s Avatar answered Oct 15 '22 13:10

marc_s


You should replace encoding="utf-16" to encoding="utf-8" or ''(blank) and then perform your operation.

a. Converting encoding="utf-16" to encoding="utf-8"

SELECT 
  CAST(
    REPLACE(CAST([xml] AS VARCHAR(MAX)), 'encoding="utf-16"', 'encoding="utf-8"')
  AS XML).value('(/Record//UserGuid/node())[1]', 'NVARCHAR(max)') as UserGuid
from tbl_Module_RequestForms_Items

b. Replacing encoding="utf-16" to ''(blank)

SELECT 
  CAST(
    REPLACE(CAST([xml] AS VARCHAR(MAX)), 'encoding="utf-16"', '')
  AS XML).value('(/Record//UserGuid/node())[1]', 'NVARCHAR(max)') as UserGuid
from tbl_Module_RequestForms_Items
like image 40
Elias Hossain Avatar answered Oct 15 '22 13:10

Elias Hossain