if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_GetDiscountCodes]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[usp_GetDiscountCodes] GO CREATE PROCEDURE [dbo].[usp_GetDiscountCodes] -- Add the parameters for the stored procedure here @sDiscountCode VARCHAR(255) = '', @sStartDate VARCHAR(20) = '', @sEndDate VARCHAR(20) = '', @pageNo int, @pageLength int, @recordCount int out AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @dtStartDate DATETIME, @dtEndDate DATETIME -- convert the datatype of startdate & enddate parameter to datetime SELECT @dtStartDate = CONVERT(DATETIME,@sStartDate) SELECT @dtEndDate = CONVERT(DATETIME,@sEndDate) --Get the records on the basis of parameters page length and page number rows select LD.Id, LD.DiscountCode, LD.Percentage, LD.StartDate, LD.EndDate, LD.Status from (Select ROW_NUMBER() OVER (ORDER BY Id) AS RowNo, Id, DiscountCode, Percentage, CONVERT(VARCHAR(10),StartDate,101) as StartDate, CONVERT(VARCHAR(10),EndDate,101) as EndDate, (CASE IsActive WHEN 1 THEN 'Active' ELSE 'Inactive' END) AS Status FROM Discount WHERE StartDate >= (CASE WHEN LEN(@sStartDate) > 0 THEN @dtStartDate ELSE StartDate END) AND EndDate <= (CASE WHEN LEN(@sEndDate) > 0 THEN @dtEndDate ELSE EndDate END) AND DiscountCode like (CASE WHEN LEN(@sDiscountCode) > 0 THEN '%' + @sDiscountCode + '%' ELSE DiscountCode END)) as LD where RowNo > @pageLength * (@pageNo - 1) AND RowNo <= @pageLength * @pageNo --Calculate total number of records select @recordCount = count(ResultTable.Id) from (Select Id, DiscountCode, Percentage, CONVERT(VARCHAR(10),StartDate,101) as StartDate, CONVERT(VARCHAR(10),EndDate,101) as EndDate, (CASE IsActive WHEN 1 THEN 'Active' ELSE 'Inactive' END) AS Status FROM Discount WHERE StartDate >= (CASE WHEN LEN(@sStartDate) > 0 THEN @dtStartDate ELSE StartDate END) AND EndDate <= (CASE WHEN LEN(@sEndDate) > 0 THEN @dtEndDate ELSE EndDate END) AND DiscountCode like (CASE WHEN LEN(@sDiscountCode) > 0 THEN '%' + @sDiscountCode + '%' ELSE DiscountCode END)) as ResultTable; END