我有两张格式完全相同的表格。我想将这两个表相互比较,如果表A没有表B的记录,那么我想将该列添加到表A.如何使用SQL实现此目的。我只想比较以下列CompanyNumber,EmployeeNumber,StatusFlag和Initials的表格。
使用SQL执行此操作的最佳方法是什么?
此查询的错误是什么?
MERGE EmployeeMaster AS Dest
USING ( SELECT * FROM EmployeeMasterCopy ) AS Src
JOIN Dest.CompanyNumber = Src.CompanyNumber
and Dest.EmployeeNumber = Src.EmployeeNumber
and Dest.StatusFlag = Src.StatusFlag
and Dest.Initials = Src.Initials
WHEN NOT MATCHED THEN
INSERT INTO EmployeeMaster(CompanyNumber, FirstName, LastName, FullName, Branch, DepartmentNumber, Initials,
JobTitle, StartDate, EmployeeNumber, EmployeeType,
PayType, Rate, UnionNo, G2ID, EnterTimeFl, StatusFlag, CreateBy, CreateDate, MiddleName,ManagerEmpNo, NextReviewDate, UserName, TempFl, PrimaryDivision,PEWFl,PGTFl,PMPFl,PPGEFl,PPGFl,PRCFl,PTCFl,PPFl,SWPFl,ReviewPeriod, CorpFl, NickName, RateEffectiveDate, VacationBalance, SickBalance, TempEmployeeType, BusinessSegment)
VALUES (Src.CompanyNumber, Src.FirstName, Src.LastName,Src.LastName + ', ' + Src.FirstName, Src.Branch, Src.DeptNo, upper(Src.Initials), Src.JobTitle, Src.StartDate, Src.EmployeeNumber,
Src.EmployeeType, Src.PayType, Src.Rate, Src.UnionNo, Src.G2ID, Src.EnterTimeFl, 1, 'AJOHNSON', GETDATE(), Src.MiddleName, Src.ManagerEmpNo, Src.NextReviewDate, Src.UserName, Src.TempFl, Src.PrimaryDivision,Src.PEWFl,Src.PGTFl,Src.PMPFl,Src.PPGEFl,Src.PPGFl,Src.PRCFl,Src.PTCFl,Src.PPFl,Src.SWPFl,Src.ReviewPeriod, Src).CorpFl, Src.NickName,Src.RateEffectiveDate ,
Src.VacationBalance ,
Src.SickBalance ,
Src.TempEmployeeType, Src.BusinessSegment
以下是错误:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'as'.
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'AS'.
Msg 128, Level 15, State 1, Line 13
The name "Src.CompanyNumber" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
答案 0 :(得分:2)
您可以使用 MERGE
MERGE TableA as Dest
USING ( select * from TableB ) as Src
ON Dest.CompanyNumber = Source.companyNumber
and Dest.EmployeeNumber = Source.EMployeeNumber
and Dest.StatusFlag = Source.StatusFlag
and Dest.initials = Source.initials
WHEN NOT MATCHED then
INSERT (CompanyNumber, EmployeeNumber, StatusFlag, initials, ...)
values ( Src.CompanyNumber, Src.EmployeeNumber, Src.StatusFlag, Src.initials....)
答案 1 :(得分:0)
想一个简单的方法可能是:
select
TableA.CompanyNumber as "Tab A Company No",
TableB.CompanyNumber as "Tab B Company No",
TableA.EmployeeNumber as "Tab A Employee No",
TableB.EmployeeNumber as "Tab B Employee No",
TableA.StatusFlag as "Tab A Status Flag",
TableB.StatusFlag as "Tab B Status Flag",
TableA.Initials as "Tab A Initials",
TableB.Initials as "Tab B Initials",
from
TableA,
TableB