Home > Software design >  C# Guid.ToByteArray() equivalent in SqlServer
C# Guid.ToByteArray() equivalent in SqlServer

Time:12-16

C# has a buit-in function ToByteArray() please see below:

public byte[] ToByteArray()
{
    return new byte[16]
    {
        (byte)_a,
        (byte)(_a >> 8),
        (byte)(_a >> 16),
        (byte)(_a >> 24),
        (byte)_b,
        (byte)(_b >> 8),
        (byte)_c,
        (byte)(_c >> 8),
        _d,
        _e,
        _f,
        _g,
        _h,
        _i,
        _j,
        _k
    };
}

Is there any equivalent or an easy way to convert SqlServer's uniqueidentifier to get the same byte array (varbinary)?

Basically, I'm looking for equivalent of C#

byte[] arr = new Guid("FFFA9208-0391-4924-947F-C0556198D2FC").ToByteArray();

in Sql Server:

select MagicalFunction('FFFA9208-0391-4924-947F-C0556198D2FC') -- outputs varbinary

Thank you!

CodePudding user response:

Your psuedocode is this:

select MagicalFunction('FFFA9208-0391-4924-947F-C0556198D2FC') -- outputs varbinary

Currently your GUID is actually a textual type, so you will first need to convert it to a UNIQUEIDENTIFIER and then finally to a VARBINARY. You can do this like so:

SELECT CAST(CAST('FFFA9208-0391-4924-947F-C0556198D2FC' AS UNIQUEIDENTIFIER) AS VARBINARY(16))
  • Related