码迷,mamicode.com
首页 > 数据库 > 详细

初识 Sql Server存储过程

时间:2016-09-14 12:39:38      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

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

这次做的功能,为了保持风格一致,也是需要使用存储过程来实现动态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

 

 

初识 Sql Server存储过程

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!