初识 Sql Server存储过程

开篇语

之前的公司并未使用存储过程来做项目,所以小生对存储过程的调用、使用也是一知半解,刚好这家公司就大量用到了存储过程

这次做的功能,为了保持风格一致,也是需要使用存储过程来实现动态sql和数据分页

下面一起来看看如何实现的吧(小白一枚,不喜勿喷,请轻拍)~

调用存储过程(其中condition 是前台传入的拼接查询条件,parameters[4] 是排序字段)

 

存储过程实现

是否

USE [EPMS]
GO
/****** Object:  StoredProcedure [dbo].[sp_GetCollectionManage]    Script Date: 2016/9/14 10:14:00  ZhangXiaoYong******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_GetCollectionManage]
     @PageSize  INT,--页面大小
     @pageCurrentIndex INT,--当前页数
     @condition nvarchar(MAX),-- 查询条件
     @pageCount INT OUT ,-- 当前页 内容数量
     @orderStr  nvarchar(MAX)  --排序字段
AS 
begin
/*获取记录数*/
declare @RecordCount int
/*计算页面数据*/

declare @SqlMain nvarchar(4000)
declare @SqlStr nvarchar(4000)
/* SQL SERVER 拿到查询的数据总数*/
set @SqlMain='select @CountTemp=count(1) from 
(
select ef.id, e.dictdata_name, ef.city_id,ef.receive_time,ef.receive_amount,ef.batch_id,ef.city__Manager,ef.contract_id
,ROW_NUMBER()  Over(order by '+@orderStr+' desc) As SerialNumber 
from V_city e 
left join Collection_Confirmation ef on e.id = ef.city_id where '+@condition+') as T left join Contract fa on T.contract_id = fa.id  
left join V_employeeDutyMerger show 
on T.dictdata_name=show.cityname and show.dutyname=''城市经理''';
exec sp_executesql @SqlMain,N'@CountTemp int output',@pageCount output; --重要执行

declare @beginIndex as varchar(20)
declare @endIndex as varchar (20)
--定义一个开始数,和一个结束数,用于分页
set @beginIndex=(@pageCurrentIndex-1)*@PageSize+1    set @endIndex=@pageCurrentIndex*@PageSize
/* SQL SERVER 执行查询并分页输出 */
set @SqlStr=
'select T.id, T.dictdata_name, T.receive_time,T.receive_amount,T.batch_id, fa.contract_name,show.name from 
(
select ef.id, e.dictdata_name, ef.city_id,ef.receive_time,ef.receive_amount,ef.batch_id,ef.city__Manager,ef.contract_id
,ROW_NUMBER()  Over(order by '+@orderStr+' desc) As SerialNumber 
from V_city e 
left join Collection_Confirmation ef on e.id = ef.city_id where '+@condition+') as T left join Contract fa on T.contract_id = fa.id  
left join V_employeeDutyMerger show 
on T.dictdata_name=show.cityname and show.dutyname=''城市经理'' where  T.SerialNumber>='+cast(@beginIndex as varchar(20) )+ ' and T.SerialNumber <='+ 
cast(@endIndex as varchar(20)) 

--print (@pageCurrentIndex * @PageSize)
--print @SqlCount1
--print @SqlStr
exec (@SqlStr)

end

-- 执行该存储过程
declare @pageCount int;
exec [dbo].[sp_GetCollectionManage] 15,1,' ef.city_id in(210)',@pageCount output,'ef.id'
存储过程实现

前台效果

第一页

第二页

注:此存储过程还有很多需要优化的地方,仅供参考,欢迎提宝贵意见~

 End

 

原文地址:https://www.cnblogs.com/zhangxiaoyong/p/5871156.html