如何在一个没有主键的表中获取第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
--*/--------------------------------------------------------
很多人发蛋贴攒分,我也发发,但是有1分,发了也不能白发,我会随口说个技术基础点,不只局限于代码。
高手可以忽略本贴

解决方案 »

  1.   

    很多人问我怎么看到我每天的这类帖子,我都同步在blog上http://blog.csdn.net/jinjazz/category/407229.aspx
      

  2.   

    --好像还是需要指定排序列
    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 行)
    */
      

  3.   

    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'
    --查询
    select top 1 * from Test where id not in (select top 2 id from Test)
      

  4.   

    用游标不好:
    select TOP N * into #temp1 from table1 order by field1
    select TOP N+1 * into #temp2 from table1 order by field1select * from #temp2
    except
    select * from #temp1在使用过程中,临时表还是比游标来得好
      

  5.   

    用游标的fetch  absolute语句可以获取绝对行数下的某行数据,测试代码如下: 
      

  6.   

    看不懂 有注释就更好了这些代码怎么运行呢
    我只会写语句 直接在查询分析器里运行
    比如 select * from CSDN Where id='坏蛋'
      

  7.   


    select * from CSDN Where id='坏蛋' 
    (所影响的行数为 77 行)
    id          name       
    ----------- ---------- 
    LZ         jinjazz
    ....
    LS         clq271520093我X,楼上的注册的个什么名字。
      

  8.   


    id          name      
    ----------- ---------- 
    LZ坏蛋       jinjazz 
    .... 
    LS坏蛋       clq271520093 
      

  9.   

    我X..
    select * from CSDN Where id LIKE '%坏蛋%' id          name      
    ----------- ---------- 
    LZ坏蛋      jinjazz 
    .... 
    LS坏蛋      clq271520093 
      

  10.   

    取第N行在sql里面有什么意义?
      

  11.   

    楼主好强大啊,不愧是微软的MVP,小小弟收藏了