I think it was v2008 of SQL-Server, when base64 was made the default in XML for binaries (before it was a hex string). No need to specify this explicitly.
(The option BINARY BASE64
is needed with mode AUTO
...)
Just to demonstrate the back and forth I declare some text (a chain of characters) and cast it to binary (the same chain of bytes, but not a string any more):
DECLARE @someText VARCHAR(100) = 'This is just some text...';
DECLARE @binary VARBINARY(MAX) = CAST(@someText AS VARBINARY(MAX));
--In this case it's okay to rely on implicit casting: easy approach
DECLARE @base64_easy VARCHAR(100) = (SELECT @binary FOR XML PATH(''));
--Just to demonstrate that the base64 we found (VGhpcyBpcyBqdXN0IHNvbWUgdGV4dC4uLg==
) is correct we reconvert it simply by casting it to XML
and using .value()
to retrieve it as binary
:
DECLARE @reConverted VARBINARY(MAX) = (SELECT CAST(@base64_easy AS XML).value('.','varbinary(max)'));
--Casting this chain of bytes into a varchar
again will show its (unchanged) content:
SELECT CAST(@reConverted AS VARCHAR(100));
All of this can be used within ad-hoc queries.
Hint:
The more explicit statement SELECT
s the value into XML and reads this into text via .value()
(The ,type
is needed to allow for XML methods)
DECLARE @base64 VARCHAR(100) = (SELECT @binary FOR XML PATH(''), type).value('.','nvarchar(max)'); --VGhpcyBpcyBqdXN0IHNvbWUgdGV4dC4uLg==