一、存储过程
1、当存储过程传入参数很多,为空的参数不参与where语句查询如何处理
USE [数据库名] GO /****** Object: StoredProcedure [dbo].[cp_Table1] Script Date: 2018/7/9 11:48:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO --取得分页记录列表 ALTER PROCEDURE [dbo].[cp_存储过程名] @Page int,--页数 @PageSize int,--每页条数 @Title varchar(200),--标题(查询内容) @RowCount int output,--总行数
@Downloader bit,--是否导出 AS DECLARE @iBeginID int --开始分页ID DECLARE @iEndID int --结束分页ID set nocount on --提高性能 SET @iBeginID = (@Page-1) * @PageSize + 1 SET @iEndID = @iBeginID + @PageSize - 1 SET @RowCount = 0 DECLARE @Sql_GetCount NVARCHAR(MAX); DECLARE @Sql_Sigel NVARCHAR(MAX); DECLARE @DateNow DateTime =GETDATE();
SET @Sql_GetCount=N' SELECT @RowCount = COUNT(ID) FROM Table1 WITH(NOLOCK) WHERE 1=1'
--这是关键,拼接查询语句(有其他条件继续写if,与程序里写拼接类似) IF(LEN(@Title)>0) SET @Sql_GetCount+=N' AND Title LIKE ''%''+@Title+''%'' '
--执行拼接代码 EXECUTE sp_executesql @Sql_GetCount,N' @RowCount INT OUTPUT,@Title varchar(200)', @RowCount =@RowCount OUTPUT,@Title =@Title
--如果没数据直接return,提高效率 IF(@RowCount = 0) RETURN 0;
--以下是主要查询语句 SET @Sql_Sigel=N' WITH t AS ( SELECT ROW_NUMBER() OVER (ORDER BY OrderNum DESC) AS R_Number, * FROM Table1 WITH(NOLOCK) WHERE 1=1 ' IF(LEN(@Title)>0) SET @Sql_Sigel+=N' AND Title LIKE ''%''+@Title+''%'' ' SET @Sql_Sigel+=N') SELECT * FROM t’ IF(@Downloader=0) SET @Sql_Sigel+=N' WHERE R_Number BETWEEN @iBeginID AND @iEndID;'
--执行代码 EXECUTE sp_executesql @Sql_Sigel,N' @RowCount INT OUTPUT,@Title varchar(200),@iBeginID int,@iEndID int', @RowCount =@RowCount OUTPUT,@Title =@Title,@iBeginID=@iBeginID,@iEndID=@iEndID
结果分析:当参数较多时使用拼接sql方式可减少代码冗余,且效率更高。SELECT ROW_NUMBER() OVER (ORDER BY OrderNum DESC) AS R_Number, 此句给数据排序并每条按顺序编号,用于分页