CREATE PROCEDURE [dbo].[PROC_GetPriviousAndNextDetailContent]
@Index varchar(20),--表主键
@Table varchar(100),--从哪个表获取数据
@Columns varchar(100),--需要获取哪些字段
@OrderStr varchar(100),--排序字段及方式
@Where1 varchar(100),--row_number中的初步过滤条件
@Where2 varchar(100)--当前要查询详细内容的ID条件
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare @sql nvarchar(1000),@rowid int,@Previousid int,@Nextid int
set @sql=N‘select @rowid=rowindex from(select ‘[email protected]+‘,ROW_NUMBER() over(order by ‘[email protected]+‘)rowindex from ‘[email protected]+‘ where ‘[email protected]+‘ )rt where ‘[email protected]
--print @sql
exec sp_executesql @sql,N‘@rowid int output‘,@[email protected] output
--获取前一条ID
set @sql=N‘select @Previousid=‘[email protected]+‘ from(select ‘[email protected]+‘,ROW_NUMBER() over(order by ‘[email protected]+‘)rowindex from ‘[email protected]+‘ where ‘[email protected]+‘ )rt where rowindex=‘+cast((@rowid-1) as varchar)
exec sp_executesql @sql,N‘@Previousid int output‘,@[email protected] output
if @Previousid is null
set @Previousid=0
--获取后一条ID
set @sql=N‘select @Nextid=‘[email protected]+‘ from(select ‘[email protected]+‘,ROW_NUMBER() over(order by ‘[email protected]+‘)rowindex from ‘[email protected]+‘ where ‘[email protected]+‘ )rt where rowindex=‘+cast((@rowid+1) as varchar)
exec sp_executesql @sql,N‘@Nextid int output‘,@[email protected] output
if @Nextid is null
set @Nextid=0
--print @Previousid
--print @Nextid
--获取最后完整数据
exec(‘select ‘[email protected]+ ‘,‘[email protected]+‘ Previousid,‘[email protected]+‘ Nextid from ‘[email protected]+‘ where ‘[email protected])
END
表结构:
Id two three
1 2 3
4 5 6
7 8 9
根据传入参数“4”查询结果:
1 7 5 6
sql server存储过程分页,行变列,布布扣,bubuko.com