ITTrucker
Yak Posting Veteran
64 Posts |
Posted - 2014-11-05 : 10:35:20
|
I'm bulk loading employees into an etl table, each employee has a unique ID number, but they have multiple records in the data. Sometimes their name or birthdate will change and I want to identify those records and only insert the newest version into production. I can do this with a series of temp tables, but I'm sure there's a better way. The SQL below updates the etl table with the flag I want to mark the inserts, but it seems convoluted. (Jon's birthday changes, Jane's birthday changes, Bill's gender changes, Amy nothing changes(I handle those inserts later))DECLARE @Records TABLE(firstname varchar(50), lastname varchar(50), birthdate date, sex char(1), IDNum varchar(15), moddate date, opflag char(1))INSERT INTO @RecordsVALUES ('JON','SMITH','20000101','M','12345','20140101','I'),('JON','SMITH','20000101','M','12345','20140201','I'),('JON','SMITH','20000102','M','12345','20140301','I'),('JANE','SMITH','20010101','F','54321','20140401','I'),('JANE','SMITH','20010101','F','54321','20140501','I'),('JANE','SMITH','20010102','F','54321','20140505','I'),('BILL','JONES','20020101','M','23456','20140501','I'),('BILL','JONES','20020101','M','23456','20140601','I'),('BILL','JONES','20020101','F','23456','20140701','I'),('AMY','LEE','20030101','F','9876','20140501','I'),('AMY','LEE','20030101','F','9876','20140601','I')DECLARE @EmpTemp TABLE(firstname varchar(50), lastname varchar(50), birthdate date, sex char(1), IDNum varchar(15))INSERT INTO @EmpTempSELECT firstName,LastName,birthDate,sex,IDNumFROM @RecordsGROUP BY firstName,LastName,birthDate,sex,IDNumupdate @Recordsset opflag = 'X' where IDNum in(select IDNum from @EmpTempGROUP BY IDNumhaving count(IDNum) >1)update R1set opflag = 'I'From @Records R1where R1.opflag = 'X'and R1.moddate = (select MAX(R2.moddate) from @Records R2 where R1.IDNum = R2.IDNum group by R2.IDNum)select * from @Records--Sorry for the terrible subject, had trouble wording it. |
|