How to generate a Guid in SQL Server?

SqlSql Server

Sql Problem Overview


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

Sql Solutions


Solution 1 - Sql

try this:

SELECT NEWID()

hope helped you

Solution 2 - Sql

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

Solution 3 - Sql

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlmaView Question on Stackoverflow
Solution 1 - SqlAmazigh.CaView Answer on Stackoverflow
Solution 2 - SqlManish Kumar GurjarView Answer on Stackoverflow
Solution 3 - SqlDiego VenâncioView Answer on Stackoverflow