选择并将行插入多个表,即sql server

时间:2013-10-17 21:16:36

标签: sql sql-server insert

如何同时在两个不同的表中插入多行。

我有3张桌子

create table temp_source
(
  GroupID varchar(10) primary key,
  ExMsg varchar(20)
); 


create table temp_exceptions
(
  ExID int identity primary key,
  ExMsg varchar(20)
); 

create table temp_sjobs
(
  GroupID varchar(10) primary key,  
  ExID int 
); 

temp_sjobs.ExIDtemp_exceptions.ExID

有外键关系

现在我想同时将temp_source表中的所有行插入temp_sjobstemp_exceptions表。

我能做到的唯一方法是遍历temp_source表中的每一行,将行插入temp_exceptions表,获取@ExID = scope_identity()并将该行插入 temp_sjobs表。

这看起来非常慢,并且由于循环,查询需要花费大量时间。

是否有更好的方法可以同时插入多个表格。

4 个答案:

答案 0 :(得分:1)

使用OUTPUT条款可以帮助您的案例,请在下面的示例查询中找到

DECLARE @temp_source table
(
 GroupID varchar(10) primary key,
 ExMsg varchar(20)
); 

DECLARE @temp_exceptions table
(
 ExID int identity primary key,
 ExMsg varchar(20)
); 


INSERT INTO @temp_source Select 1,'message1'
INSERT INTO @temp_source Select 2,'message2'
INSERT INTO @temp_source Select 3,'message3'
INSERT INTO @temp_source Select 4,'message4'


DECLARE @temp_sjobs table
(
 GroupID varchar(10) primary key,  
 ExID int 
); 


DECLARE @temp_InsertedExceptionOutput table
(
    ExID Int,
   ExMsg varchar(20)
)

INSERT INTO @temp_exceptions (ExMsg)
OUTPUT inserted.ExID, inserted.ExMsg into @temp_InsertedExceptionOutput
Select ExMsg from @temp_source

INSERT INTO @temp_sjobs(GroupID,ExID)
SELECT ts.GroupID, eo.ExID
FROM @temp_InsertedExceptionOutput eo
JOIN @temp_source ts on ts.ExMsg = eo.ExMsg


Select * from @temp_source
Select * from @temp_exceptions
Select * from @temp_sjobs

使用表格设计,我认为ExMsg是独一无二的,您可能会发现完整性问题。

答案 1 :(得分:0)

当然,您可以执行以下操作 - 可能是最简单的方法:

SELECT INTO temp_sjobs FROM temp_source
SELECT INTO temp_exceptions FROM temp_source

如果您想同时执行所有操作,可以将其设为 CTE CURSOR 。除此之外,您必须将其作为 TRIGGER - 基本上,如果 temp_source 中有新条目,它将 INSERT a新记录到 temp_sjobs temp_exceptions

答案 2 :(得分:0)

我认为你最好的选择是使用两个插入语句

INSERT INTO temp_exception (ExMsg)
SELECT DISTINCT ExMsg
  FROM temp_source

INSERT INTO temp_sjobs (GroupID, ExID)
SELECT ts.GroupID, te.ExID
  FROM temp_exceptions te
  JOIN temp_source ts
    ON ts.ExMsg = te.ExMsg

首先构建temp_exception表,然后创建temp_sjobs表并将两者链接在一起。

答案 3 :(得分:0)

据我所知,您希望将表temp_source拆分为temp_exceptions和temp_sjobs,并在它们之间使用外键关系。有些时候我也遇到过同样的情况,我选择了下面的解决方案以获得更好的性能:

declare @Exid int
select @Exid = max(ExID) from temp_exceptions 

if @Exid is null
set @Exid = 0

set Identity_insert temp_exceptions ON

insert into temp_exceptions (ExID, ExMsg)
select @Exid + row_number() over(order by (select NULL)), ExMsg from temp_source

insert into temp_sjobs (ExID, GroupID)
select @Exid + row_number() over(order by (select NULL)), GroupID from temp_source

set Identity_insert temp_exceptions OFF

select * from temp_exceptions;
select * from temp_sjobs;
相关问题