有两个数据表:
用户表user
userId username productsum LastproductId --这一行是数据表表头,其中productsum 保存着此用户的物品数目.
1       userA    2             5
2       userB    3             4
3       userC    4             9
物品表product
productId productName ProductOwner
1           ddd        userA    
2           ddew       userB    
3           er234      userB
4           rewqr      userB  
5           w32re      userA
6           erqw32     userC
7           rewqr      userC
8           fwqfe      userC
9           erqrewq    userC 
因为物品表是不断增加的,随着物品表中物品的增加,在用户表中的productsum 也增加个数,用户表中的LastproductId保存最后统计的物品ID,目前他们的对应关系是上面所示.
之所以在user表中设置LastproductId,是因为product表是一个记录相当多的表(记录超过60万条),而用户表中只需要统计每个用户所拥有物品的数目,所以上次统计过了数目不必要再重新加一次了,每次只需要从上次统计过的ID这里开始统计product表中后面的物品的数目
现在的问题是能否做一个sql语句或者是存储过程,每次运行时接着上次的处理结果,对这两个表进行统计?
这个问题可能有些难,希望各位会的朋友指教,免得我次次都是对user表中一条条记录分别去处理.谢谢.

解决方案 »

  1.   

    create trriger tr_test on product for insert 
    as
    declare @count int, @lastproductid varchar(10)
    select @count = count(1) from inserted where  ProductOwner = 'userA '
    select top 1 @lastproductid=productId from inserted where ProductOwner = 'userA ' order by productid
    update  user set productsum = productsum + @count,LastproductId = @lastproductid where username  = 'userA'
    select @count = count(1) from inserted where  ProductOwner = 'userB '
    select top 1 @lastproductid=productId from inserted where ProductOwner = 'userB ' order by productid
    update  user set productsum = productsum + @count,LastproductId = @lastproductid where username  = 'userB'
    select @count = count(1) from inserted where  ProductOwner = 'userC '
    select top 1 @lastproductid=productId from inserted where ProductOwner = 'userC ' order by productid
    update  user set productsum = productsum + @count,LastproductId = @lastproductid where username  = 'userC'
    go
      

  2.   

    create trigger tritest on product
    for inserted
    as
    begin
    update user set productsum=productsum+1,LastproductId=inserted.productId
    end
    未测试,主要思路是加触发器,更新user表中内容。
      

  3.   

    触发器我也有做,但是效果不太好,有时有误差,这个功能其实不经常用,只是当有误差时,进行重新统计时才使用的.触发器应该是这样写:
    create trigger tritest on product
    for inserted
    as
    begin
    update user set productsum=productsum+a.productnum ,LastproductId=a.maxProductid from
    user b,(select count(*) as productnum ,max(productId) as maxProductid from inserted) a
    end
    这样当批量插入时不至于只对一条记录生效.
      

  4.   

    触发器我也有做,但是效果不太好,有时有误差,这个功能其实不经常用,只是当有误差时,进行重新统计时才使用的.触发器应该是这样写:
    create trigger tritest on product
    for inserted
    as
    begin
    update user set productsum=productsum+a.productnum ,LastproductId=a.maxProductid from
    user b,(select count(*) as productnum ,max(productId) as maxProductid ,username from inserted) a where a.ProductOwner=b.username
    end
    这样当批量插入时不至于只对一条记录生效.
    上面漏了条件判断.
      

  5.   

    晕了,在那个括号里面还是漏了一个GROUP BY UserName,不加这个会出错的.