Thursday, September 06, 2012

Sql Server converting Base64 to varchar and back

Especially useful to convert all the CRM data stored in the MSCRM database

Convert from base64 to varchar:

DECLARE
    @Encoded VARCHAR(max) = 'VGVzdA==',
    @Decoded VARCHAR(max)   
SELECT @Decoded = 
CAST(
    CAST(N'' AS XML).value(
        'xs:base64Binary(sql:column("bin"))'
      , 'VARBINARY(MAX)'
    )
    AS VARCHAR(MAX)
)
FROM (
    SELECT CAST(@Encoded AS VARCHAR(MAX)) AS bin
) AS bin_sql_server_temp;
PRINT @Decoded 

Convert from varchar to base64:

DECLARE
    @plain VARCHAR(max) = 'Test',
    @encoded VARCHAR(max)
SELECT @encoded = 
    CAST(N'' AS XML).value(
          'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
        , 'VARCHAR(MAX)'
    )
FROM (
    SELECT CAST(@plain AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp;

PRINT @encoded

2 comments:

KARTHICK J said...

Thanks for the wonderful article. It saved my time.

Retro Games said...

Your Test example makes a good check outside SQL Server too: with no space or newline the four ASCII bytes give VGVzdA==. Accidentally encoding the UTF-16 bytes of an NVARCHAR changes the result even though PRINT shows the same word. I maintain a browser encoder for comparing test strings: https://base64encode.si/