最近忙于找工作,面试时,遇到面试官要用我用T-SQL语句写一个分页存储过程,当时我一下子就傻了,好长时间没有写了,一时都忘记了,趁着今天有空,花时间写了一下,下面将Code粘贴出来,如有错误之处,望大家指正。
第一个存储过程相对比较复杂,传入参数较多,涉及到排序。第二个存储过程相对简单点。
分页存储一:
1 create Procedure prc_GetRecordForPaging 2 @tableName varchar(255),--表名 3 @fieldName varchar(255),--字段名称 4 @pageSize int=10, --单页显示大小 5 @pageIndex int=1, --页码 6 @orderType bit=0, --设置排序类型,非0则是降序 7 @strCondition varchar(2000)='' --查询条件(注意,不要添加where语句) 8 as 9 declare @strSQL varchar(6000) --主执行语句10 declare @strTemp varchar(1000) --临时执行语句11 declare @strOrder varchar(500) --排序语句12 if @orderType != 0 --降序13 begin14 set @strTemp='< (select min' 15 set @strOrder=' order by ['+@fieldName+'] desc' --排序语句16 end17 else -- 升序18 begin19 set @strTemp ='> (select Max'20 set @strOrder =' order by ['+@fieldName+'] asc'21 end22 set @strSQL ='select top'+str(@pageSize)+' * from '23 + @tableName+'] where ['+ @fieldName+ ']'24 + @strTemp+ '(['+ @fieldName+ ']) from ( select top'+25 + str(@pageSize*(@pageIndex-1))+'['26 + @fieldName +'] from ['+ @tableName+']'27 + @strOrder + ') as tableTemp)'28 + @strOrder29 30 if @strCondition != ''31 set @strSQL ='select top'+str(@pageSize)+' * from '32 + @tableName+'] where ['+ @fieldName+ ']'33 + @strTemp+ '(['+ @fieldName+ ']) from ( select top'+34 + str(@pageSize*(@pageIndex-1))+'['35 + @fieldName +'] from ['+ @tableName+'] where '36 + @strCondition + '' + @strOrder + ') as tableTemp) and'37 + @strCondition + '' + @strOrder38 if @pageIndex = 139 begin40 set @strTemp =''41 if @strCondition !=''42 set @strTemp =' where ('+ @strCondition + ')'43 44 set @strSQL ='select top'+ str(@pageSize)+ ' * from ['45 + @tableName+ ']'+ @strTemp+ '' + @strOrder46 end47 Execute(@strSQL)48 Go
分页存储二:
1 create procedure pro_GetRecordForPaging 2 @tableName varchar(200),--表名 3 @pageSize int, --每页显示记录数 4 @pageIndex int, --当前页码 5 @colName varchar(30) --排序的字段名 6 as 7 begin 8 declare @strSQL varchar(300) 9 if @pageIndex = 110 set @strSQL ='select top ['+cast(@pageSize as varchar(20)) + ']'11 + ' * from ['+ @tableName + ']'12 + ' order by ['+ @colName + ']'13 else14 set @strSQL='select top ['+cast(@pageSize as varchar(20)) + ']'15 + ' * from ['+ @tableName + ']'16 + ' where ['+ @colName + ']'17 + ' not in ( select top ['18 + cast((@pageIndex-1)*pageSize as varchar(20)) + ']'19 + @colName + ' from ['+ @tableName + ']'20 + 'order by ['+ @colName +'])'21 + 'order by ['+ @colName +']'22 --print23 Execute(@strSQL)24 end25 go