我有一个数据库,其中包含HR输入的员工记录,另一个数据库的表格中包含来自这些员工的匹配信息。我需要帮助的是,从HR数据库中收集员工,然后检查员工是否已经存在于目标数据库中,如果是,则跳过,如果不存在则创建记录。
这是我到目前为止所做的事情,但我对如何检查目标数据库中是否存在该员工的记录以及如何使其跳过或插入新记录感到困惑:
QUERY 1:
Insert INTO MainDB.dbo.employees (DriverID, Name, EntityID, EmployeeTypeID, SecureEmployee, Inactive, CreatedDateTime, CreatedBy)
SELECT a.DET_NUMBERA AS DriverId
, LTRIM(RTRIM(a.DET_SURNAMEA)) + ' ' + LTRIM(RTRIM(a.DET_G1_NAME1A)) AS FullName
, 1 as EntityID
, 1 as EmployeeTypeID
, 0 as SecureEmployee
, 0 as inactive
, GETDATE() as CreatedDateTime
, 'BRAD' as CreatedBy
FROM
(
SELECT Emp_Details.DET_NUMBERA, DET_SURNAMEA, DET_G1_NAME1A, PYD_LOCN_CDA, PYD_COMPANYA , POS_STATUSA, POS_ENDD, Emp_Salary_Main.SMN_DATEC, Emp_Salary_Main.SMN_CLASSA, POS_STARTC
FROM chrisbflprod.dbo.EMDET Emp_Details
INNER JOIN chrisbflprod.dbo.EMPAY Emp_Pay ON Emp_Details.DET_NUMBERA=Emp_Pay.DET_NUMBERA
INNER JOIN chrisbflprod.dbo.EMPOS Emp_Position ON Emp_Details.DET_NUMBERA=Emp_Position.DET_NUMBERA
INNER JOIN chrisbflprod.dbo.EMSAL Emp_Salary_Main ON Emp_Details.DET_NUMBERA=Emp_Salary_Main.DET_NUMBERA
WHERE Emp_Pay.PYD_COMPANYA='VIL'
) a INNER JOIN
(
SELECT MAX(SMN_DATEC) AS MAX_DATE_SAL, DET_NUMBERA FROM chrisbflprod.dbo.EMSAL Emp_Salary
--- (test employeeID) WHERE DET_NUMBERA='0000026'
GROUP BY DET_NUMBERA
) b ON a.DET_NUMBERA=b.DET_NUMBERA
INNER JOIN
(
Select MAX(POS_STARTC) AS MAX_DATE_POS, DET_NUMBERA FROM chrisbflprod.dbo.EMPOS
GROUP BY DET_NUMBERA
) c ON a.DET_NUMBERA=c.DET_NUMBERA
WHERE a.DET_NUMBERA=b.DET_NUMBERA AND a.SMN_DATEC=b.MAX_DATE_SAL
AND a.DET_NUMBERA=c.DET_NUMBERA AND a.POS_STARTC=c.MAX_DATE_POS AND
a.POS_ENDD IS NULL OR a.POS_ENDD=''
ORDER BY DriverID
上述过程盲目地检查源数据库中存在的记录,并将它们简单地插入到目标数据库中。因此,您可以想象,每次运行时,一次又一次地在目标数据库中复制所有内容。我需要做的是检查目标数据库中是否已存在记录(仅匹配DriverID)。
任何有助于你们所有人提供的帮助都会非常感激。
答案 0 :(得分:0)
添加此条件..
......
WHERE a.DET_NUMBERA = b.DET_NUMBERA
AND a.SMN_DATEC = b.MAX_DATE_SAL
and not exists (select 1 from MainDB.dbo.employees emp where a.DET_NUMBERA = emp.DriverID)
....
OR
可能在这里
WHERE Emp_Pay.PYD_COMPANYA = 'VIL'
and not exists (select 1 from MainDB.dbo.employees emp where Emp_Details.DET_NUMBERA = emp.DriverID)