SQL Server中Base64編碼

declare @source varbinary(max), @encoded varchar(max), @decoded varbinary(max) 
set @source = convert(varbinary(max), 'Hello Base64') 
set @encoded = cast('' as xml).value('xs:base64Binary(sql:variable(''@source''))', 'varchar(max)') 
set @decoded = cast('' as xml).value('xs:base64Binary(sql:variable(''@encoded''))', 'varbinary(max)') 
 
select 
convert(varchar(max), @source) as source_varchar, 
@source as source_binary, 
@encoded as encoded, 
@decoded as decoded_binary, 
convert(varchar(max), @decoded) as decoded_varchar 

可以直接書寫為兩個標量值函數

Alter FUNCTION [dbo].[FromBase64] 
( 
        @encoded varchar(max) 
) 
RETURNS varchar(max) 
AS 
BEGIN 
        
        declare @decoded varbinary(max) 
        set @decoded = cast('' as xml).value('xs:base64Binary(sql:variable(''@encoded''))', 'varbinary(max)') 
        RETURN convert(varchar(max), @decoded) 
 
 
END 
GO 
 
 
Alter FUNCTION [dbo].[ToBase64] 
( 
        @source varbinary(max) 
) 
RETURNS varchar(max) 
AS 
BEGIN 
        
        RETURN cast('' as xml).value('xs:base64Binary(sql:variable(''@source''))', 'varchar(max)') 
 
END 
GO 

 

--BASE64编码
CREATE FUNCTION [dbo].[FnBase64Encode](@src varchar(max))
  RETURNS VARCHAR(max)
as
begin
  declare @bin varbinary(max)
  set @bin=Convert(varbinary(max), @src)
  return cast(N'' as xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@bin")))', 'varchar(max)')
end
GO

 

--BASE64解码

CREATE FUNCTION [dbo].[FnBase64Decode](@64 varchar(max))
  RETURNs VARCHAR(max)
AS
BEGIN
  declare @bin varbinary(max)
  set @bin=cast(N'' as xml).value('xs:base64Binary(sql:variable("@64"))', 'varbinary(max)')
  return Convert(varchar(max),@bin)
END
GO

--测试案例


declare @source varbinary(max), @encoded varchar(max), @decoded varbinary(max) 
set @source = convert(varbinary(max), 'Hello Base64') 
set @encoded = cast('' as xml).value('xs:base64Binary(sql:variable(''@source''))', 'varchar(max)') 
set @decoded = cast('' as xml).value('xs:base64Binary(sql:variable(''@encoded''))', 'varbinary(max)') 
 
select 
convert(varchar(max), @source) as source_varchar, 
@source as source_binary, 
@encoded as encoded, 
@decoded as decoded_binary, 
convert(varchar(max), @decoded) as decoded_varchar

你可能感兴趣的:(SQL,Server)