sqlpaginationsql-updatewith-statement

update table after ;with() select statement


I use this procedure to select records with paging :

ALTER PROCEDURE [PorSun].[soalPagingByIdGroupIdUser]  ( 
   @IdGroup , 
   @pageNo int, 
   @pageSize int)  
AS 
   DECLARE @start int, @end int 
   SET @start = @pageSize*(@pageNo-1)+1 
   SET @end= @start+@pageSIze-1

   ;with Records as
   (
       SELECT 
          PorSun.soal.Id, PorSun.soal.IdUser, PorSun.soal.VisitCount
          , ROW_NUMBER() over(order by PorSun.soal.Id) as RN
       FROM PorSun.soal 
       WHERE (PorSun.soal.IdGroup=@IdGroup)
   )
   SELECT Records.Id, Records.IdUser, Records.VisitCount
   FROM Records
   WHERE RN between @start and @end and (Records.IdGroup=@IdGroup)
   ORDER BY Records.Id desc

   UPDATE [PorSun].[Soal]
   SET [VisitCount] = [VisitCount]+1
   WHERE Id IN (SELECT Id FROM Records)

There is no syntax error, but on execute error.

How is it possible?


Solution

  • You can use a table variable instead of a CTE:

    DECLARE @Records TABLE
    (
       Id         int,
       IdUser     int,
       VisitCount int,
       RN         int
    )
    
    INSERT INTO @Records
    SELECT 
        PorSun.soal.Id, 
        PorSun.soal.IdUser, 
        PorSun.soal.VisitCount,
        ROW_NUMBER() over(order by PorSun.soal.Id) as RN
    FROM PorSun.soal 
    WHERE (PorSun.soal.IdGroup=@IdGroup)
    
    
    SELECT Id, IdUser, VisitCount
    FROM @Records 
    WHERE RN between @start and @end and (IdGroup=@IdGroup)
    ORDER BY Id desc
    
    UPDATE [PorSun].[Soal]
    SET [VisitCount] = [VisitCount]+1
    WHERE Id IN (SELECT Id FROM @Records)