分类目录

链接

2012 年 1 月
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > SQL Server > 正文
SQL语句记录搜索
SQL Server 暂无评论 阅读(2,409)

记录搜索:

开头到N条记录

Select Top N * From 表

-------------------------------

N到M条记录(要有主索引ID)

Select Top M-N * From 表 Where ID in (Select Top M IDFrom 表) Order by ID   Desc

----------------------------------

N到结尾记录

Select Top N * From 表 Order by ID Desc

案例

例如1:一张表有一万多条记录,表的第一个字段 RecID 是自增长字段, 写一个SQL语句, 找出表的第31到第40个记录。

select top 10recid from A where recid not  in(selecttop 30 recid from A)

分析:如果这样写会产生某些问题,如果recid在表中存在逻辑索引。

selecttop 10 recid from A where……是从索引中查找,而后面的select top 30 recidfrom A则在数据表中查找,这样由于索引中的顺序有可能和数据表中的不一致,这样就导致查询到的不是本来的欲得到的数据。

解决方案

1, 用order by selecttop 30 recid from A order by ricid 如果该字段不是自增长,就会出现问题

2,在那个子查询中也加条件:selecttop 30 recid from A where recid>-1

例2:查询表中的最后以条记录,并不知道这个表共有多少数据,以及表结构。

set @s = 'select top 1 * from T   where pid not in (select top ' +str(@count-1) + ' pid  from  T)'

print @s      exec sp_executesql  @s

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:SQL语句记录搜索 | Bruce's Blog

发表评论

留言无头像?