use ChongQing_Chunyi


SELECT 
* FROM ham13

WHERE 1=1
 AND FEmpId IS   NULL
AND FRefEmpId IS NOT NULL

ALTER TABLE ham13 ADD FEmpId BIGINT
ALTER TABLE ham13 ADD FRefEmpId BIGINT
ALTER TABLE ham13 ADD FRelation VARCHAR(1000)
ALTER TABLE ham13 ADD FReason VARCHAR(1000)

UPDATE ham13 SET FEmpId = 0

UPDATE A
   SET A.FEmpId = B.FId
  FROM ham13 AS A,ham01 AS B
 WHERE A.ham06c = B.haa01c
   AND A.ham04c = B.haa20c
 
 UPDATE A
   SET A.FEmpId = B.FId
  FROM ham13 AS A,ham01 AS B
 WHERE A.ham04c = B.haa20c
   AND A.FEmpId = 0 
   
UPDATE ham13 SET FRefEmpId = 0

UPDATE A
   SET A.FRefEmpId = B.FId
  FROM ham13 AS A,ham01 AS B
 WHERE A.ham01c = B.haa01c
 
 
 UPDATE ham13 SET FRelation = ham07c ,FReason = ham08c 
 
 DELETE ChongQing_ChunYi..TEmployeeReferral WHERE 
 SELECT * FROM ChongQing_ChunYi..TEmployeeReferral
 
 INSERT ChongQing_ChunYi..TEmployeeReferral(FEmpId,FRefEmpId,FCreateTime,FCompId,FRelation,FReason)
 SELECT  A.FEmpId,A.FRefEmpId,A.FCreateTime,A.FCompId,A.FRelation,A.FReason FROM  #T AS A
 WHERE NOT EXISTS(SELECT 1 FROM ChongQing_ChunYi..TEmployeeReferral AS B WHERE B.FEmpId = A.FEmpId)
 
 
 drop table #T 
 
 SELECT ham02i FIndex, FEmpId,FRefEmpId,GETDATE() AS FCreateTime,'' AS FCompId,ISNULL(FRelation,'') AS FRelation,ISNULL(FReason,'') AS FReason
 INTO #T
 FROM s3mei..ham13 
 WHERE ISNULL(FEmpId,0)  != 0
 AND ISNULL(FRefEmpId,0)  != 0
 
 DELETE A
    FROM #T AS A,
   (
 SELECT FEmpId,FRefEmpId,MIN(FIndex) AS FIndex FROM #T
 GROUP BY FEmpId,FRefEmpId HAVING(SUM(1) > 1)) AS B
WHERE A.FEmpId = B.FEmpId
 AND A.FRefEmpId = B.FRefEmpid
 AND A.FIndex != B.FIndex
 
 
 SELECT * FROM S3MEI..ham13 WHERE FEmpId = 4681829690374721731
 
 SELECT * FROM ham01 WHERE FId = 
 4645087540811206799
 
 SELECT * FROM ham01 WHERE haa01c = '04203'
 
 SELECT FEmpId,SUM(1)
 FROM #T 
 GROUP BY FEmpId
 HAVING(SUM(1) > 1)
 
 
SELECT * FROM ham01 WHERE haa01c = '05214'

SELECT * FROM ham01 WHERE haa20c = '13617601033'

DROP INDEX TEmployeeReferral.IX_EMPLOYEE_REFERRAL_REF_EMP_ID

/*==============================================================*/
/* Index: IX_EMPLOYEE_REFERRAL_REF_EMP_ID                       */
/*==============================================================*/
IF NOT EXISTS (SELECT 1
                 FROM sysindexes
                WHERE id    = object_id('dbo.TEmployeeReferral')
                  AND name  = 'IX_EMPLOYEE_REFERRAL_REF_EMP_ID'
                  AND indid > 0
                  AND indid < 255)
BEGIN
    CREATE INDEX IX_EMPLOYEE_REFERRAL_REF_EMP_ID ON dbo.TEmployeeReferral 
    (
        FRefEmpId ASC
    )
    
END
GO


SELECT* FROM TEmployee WHERE FIntrId != 0

UPDATE B
   SET B.FRefEmpId = A.FIntrId
  FROM TEmployee AS A,TEmployeeReferral AS B
 WHERE A.FId = B.FEmpid
 
SELECT
 
 SELECT * FROM TEmployeeReferral
 
 
 INSERT TEmployeeReferral(FEmpId,FRefEmpId,FCreateTime,FCompId,FRelation,FReason)
 SELECT FId,FIntrId,ISNULL(FEntryDate,FCreateDate),'','',''
 FROM TEmployee 
 WHERE FIntrId != 0
 