How to generate a Guid in SQL Server?

I need to create an Id as Guid in SQL(no identity) How I can do this? I defined the Id as uniqueidentifier but what is save in Db is 00000000-0000-0000-0000-000000000000


try this:

SELECT NEWID()

hope helped you


What is a GUID? GUID is a 16 byte binary SQL Server data type that is globally unique across tables, databases, and servers. The term GUID stands for Globally Unique Identifier and it is used interchangeably with UNIQUEIDENTIFIER.

To create a GUID in SQL Server, the NEWID() function is used as shown below:

SELECT NEWID()

Execute the above line of SQL multiple times and you will see a different value every time. This is because the NEWID() function generates a unique value whenever you execute it.

To declare a variable of type GUID, the keyword used is UNIQUEIDENTIFIER as mentioned in the script below:

DECLARE @UNI UNIQUEIDENTIFIER;
SET @UNI = NEWID(); 
SELECT @UNI;

As mentioned earlier, GUID values are unique across tables, databases, and servers. GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table. On the other hand, GUIDs can be used to uniquely identify records across tables, databases, and servers.

For Example:

create table AspNetUsers
(
Id UNIQUEIDENTIFIER PRIMARY KEY default NEWID(),
Name nvarchar(200)
)

INSERT INTO AspNetUsers VALUES (default,'Shane')
INSERT INTO AspNetUsers VALUES (default,'Jonny')

select * from AspNetUsers

enter image description here


A aspnet role created manually

DECLARE @ID UNIQUEIDENTIFIER
SET @ID = NEWID()

DECLARE @STAMP UNIQUEIDENTIFIER
SET @STAMP = NEWID()

INSERT INTO [dbo].[AspNetRoles]
           ([Id]
           ,[Name]
           ,[NormalizedName]
           ,[ConcurrencyStamp])
     VALUES
           (@ID
           ,'Admin'
           ,'ADMIN'
           ,@STAMP)