Base64 encoding in SQL Server 2005 T-SQL

后端 未结 10 808
傲寒
傲寒 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:39

    DECLARE @source varbinary(max),  
    @encoded_base64 varchar(max),  
    @decoded varbinary(max) 
    SET @source = CONVERT(varbinary(max), 'welcome') 
    -- Convert from varbinary to base64 string 
    SET @encoded_base64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable       
    ("@source"))', 'varchar(max)') 
      -- Convert back from base64 to varbinary 
       SET @decoded = CAST(N'' AS xml).value('xs:base64Binary(sql:variable             
      ("@encoded_base64"))', 'varbinary(max)') 
    
     SELECT
      CONVERT(varchar(max), @source) AS [Source varchar], 
       @source AS [Source varbinary], 
         @encoded_base64 AS [Encoded base64], 
         @decoded AS [Decoded varbinary], 
         CONVERT(varchar(max), @decoded) AS [Decoded varchar]
    

    This is usefull for encode and decode.

    By Bharat J

提交回复
热议问题