Stweet
Stweet

Reputation: 713

SQL Server : hex to base64

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 :/

Upvotes: 6

Views: 4521

Answers (2)

Tim
Tim

Reputation: 6060

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;

Upvotes: 7

dadde
dadde

Reputation: 659

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;

Upvotes: 0

Related Questions