Base64 encoding in SQL Server 2005 T-SQL

后端 未结 10 1056
傲寒
傲寒 2020-11-22 10:06

I\'d like to write a T-SQL query where I encode a string as a Base64 string. Surprisingly, I can\'t find any native T-SQL functions for doing Base64 encoding. Does a nativ

10条回答
  •  借酒劲吻你
    2020-11-22 10:29

    Here's a modification to mercurial's answer that uses the subquery on the decode as well, allowing the use of variables in both instances.

    DECLARE
        @EncodeIn VARCHAR(100) = 'Test String In',
        @EncodeOut VARCHAR(500),
        @DecodeOut VARCHAR(200)    
    
    SELECT @EncodeOut = 
        CAST(N'' AS XML).value(
              'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
            , 'VARCHAR(MAX)'
        )
    FROM (
        SELECT CAST(@EncodeIn AS VARBINARY(MAX)) AS bin
    ) AS bin_sql_server_temp;
    
    PRINT @EncodeOut
    
    SELECT @DecodeOut = 
    CAST(
        CAST(N'' AS XML).value(
            'xs:base64Binary(sql:column("bin"))'
          , 'VARBINARY(MAX)'
        ) 
        AS VARCHAR(MAX)
    ) 
    FROM (
        SELECT CAST(@EncodeOut AS VARCHAR(MAX)) AS bin
    ) AS bin_sql_server_temp;
    
    PRINT @DecodeOut
    

提交回复
热议问题