摘要:
当我们在设计表时,通常需要为主业务表设置一个数据库系统内部ID作为主键,
下文讲述通过标识列和全球唯一标识列作为默认值设置主键的方法,
如下所示:
实验环境:sql server 2008 R2
方法1:标识列生成主键
---由于表test中列keyId指定了identity属性,因此插入时,不能指定值,系统会自动默认keyId中的值,
---此标识信息,由数据库底层控制,不会出现重复值,并且会按照标识种子的定义,依次流水下来。
create table test (keyId int identity(1,1) primary key,info varchar(30))
go
insert into test(info)values('maomao365.com')
insert into test(info)values(N'sql教程')
go
truncate table test
drop table test
方法2:全球唯一标识列生成主键
---表test中列keyId指定了默认值newId(),由于newId会自动生成全球唯一标识信息,此值永远都不会重复
create table test (keyId uniqueidentifier default newId() primary key,
info varchar(30))
go
insert into test(info)values('maomao365.com')
insert into test(info)values(N'sql教程')
go
truncate table test
drop table test