如何将整列转换为Base64字符串?

时间:2016-04-04 14:06:34

标签: sql-server sql-server-2012 sql-server-2008-r2 base64

我想将表的整列转换为Base64字符串。

例如我有下表:

|Id |EmailID       |
|123|test1@test.com|
|456|test2@test.com|

现在我想要输出如下:

|Id |EmailID       |Base64String                 |
|abc|test1@test.com|Base64 string of (Id+EmailID)|
|xyz|test2@test.com|Base64 string of (Id+EmailID)|

任何答案都将非常感谢。

先谢谢。

1 个答案:

答案 0 :(得分:0)

;WITH cte AS (
SELECT *
FROM (VALUES
(123, 'test1@test.com'),
(456, 'test2@test.com')
) AS t(Id, EmailID)
)

SELECT  Id,
        EmailID,
        CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("bin")))', 'NVARCHAR(MAX)') as Base64String
FROM (
    SELECT Id, EmailID, CAST(CAST(Id as nvarchar(10)) + EmailID AS VARBINARY(MAX)) AS bin
    FROM cte
) as t

输出:

Id          EmailID        Base64String
----------- -------------- ------------------------------------------------
123         test1@test.com MQAyADMAdABlAHMAdAAxAEAAdABlAHMAdAAuAGMAbwBtAA==
456         test2@test.com NAA1ADYAdABlAHMAdAAyAEAAdABlAHMAdAAuAGMAbwBtAA==

(2 row(s) affected)