更新表; with()select语句

时间:2014-06-04 13:25:52

标签: sql sql-update paging with-statement

我使用此过程选择带分页的记录:

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)

没有语法错误,但执行错误。

怎么可能?

1 个答案:

答案 0 :(得分:0)

您可以使用表变量而不是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)