Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from UniqueIdentifier to BigInt and Back?

declare @uu uniqueidentifier =  'C50B0567-F8CC-4219-A1E1-91C97BD9AE1B'
select @uu
declare @zaza bigint = ( select convert(bigint, convert (varbinary(8), @uu, 1)) )
select @zaza
select CONVERT( uniqueidentifier , convert( varbinary(16) , @zaza , 1 ) )

I thought I had a fast way to convert Unique Identifier values to a Big Int, and back. But there is a problem in my second convert. Can anyone comment on the right way to fully convert a GUID to a number and back? I am only getting part of the GUID and not the whole thing when I try to convert it back from the numeric representation to its original GUID.

I want to pass an integer (I think it would be classified as a "Large BigInt" in MSSQL?) to a remote system and just use characters 0-9, and still get the random uniqueness of NewId().

like image 493
Snowy Avatar asked Apr 09 '12 18:04

Snowy


People also ask

What data type is Uniqueidentifier?

The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites.

Can Uniqueidentifier be null in SQL?

You can make uniqueidentifiers null.

How do you use Uniqueidentifier?

Create a variable of uniqueidentifier data type. Type the below code in SSMS and execute. DECLARE @guid uniqueidentifier = NEWID(); SELECT @guid as 'GUID'; Here we created a variable named guid of data type uniqueidentifier.

How do I get the new Uniqueidentifier in SQL?

-- If you want to generate a new Guid (uniqueidentifier) in SQL server the you can simply use the NEWID() function. -- This will return a new random uniqueidentifier e.g. You can directly use this with INSERT statement to insert new row in table.


1 Answers

There is no problem with your second convert. When I run your SQL statement in SQL management studio, I get:

------------------------------------
C50B0567-F8CC-4219-A1E1-91C97BD9AE1B

(1 row(s) affected)


--------------------
7423352504965404994

(1 row(s) affected)


------------------------------------
C50B0567-F8CC-4219-0000-000000000000

(1 row(s) affected)

Since you are converting 8 byte value to 16-byte guid, half of guid will be zeroes, which is exactly what you are seeing.

like image 92
galets Avatar answered Oct 12 '22 23:10

galets