数据库问题 (急)!

yao3892 2011-07-15 11:11:22
MS SQLServer数据库怎么才能在一个无序的表中查询出第30-40条的记录?
...全文
67 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
--小F-- 2011-07-15
  • 打赏
  • 举报
回复
取n到m行

1.
select top (n-m+1) * from tablename where id not in (select top n id from tablename order by id asc/*|desc*/)

2.
select top m * into 临时表(或表变量) from tablename order by columnname -- 将top m笔插入到临时表
set rowcount n --只取n条结果
select * from 表变量 order by columnname desc

3.
select top n * from
(select top m * from tablename order by columnname) a
order by columnname desc


4.如果tablename里没有其他identity列,那么:
先生成一个序列,存储在一临时表中.
select identity(int) id0,* into #temp from tablename

取n到m条的语句为:
select * from #temp where id0 > =n and id0 <= m

如果你在执行select identity(int) id0,* into #temp from tablename这条语句的时候报错,那是因为你的DB中间的select into/bulkcopy属性没有打开要先执行:
exec sp_dboption 你的DB名字,'select into/bulkcopy',true


5.如果表里有identity属性,那么简单:
select * from tablename where identity_col between n and m

6.SQL2005开始.可以使用row_number() over()生成行号
;with cte as
(
select id0=row_number() over(order by id),* from tablename
)
select * from cte where id0 between n to m
yao3892 2011-07-15
  • 打赏
  • 举报
回复
[Quote=引用楼主 yao3892 的回复:]
MS SQLServer数据库怎么才能在一个无序的表中查询出第30-40条的记录?
[/Quote]
能不能举例? 不会用这个函数啊
bancxc 2011-07-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 qgqch2008 的回复:]
row_number()
[/Quote]o
qgqch2008 2011-07-15
  • 打赏
  • 举报
回复
row_number()
cd731107 2011-07-15
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 ap0405140 的回复:]
简单例子如下,各SQL版本通用..

SQL code

select identity(int,1,1) rn,*
into [临时表名]
from [TableName]

select * from [临时表名] where rn between 30 an 40
[/Quote]
这种方法也很实用
mc168199 2011-07-15
  • 打赏
  • 举报
回复
木有积分了 杯具了
WXM8511 2011-07-15
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 ap0405140 的回复:]
简单例子如下,各SQL版本通用..

SQL code


select identity(int,1,1) rn,*
into [临时表名]
from [TableName]

select * from [临时表名] where rn between 30 an 40
[/Quote]

正解
yagebu1983 2011-07-15
  • 打赏
  • 举报
回复
采用Row_Number函数!!
ly745455 2011-07-15
  • 打赏
  • 举报
回复
+[Quote=引用 5 楼 ap0405140 的回复:]
简单例子如下,各SQL版本通用..

SQL code

select identity(int,1,1) rn,*
into [临时表名]
from [TableName]

select * from [临时表名] where rn between 30 an 40
[/Quote]
唐诗三百首 2011-07-15
  • 打赏
  • 举报
回复
简单例子如下,各SQL版本通用..

select identity(int,1,1) rn,*
into [临时表名]
from [TableName]

select * from [临时表名] where rn between 30 an 40

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