Generate New GUID (uniqueidentifier) in SQL Server

What is new GUID?

The New-GUID cmdlet creates a random globally unique identifier (GUID). If you need a unique ID in a script, you can create a GUID, as needed.

What is Uniqueidentifier datatype in SQL Server?

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.

What is a valid GUID?

Generate New GUID, The valid GUID (Globally Unique Identifier) must specify the following conditions: It should be 36 characters (32 hexadecimal characters and 4 hyphens) long. It should be displayed in five groups separated by hyphens (-). Microsoft GUIDs are sometimes represented with surrounding brace

If you want to generate a new Guid (uniqueidentifier) in SQL server the you can simply use the NEWID() function.

Example

SELECT NEWID()
GO
— This will return a new random uniqueidentifier e.g.
E75B92A3-3299-4407-A913-C5CA196B3CAB

To select this Guid in in a variable

–assign uniqueidentifier in a variable
DECLARE @EmployeeID uniqueidentifier
SET @EmployeeID = NEWID()

You can directly use this with INSERT statement to insert new row in table.

— Inserting data in Employees table.
INSERT INTO Employees
(EmployeeID, Name, Phone)
VALUES
(NEWID(), ‘John Kris’, ’99-99999′)

Happy Coding 🙂


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top