使用此条件复制表另一个表
答案 0 :(得分:0)
对你要做的事做一些大的假设,但是......如果我猜对了,这应该会让你接近:
Insert Into New_Table
Select *
From Old_Table
Where NOT EXISTS ( Select * from New_Table )
Update New_Table NT
From Old_Table OT
Where NT.PK = OT.PK
and ( NT.attrib_fld_1 <> OT.atrib_fld_1
OR
NT.attrib_fld_1 <> OT.atrib_fld_1
OR
NT.attrib_fld_1 <> OT.atrib_fld_1
OR
NT.attrib_fld_1 <> OT.atrib_fld_1
-- etc..for as many non key fields as need evaluated
)
答案 1 :(得分:0)
--Here is an example with merge statement
USE tempdb;
GO
CREATE TABLE dbo.NewTable(EmployeeID int, EmployeeName varchar(10),
CONSTRAINT NewTable_PK PRIMARY KEY(EmployeeID));
CREATE TABLE dbo.OldTable(EmployeeID int, EmployeeName varchar(10),
CONSTRAINT OldTable_PK PRIMARY KEY(EmployeeID));
GO
INSERT dbo.NewTable(EmployeeID, EmployeeName) VALUES(100, 'Mary');
INSERT dbo.NewTable(EmployeeID, EmployeeName) VALUES(101, 'Sara');
INSERT dbo.NewTable(EmployeeID, EmployeeName) VALUES(102, 'Stefano');
INSERT dbo.NewTable(EmployeeID, EmployeeName) Values(103, 'John');
GO
INSERT dbo.OldTable(EmployeeID, EmployeeName) Values(103, 'Bob');
INSERT dbo.OldTable(EmployeeID, EmployeeName) Values(104, 'Steve');
GO
USE tempdb;
GO
BEGIN TRAN;
MERGE [NewTable] AS T
USING [OldTable] AS S
ON (T.EmployeeID = S.EmployeeID)
WHEN NOT MATCHED BY TARGET
THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName)
WHEN MATCHED
THEN UPDATE SET T.EmployeeName = S.EmployeeName
OUTPUT $action, inserted.*, deleted.*;
IF @@ERROR <> 0
ROLLBACK TRAN;
ELSE
COMMIT TRAN;
GO
&#13;