Retrieve varbinary value as BASE64 in MSSQL

Finally found this article:

https://social.technet.microsoft.com/wiki/contents/articles/36388.transact-sql-convert-varbinary-to-base64-string-and-vice-versa.aspx#Convert_VARBINARY_to_Base64_String

So, running the query gets what I wanted, valid Base64.

Using XML and the hint "for xml path"

select Model, baze64
from __MigrationHistory
cross apply (select Model as '*' for xml path('')) T (baze64)

Other presented queries in article will also work

Using XML XQuery

Using JSON


It's apparently gzip'd xml. eg

SELECT MigrationId
      ,ContextKey
      ,cast(decompress(model) as xml) model
  FROM __MigrationHistory

Based on your solution I'm sharing the code for 2 scalar function for conversion in both direction:

Base64Decode

CREATE FUNCTION [dbo].[fnBase64ToBinary]
(
    @Str AS NVARCHAR(MAX)
)
RETURNS VARBINARY(MAX)
AS
BEGIN
    RETURN (
        SELECT
                CONVERT(
                    VARBINARY(MAX), CAST('' AS XML).value('xs:base64Binary(sql:column("BASE64_COLUMN"))', 'VARBINARY(MAX)')
                )
        FROM    (SELECT @Str AS BASE64_COLUMN) A
    );
END;

Base64 encode

CREATE FUNCTION [dbo].[fnBinaryToBase64]
(
    @Var AS VARBINARY(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    RETURN (
        SELECT  @Var AS '*' FOR XML PATH('')
    );
END;