想必很多人会遇到这样的情况,那么看看如何实现,下面的SQL语句已经有过 “30W/天” 数据的考验
-
思路
- 数据库表中应该有一个是否被读取的状态字段:
Status 取值:0未读取 1已读取;
- 将要读取的记录更新状态,通过deleted表存储(就像是在触发器中使用一样)取出的方式,来保证每条记录只会被读取一次:
update Admins set [Status]= 1 output deleted.ID into @Rowid Where Id in (Select top 2 Id from Admins WITH(NOLOCK) Where [Status] = 0 order by id );
- 读取deleted表的记录
select * from Admins WITH(NOLOCK) where ID in (select Rowid from @Rowid);
-
实现
N个接口线程,每个线程需要获取的是前2条未读取的数据,固然实现以下代码:
declare @Rowid table(rowid int);
update Admins set [Status]= 1 output deleted.ID into @Rowid Where Id in
(Select top 2 Id from Admins WITH(NOLOCK) Where [Status] = 0 order by id );
select * from Admins where ID in (select Rowid from @Rowid);
网友评论