了解SQL Server中的GUID数据类型

GUID是SQL Server中一种16字节的全局唯一标识符,用于在表、数据库和服务器间创建唯一的主键。NEWID()函数用于生成GUID。当在不同数据库中存在冗余记录时,使用GUID可以避免主键冲突。通过将INT主键替换为UNIQUEIDENTIFIER,可以实现跨数据库的记录唯一性。
摘要由CSDN通过智能技术生成

什么是GUID? (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.

GUID是16字节的二进制SQL Server数据类型,在表,数据库和服务器之间全局唯一。 GUID代表全局唯一标识符,可与UNIQUEIDENTIFIER互换使用。

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

要在SQL Server中创建GUID,将使用NEWID()函数,如下所示:

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.

多次执行上面SQL行,您每次都会看到一个不同的值。 这是因为NEWID()函数每执行一次都会生成一个唯一值。

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

要声明类型为GUID的变量,使用的关键字是UNIQUEIDENTIFIER,如以下脚本中所述:

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.

如前所述,GUID值在表,数据库和服务器之间是唯一的。 GUID可以视为全局主键。 本地主键用于唯一标识表中的记录。 另一方面,GUID可用于唯一地标识跨表,数据库和服务器的记录。

问题GUID解决了 (The Problem GUID Solves)

Let’s see what issues we face if we have redundant records within tables across different databases and how GUID solves these issues.

让我们看看如果我们在不同数据库的表中有冗余记录会遇到什么问题,以及GUID如何解决这些问题。

Execute the following script.

执行以下脚本。

CREATE DATABASE EngDB
GO
 
USE EngDB
GO
 
CREATE TABLE EnglishStudents
(
	Id INT PRIMARY KEY IDENTITY,
	StudentName VARCHAR (50)
 
)
GO
 
INSERT INTO EnglishStudents VALUES ('Shane')
INSERT INTO EnglishStudents VALUES ('Jonny')

In the script above, we create a database named “EngDB”. We then create a table “EnglishStudents” within this database. The table has two columns: Id and StudentName. The Id column is the primary key column and we set it to auto increment using Identity as the constraint. Finally, we insert two records for students called ‘Shane’ and ‘Jonny’ into the “EnglishStudents” table.

在上面的脚本中,我们创建一个名为“ EngDB”的数据库。 然后,我们在此数据库中创建一个表“ EnglishStudents”。 该表有两列:Id和StudentName。 Id列是主键列,我们使用Identity作为约束将其设置为自动递增。 最后,我们将两个名为“ Shane”和“ Jonny”的学生记录插入“ EnglishStudents”表中。

Now if you select all the records from the “EnglishStudents” table, you should see the following output:

现在,如果您从“ EnglishStudents”表中选择所有记录,您将看到以下输出:

Id StudentName
1 Shane
2 Jonny
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值