i have 2 tables (both containing the same column names/datatypes), say table1 and table2.. table1 is the most recent, but some rows were deleted on accident.. table2 was a backup that has all the data we need, but some of it is old, so what i want to do is overwrrite the rows in table 2 that also exist in table 1 with the table 1 rows, but the rows in table 2 that do not exist in table one, leave those as is.. both tables have a primary key, user_id.
any ideas on how i could do this easily?
thanksUSE Northwind
GO
SET NOCOUNT ON
SELECT * INTO myTable1 FROM Employees
GO
-- Have a Look
SELECT * FROM myTable1
-- Make a Backup
SELECT * INTO myTable2 FROM myTable1
GO
-- oops
DELETE FROM myTable1 WHERE EmployeeID BETWEEN 2 AND 6
GO
-- Have a Look
SELECT * FROM myTable1
GO
SET IDENTITY_INSERT myTable1 ON
GO
-- Recover the Rows
INSERT INTO myTable1 (
EmployeeID
, LastName
, FirstName
, Title
, TitleOfCourtesy
, BirthDate
, HireDate
, Address
, City
, Region
, PostalCode
, Country
, HomePhone
, Extension
, Photo
, Notes
, ReportsTo
, PhotoPath
)
SELECT EmployeeID
, LastName
, FirstName
, Title
, TitleOfCourtesy
, BirthDate
, HireDate
, Address
, City
, Region
, PostalCode
, Country
, HomePhone
, Extension
, Photo
, Notes
, ReportsTo
, PhotoPath
FROM myTable2
WHERE EmployeeID NOT IN (SELECT EmployeeID
FROM myTable1)
GO
SET IDENTITY_INSERT myTable1 OFF
GO
-- Have a Look
SELECT * FROM myTable1
GO
-- Clean up
DROP TABLE myTable1
DROP TABLE myTable2
GO
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment