Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary to uniqueidentifier in t-sql?

I have the following code that converts Unique-identifier to Binary:

CAST(GUID AS BINARY(16))

which results in this '0x56B3C0955919CD40931F550749A83AF3'

Now, I want to convert this (i.e. the binary string value '0x56B3C0955919CD40931F550749A83AF3') to Unique-Identifier.

Any simple way to achieve this?

like image 989
Learner Avatar asked Jul 09 '13 20:07

Learner


1 Answers

Uh, just convert it back?

DECLARE @n UNIQUEIDENTIFIER = NEWID();

SELECT @n;
SELECT CONVERT(BINARY(16), @n);
SELECT CONVERT(UNIQUEIDENTIFIER, CONVERT(BINARY(16), @n));

If you have a binary value like 0x56B3C0955919CD40931F550749A83AF3, stop putting it into quotes when trying to convert it. For example:

SELECT CONVERT(UNIQUEIDENTIFIER, 0x56B3C0955919CD40931F550749A83AF3);

Isn't this the result you're after?

95C0B356-1959-40CD-931F-550749A83AF3
like image 110
Aaron Bertrand Avatar answered Sep 27 '22 22:09

Aaron Bertrand