posts - 12, comments - 176, trackbacks - 3, articles - 8
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

update碰到一个问题

Posted on 2008-03-18 12:20 City22 阅读(141) 评论(0)  编辑 收藏 网摘 所属分类: Sql Server
最近在做一个统计功能的时候发现一个很奇怪的问题,如下的两段代码:

update pv6 
set pv0=(select count(0
    
from clubreply with(nolock) 
    
where rReplyDate>=convert(char(10),getdate(),121))
where title=1

select count(0
    
from clubreply with(nolock) 
    
where rReplyDate>=convert(char(10),getdate(),121))

上面一个update执行2分钟,下面的只需要执行10秒!

注明一下:
where title=1只会查出1行,也就是说update只会更新1行
clubreply是一个超级大的表,几千万行,rReplayDate无索引
pv6是一个超级小的表,3行2列,而且极少查这个表,不会出现锁的问题

不明白为什么于是做成了如下的方式
declare @pv int;
set @pv=(select count(*)
from clubreply with(nolock) 
where rReplyDate>=convert(char(10),getdate(),121));
update pv6 set pv0=@pv where title=1
发现还是执行了2分钟

于是又改了这种方法实现
declare @count int
select @count=count(0
from clubreply with(nolock) 
where rReplyDate>=convert(char(10),getdate(),121)
update pv6 set pv0=@count where title=1
终于执行了10秒

然而这一切很奇怪呢,这语句里面最大的效率问题好像是convert(char(10),getdate(),121),为了证明一下,把两个执行2分钟的语句优化一下得到
declare @date datetime;
set @date=convert(char(10),getdate(),121);
update pv6 set pv0=(select count(0
    
from clubreply with(nolock) 
    
where rReplyDate>=@date)
where title=1
declare @pv int;
declare @date datetime;
set @date=convert(char(10),getdate(),121);
set @pv=(select count(*)
    
from clubreply with(nolock) 
    
where rReplyDate>=@date);
update pv6 set pv0=@pv where title=1

以上这两条语句执行的时间为10秒
果然是convert在捣鬼.

最后的结论如下:在select作为结果集赋值的时候,其中的条件会按照select的条数计算

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-03-18 14:13 编辑过
Google站内搜索

China-pub 计算机图书网上专卖店!6.5万品种 2-8折!
近千种 9-95 新二手计算图书火热销售中!
开发者征途系统新作:《设计模式——基于C#的工程化实现及扩展》



相关文章:

相关链接: