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

1 comment:

KARTHICK J said...

Thanks for the wonderful article. It saved my time.