我需要查询临近几条记录,比如输入的id是20,就需要查到18、19、20、21、22。
这样的存储过程该怎么写呢?

解决方案 »

  1.   

    declare @id int
    set @id=20select * from tb where id in(@id-2,@id-1,@id,@id+1,@id+2)
    ?
      

  2.   

    declare @id int
    set @id = 20
    select *
    from tb
    where id between @id - 2 and @id + 2
      

  3.   

    create proc proc_name
    @id int 
    as
    select *
    from tb
    where id between @id - 2 and @id + 2
      

  4.   

    我居然忘记了between~~
    但是如果相邻的记录被删除呢?
      

  5.   

    那就用虛列前後判斷吧.
    select 
      *,
      编号=(select count(id)+1 from tb where id<t.id)
    from tb t
      

  6.   


    CREATE PROCEDURE [dbo].[near5pic] 
    @id int
    AS
    BEGIN
    declare @userid int
    select @userid = userid from pic Where id = @id
    select id,smallpic   
      FROM pic     
      WHERE id=@id
      OR id in(SELECT top 3 id 
      FROM pic WHERE id < @id and userid = @userid order by id desc) 
      OR id in(SELECT top 3 id     
      FROM pic WHERE id > @id and userid = @userid order by id) 
    end结贴