Reputation: 3292
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
Upvotes: 1
Views: 1285
Reputation: 67311
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;
Upvotes: 2
Reputation: 1269873
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.
Upvotes: 0