insert into tab2 (select * from tab2 union select a.itno,(用一个子查询得到最大的sn 加1 )a.qty from tab1 a,tab2 b where .....) 

解决方案 »

  1.   

    不好意思,應該是這樣的(剛剛結果中寫漏了一條記錄).
    TO amtyuranus((看看)) :就是這個子查詢不會做, 因為這個SN要變化.Tab1
    id itno qty
    1 101-001 10
    2 101-001 20
    3 101-001 30
    4 101-002 100
    5 101-002 200
    6 101-002 300
    7 101-003 21
    8 101-003 31
    Tab2 (主鍵為itno , sn)
    itno sn qty
    101-001 1 25
    101-002 1 32
    101-002 2 12結果
    Tab2(主鍵為itno , sn)
    itno sn qty
    101-001 1 25
    101-002 1 32
    101-002 2 12  ----以下記錄為tab1中的數據, sn是取itno 中的最大sn加1 
    101-001 2 10
    101-001 3 20
    101-001 4 30
    101-002 3 100
    101-002 4 200
    101-002 5 300
    101-003 1 21
    101-003 2 31如果不用游標, 直接用insert into tab2(...) select ... from tab1 可不可以實現?
      

  2.   

    主鍵為itno !!!????
    那怎么可能插入这么多一样的itno数据呢?
      

  3.   

    insert tab2 select itno,(select isnull(max(sn),0) from Tab2 where itno=tem.itno)+(select sum(1) from tab1 where itno=tem.itno and id<=tem.id),qty from Tab1 tem
      

  4.   

    sn的取法应该是只要有一个ITNO相同的记录就加1
      

  5.   

    insert tab2 select itno,(select isnull(max(sn),0) from Tab2 where itno=tem.itno)+(select sum(1) from tab1 where itno=tem.itno and id<=tem.id),qty from Tab1 tem
      

  6.   

    select * into #t from (
    select * from tab2
    union all
    select into ,0,qty from tab1 a )temupdate #t set sn=(select Max(sn)+1 from #t aa where aa.into=#t.into) where sn=0select * from #t
      

  7.   

    --测试:create table Tab1(id int,itno varchar(10),qty int)
    insert tab1 values(1,'101-001',10)
    insert tab1 values(2 ,'101-001', 20)
    insert tab1 values(3,'101-001', 30)
    insert tab1 values(4 ,'101-002', 100)
    insert tab1 values(5,'101-002', 200)
    insert tab1 values(6 ,'101-002', 300)
    insert tab1 values(7,'101-003', 21)
    insert tab1 values(8 ,'101-003', 31)
    create table Tab2(itno varchar(10),sn int,qty int)
    insert tab2 values('101-001', 1 ,25)
    insert tab2 values('101-002', 1 ,32)
    insert tab2 values('101-002', 2, 12)insert tab2 select itno,(select isnull(max(sn),0) from Tab2 where itno=tem.itno)+(select sum(1) from tab1 where itno=tem.itno and id<=tem.id),qty from Tab1 tem
    select * from tab2
    go
    drop table tab2,tab1