SQL批量插入select

时间:2013-03-12 17:11:10

标签: sql sql-server-2008 tsql

这是情况

我在SQL中有一个SP,它适用于两个Table type variables,它们分别用于Mails & attachments批量插入,现在它们在one to many的SQL中都有{{}} {1}},SP看起来像这样

MailId

直到现在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 MailDate邮件,所以这段代码工作正常,但现在我的情况是unique两行相同,我没有任何其他可以用作唯一键的列,所以我需要的是一些解决方案,以便我可以在Mails中插入并生成可以在下一次插入附件时使用的ID。

如果解决方案没有以下

,那将是值得注意的
  1. 任何类型的循环。

  2. 光标。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

相关问题