如何在一个没有主键的表中获取第n行数据,在sql2005中可以用row_number,但是必须指定排序列,否则你就不得不用select into来过渡到临时表并增加一个排序字段。
用游标的fetch absolute语句可以获取绝对行数下的某行数据,测试代码如下:
- set nocount on
- --建立测试环境并插入数据,并且表没有主键
- create table test(id int ,name varchar(10))
- insert into test select 999,'jinjazz'
- insert into test select 888,'csdn'
- insert into test select 999,'sqlserver'
- --通过游标获取绝对行数
- declare myCursor scroll cursor for select * from test
- open myCursor
- fetch absolute 3 from myCursor
- close myCursor
- deallocate myCursor
- --删除测试环境
- drop table test
- set nocount off
- /*--
- id name
- ----------- ----------
- 999 sqlserver
- --*/
- --好像还是需要指定排序列
- declare @t table(id int ,name varchar(10))
- insert into @t select 999,'jinjazz'
- insert into @t select 888,'csdn'
- insert into @t select 999,'sqlserver'
- select top 1 * from
- (select top 3 * from @t order by id desc)t
- /*
- (所影响的行数为 1 行)
- (所影响的行数为 1 行)
- (所影响的行数为 1 行)
- id name
- ----------- ----------
- 999 jinjazz
- (所影响的行数为 1 行)
- */