什么是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 |