• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 598
  • Last Modified:

SQL 2005 Query copy between two tables

I have 2 tables that I need to do some copying with:
table hrdata will update table Customers
I need to copy some fields and combine 2 fields into 1 field
So:
hrdata.Ansattnr will update Customers.CustomerID
hrdata.FirstName + hrdata.LastName will update Customers.ContactName
hrdata.Title will update Customers.ContactTitle

If hrdata.Ansattnr is not in Customers.CustomerID then it will be added as new record in Customers
If hrdata.Ansattnr is in Customers.CustomerID then it will be updated in Customers

Any help doing this as SQL script in SQL Server 2005 is highly appreciated.
0
Tom
Asked:
Tom
1 Solution
 
tigin44Commented:
-- update the records that are exixts in customers
UPDATE
SET C.ContactName = H.FirstName + ' ' + H.LastName ,
      C.ContactTitle = H.Title
FROM hrdata H INNER JOIN Customers C ON  H.Ansattnr = C.CustomerID

GO
-- Insert the records that are not exists
INSERT INTO Customers (CustomerID, ContactName, ContactTitle)
SELECT H.Ansattnr, H.FirstName + ' ' + H.LastName, H.Title
FROM hrdata H
WHERE NOT EXISTS (SELECT CustomerID FROM Customers  C WHERE H.Ansattnr = C.CustomerID)
GO
0

Featured Post

Get quick recovery of individual SharePoint items

Free tool – Veeam Explorer for Microsoft SharePoint, enables fast, easy restores of SharePoint sites, documents, libraries and lists — all with no agents to manage and no additional licenses to buy.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now