实现查询时差在五分钟以内的数据 (sql)

    xiaoxiao2021-03-25  135

    方案大致三种,核心的原理都一样 都是逐行比对

    第一种:使用游标实现

    第二种:写一个存储过程 ,存储过程中实现 逐行比对逻辑

    第三种:在代码中进行逐行比对逻辑(推荐,数据库对服务器的性能影响最小)

    ·

    create table #tempTable

    (id int, dateS datetime ) declare @id int declare @date varchar(50) declare cursor1 cursor for         --定义游标cursor1 select BlogLogId,CreationTime from Tb_BlogLog               --使用游标的对象(跟据需要填入select文) open cursor1                       --打开游标 fetch next from cursor1 into @id,@date  --将游标向下移行,获取的数据放入之前定义的变量@id,@@date中 while @@fetch_status=0           --判断是否成功获取数据 begin --临时表 declare @temp int; select @temp=COUNT(*) from Tb_BlogLog where BlogLogId!=@id --自己除外的分钟之内有多少条数据 and DATEDIFF(Minute, CreationTime,@date)<=5 and  DATEDIFF(Minute, CreationTime,@date)>=-5 if(@temp>0) begin insert into #tempTable(id,dateS) values(@id,@date); end fetch next from cursor1 into @id,@date  --将游标向下移行 end close cursor1; --关闭游标 deallocate cursor1; select * from #tempTable; --最后查询临时表得出结果
    转载请注明原文地址: https://ju.6miu.com/read-14005.html

    最新回复(0)