如下,写了一游标代码,其中表tb_photo1中数据有5万多条,表tb_toupiao中数据有300万多条,下面游标实现的功能是更新
tb_photo1表中ptrq的值,发现效率不是一般的慢,现在sql已运行2个多小时,还没有运行完,查影响行数的时候,看数据在sql运行的情况下不断的变化,现在的问题是有没有更高效的方法来解决这样批量更新的问题呢。因表中字段ptrq的值是根据其他表中数据相减的差值得出的,所以肯定不能直接update ptrq,不知道我表达的意思各位仁兄是否明白 ,望指教 ~declare @ptid int
declare @ptrq int
declare @i int
declare cursor1 cursor for         --定义游标cursor1
select top 10 ptid,ptrq from tb_photo1 order by ptrq desc               --使用游标的对象(跟据需要填入select文)
open cursor1                       --打开游标fetch next from cursor1 into @ptid,@ptrq  --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中while @@fetch_status=0           --判断是否成功获取数据
begin
update tb_photo1 set ptrq=ptrq-(
select 
(select count(id) from tb_toupiao where ptid=@ptid)-
(select count(*)
from(
select count(id) as id
from tb_toupiao
where ptid = @ptid
group by convert(varchar(16),addtime,120),usid) a)) where ptid=@ptid
                    --进行相应处理(跟据需要填入SQL文)fetch next from cursor1 into @ptid,@ptrq  --将游标向下移1行
endclose cursor1                   --关闭游标
deallocate cursor1

解决方案 »

  1.   


    update tb_photo1 set ptrq=ptrq-(
    select 
    (select count(id) from tb_toupiao where ptid=@ptid)-
    (select count(*)
    from(
    select count(id) as id
    from tb_toupiao
    where ptid = @ptid
    group by convert(varchar(16),addtime,120),usid) a)) 这里是不是多写了。这么我么多。你游标只选了10条不可能运行两个小时吧。
      

  2.   


    declare @ptid int
    declare @ptrq int
    declare @i int
    declare cursor1 cursor for         --定义游标cursor1
    select  ptid,ptrq from tb_photo1 order by ptrq desc               --使用游标的对象(跟据需要填入select文)
    open cursor1                       --打开游标fetch next from cursor1 into @ptid,@ptrq  --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中while @@fetch_status=0           --判断是否成功获取数据
    begin
    update tb_photo1 set ptrq=ptrq-(
    select 
    (select count(id) from tb_toupiao where ptid=@ptid)-
    (select count(*)
    from(
    select count(id) as id
    from tb_toupiao
    where ptid = @ptid
    group by convert(varchar(16),addtime,120),usid) a)) where ptid=@ptid
                        --进行相应处理(跟据需要填入SQL文)fetch next from cursor1 into @ptid,@ptrq  --将游标向下移1行
    endclose cursor1                   --关闭游标
    deallocate cursor1
    这样子,应该是没有top10的 我复制的时候忘记去掉啦 ~
      

  3.   

    update a set ptrq=ptrq-(select count(id) from tb_toupiao where ptid=a.ptid)- 
                 (select count(*)from( select count(id) as idfrom tb_toupiao
       where ptid = a.ptid group by convert(varchar(16),addtime,120),usid)a)
    from tb_photo1 a
      

  4.   

    update a set ptrq=ptrq-
    (select count(id)-count(distinct convert(char(16),addtime,120)+usid) 
             from tb_toupiao where ptid=a.ptid
    from tb_photo1 a把两表的PTID加上索引,以利于子查询查找统计,要不然速度更慢,还有需要考虑一下时间或者USID相加为空的情形,或者没有投票的情形