SQL Server : hex to base64
Asked Answered
O

2

6

I have a SQL Server database with jpeg images stored as hex (0xFFD8...) Is there a way to do a query where result will be in base64 instead of hex?

I tried to google but I can't find anything like it :/

Otilia answered 20/1, 2017 at 7:40 Comment(4)
Probably a duplicate of #5082845. The accepted answer should meet your requirement. (I can't vote to close as a duplicate because of the open bounty)Pontius
@EdHarper Not really, thats a string to base64, the question was hex to base64.Urial
@Urial - minimal changes are required to make the answer I linked to work on a binary data type. I stand by the assertion that this is a duplicate.Pontius
@EdHarper okay, I was also looking at that answer but I think the main problem here is the hex conversion, not the base64 conversion. I respect your comment though.Urial
H
7

You can convert hex to to varbinary by leveraging the sql parser itself:

DECLARE @TestBinHex varchar(max), @TestBinary varbinary(max), @Statement nvarchar(max);
SELECT @TestBinHex = '0x012345';
SELECT @Statement = N'SELECT @binaryResult = ' + @TestBinHex;
EXECUTE sp_executesql @Statement, N'@binaryResult varbinary(max) OUTPUT', @binaryResult=@TestBinary OUTPUT;
SELECT @TestBinary

This will get sp_executesql to execute dynamic SQL containing the literal 0x012345 which the T-SQL parser understands perfectly well. You can then feed the results of that into the XML trick referred to by @EdHarper as shown below:

DECLARE @TestBinHex varchar(max), @TestBinary varbinary(max), @Statement nvarchar(max);
SELECT @TestBinHex = '0x012345';
SELECT @Statement = N'SELECT @binaryResult = ' + @TestBinHex;
EXECUTE sp_executesql @Statement, N'@binaryResult varbinary(max) OUTPUT', @binaryResult=@TestBinary OUTPUT;

SELECT
    CAST(N'' AS XML).value(
          'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
        , 'VARCHAR(MAX)'
    )   Base64Encoding
FROM (
    SELECT @TestBinary AS bin
) AS bin_sql_server_temp;
Holstein answered 30/1, 2017 at 0:12 Comment(3)
This was really helpful - just saved me a lot of work. Thank youApterous
@RobP. if this solved your issue, why not marking this answer as correct?Middlings
@Middlings - I'm not the asker, but it did help me out a lot.Apterous
U
0

Here's an example on a table containing a image stored as hex:

create table t (s image,s_base64 varchar(max));
insert t(s)
values(CAST('This is an image column' as image));

And here's an example on casting the hex image to base64

 create view v
 as
 select CAST(s as varbinary(max)) as s,s_base64 from t;
 GO
 update v set s_base64= CAST(N'' AS xml).value('xs:base64Binary(sql:column("v.s"))', 'varchar(max)');
 GO

 select * from v;
Urial answered 25/1, 2017 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.