Link to home
Start Free TrialLog in
Avatar of brasso_42
brasso_42

asked on

MSSQL Insert into multiple tables

Hi

I want to insert into 2 tables multiple values.  e.g.

I have 2 tables.  

Table 1 = Emails_Sent
ES_ID, Cont_ID, DateTime

Table2 = Countrys_SentTo
CST_ID, ES_ID, Country_ID

A contact has multiple Countries.  When an e-mail is sent to them it logs in the Emails_Sent
and also logs the countries that contact is responsible for.  

If this was just one I'd have no problem using SCOPE_IDENTITY(), but I need to be able to do multiple e-mails sent at once

I have tried
Declare @ID int
Insert into  Emails_Sent (Cont_ID, DateTime) Select Cont_ID, getdate() From MyContTable
Set @ID = SCOPE_IDENTITY()
Insert into  Countrys_SentTo (ES_ID, Country_ID) Select @ID, County_F From MyCont_County_Table

The other issue I have is linking the 2 inserts into together e.g.MyContTable.Cont_ID = MyCont_County_Table.Cont_ID

I think I need to loop through the first, but don’t know how to do this.

Can any one help

Thanks

Brasso
ASKER CERTIFIED SOLUTION
Avatar of Om Prakash
Om Prakash
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of man2002ua
man2002ua

The example above is simple and will work on any MSSQL, but as I can see you are using 2008, so you can use all power of MSSQL2008:


DECLARE @TmpTable table( InsID INTEGER);

Insert into  Emails_Sent (Cont_ID, DateTime) 
   OUTPUT INSERTED.<YOUR_IDENTITY_NAME_HERE>
   INTO @TmpTable
Select Cont_ID, getdate() From MyContTable;

Insert into  Countrys_SentTo (ES_ID, Country_ID) 
Select tmp.InsID, County_F From @TmpTable tmp, MyCont_County_Table;

Open in new window

Avatar of brasso_42

ASKER

Awsome workd like a dream!

Many thanks

Brasso