SQL2005递归查询+存储过程分页

超、凢脫俗 2022-06-07 23:38 309阅读 0赞

一、资讯类别表ArticleType

1343287504_9563.jpg

资讯表Article

1343287667_8113.jpg

二、递归查询一

with

table1 as

(

  1. select \* from ArticleTypewhere Id=1 \--定位点成员(也就是初始值或第一个结果集)
  2. union all
  3. select a.\* from ArticleType ainner join table1on a.ParentId=table1.Id\--递归成员

)

select* from table1

1343287791_1739.jpg结果1
三、递归查询二

with

table1 as

(

  1. select \* from ArticleTypewhere Id=4 \--定位点成员(也就是初始值或第一个结果集)
  2. union all
  3. select a.\* from ArticleType ainner join table1on a.Id=table1.ParentId\--递归成员

)

select* from table1

1343287848_9257.jpg结果2

四、递归查询结合分页存储过程

alterprocedure UP_Article_ListOfPre_select

@PageIndex int=1,--当前页码

@PageSize int=10,--每页大小

@TypeName nvarchar(20)=’彩票资讯’,--资讯类别名称

@RecordCount int=0 output--当前条件下的总记录数

as

begin

declare @StartIndexint,@EndIndex int

declare @Idint

set @StartIndex=(@PageIndex-1)*@PageSize

set @EndIndex=@StartIndex+@PageSize-1

select @Id=Idfrom ArticleType where TypeName=@TypeName

;with

table1 as

(

  1. select Id from ArticleType where Id=@Id \--定位点成员(也就是初始值或第一个结果集)
  2. union all
  3. select a.Id from ArticleType ainner join table1on a.ParentId=table1.Id\--递归成员

)

-- select * from table1 —CTE with之后第一句必须使用CTE的select。CTE的生命周期只是在第一次使用之后就消亡。

select Idinto #mytb from table1

--获取当前条件下的总记录数

select @RecordCount=count(Id)from Article where TypeIdin(select Id from #mytb)

--分页查询

select* from

(

  1. select row\_number() over(orderby AddTime desc)as Row,Id, Title,AddTimefrom Article
  2. where TypeId in(select Idfrom \#mytb)

) awhere Row between @StartIndexand @EndIndex

end

1343288045_1625.jpg分页结果

五、C#调用代码

///

  1. ///根据条件分页查询信息
  2. ///</summary>
  3. ///<param name="pageIndex">当前页码</param>
  4. ///<param name="pageSize">每页大小</param>
  5. ///<param name="typeName">资讯类别名称</param>
  6. ///<param name="recordCount">out参数,当前条件下的总记录数</param>
  7. ///<returns>分页查询后的列表</returns>
  8. public DataTable GetList(int pageIndex, int pageSize, string typeName, out int recordCount)
  9. \{
  10. SqlParameter\[\] parms = \{
  11. new SqlParameter("@PageIndex",SqlDbType.Int),
  12. new SqlParameter("@PageSize",SqlDbType.Int),
  13. new SqlParameter("@TypeName",SqlDbType.NVarChar,20),
  14. new SqlParameter("@RecordCount",SqlDbType.Int)
  15. \};
  16. parms\[0\].Value = pageIndex;
  17. parms\[1\].Value = pageSize;
  18. parms\[2\].Value = typeName;
  19. parms\[3\].Direction = ParameterDirection.Output;
  20. DataTable dt = SQLHelper.GetDataTable(CommandType.StoredProcedure, "UP\_Article\_ListOfPre\_select", parms);
  21. recordCount = Convert.ToInt32(parms\[3\].Value);
  22. return dt;
  23. \}

发表评论

表情:
评论列表 (有 0 条评论,309人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SQL 存储过程

    SQL 分页存储过程 支持:多表连接查询、Group by分组查询等。(多表连接查询时请指定字段,不要用SELECT \) 返回为一结果集,有一个输出参数为记录总数,配