加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

善用临时表---同时查询多张表的存储过程

发布时间:2020-12-12 14:12:48 所属栏目:MsSql教程 来源:网络整理
导读:一个存储过程的需求是这样的: 1、取出三张表里的符合条件的数据,合成一张表,并对这一张表分页; 2、计算合成的这张表总共多少条数据 存储过程语句如下: Create PROCEDURE? GetAnnouncementList ?? ?@pageSize int, ?? ?@pageIndex int AS BEGIN --不返回
一个存储过程的需求是这样的:
1、取出三张表里的符合条件的数据,合成一张表,并对这一张表分页;

2、计算合成的这张表总共多少条数据


存储过程语句如下:

Create PROCEDURE? GetAnnouncementList
?? ?@pageSize int,
?? ?@pageIndex int
AS
BEGIN

--不返回影响的行数,提高性能--
?? ?SET NOCOUNT ON;


?? ?declare @rowCount int


--将数据查询出来放入临时表#temptable中,语法:“ select? 字段 into 临时表名 from ” --
select ROW_NUMBER()over (order by #temptable.CreatedOn desc)as tempNum,* into #temptable from
(select 'markNews' as mark,News.NewsID,News.NewsTitle,News.CreatedOn from dbo.News where CategoryID ='8b041bf4-24bf-4b35-85c7-f72717dc5752'
union all
select 'markActivity' as mark,Activities.ActivityID,Activities.Subject,Activities.CreatedOn from dbo.Activities where Activities.CheckStatus=1 and IsDeleted=0 and Activities.RealEndTime>(select GETDATE())
union all
select 'markTrain' as mark,Train.TrainID,Train.Subject,Train.CreatedOn from dbo.Train where CheckStatus=1 and Train.PlannedEndTime>(select GETDATE()))as #temptable

--计算临时表中的数据条数--
select @rowCount=COUNT(*) from #temptable

--对临时表中的数据分页读取-- select * from #temptable where #temptable.tempNum>(@pageIndex-1)*@pageSize and #temptable.tempNum<=(@pageIndex*@pageSize) return @rowCount END

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读