码迷,mamicode.com
首页 > 数据库 > 详细

sql server存储过程分页,行变列

时间:2014-06-18 00:01:07      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   ext   color   get   数据   set   

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 ‘+@Columns+‘,ROW_NUMBER() over(order by ‘+@OrderStr+‘)rowindex from ‘+@Table+‘ where ‘+@Where1+‘ )rt where ‘+@Where2
    --print @sql
    exec sp_executesql @sql,N‘@rowid int output‘,@rowid=@rowid output
    --获取前一条ID
        set @sql=N‘select @Previousid=‘+@Index+‘ from(select ‘+@Columns+‘,ROW_NUMBER() over(order by ‘+@OrderStr+‘)rowindex from ‘+@Table+‘ where ‘+@Where1+‘ )rt where rowindex=‘+cast((@rowid-1) as varchar)
exec sp_executesql @sql,N‘@Previousid int output‘,@Previousid=@Previousid output
if @Previousid is null
set @Previousid=0
--获取后一条ID
  set @sql=N‘select @Nextid=‘+@Index+‘ from(select ‘+@Columns+‘,ROW_NUMBER() over(order by ‘+@OrderStr+‘)rowindex from ‘+@Table+‘ where ‘+@Where1+‘ )rt where rowindex=‘+cast((@rowid+1) as varchar)
exec sp_executesql @sql,N‘@Nextid int output‘,@Nextid=@Nextid output
if @Nextid is null
set @Nextid=0
--print @Previousid
--print @Nextid
--获取最后完整数据
exec(‘select ‘+@Columns+ ‘,‘+@Previousid+‘ Previousid,‘+@Nextid+‘ Nextid from ‘+@Table+‘ where ‘+@Where2)
END
表结构:

Id   two    three

1        2        3

4        5        6

7        8        9

根据传入参数“4”查询结果:

1        7        5        6

sql server存储过程分页,行变列,布布扣,bubuko.com

sql server存储过程分页,行变列

标签:style   ext   color   get   数据   set   

原文地址:http://www.cnblogs.com/fourw/p/3793481.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!