update b
set b.hitnum=b.hitnum+1
from a
where a.a1=b.b1 and a.a2=b.b2insert b select a1,a2,1 
from a 
where not exists(
  select 1 from b where b.b1=a.a1 and b.b2=a.a2)

解决方案 »

  1.   

    Tony:哥们thanks 你的回复,但是此语句是实现不了的。我已经尝试过了!
      

  2.   

    Tony:哥们,你的语句,我试了一下,是没有成功掉!
      

  3.   

    if object_id('a') is not null drop table a 
     go 
    create table a([a1] int,[a2] int)
    insert a select 1,2
    union all select 1,2
    union all select 1,3
    union all select 2,2
    union all select 2,2
    union all select 3,3if object_id('[b]') is not null drop table [b] 
     go 
    create table [b]([b1] int,[b2] int,[hitnum] int)
    insert [b] select 1,2,2
    union all select 1,3,1
    union all select 2,2,2
    union all select 3,3,1
    if object_id('tg_a') is not null drop trigger tg_a 
     go 
    create trigger tg_a on a
    for insert
    as
    update b
    set b.hitnum=b.hitnum+1
    from inserted
    where inserted.a1=b.b1 and inserted.a2=b.b2
    goselect * from b
    /*
    b1          b2          hitnum
    ----------- ----------- -----------
    1           2           NULL
    1           3           NULL
    2           2           NULL
    3           3           NULL(4 行受影响)
    */insert a select 2,2select * from b
    /*
    b1          b2          hitnum
    ----------- ----------- -----------
    1           2           2
    1           3           1
    2           2           3
    3           3           1(4 行受影响)
    */这是插入的例子,看看是不是要像这样的.
      

  4.   

    --插入前:
    b1          b2          hitnum
    ----------- ----------- -----------
    1           2           2
    1           3           1
    2           2           2
    3           3           1(4 行受影响)--插入后:b1          b2          hitnum
    ----------- ----------- -----------
    1           2           2
    1           3           1
    2           2           3
    3           3           1(4 行受影响)
      

  5.   

    Tony:哥们 ,请问可以使用存储过程实现的吗?
    我现在是用group来弄,但是效率肯定不高
      

  6.   

    Tony:哥们 实现的效果还可以,但是在hitnum,第二次又会自动加上去的?这个是为什么?
      

  7.   

    Tony:哥们,如果有新记录,B表中没有自动加上去。只有在B记录有的情况下,A记录向B表添加记录,会自动累加数据,但是不会自动添加新记录!
      

  8.   

    看楼主的意思是,数据库要改表结构吧?A表应该是legacy,B表是新的表结构,A表用完就可以drop了对吗?如果不是这样的话,那么楼主最好修改数据表结构。这两个表应该各有primary key,假定是类似自动增量的。那么,如果上面的假设成立,你就用最简单的update去做就OK了,一次不能update太多(比如一次5000条),否则回滚段受不了的。另外,做这项操作之前:
    1. 做好A表和B表的备份;
    2. 数据库在做这项操作的时候,最好能够不被其他应用使用。