//Pass FirstRec ,CurrentPage ,PageSize ,LastRec,OrderBy,OrderByType parameter through .Net
declare @total int //count total row
Declare @FirstRec int
declare @CurrentPage int
declare @PageSize int
Declare @LastRec int
Set @FirstRec = (@CurrentPage - 1) * @PageSize
Set @LastRec = (@CurrentPage * @PageSize + 1)
IF(@OrderBy = '' or @OrderBy = 'Default')
BEGIN
set @OrderBy = 'mpv.VisitDate '
set @OrderByType='desc'
END
exec ( '
SELECT * FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY ' + @OrderBy + ' ' + @OrderByType + ') AS RowNum,
mp.PatientID,mp.FirstName+'' '' +mp.LastName + case when mp.MobileNumber <>'''' then ''/ '' + mp.mobilenumber else '''' END Name , convert(varchar(10),mpv.VisitDate,103)VisitDate,mpv.PatientVisitID,(select count(*) from MDTM_Patient mp left JOIN MDTM_Patient_VisitDetail mpv on mp.PatientID=mpv.PatientID
where mp.IsDeleted=0 and mp.CreatedBy='+@LoginUserId +')as totalpatient,mc.ConsultationType,convert(varchar(10),mc.SentForReviewOn,103)SentForReviewOn,mu.FirstName +'' ''+ mu.LastName as Referto,mc.CaseStatus
FROM MDTM_Patient mp left JOIN MDTM_Patient_VisitDetail mpv on mp.PatientID=mpv.PatientID left join MDTM_Patient_Consultation mc on mpv.PatientID=mc.PatientID and mc.isdeleted=0 left join MDTM_Users mu on mc.ReferredToDoctor=mu.UserID and mu.IsDeleted=0
where mp.IsDeleted=0 and mp.CreatedBy='+@LoginUserId +' and
(
mp.FirstName like '''+ @search+ '%'' or mp.LastName like '''+ @search+ '%'' or
mp.FirstName+'' ''+mp.LastName LIKE '''+ @search+ '%'' OR
mu.FirstName like '''+ @search+ '%'' or mu.LastName like '''+ @search+ '%'' OR
mu.FirstName+'' ''+mu.LastName LIKE '''+ @search+ '%'' OR
mc.CaseStatus LIKE '''+ @search+ '%'' OR
CONVERT(varchar,mpv.VisitDate,105)= '''+ @search+ ''' OR
CONVERT(varchar,mc.SentForReviewOn,105)= '''+ @search+ '''
)
) records
where records.RowNum>' + @FirstRec + ' and records.RowNum< '+@LastRec )