SQL中类似For循环处理的实例


  本文标签:SQL For循环

  原本CreatDate的yyyy-MM-dd hh:mm:ss:fff格式被变成了yyyy-MM-dd格式,下面就将对SQL进行类似For循环处理,该方法供您参考,希望对您学习SQL中的For循环能有所帮助  。

  

  1. declare @itemnumber int --定义需要循环的次数  
  2.  declare @tagint int --定义标志字段,用于结束循环  
  3.  set @tagint=1 
  4.  select @itemnumber = count(distinct Creater) from Demo_TestTable where isnull(Creater,)<> And   
  5.    DATEDIFF(DAY,CreatDate,GETDATE())<1 
  6.    if(@itemnumber>0)  
  7.    begin  
  8.      while @tagint<=@itemnumber  
  9.          begin  
  10.               waitfor delay 00:00:01 --每隔一秒再执行 可用参数变量替换  
  11.              Update Demo_TestTable set CreatDate=GETDATE() where Creater =(  
  12.              Select Creater from (  
  13.                  select Creater,ROW_NUMBER() over(order by Creater) as RowID from Demo_TestTable where   
  14. isnull(Creater,)<> And DATEDIFF(DAY,CreatDate,GETDATE())<1 group by Creater  
  15.              ) TableA  
  16.               where  TableA.RowID=@tagint  
  17.               )  
  18.               set @tagint=@tagint+1  
  19.         end  
  20.    end