先插主表,insert into select.....
然后关联主表取id,再插明细表!

解决方案 »

  1.   

    不行啊。主表的ID 是自增的。先插了主表后,主表里货有多条记录,他的哪个ID应该对应到明细表的ID就不知道了。
      

  2.   

    分两次插入阿。。
    先主表
    然后根据主表Id  select into 字表
      

  3.   

    两条INSERT 语句就可以了吧
      

  4.   

    不行啊。主表的ID 是自增的。先插了主表后,主表里货有多条记录,他的哪个ID应该对应到明细表的ID就不知道了。那你看看这个帖子 跟你情况差不多
    http://www.chinesejy.com/jishu/508/519/2006061781718.html
      

  5.   

    http://www.wangchao.net.cn/bbsdetail_577538.html这个比较全,上面那个内容断了
      

  6.   

    有没有具体sql语句呢,不是很清楚,你是怎么取数,分别插入到主表 和 子表的。关键就是子表的数据 和 主表的数据,你是如何生成的,有没有关联。
      

  7.   

    楼主不妨先去掉外键的关联关系,我想知道楼主查询到的数据是否和要插入的表结构一样,而且有外键关联如果是的话,可以这么做1.去掉插入明细表的外键关系
    2.给主表新增一个字段,存查询数据主表的自增ID
    3.插入主表 明细表数据,按照新增字段关联更新明细表的外键字段例如:
    插入主表  testA(ID,NAME)
    明细表    testB(ID,KEY_ID,NAME)  KEY_ID为外键字段值去掉明细表外键关系查询主表数据为:  select id,name from 查询主表
    明细表数据为:    select id,key_id,name from 查询明细给主表加一个字段,key_id  插入主表数据
    insert into testA(name,key_id)
    select name,id from 查询主表
    插入明细表数据
    insert into testB(key_id,name)
    select key_id,name from 查询明细
    更新明细外键数据
    update testB a
    set a.key_id = b.key_id
    from testA b
    where a.key_id = b.id and b.key_id is not null
    然后删掉主表新增的字段  key_id  即可。在测试表先试试!
      

  8.   

    不行啊。主表的ID 是自增的。先插了主表后,主表里货有多条记录,他的哪个ID应该对应到明细表的ID就不知道了。插入主表的数据应该不会重复吧,用其他唯一的字段确定一下呗!
      

  9.   


    更新语句也错了update testB a
    set a.key_id = b.id
    from testA b
    where a.key_id = b.key_id and b.key_id is not null
      

  10.   

    我弄个例子,大家就明白了create table tmain
    (MainID int identity(1,1),PName varchar(20)) --这个是主表create table tDetail
    (DetailID int identity(1,1), MainID int,Spec varchar(200))--这个是明细表。--这个是其他的表。要从这里把数据插入主表和明细表
    create table tOther(PName varchar(20),PSpec varchar(200))--先弄点数据到其他表里
    insert into tOther (PName,PSpec)
    select 'PN1','Pspec1' union all
    select 'PN1','Pspec2' union all
    select 'PN1','Pspec3' union all
    select 'PN2','Pspec4' union all
    select 'PN2','Pspec5' --要求查出来的数据如下