欢迎光临

木子屋

标题: SQL Server2005获取第N条记录两种方法

作者: dnawo

日期: 2012-09-12 03:50 PM

分类: 服务器

内容: 表结构如下，要求取出第2条记录：
复制内容到剪贴板 程序代码Create TABLE Pet
(
[Id] int identity(1,1) primary key,
[Name] nvarchar(50)
)
方法一：SQL Server2000经典查询法(TOP)
复制内容到剪贴板 程序代码Select TOP 1 [Name] FROM Pet Where [Id]=(Select max([Id]) FROM Pet Where [Id] in (Select TOP 2 [Id] FROM Pet orDER BY [Id]))
简化版：
复制内容到剪贴板 程序代码Select TOP 1 [Name] FROM Pet Where [Id]=(Select max([Id]) FROM (Select TOP 2 [Id] FROM Pet orDER BY [Id]) as tab)
若N需动态指定，可用sp_executesql：
复制内容到剪贴板 程序代码declare @sql nvarchar(200)
declare @Name nvarchar(50), @Number int
select @Number = 2, @sql = N'Select TOP 1 @Name=[Name] FROM Pet Where [Id]=(Select max([Id]) FROM (Select TOP ' + convert(nvarchar,@Number) + ' [Id] FROM Pet orDER BY [Id]) as tab)'
EXECUTE sp_executesql @sql, N'@Name nvarchar(50) output', @Name output
Select @Name
SQL Server2005增强型TOP(N)法：
复制内容到剪贴板 程序代码Select TOP 1 [Name] FROM Pet Where [Id]=(Select max([Id]) FROM (Select TOP(@Number) [Id] FROM Pet orDER BY [Id]) as tab)
方法二：SQL Server2005新查询法(row_number() over())
复制内容到剪贴板 程序代码Select [Name] FROM (Select (row_number() over(ORDER BY [Id])) as RowNumber,[Name] FROM Pet) as tab Where RowNumber=2

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.412 ms

返回

标题: SQL Server2005获取第N条记录两种方法

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.412 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.570 ms

返回