SQLServer遍历表----慎用游标

来源:互联网 发布:淘宝直通车任务怎么做 编辑:程序博客网 时间:2024/06/18 15:06

         在编写存储过程的时候,通常都会碰到需要遍历表的情况,这个是时候最好选择临时表的方法,而不是使用游标,如果数据量很大,慎用游标.

         现在有一个名为POI的表,里面大概存储有250万的POI记录.

         使用游标遍历的存储过程代码如下:

        declare  myCursor cursor for select MESHID,POIID from POIopen myCursordeclare @MESHID nvarchar(50)declare @POIID nvarchar(50)fetch next from myCursor into @MESHID,@POIIDwhile(@@FETCH_STATUS=0)begin    -------------------------------------------    --do something you like-------------------    -------------------------------------------fetch next from myCursor into @MESHID,@POIIDendclose myCursordeallocate myCursor

       执行存储过程,总计花费2分13秒

 

       使用临时表的存储过程代码如下:

        create table tmpTable(nID bigint primary key identity(1,1),MESHID nvarchar(50),POIID nvarchar(50))insert into tmpTable(MESHID,POIID) select MESHID,POIID from POIdeclare @totalCount intselect @totalCount=COUNT(*) from tmpTabledeclare @index intset @index =1 declare @MESHID nvarchar(50)declare @POIID nvarchar(50)while(@index<=@totalCount)beginselect @MESHID=MESHID,@POIID=POIID from tmpTable where nID=@index    -------------------------------------------    --do something you like-------------------    -------------------------------------------set @index=@index+1enddrop table tmpTable

       执行存储过程,总计花费53秒.


原创粉丝点击