I have an Image saved as varbinary(max)
in SQL Server 2014:
0xFFD8FFE115064578696600004D4D002A0000000800070...........
I want to convert it to Base64 To use it in Flutter. I tried
SELECT CAST('' as varbinary(max)) FOR XML PATH(''), BINARY BASE64
and get :
MHhGRkQ4RkZFMTE1MDY0NTc4Njk2NjAwMDA0RDREMDAyQTAwMDAwMDA4MDAwN..........
But according to this site I should get:
/9j/4RUGRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEaAAUAAAABAAAAYgEbAA........
So how to convert varbinary(max)
to base64?
3条答案
按热度按时间ztyzrc3y1#
To select a bare Base64 value in SQL Server, without any XML node around it, you just need an unnamed column in
FOR XML
Or as a correlated subquery
db<>fiddle
wljmcqd82#
Why are you attempting to
CAST()
the varbinary data? You just need to select it as an element or an attribute for the varbinary value to get base64 encoded...The first select outputs the base data in an element:
The second select outputs the base64 data in an attribute:
Following comments discussion with @DaleK, a third alternative to return the bare base64 characters without any XML tags:
Which outputs:
e5njpo683#
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 modeAUTO
...)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):
--In this case it's okay to rely on implicit casting: easy approach
--Just to demonstrate that the base64 we found (
VGhpcyBpcyBqdXN0IHNvbWUgdGV4dC4uLg==
) is correct we reconvert it simply by casting it toXML
and using.value()
to retrieve it asbinary
:--Casting this chain of bytes into a
varchar
again will show its (unchanged) content: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)