uniqueidentifier中文含义“唯一的标识符”。
uniqueidentifier数据类型是16个字节的二进制值,应具有唯一性,必须与NEWID()函数配合使用。
uniqueidentifier数据类型与identity自增不同,不会为插入的新行自动生成新的ID,新值由NEWID()函数指定。
NEWID()函数值会生成全球唯一的标识,标识由网卡号和CPU时钟组成,如:6F9619FF-8B86-D011-B42D-00C04FC964FF
CREATE TABLE MyUniqueTable |
(UniqueColumn UNIQUEIDENTIFIER DEFAULT NEWID(), |
INSERT INTO MyUniqueTable(Characters) VALUES ('abc') |
INSERT INTO MyUniqueTable VALUES (NEWID(), 'def') |
一个表可以定义多个uniqueidentifier列。
对变量使用NEWID()函数
DECLARE @myid uniqueidentifier |
PRINT 'Value of @myid is: '+ CONVERT(varchar(255), @myid) |
在 CREATE TABLE 语句中使用 NEWID
-- Creating a table using NEWID for uniqueidentifier data type. |
CustomerID uniqueidentifier NOT NULL |
Company varchar(30) NOT NULL, |
ContactName varchar(60) NOT NULL, |
Address varchar(30) NOT NULL, |
City varchar(30) NOT NULL, |
StateProvince varchar(10) NULL, |
PostalCode varchar(10) NOT NULL, |
CountryRegion varchar(20) NOT NULL, |
Telephone varchar(15) NOT NULL, |
-- Inserting data into cust table. |
(CustomerID, Company, ContactName, Address, City, StateProvince, |
PostalCode, CountryRegion, Telephone, Fax) |
(NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL, |
'90110', 'Finland', '981-443655', '981-443655') |
(CustomerID, Company, ContactName, Address, City, StateProvince, |
PostalCode, CountryRegion, Telephone, Fax) |
(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP', |
'08737-363', 'Brasil', '(14) 555-8122', '') |
(CustomerID, Company, ContactName, Address, City, StateProvince, |
PostalCode, CountryRegion, Telephone, Fax) |
(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL, |
'1010', 'Argentina', '(1) 135-5555', '(1) 135-4892') |
(CustomerID, Company, ContactName, Address, City, StateProvince, |
PostalCode, CountryRegion, Telephone, Fax) |
(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL, |
'8010', 'Austria', '7675-3425', '7675-3426') |
(CustomerID, Company, ContactName, Address, City, StateProvince, |
PostalCode, CountryRegion, Telephone, Fax) |
(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL, |
'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68') |
使用 uniqueidentifier 和变量赋值,将名为 @myid 的局部变量声明为 uniqueidentifier 数据类型的变量。然后使用 SET 语句为该变量赋值。 |
DECLARE @myid uniqueidentifier |
SET @myid = 'A972C577-DFB0-064E-1189-0154C99310DAAC12' |
|