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

公告

update碰到一个问题

Posted on 2008-03-18 12:20 城市兔子 阅读(224) 评论(0) 编辑 收藏
最近在做一个统计功能的时候发现一个很奇怪的问题,如下的两段代码:

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的条数计算