日期:2014-05-18 浏览次数:21477 次
在数据库表设计时,许多人为采用INT类型还是GUID(uniqueidentifyer)作为主键争论不休,有认为int型字段好的,有认为GUID好的,很多时候的焦点集中在效率上。
为了弄清事实真相,我想还是要以实验来进行测试为准。以下就是为了测试插入效率而写的一段脚本。测试环境是:Xeon 1.6/2G内存 win2003/sqlserver2005 企业版。
测试脚本:
--测试无主键/Identity/Uniqueidentifier/varchar类型主键插入表时的效率
set nocount on
declare @now datetime,@i int
set @i=1
set @now=getdate()
Create table  test1(nopkey int,col uniqueidentifier )
while @i<10000000
Begin
    insert into test1 values (1,newid())
    set @i=@i+1
end
Print'新表无主键插入100万条数据所耗时间:'+convert(varchar(200),datediff(ms,@now,Getdate()))+'毫秒'
set @i=1
set @now=getdate()
while @i<10000 
Begin
    insert into test1 values (1,newid())
    set @i=@i+1
end
Print'100万行中再插入10000条数据时间:'+convert(varchar(200),datediff(ms,@now,Getdate()))+'毫秒'
GO
Create table Test2(pkey int identity(1,1) primary key , col uniqueidentifier default(newid()))
declare @now datetime,@i int
set @i=1
set @now=getdate()
while @i<1000000
Begin
    insert into test2(col) values (newid())
    set @i=@i+1
end
Print '新表以int为主键插入100万条数据所耗时间:'+convert(varchar(200),datediff(ms,@now,Getdate()))+'毫秒'
set @i=1
set @now=getdate()
while @i<10000
Begin
    insert into test2(col) values (newid())
    set @i=@i+1
end
Print'100万行中再插入10000条数据所耗时间:'+convert(varchar(200),datediff(ms,@now,Getdate()))+'毫秒'
GO
Create table test3(Pkey uniqueidentifier Primary key, col int)
declare @now datetime,@i int
set @i=1
set @now=getdate()
while @i<1000000
Begin
    insert into test3 values (newid(),3)
    set @i=@i+1
end
Print '新表以uniqueidentifier主键插入100万条数据所耗时间:'+convert(varchar(200),datediff(ms,@now,Getdate()))+'毫秒'
set @i=1
set @now=getdate()
while @i<10000
Begin
    insert into test3 values (newid(),3)
    set @i=@i+1
end
Print'100万行中再插入10000条数据所耗时间:'+convert(varchar(200),datediff(ms,@now,Getdate()))+'毫秒'
GO
Create table test4(Pkey varchar(36) Primary key, col int)
declare @now datetime,@i int
set @i=1
set @now=getdate()
while @i<1000000
Begin
    insert into test4 values (convert(varchar(36),newid()),3)
    set @i=@i+1
end
Print '新表以varchar(36)类型为主键插入100万条数据:所耗时间:'+convert(varchar(200),datediff(ms,@now,Getdate()))+'毫秒'
set @i=1
set @now=getdate()
while @i<10000
Begin
    insert into test4 values (convert(varchar(36),newid()),3)
    set @i=@i+1
end
Print'100万行中再插入10000条数据所耗时间:'+convert(varchar(200),datediff(ms,@now,Getdate()))+'毫秒'
GO
drop table test1
drop table test2
drop table test3
drop table test4
运行测试结果如下: 新表无主键插入100万条数据所耗时间:1212856毫秒
100万行中再插入10000条数据时间:19360毫秒
新表以int为主键插入100万条数据所耗时间:111623毫秒
100万行中再插入10000条数据所耗时间:1110毫秒
新表以uniqueidentifier主键插入100万条数据所耗时间:118753毫秒
100万行中再插入10000条数据所耗时间:1153毫秒
新表以varchar(36)类型为主键插入100万条数据所耗时间:132830毫秒
100万行中再插入10000条数据所耗时间:1263毫秒 经过多次测试,均为相应结果,可见在插入表时,对于无主键和有主键的表来说,无主键的表其