SQL GUID和自增列做主键的优缺点 (转)

转载自:http://www.cnblogs.com/allen0118/p/4103322.html

--
创建数据库 create database MyTest --引用数据库 use MyTest /* uniqueidentifier(Guid)字段 在MS Sql 数据库中可以在建立表结构是指定字段类型为uniqueidentifier, 并且其默认值可以使用NewID()来生成唯一的Guid(全局唯一标识符).使用 NewID生成的比较随机,如果是SQL 2005可以使用NewSequentialid()来顺序生成, 在此为了兼顾使用SQL 2000使用了NewID(). NewSequentialid()只能在创建表时当做默认值设置,不能在插入记录时使用 */ create table [User] ( [Guid] uniqueidentifier NOT NULL DEFAULT(NewSequentialid()) primary key , StudentId int not null , Email varchar(100) not null, [Password] varchar(100) not null ) --给创建好的表设置主键 alter table [User] add constraint PK_Guid primary key([Guid]) --删除约束 alter table [User] drop constraint PK_Guid --修改字段类型 alter table [User] alter column StudentId int not null alter table [User] alter column Email varchar(100) not null alter table [User] alter column [Password] varchar(100) not null --增加列 alter table [User] add column XX int not null --删除列 alter table [User] drop column XX --删除表 drop table [User] insert into [User](StudentId,Email,[Password]) values(1001,'100@qq.com','0000')
--sql 所有的表建好后,为表添加外键约束 

alter table B

--cc是外键约束名,不能重复,也不能是int类型(如1,2,3)

add constraint cc

--B表里的需要约束的字段(id)

foreign key (id)

--A表后的(id)可省略

references A (id) 

 


/*
使用INT做主键的优点:

    1、需要很小的数据存储空间,仅仅需要4 byte 。

    2、insert和update操作时使用INT的性能比GUID好,所以使用int将会提高应用程序的性能。

    3、index和Join 操作,int的性能最好。

    4、容易记忆。

    5、支持通过函数获取最新的值,如:Scope_Indentity() 。

使用INT做主键的缺点

    1、如果经常有合并表的操作,就可能会出现主键重复的情况。

    2、使用INT数据范围有限制。如果存在大量的数据,可能会超出INT的取值范围。

    3、很难处理分布式存储的数据表。

使用GUID做主键的优点:

    1、它是独一无二的。

    2、出现重复的机会少。

    3、适合大量数据中的插入和更新操作。

    4、跨服务器数据合并非常方便。

使用GUID做主键的缺点:

    1、存储空间大(16 byte),因此它将会占用更多的磁盘大小。

    2、很难记忆。join操作性能比int要低。

    3、没有内置的函数获取最新产生的guid主键。

    4、GUID做主键将会添加到表上的所以其他索引中,因此会降低性能。

总结:

    上面列出了GUID和INT两种数据类型做主键优缺点。我觉得,对于大数据量,建议使用guid做主键。而使用int会得到最佳的性能。
*/

 

posted @ 2015-08-12 11:40  清幽紫竹  Views(589)  Comments(0)    收藏  举报