I have a query that's pulling data from a linked server into a temp table (#SWTable). Here is a sample of the data in that table:
It's being ordered by Code, Date
Code Cust Date Plan
123 111 4/27/2011 C25
456 222 4/19/2011 LMN
789 333 4/19/2011 LMN
789 333 4/20/2011 LMN
011 444 4/25/2011 C25
011 444 4/26/2011 LMN
I need to insert that data into a table I have created: PACust
The part I'm having trouble with is my insert statement, because the PACust table cannot have duplicate Cust. The logic that I need to create the insert statement is:
Insert Code, Cust, Date, Plan INTO PACust
From the #SWTable only if that Cust is not already in the PACust Table.
So for example (from my sample data) It would insert:
123 111 4/27/2011 C25
456 222 4/19/2011 LMN
789 333 4/19/2011 LMN
011 444 4/25/2011 C25
Then what I need to do after only ONE of each Cust record is inserted, is run an update statement so that it updated the Code, Date, and Plan ( I need the most recent Plan, Code, and Date in the final PACust table ).
Here is the insert statement that I have now, but it's inserting ALL of the rows (including duplicates), so I need it to do what I described above. Any help would really be appreciated!
Insert INTO PACust (Code, Cust, Date, Plan)
SELECT A.Code, A.Cust, A.Date, A.Plan
FROM #SWTable A
WHERE NOT EXISTS
(SELECT CustOBJID
FROM PACust
WHERE PACust.Cust = A.Cust)
It's being ordered by Code, Date
Code Cust Date Plan
123 111 4/27/2011 C25
456 222 4/19/2011 LMN
789 333 4/19/2011 LMN
789 333 4/20/2011 LMN
011 444 4/25/2011 C25
011 444 4/26/2011 LMN
I need to insert that data into a table I have created: PACust
The part I'm having trouble with is my insert statement, because the PACust table cannot have duplicate Cust. The logic that I need to create the insert statement is:
Insert Code, Cust, Date, Plan INTO PACust
From the #SWTable only if that Cust is not already in the PACust Table.
So for example (from my sample data) It would insert:
123 111 4/27/2011 C25
456 222 4/19/2011 LMN
789 333 4/19/2011 LMN
011 444 4/25/2011 C25
Then what I need to do after only ONE of each Cust record is inserted, is run an update statement so that it updated the Code, Date, and Plan ( I need the most recent Plan, Code, and Date in the final PACust table ).
Here is the insert statement that I have now, but it's inserting ALL of the rows (including duplicates), so I need it to do what I described above. Any help would really be appreciated!
Insert INTO PACust (Code, Cust, Date, Plan)
SELECT A.Code, A.Cust, A.Date, A.Plan
FROM #SWTable A
WHERE NOT EXISTS
(SELECT CustOBJID
FROM PACust
WHERE PACust.Cust = A.Cust)