if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_GetExportedImageDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[usp_GetExportedImageDetails] GO CREATE PROCEDURE [dbo].[usp_GetExportedImageDetails] @sStartDate varchar(20) = '', @sEndDate varchar(20) = '', @sAccoutNumber varchar(50)='', @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; Select RowNum, LicenseId, ExportedDate, ImageName, AccountNumber, OriginalFileName, Title, ModuleName, ExportLimit, UserName, imageCount from ( SELECT ROW_NUMBER() OVER (ORDER BY LID.LicenseId) AS RowNum , LID.LicenseId, LID.ExportedDate, LID.ImageName, L.AccountNumber, LID.OriginalFileName, LID.Title, LID.ModuleName, (SELECT TOP(1) LSD.NoofImages FROM LicenseSubscriptionDetail LSD WHERE LSD.LicenseId = LID.LicenseId order by LSD.SubscriptionValidFrom desc) as ExportLimit, USR.FirstName + ' '+ USR.LastName as UserName, (SELECT COUNT(LID1.Id) FROM LicenseImageExportDetail LID1 WHERE LID1.LicenseId = LID.LicenseId group by LID1.LicenseId) as imageCount FROM LicenseImageExportDetail LID LEFT JOIN License L ON LID.LicenseId =L.Id INNER JOIN AIAUser USR ON LID.UserId = USR.Id WHERE ((LEN(@sStartDate)=0) OR (LID.ExportedDate >= (CONVERT(DATETIME,@sStartDate)))) AND ((LEN(@sEndDate)=0) OR (LID.ExportedDate <= (DATEADD(ms,-3,DATEADD(DAY,1,CONVERT(DATETIME,@sEndDate)))))) AND ((LEN(@sAccoutNumber)=0) OR (AccountNumber LIKE '%'+@sAccoutNumber+'%'))) as usr WHERE RowNum > @pageLength * (@pageNo - 1) AND RowNum <= @pageLength * @pageNo order by LicenseId --Calculate total number of records select @recordCount = count(ResultTable.LicenseId) from ( SELECT LID.LicenseId, LID.ExportedDate, LID.ImageName, L.AccountNumber, LID.OriginalFileName, LID.Title, LID.ModuleName, (SELECT TOP(1) LSD.NoofImages FROM LicenseSubscriptionDetail LSD WHERE LSD.LicenseId = LID.LicenseId order by LSD.SubscriptionValidFrom desc) as ExportLimit, USR.FirstName + ' '+ USR.LastName as UserName, (SELECT COUNT(LID1.Id) FROM LicenseImageExportDetail LID1 WHERE LID1.LicenseId = LID.LicenseId group by LID1.LicenseId) as imageCount FROM LicenseImageExportDetail LID LEFT JOIN License L ON LID.LicenseId =L.Id INNER JOIN AIAUser USR ON LID.UserId = USR.Id WHERE ((LEN(@sStartDate)=0) OR (LID.ExportedDate >= (CONVERT(DATETIME,@sStartDate)))) AND ((LEN(@sEndDate)=0) OR (LID.ExportedDate <= (DATEADD(ms,-3,DATEADD(DAY,1,CONVERT(DATETIME,@sEndDate)))))) AND ((LEN(@sAccoutNumber)=0) OR (AccountNumber LIKE '%'+@sAccoutNumber+'%'))) as ResultTable; END