2013-03-12 86 views
0

这里的情况SQL批量插入到选择

我在SQL有一个SP这两个Table type variables这是用来分别执行批量插入到Mails & attachments现在,他们都对MailId在课程one to many SQL关系工作,SP看起来像这样

MailInsertSP 
    @Mails mailsTableVar 
    @Attachements attachementsTableVar 

-- this query will insert mails & generate MailIds 
insert into Mails 
(mails table column list...) 
select 
value list 
from @Mails 

-- this query will insert attachments 
insert into Attachments 
(MailId, other columns...) 
select 
(select MailId from Mails where MailDate = TBL.MailDate) as MailId, 
other values 
from @Attachements as TBL 

到目前为止MailDateunique的邮件因此,此代码工作正常,但现在我已经得到的情况下MailDate两行是相同的,我没有任何其他的列whic h可以用作唯一键,所以我需要的是一些解决方案,以便我可以插入邮件并获取生成的ID,这些ID可以用于下一次插入附件。

如果解决方案将不会跟随

  1. 任何种类的循环,这将是明显的。

  2. 游标。

+0

您可以使用MailDate和MailFrom的组合(假设您有)来确定唯一性而不仅仅是MAILDATE? – 2013-03-12 17:27:11

回答

0

我假设MAILDATE是@Mails

insert into Attachments 
(MailId, other columns...) 
select 
(select MailId from @Mails where MailDate = TBL.MailDate) as MailId, 
other values 
from @Attachements as TBL 
0

唯一我假设你有一个@mails和@attachments之间一对多的关系,例如列X.如果是这样,你可以通过用户[合并... on 1 = 0 ....]/[output ...]将@mail合并到您的邮件表并输出mailID,并将@从@mail输入到temp表中,然后将@attachment插入到表附件中,加入具有maileid和X的临时表。

+0

如果您的表变量邮件和表变量附件之间没有任何唯一关系,那么您的问题是不可避免的。例如,如果您在@mails中有完全重复的记录,那么您如何区分哪个附件属于哪个邮件 – ljh 2013-03-12 17:54:07