string to base64 or base64 to string in ms sql server

代码如下:

源代码:

CREATE FUNCTION [dbo].[svf_StringToBase64] 
(
    @input NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN   
  RETURN (SELECT CAST(@input AS VARBINARY(MAX)) FOR XML PATH(''))
END
GO

CREATE FUNCTION [dbo].[svf_Base64ToString] 
(
    @input NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX) 
AS
BEGIN 
  RETURN (SELECT CAST(CAST(@input AS XML).value('.','VARBINARY(MAX)') AS NVARCHAR(MAX)))
END
GO
Source Code

 

 

实例:

 

源代码:

SELECT [dbo].[svf_StringToBase64] (N'insus.net@中国')
GO

SELECT [dbo].[svf_Base64ToString] (N'aQBuAHMAdQBzAC4AbgBlAHQAQAAtTv1W')
GO
Source Code

 

以下内容于2022-06-14 08:45添加:

 

源代码:

CREATE FUNCTION [dbo].[svf_Base64_Encode] (
    @string NVARCHAR(MAX)
) 
RETURNS NVARCHAR(MAX)
AS BEGIN
 
    DECLARE 
        @source VARBINARY(MAX), 
        @encoded NVARCHAR(MAX)
        
    SET @source = CONVERT(VARBINARY(MAX), @string)
    SET @encoded = CAST('' AS XML).value('xs:base64Binary(sql:variable("@source"))', 'NVARCHAR(MAX)')
 
    RETURN @encoded 
END
GO

CREATE FUNCTION [dbo].[svf_Base64_Decode] (
    @string NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS BEGIN
 
    DECLARE @decoded NVARCHAR(MAX)
    SET @decoded = CAST('' AS XML).value('xs:base64Binary(sql:variable("@string"))', 'VARBINARY(MAX)')
 
    RETURN CONVERT(NVARCHAR(MAX), @decoded)    
END
GO
Source Code

 

posted @ 2022-06-13 22:14  Insus.NET  阅读(267)  评论(0编辑  收藏  举报