有ID一类的东西,但没有规律 比如 
id   a   b   c
29   1   2   3
33   4   5   6 
102  7   8   9
现在是知道 id=29的数据但怎么才能通过以知的这条数据输出他前后两条数据 不能用游标

解决方案 »

  1.   

    这样可否create table tb(
    id int,
    a int,
    b int,
    c int
    )
    insert into tb values(10,2,5,1)
    insert into tb values(21,3,4,3)
    insert into tb values(29,1,2,3)
    insert into tb values(33,4,5,6)
    insert into tb values(102,7,8,9)select * from
    (
      select top 2 * from tb where id <29 order by id desc
    ) a
    union all
      select top 2 * from tb where id >29 order by id ascdrop table tb/*
    id          a           b           c           
    ----------- ----------- ----------- ----------- 
    10          2           5           1
    21          3           4           3
    33          4           5           6
    102         7           8           9
    */
      

  2.   

    create table tb(
    id int,
    a int,
    b int,
    c int
    )
    insert into tb values(10,2,5,1)
    insert into tb values(9,2,5,1)
    insert into tb values(21,3,4,3)
    insert into tb values(29,1,2,3)
    insert into tb values(33,4,5,6)
    insert into tb values(102,7,8,9)
    declare @id int
    set @id = 29
    --前两条
    select * 
    from (select top 2 * from tb where id < @id order by id desc) aselect top 2 * from tb where id >29 order by id asc
    /*
    id          a           b           c           
    ----------- ----------- ----------- ----------- 
    21          3           4           3
    10          2           5           1(所影响的行数为 2 行)id          a           b           c           
    ----------- ----------- ----------- ----------- 
    33          4           5           6
    102         7           8           9(所影响的行数为 2 行)
    */
    drop table tb