用户登录
用户注册

分享至

NewID()创建uniqueidentifier类型的唯一值

  • 作者: 呆琲琲
  • 来源: 51数据库
  • 2021-07-30

newid()创建uniqueidentifier类型的唯一值

 

创建 uniqueidentifier 类型的唯一值。

 

语法

newid ( )

 

返回类型

uniqueidentifier

 

示例

a.对变量使用 newid 函数

下面的示例使用 newid 对声明为 uniqueidentifier 数据类型的变量赋值。在测试该值前,将先打印 uniqueidentifier 数据类型变量的值。

 

-- creating a local variable with declare/set syntax.
declare @myid uniqueidentifier
set @myid = newid()
print 'value of @myid is: '+ convert(varchar(255), @myid)

 

下面是结果集:

 

value of @myid is: 6f9619ff-8b86-d011-b42d-00c04fc964ff

 

 

说明  对于每台计算机,由 newid 返回的值不同。所显示的数字仅起解释说明的作用。

 

b.在 create table 语句中使用 newid

下面的示例创建具有 uniqueidentifier 数据类型的 cust 表,并使用 newid 将默认值填充到表中。为 newid() 赋默认值时,每个新行和现有行均具有 cust_id 列的唯一值。

 

-- creating a table using newid for uniqueidentifier data type.
create table cust
(
cust_id uniqueidentifier not null
default newid(),
company varchar(30) not null,
contact_name varchar(60) not null,
address varchar(30) not null,
city varchar(30) not null,
state_province varchar(10) null,
postal_code varchar(10) not null,
country varchar(20) not null,
telephone varchar(15) not null,
fax varchar(15) null
)
go
-- inserting data into cust table.
insert cust
(cust_id, company, contact_name, address, city, state_province,
postal_code, country, telephone, fax)
values
(newid(), 'wartian herkku', 'pirkko koskitalo', 'torikatu 38', 'oulu', null,
'90110', 'finland', '981-443655', '981-443655')
insert cust
(cust_id, company, contact_name, address, city, state_province,
postal_code, country, telephone, fax)
values
(newid(), 'wellington importadora', 'paula parente', 'rua do mercado, 12', 'resende', 'sp',
'08737-363', 'brazil', '(14) 555-8122', '')
insert cust
(cust_id, company, contact_name, address, city, state_province,
postal_code, country, telephone, fax)
values
(newid(), 'cactus comidas para ilevar', 'patricio simpson', 'cerrito 333', 'buenos aires', null,
'1010', 'argentina', '(1) 135-5555', '(1) 135-4892')
insert cust
(cust_id, company, contact_name, address, city, state_province,
postal_code, country, telephone, fax)
values
(newid(), 'ernst handel', 'roland mendel', 'kirchgasse 6', 'graz', null,
'8010', 'austria', '7675-3425', '7675-3426')
insert cust
(cust_id, company, contact_name, address, city, state_province,
postal_code, country, telephone, fax)
values
(newid(), 'maison dewey', 'catherine dewey', 'rue joseph-bens 532', 'bruxelles', null,
'b-1180', 'belgium', '(02) 201 24 67', '(02) 201 24 68')
go
c. 使用 uniqueidentifier 和变量赋值
下面的示例声明局部变量 @myid 为 uniqueidentifier 数据类型。然后使用 set 语句为该变量赋值。

declare @myid uniqueidentifier
set @myid = 'a972c577-dfb0-064e-1189-0154c99310daac12'
go

 


软件
前端设计
程序设计
Java相关