February 22, 2016

MS SQL : Use of GUID function

If you want to generate a new Guid (Unique Identifier) 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

--To 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( ), 'Shyam Sundar', '123-4567')

No comments:

Post a Comment