问题3出错是这段:select datediff(ss,starttime,endtime)as status_time,uid,status,@starttime as starttime,@endtime as endtime from statrecord 其实中间where ...到order by uid,status 大家不需要关注,这只是我取值的一个方式.不会出问题.一直使用,也加段点测试过...我也就是把这个SQL的语句查询出来.把里面的数据2个时间减一减在 拼起来插入到另外一个表中

解决方案 »

  1.   

    问题1:解决办法:在while循环中不要直接运行select语句,改为  “insert 临时表/表变量 select...”  格式, 然后在while循环结束时再 select.. from 临时表/表变量.
    问题2:查出全部的数据,说明where子句的条件有误
    问题3:第24次之所以出错,是因为第24次时,@wang =23,而@endtime= '2008-12-21 24:00:00',报错了。应改为'2008-12-22 00:00:00'
      

  2.   

    能帮我重点看下问题2是什么问题么???
    问题1其实我大概也了解.不管怎么样.反正INSERT时候都是查到表里去的.
    问题3谢谢说明哦...
    帮我解说下问题2可以么
      

  3.   

    可能是where 条件中and 和or的优先级问题导致了此原因哦;
    因为是先进行and运算然后在进行or运算
      

  4.   

    仔细看了一下你的代码,发现问题还真是多啊。DECLARE @statusstarttime varchar(60); 
    DECLARE @statusendtime varchar(60); 
    DECLARE @starttime varchar(60); 
    DECLARE @endtime varchar(60); 
    Declare @wang int; select @wang =0 
    select @statusstarttime = '2008-12-20 ',@statusendtime='2008-12-21 ' 
    while @wang <24 
    BEGIN 
    --下面的@endtime赋值是有误的,按照你当前的代码,@starttime和@endtime一直相差1天又多一个小时。这是不对的,应该改为相差一个小时,,@endtime=@statusstarttime+ Convert(varchar(30),@wang+1)+':00:00' ,这就是你每次循环都查出全部数据的原因
    select @starttime =@statusstarttime + Convert(varchar(30),@wang)+':00:00',@endtime=@statusendtime+ Convert(varchar(30),@wang+1)+':00:00' 
    --下面是为你整理后的select语句
    select datediff(ss,starttime,endtime)as status_time,
    uid,status,
    @starttime as starttime,
    @endtime as endtime 
    from statrecord 
    where  (
    --下面几个isnull函数是没必要的,因为where条件包含有endtime 和starttime非空、
    --下面几个or语句也很罗嗦,要表达表中数据的时间段和变量的时间段有重叠区间,完全可以用一个or就可以了。只要用类似(starttime between @starttime and @endtime) or (endtime between @starttime and @endtime) 的条件就行了
    (
             isnull(endtime, getdate()) >= convert(datetime, @starttime) 
    and  isnull(endtime, getdate()) <= convert(datetime, @endtime) 
    and  starttime < convert(datetime, @starttime)
             )  
    or      (
    isnull(endtime, getdate()) <= convert(datetime, @endtime) 
    and  starttime >= convert(datetime, @starttime)
         )  
    or   (
    isnull(endtime, getdate()) > convert(datetime, @endtime) 
    and  starttime >= convert(datetime, @starttime) 
    and  starttime <= convert(datetime, @endtime)
          )  
    or   (
    isnull(endtime, getdate()) > convert(datetime, @endtime) 
    and  starttime < convert(datetime, @starttime)
         )
           ) 
           and endtime is not null 
           and  starttime is not null 
           and status <>12 and datediff(ss,starttime,endtime) between 0 and 100000 
    order by uid,status set @wang=@wang+1 
    if @wang=24 break 
    else 
    continue 
    end