一般数据比较多情况下,仅这两个比较的话,第二个效率要高。
如果几行数据,就不明显了。
原因:
第一个是需要不停的到表里读取数据,不停的读io(或是内存缓存数据),造成大量的io读取,而io操作,是最慢最耗资源的。
第二个是一次性写入游标里,然后进行操作,读到的io相对的第一种是极小的,而游标效率也并非是极差,不然,ms也就不用它了。
解决方案 »
- 如果好多个对同字段的update怎么批处理啊,一起执行会timeout的
- 用户只访问一张表,不能看见其他库名的权限问题~
- 多字段模糊查询问题
- 【简单的数据筛选问题!晕~】
- SQL Server DB镜像中Ldf文件过大,如何处理?
- 关于事务回滚造成事物日志过大的问题
- SQL自动备份文件增大
- ??SQL Server中我用Select into 问题,高手???
- 直接把A机器sql server中通过"企业管理器"创建的数据库文件.mdf和.ldf拷贝到B台机器上后,可以在B机器
- 救命!!SQLServer2000,什么叫“未与信任 SQL Server 连接相关联”啊?
- 数据更新问题,牛人来帮帮忙!!!!
- 挑战CSDN 数据统计 谢谢
create table t_test(id int identity(1,1) primary key,class_a varchar(50),class_b varchar(50),add_dt datetime)
go
declare @i int
select @i = 1
while @i < = 10000
begin
insert into t_test(class_a,class_b,add_dt)
select case @i%2 when 0 then 'class_a' + cast(@i as varchar) else cast(@i as varchar) end,
case @i%5 when 0 then 'class_b' + cast(@i as varchar) else cast(@i as varchar) end, getdate()
select @i = @i + 1
end
--测试第一种所需时间
declare @t1 datetime,@t2 datetime
declare @a int,@b int
select @t1 = getdate()
declare @depot nvarchar(10)
select @depot='2'
while 1=1
begin
select @depot =id from t_test where id > @depot order by id desc
if @@rowcount <1
break
print @depot
end
select @t2 = getdate()
select cast(datediff(ms,@t1,@t2) as varchar)+'ms'
--结果:
30983ms
--测试第二种:
declare @t1 datetime,@t2 datetime
declare @a int,@b int
select @t1 = getdate()
declare @depot nvarchar(10)
declare cur1 cursor for select id from t_test where id between 3 and 10000 order by id
open cur1
fetch next from cur1 into @depot
while @@fetch_status = 0
begin
print @depot
fetch next from cur1 into @depot
end
close cur1
deallocate cur1
select @t2 = getdate()
select cast(datediff(ms,@t1,@t2) as varchar)+'ms'
--结果:
623ms通过查看io读:
set statistics io on发现这两个的区别在于:
第一个查询执行时是:select id from t_test where id > 30 order by id desc
而第二个查询是直接取某一行:select id from t_test where id = 30 也就是说楼主的:
SELECT @depot =depot FROM s_depot WHERE depot > @depot ORDER BY depot desc在while时,每次要读取depot > @depot的所有数据页,而游标的则只读取一条记录的数据页。
去循环这个内存表,在你服务器内存足够大时,或许性能好于游标。