简体   繁体   中英

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

这将在 SQL Server 中生成一个 Guid:

SELECT NEWID()

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

在此处输入图像描述

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM