标题可能和正文不太相符。我主要是记录工作中遇到使用游标的语句改成普通set-based operation,执行时间快了很多。

1、游标语句

declare @startDate dateTime
declare @endDate dateTime
set @startDate = convert(varchar(10),dateAdd(day,-1,getDate()),120)
set @endDate = convert(varchar(10),getDate(),120) declare @serverID int
declare loop_cursor cursor for
select distinct serverID from OnLineUserStat with(nolock)
where realTime between @startDate and @endDate
open loop_cursor
fetch next from loop_cursor into @serverID
while @@fetch_status = 0
begin
declare @loopTime dateTime
set @loopTime = @startDate
while @loopTime < @endDate
begin
insert into OnLineUserStat2
(serverID,kindID,OnLineUserCount,playUserCount,RoomName,StatTime,RealTime)
select top 1 serverID,kindID,OnLineUserCount,playUserCount,RoomName,@looptime,RealTime
from OnLineUserStat with(nolock)
where serverID = @serverID and statTime <= @loopTime
and dateDiff(minute,statTime,@loopTime) <= 7
order by statTime desc set @loopTime = dateAdd(minute,5,@loopTime)
end
fetch next from loop_cursor into @serverID
end
close loop_cursor
deallocate loop_cursor

OnLineUserStat表的记录如下:

OnLineUserStat2表的记录如下:

游标的目的是针对每一个房间,创建时间基准(每5分钟一个基准,一天总计288个),针对各个时间基准获取前7分钟内最近的记录。
每天的distinct ServerID个数约400,每个房间创建288个时间基准,每天insert数量约11万。游标语句在服务器上执行耗时17分钟。

2、set-based语句

create table #date(StandTime datetime)
declare @StandTime datetime
select @StandTime=convert(varchar(10),getdate()-1,112)
while @StandTime<convert(varchar(10),getdate(),112)
begin
insert into #date(StandTime) values(@StandTime)
set @StandTime=dateadd(mi,5,@StandTime)
end ;with a as(
select a.StandTime,b.*
,row_number() over(partition by b.ServerID,a.StandTime order by b.ServerID,b.RealTime desc) rankid from #date a
,LK78DB.dbo.OnLineUserStat b with(nolock)
where b.RealTime<=a.StandTime
and b.RealTime>=dateadd(mi,-7,a.StandTime)
)
insert into OnLineUserStat2
select serverID,kindID,OnLineUserCount,playUserCount,RoomName,StandTime as StatTime,RealTime
from a
where rankid=1 drop table #date

借助于临时表生成所有时间基准,然后关联临时表与OnLineUserStat,得到最终结果。此语句耗时3秒。

3、计划对比

至于两者消耗为什么差别这么大,我们来看下它们的主体语句对应的执行计划,为了演示方便这里仅取三条数据。

3.1、while对应的执行计划


3.2、set-based对应的执行计划



while的逻辑读远高于set-based,while外面再套层cursor,需要repeats更多。
实际while语句的消耗在键查找,注意OnLineUserStat表的记录,StatTime和RealTime相同!可将where条件及order by更改为RealTime


相比第一个语句,逻辑读低了很多。。。

4、验证数据

例中将cursor+while修改为set-based,变动还是比较大。修改后我们需要验证语句与修改前是等效的,即修改后得到的结果与修改前得到的结果相同,不然修改的意义何在。

4.1、逻辑检查

语句逻辑是否满足原始需求

4.2、结果对比

最终会将数据写入到数据表,我们可以针对某一天的数据使用TableDiff对比是否存在差异。
我是将要对比的数据导入本地,当然可以直接带上源和目标的用户和密码对比数据(详细参数请参考 TableDiff /?) ,本例使用下面的命令对比

cd C:\Program Files\Microsoft SQL Server\\COM
TableDiff -sourceserver "127.0.0.1,7777" -sourcedatabase "Test" -sourcetable "OnLineUserStat2_17" -destinationserver "127.0.0.1,7777" -destinationdatabase "Test" -destinationtable "OnLineUserStat2_204" -f "C:\diff"


结果显示源和目标是相同的(identical)

4.3、TableDiff补充

如果对比的两表数据不一致,会产生什么样的结果?为了模拟这种情况,首先更新源OnLineUserStat2_17前7行数据,使其与OnLineUserStat2_204不一致,然后运行对比代码

结果显示有7处不同,并且生成应用目标的sql脚本(C:\diff.sql)

在对应Host->Database执行diff.sql就能让目标与源保持一致(以源为标准)
如果对比的两表没有自增列,会产生什么样的结果?为了模拟这种情况,删除ID自增字段,然后运行对比代码

也就是说对比的两表至少需要有唯一标识字段,否则无法分辨对比什么数据。

