代码之家  ›  专栏  ›  技术社区  ›  Msa Man

在SQL Server 2008中向我的表中插入累计总数

  •  1
  • Msa Man  · 技术社区  · 10 年前

    我想这样计算跑步总数( idd 不是主键或外键)

    idd    svalue      acctotal
    1       5             5
    2       6             11
    1       2             13
    3       4             17
    2       1             18
    

    等等

    我在许多触发器中工作,但它不起作用:

     create trigger acc on detail 
     for update, insert 
     as 
         DECLARE @AccountID INT
         DECLARE @getAccountID CURSOR
    
         SET @getAccountID = CURSOR FOR
            SELECT idd
            FROM detail
    
         declare @tot as int
         set @tot = (select sum(dvalues) from detail)
    
         OPEN @getAccountID
    
         FETCH NEXT FROM @getAccountID INTO @AccountID
    
         WHILE @@FETCH_STATUS = 0
         BEGIN
            PRINT @AccountID
    
            UPDATE detail 
            SET acctotal = @tot
    
            FETCH NEXT FROM @getAccountID INTO @AccountID
         END
    
         CLOSE @getAccountID
    
    2 回复  |  直到 10 年前
        1
  •  0
  •   Liam Wheldon    10 年前

    你能不这样做吗

    @tot = (select top 1 isnull(acctotal, 0) + @newvalue from detail order by acctotal desc)
    

    只有当你只处理正数时,这才有效。。。最好的方法是提供一些独特的建议。即使只是添加一个种子列也可以按顺序排序。

    当做

    利亚姆

        2
  •  0
  •   Deepshikha    10 年前

    您可以将触发器编写为:

    create trigger acc on detail for update, insert 
    as 
    
    ;with cte as
    (
        select idd,svalue,acctotal, row_number() over ( order by (select 1)) as rownum
        from detail
    )
    Update T1 set acctotal = 
            (SELECT SUM(svalue)
             from cte as T2
             where T1.rownum >= T2.rownum )        
    from cte T1
    
    Go
    

    Check Demo here..