如果现有记录的所有列都相同,则不执行任何操作

时间:2016-07-18 14:58:27

标签: sql sql-server

我有一个带有一些记录的sql表,每天我将记录导入到表中但我不想导入记录,其中10个字段中的5个没有变化。例如:

Table_A
A(PK) B C D E
1     2 2 3 4

现在,如果我导入记录并且A,B,C和D列中的值没有改变,那么我不想将该记录导入A列。

以下是我试图运行的查询

insert into STG_EmployeeMaster
(Name,PrefName,GPN,BU,BUName,SMU,SMUName,OU,Sector,Rank,MU,MUName,EmpStatus,Grade,StartDate,StdHrs,SSL1,SSL2,City,StateProv,Country,CounselorName,CFL,FTE,LastPromoDate,CurEmpDate,BULevel2,ExpReturnDate,GUI,Ac_Flg,Exist_Flg,Ac_Flg_StartDate,EmpSubCompetency,SectorTagClassification)

select 
t1.Name,
t1.PrefName,
t1.GPN,
t1.BU,
t1.BUName,
t1.SMU,
t1.SMUName,
t1.OU,
t1.Sector,
t1.Rank,
t1.MU,
t1.MUName, 
t1.EmpStatus,
t1.Grade,
t1.StartDate,
t1.StdHrs,
t1.SSL1,
t1.SSL2,
t1.City,
t1.StateProv,
t1.Country,
t1.CounselorName,
t1.CFL,
t1.FTE,
t1.LastPromoDate,
t1.CurEmpDate,
t1.BULevel2,
t1.ExpReturnDate, 
t1.GUI,
'Y',
case when t1.GPN in (select distinct GPN from STG_EmployeeMaster)
then 'N' else 'Y' end,
getdate(),
t3.EmpSubCompetency,
t3.SectorTagClassification

from Temp_EmployeeMaster t1

left join SRC_EMS t3
on t1.GPN=t3.resourceGPN
left join STG_EmployeeMaster t2 
on t1.GPN=t3.ResourceGPN

where not exists( select 1
from dbo.stg_employeemaster t2
where t2.GPN = t1.GPN
and t2. BU = t1.BU
and t2.SMU = t1.SMU
and t2.OU = t1.OU
and t2.Sector =  t1.Sector
and t2.Rank = t1.Rank
and t2.MU = t1.MU
and t2.Grade =  t1.Grade
and t2.EmpSubCompetency = t1.EmpSubCompetency
and t2.SectorTagClassification = t1.SectorTagClassification
and t2.City = t1.City
);

1 个答案:

答案 0 :(得分:3)

您可以使用not exists

insert into table_a( . . . )
    select . . .
    from <records to insert) t
    where not exists (select 1
                      from table_a a
                      where a.a = t.a
                     );

您只需a上的条件,因为它是主键。如果要检查多个列,则可以在多个列上具有条件。