日期:2014-05-18  浏览次数:20489 次

sql如何向一个表插入时,向另外一个表插入多行
表kh(khdm,khmc)
  001,单位1
  002,单位2
.....
表xm(xmdm,xmmc)
  1001,牙刷
  1002,牙膏
.....
表gx(khdm,xmdm,jg)
  001,1001,10
  001,1002,20
  002,1001,11
  002,1002,19
 .....
向kh插入(003,单位3)时gx表也自动插入(003,1001,null),(003,1002,null)....xm表有多少条记录就插入多少

------解决方案--------------------
SQL code
insert kh select '003','单位3'
insert gx select a.khdm,b.xmdm,null from (select '003' khdm)a,(select xmdm from xm)b

------解决方案--------------------
SQL code

SET XACT_ABORT ON 
BEGIN TRANSACTION

INSERT INTO kh
(
    khdm,
    khmc
)
VALUES 
(
    '003',
    '单位3'
)

INSERT INTO gx
(
    khdm,
    xmdm,
    jg
)
SELECT    '003',
        xmdm,
        NULL
FROM    xm WITH(NOLOCK)
        
COMMIT TRANSACTION

------解决方案--------------------
SQL code
if not object_id('kh') is null
    drop table kh
Go
Create table kh([khdm] nvarchar(3),[khmc] nvarchar(3))
Insert kh
select N'001',N'单位1' union all
select N'002',N'单位2'
Go
 
if not object_id('xm') is null
    drop table xm
Go
Create table xm([xmdm] int,[xmmc] nvarchar(2))
Insert xm
select 1001,N'牙刷' union all
select 1002,N'牙膏'
Go
if not object_id('gx') is null
    drop table gx
Go
Create table gx([khdm] nvarchar(3),[xmdm] int,[jg] int)
go
if object_id('tri','TR')is not null drop trigger tri
go
create trigger tri on kh
for insert 
as
insert gx 
select a.khdm,
       b.xmdm,
       null 
from (select  khdm from inserted)a,(select xmdm from xm)b
go
insert kh select '001',N'单位1'
select * from gx
insert kh select '002',N'单位2' union all select '003',N'单位3'
select * from gx
/*
khdm xmdm        jg
---- ----------- -----------
001  1001        NULL
001  1002        NULL

(2 row(s) affected)

(4 row(s) affected)


(2 row(s) affected)
khdm xmdm        jg
---- ----------- -----------
001  1001        NULL
001  1002        NULL
003  1001        NULL
002  1001        NULL
003  1002        NULL
002  1002        NULL

(6 row(s) affected)
*/