Search 
DailyCoding > Database

Generate New Guid (uniqueidentifier) in SQL Server

About how to generate a random unique identifier in using sql query in SQL server
Author admin on Jun 19, 2008 8 Comments
Rate it    (Rated 4 by 12 people)
13,133 Views

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

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')
Data | SQL

Discussion

shahzeb On Oct 14, 2008 10:35 PM
nice example...

Sachin Gaur On Dec 23, 2008 09:14 PM
That's really nice. But can we get the empty Guid in the SEELCT statement?

Randheer On Jan 20, 2009 11:02 PM
Here the system generates the unique identity itself.
But if I want to generate my own unique identifier using some other columns. Then how can I do it? Please tell the answer.

Name On Feb 18, 2009 07:32 AM
super

Reddymade On Jul 16, 2009 08:57 AM
How can I gernerate a GUID on existing records on a data table?

Alfonso Paredes On Aug 8, 2009 10:11 AM
Reddymade

you can do something like the following

update people
set personId=NEWID()

CM On Sep 24, 2009 03:35 PM
Above didn't work for me so I used a derived table to create an 8 character default password within an existing table.

UPDATE Customers
SET custPword = newPass.newPass
FROM (SELECT Left( NEWID(),8) AS newPass) AS newPass

Pooja On Oct 21, 2009 10:59 AM
That's a good example, compact and perfect.

Leave a Comment

Name
Email Address
Web Site
© Copyright 2008 Daily Coding • All rights reserved