Create Proc CMST_QueryInterrelated
@ID int, ----给定的记录的主键
@Num int ---需要条数
As
Declare @RNum int
Declare @SQL nvarchar(2000)
Set @SQL=''
Set @RNum=0
Select @RNum=Count(ID) From [CMST] Where [ID]> @ID
If(@RNum-@Num) > 0
Begin
Set @SQL='Select Top '+ cast(@Num as nvarchar) +' ID,Title,AddTime From [CMST] Where [ID]>' + cast(@Id as nvarchar)
End
Else
Begin
Set @SQL='Select Top '+ cast(@Num as nvarchar) +' ID,Title,AddTime From [CMST] Where [ID]>' + cast(@Id as nvarchar)
+ 'Union Select Top ' + cast((@Num-@RNum) as nvarchar) +' ID,Title From [CMST] Where [ID] < ' + cast(@Id as nvarchar) End
Exec (@SQL)
上面的功能是,返回比给定ID 大的 @Num 条数据,如果 比ID大的记录不足@Num条,那么少的部分由ID比@ID小的记录获取(形成一个环型),另外你可以在 where 里加入其他条件比方同一分类等等..