I am trying to add information to two tables. The first table will issue an ID number that must be included in the second table, and data is only to be added to the second table if it is not already there.
Right now, I have this (needless to say, it doesn't work). The DECLARE bit is fine and returns the ID and I can use the ID if I just select it and don't want to add multiple rows or check for previous existance. Any push in the right direction would be most welcome!
DECLARE @ID Table (ID int);
INSERT INTO Table1 (FIELD1, FIELD2, FIELD3)
OUTPUT Inserted.IDFIELD INTO @ID
VALUES(1, 2, 3);
INSERT INTO Table2 (Other1_theID, Other2, Other3)
Select (@ID.Sequence, New.Other2, New.Other3)
from @ID, NEW
(VALUES(Sequence,'A','B'),
(Sequence,'C', 'D'),
(Sequence,'E', 'F'),
(Sequence,'G', 'H')) as NEW
where not exists (SELECT 'X' FROM Table2 TT WHERE TT.Other3 IN ('B','D','F','H');
So, in the above case, I'm adding a new row to Table1 with the first four lines and that much works fine.:
ID FIELD1 FIELD2 FIELD3
1 5 8 6 <existing data
2 9 3 2 <existing data
3 4 1 7 <existing data
4 1 2 3 <my new row
^ the new ID automatically assigned by the system when the new row is added to the table
In the second bit, I need to add to a second table some data associated with the first (so I need to bring the ID along). If I use this code to bring in one row of data, it works:
INSERT INTO Table2 (Other1_theID, Other2, Other3)
Select ID, A, B from @ID
Other1_theID Other2 Other3
4 A B <my new row
^ the new ID I go from the Table1 insertion.
All of that's great, but I really want to add several rows to Table 2 AND I only want to add the if they don't already exist (if A, B exist in Other2 and Other3 with a different ID, then don't add them).