简体   繁体   中英

Converting entire table column of varchar/varbinary to xml

I have a table with one of the columns as varbinary, which actually contains base64 encoded string.

Table: Messages
Id        |   int
Payload   |   varbinary(MAX)

I can see its contents using

select cast(Payload as varchar(max)) from Messages

However, I need to convert the whole column to XMl, so that these kind of cast is not required and I can store much longer strings as XML. For a single entry I can do something like

select convert(xml, (select top 1 cast(payload as varchar(max)) 
                     from Messages
                    )
              ) as PayLoad 
for XML PATH('');

How do I convert the whole table to xml?

Thanks

This should work for you:

CREATE TABLE #temp(ID INT,PayLoad VARBINARY(MAX));
INSERT INTO #temp VALUES
                 (1,CAST('AAQSkZJRgABAQEAYABgAAD/4RDmRXhpZg' AS VARBINARY(MAX)))
                ,(2,CAST('AAAAJAAAISodpAAQAAAABAAAIVJydAAEAAAASAAAQz' AS VARBINARY(MAX)));  

--simple output
SELECT * 
FROM #temp;

--casted output
SELECT ID,CAST(PayLoad AS VARCHAR(MAX)) AS PayLoad 
FROM #temp;

--AS XML
SELECT ID
      ,CAST(PayLoad AS VARCHAR(MAX)) AS PayLoad
FROM #temp 
FOR XML PATH('Row'),ROOT('root');

--EDIT: new SELECT
--As table with Payload as XML
SELECT ID
      ,(SELECT CAST(PayLoad AS VARCHAR(MAX)) FOR XML PATH('PayLoad'),TYPE) AS PayLoad
FROM #temp 

DROP TABLE #temp;

How about using for xml path ?

select cast(Payload as varchar(max))
from Messages
for xml path ('');

You can include the appropriate annotations. You can also have multiple columns. The documentation is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM