MsSql hex - base64

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

tried google tho, I can't find anything like it: /

+4
source share
2 answers

You can convert hex to varbinary using your own sql parser:

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 cause sp_executesql to execute dynamic SQL containing the 0x012345 literal, which perfectly understands the T-SQL parser. You can then pass the results of this into the XML trick referenced 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;
+2
source

, , hex:

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

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;
0

Source: https://habr.com/ru/post/1667332/


All Articles