ALTER PROC [dbo]. [Student_friend_get] @startRowIndexId int, @maxNumberRows int, @schoolId int, @gradeId int, @cId INT, @keyWords NVARCHAR, @userName VARCHAR as BEGIN DECLARE @sqlfilter VARCHAR (max) SET @sqlfilter = "IF" (@schoolId <> -1) SET @sqlfilter = @sqlfilter + ' Tableu. SchoolID = ' + CAST (@schoolId as VARCHAR) + ' and ' IF (@gradeId <>-1) SET @sqlfilter = @sqlfilter + ' Tableu. Gradeid = ' + CAST (@gradeId as VARCHAR) + ' and ' IF (@cId <>-1) SET @sqlfilter = @sqlfilter + ' Tableu. ClassId = ' + CAST (@cId as VARCHAR) + ' and ' IF (@keyWords is not NULL) SET @sqlfilter = @sqlfilter + ' Tableu. Truename like '% '+ CAST (@keyWords as VARCHAR) + '% ' and ' DECLARE @beg INT, @en D INT Set @beg = @startRowIndexId +1 Set @end = @startRowIndexId + @maxNumb Errows SET @sqlfilter = @sqlfilter + ' Tableu.num between ' +cast (@beg as VARCHAR) + ' and ' + CAST (@end as varchar ()) DECLARE @sqlmain varchar (max) Set @sqlmain = ' Set @sqlmain = @sqlmain + ' SELECT * FROM ( SELECT row_number () over (ORDER by CJS. UserName) as Num,cta. Truename, U.username, C.classname + "(" + CAST (Year (c.gradeupdatetime) as NVARCHAR (20) + "years)" as [Classname],s. Schoolname,cjs. Applytime,g.gradename,cjs. Applyid,c.classid,g.gradeid,s.schoolid from Pe_c_studentjoinclass as CJs Left JOIN dbo. Pe_ss_studentclass as C on CJs. ClassId = C.classid left JOIN dbo. Pe_users as U on u.username = CJs. UserName left JOIN dbo. Pe_ss_grade g on G.gradeid = C.gradeid Left JOIN dbo. Pe_ss_school s on s.schoolid = G.schoolid LE FT JOIN pe_contacter CTA on CJs. UserName = CTA. UserName WHERE Applyid in ( SELECT MAX (CS1. Applyid) as [Applyid] from Pe_c_studentjoinclass as CS1Cross JOIN dbo. Pe_c_studentjoinclass as CS2 WHERE CS2. UserName = "+ CAST (@userName as VARCHAR) +" and CS1. UserName! = "+ CAST (@userName as VARCHAR) +" and CS1. ClassId = CS2. ClassId and CS1. Status = 1 GROUP by CS1. UserName)) as Tableu WHERE ' PRINT (@sqlmain + @sqlfilter) EXEC (@sqlmain + @sqlf Ilter) END GO