Base64 encoding in SQL Server 2005 T-SQL

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

    Pulling in things from all the answers above, here's what I came up with.

    There are essentially two ways to do this:

    ;WITH TMP AS (
        SELECT CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("bin")))', 'VARCHAR(MAX)') as  Base64Encoding
        FROM 
        (
            SELECT TOP 10000 CAST(Words AS VARBINARY(MAX)) AS bin FROM TestData
        ) SRC
    ) 
    
    SELECT *, CAST(CAST(N'' AS XML).value('xs:base64Binary(sql:column("Base64Encoding"))', 'VARBINARY(MAX)') AS NVARCHAR(MAX)) as ASCIIEncoding
    FROM
    (
        SELECT * FROM TMP
    ) SRC
    
    

    And the second way

    ;WITH TMP AS 
    (
        SELECT TOP 10000 CONVERT(VARCHAR(MAX), (SELECT CAST(Wordsas varbinary(max)) FOR XML PATH(''))) as BX
        FROM TestData
    )
    
    SELECT *, CONVERT(NVARCHAR(MAX), CONVERT(XML, BX).value('.','varbinary(max)'))
    FROM TMP
    

    When comparing performance, the first one has a subtree cost of 2.4414 and the second one has a subtree cost of 4.1538. Which means the first one is about twice as fast as the second one (which is expected, since it uses XML, which is notoriously slow).

提交回复
热议问题