cursor or set-based的更多相关文章

  1. SQL CURSOR

    SET NOCOUNT ON; DECLARE @vendor_id int, @vendor_name nvarchar(50),     @message varchar(80), @produc ...

  2. Use Cursor

    declare : CURSOR cursor_name IS select_statement ; open : OPEN cursor_name if the query returns no r ...

  3. Rolling Cursor Invalidations with DBMS_STATS.AUTO_INVALIDATE (文档 ID 557661.1)

      Rolling Cursor Invalidations with DBMS_STATS.AUTO_INVALIDATE (文档 ID 557661.1) 转到底部 In this Documen ...

  4. Cursor: Pin S Wait On X In The Top 5 Wait Events

    Wait Events , Posted in: Technical Track Tags: Group Blog Posts, Oracle, Technical Blog Lately, wait ...

  5. DECLARE CURSOR (Transact-SQL)

    Defines the attributes of a Transact-SQL server cursor, such as its scrolling behavior and the query ...

  6. Resource Access Based on Multiple Credentials

    A collection of multiple user credentials each associated with one of multiple different users is ob ...

  7. Oracle 11g 新特性 -- 自适应游标共享(Adaptive Cursor Sharing: ACS) 说明(转载)

    一.自适应游标共享(Adaptive Cursor Sharing) 说明 1.1 ACS概述绑定变量使Oracle DB 可以为多条SQL 语句共享单个游标,以减少分析SQL 语句所使用的共享内存量 ...

  8. Create a cursor from hardcoded array instead of DB

    https://stackoverflow.com/questions/18290864/create-a-cursor-from-hardcoded-array-instead-of-db Crea ...

  9. 自定义鼠标光标cursor

    通过css属性 Cursor:url()自定义鼠标光标. {cursor:url('图标路径'),default;} url是自定义鼠标图标路径 default指的是定义默认的光标(通常是一个箭头), ...

  10. 苹果手机不支持click文字 需要添加 cursor:pointer 才能 识别可以点击

    给一个div 绑定一个 click事件,  苹果手机会识别不了,必须添加一个 cursor:pointer 才能 识别可以点击.安卓正常识别.

随机推荐

  1. WordPress安装插件提示输入FTP账户信息

    在WP后台安装插件时提示输入FTP账户信息,其实出现这个的问题的原因是Apache/Nginx的执行身份非文件属主身份. 如果你使用的是独立服务器或VPS,WordPress的安装目录为 /home/ ...

  2. jQuery- 常规选择器(一)

    注意:用size的时候有(),而length没有括号 除了这种方式之外,还可以用转换为 DOM 对象的方式来判断,例如:i$('#pox').get(0) 或  $('#pox')[0]  //通过数 ...

  3. php 执行计划任务方式之 linux crontab 执行命令

    一.crond简介 crond 是linux下用来周期性的执行某种任务或等待处理某些事件的一个守护进程,与windows下的计划任务类似,当安装完成操作系统后,默认会安装此服务 工具,并且会自动启动c ...

  4. VBA找不到progress bar的处理办法。

    Search your pc for MSCOMCTL.Ocx. If you find it then register it by clicking on Windows Start Button ...

  5. windows下安装python科学计算环境,numpy scipy scikit ,matplotlib等

    安装matplotlib: pip install matplotlib 背景: 目的:要用Python下的DBSCAN聚类算法. scikit-learn 是一个基于SciPy和Numpy的开源机器 ...

  6. Qt quick 编程

    greaterThan(QT_MAJOR_VERSION,4):QT += widgets.在Qt 5之前,没有独立的QtWidgets模块,Qt Widgets包含在QtGui模块中. TARGET ...

  7. NOIP2015D1

    好像来的有点晚,但我的确现在刚做这套题 T1神奇的幻方 题目描述 幻方是一种很神奇的N*N矩阵:它由数字1,2,3,……,N*N构成,且每行.每列及两条对角线上的数字之和都相同. 当N为奇数时,我们可 ...

  8. 【Linux】vi 命令

    基本上 vi/vim 共分为三种模式,分别是一般模式.编辑模式与指令列命令模式. 这三种模式的作用分别是:     一般模式:以 vi 打开一个档案就直接进入一般模式了(这是默认的模式).在这个模式中 ...

  9. OSG的节点访问

    OSG的节点访问 转自:http://www.cnblogs.com/kanego/archive/2011/09/27/2193484.html SG中节点的访问使用的是一种访问器模式. 一个典型的 ...

  10. 02.JavaScript基础上

    JavaScript组成 ECMAScript:解释器.翻译 .平时我们写的代码都是用英文数字之类,而计算机只能读懂0和1,ECMAScript可以把我们写的翻译给计算机,把计算机写的传达给我们DOM ...