select * from table where id = @id union select * from table where abs(id - @id) = 1
--测试: Create table #( id int identity(1,1),Name varchar(10)) insert into # select 'A' union all select 'B' union all select 'C' union all select 'D'--查询 declare @id int set @id=3 select * from # where id in (@id-1,@id,@id+1)--结果 /* id Name ----------- ---------- 2 B 3 C 4 D(所影响的行数为 3 行) */
回happyflystone(仙林幽谷客):方法很巧妙,但是问题也同zlp321002的,就是id虽然是主键但是并不一定连续,如果连续你的方法就可以,不连续就不行了 ----select idrow=identity(int,1,1),* into #tmp from table ----自己生成连续的IDselect * from #tmp where abs(idrow - @id) <= 1drop table #tmp
回happyflystone(仙林幽谷客): 出现如下问题 无法使用 SELECT INTO 语句向表 '#tmp' 中添加标识列,该表中已有继承了标识属性的列 'ID'。 第一条语句中声名了一个主键idrow,但是我原来表里面也有主键的,这样我能明白你的方法的原理,但是要改进,我想想
方法笨一点select * from tabe where id=@id union (select top 1 * from table where id<@id order by id desc) untion (select top 1 * from table where id>@id order by id) order by id
而且用临时表的话如果这个查询使用次数一多那么数据库日志的大小就敖敖大了^_^ ----------select top 2 * from (select * from table where id <= @id order by id desc) b union select top 1 * from (select * from table where id >@id order by id asc) b
而且用临时表的话如果这个查询使用次数一多那么数据库日志的大小就敖敖大了^_^ ----------select top 2 * from table where id <= @id order by id desc union select top 1 * from table where id >@id order by id asc
union select * from table where abs(id - @id) = 1
Create table #( id int identity(1,1),Name varchar(10))
insert into # select 'A'
union all select 'B'
union all select 'C'
union all select 'D'--查询
declare @id int
set @id=3
select * from # where id in (@id-1,@id,@id+1)--结果
/*
id Name
----------- ----------
2 B
3 C
4 D(所影响的行数为 3 行)
*/
---select idrow=identity(int,1,1),* into #tmp from tableselect * from #tmp where abs(idrow - @id) <= 1drop table #tmp
----select idrow=identity(int,1,1),* into #tmp from table ----自己生成连续的IDselect * from #tmp where abs(idrow - @id) <= 1drop table #tmp
出现如下问题
无法使用 SELECT INTO 语句向表 '#tmp' 中添加标识列,该表中已有继承了标识属性的列 'ID'。
第一条语句中声名了一个主键idrow,但是我原来表里面也有主键的,这样我能明白你的方法的原理,但是要改进,我想想
出现如下问题
无法使用 SELECT INTO 语句向表 '#tmp' 中添加标识列,该表中已有继承了标识属性的列 'ID'。
第一条语句中声名了一个主键idrow,但是我原来表里面也有主键的,这样我能明白你的方法的原理,但是要改进,我想想
----------------------
在select 中不要包括你的自增列
union (select top 1 * from table where id<@id order by id desc)
untion (select top 1 * from table where id>@id order by id)
order by id
----------select top 2 * from (select * from table where id <= @id order by id desc) b
union
select top 1 * from (select * from table where id >@id order by id asc) b
----------select top 2 * from table where id <= @id order by id desc
union
select top 1 * from table where id >@id order by id asc
出现如下问题
无法使用 SELECT INTO 语句向表 '#tmp' 中添加标识列,该表中已有继承了标识属性的列 'ID'。
第一条语句中声名了一个主键idrow,但是我原来表里面也有主键的,这样我能明白你的方法的原理,但是要改进,我想想
----------------------
在select 中不要包括你的自增列
兄弟,不好意思,我要的就是自增列的值
rs. MoveLast控制指针