
 EXEC ('

UPDATE A 
   SET A.FBizEmpId = ISNULL((SELECT TOP 1 C.FEmpId FROM TMemberSaleEmployee AS C WHERE C.FBillId = A.FTransId ORDER BY FWorkType),0)
  FROM TMemberCourse AS A
 WHERE A.FTransId != 0
 
UPDATE A
   SET A.FBizEmpId = B.FChargeEmpId
  FROM TMemberCourse AS A,TMember AS B
 WHERE A.FMemId = B.FMemId
  AND A.FBizEmpId = 0
 
 
SELECT A.FCardId,A.FBillId,B.FBillTime,
ISNULL((SELECT TOP 1 FEmpId FROM TMemberSaleEmployee AS E WHERE E.FBillId = A.FBillId ORDER BY FWorkType),0) FEmpId
INTO #SaleCard
FROM TMemberSaleCard AS A,TMemberSaleBill AS B
WHERE A.FBillId = B.FBillId
 AND B.FBizType = ''CardSale''
 
UPDATE A
   SET A.FBizEmpId = ISNULL((SELECT TOP 1 FEmpId FROM #SaleCard AS B WHERE B.FCardId = A.FCardId ORDER BY FBillTime DESC),A.FBizEmpId)
  FROM TMemberCard AS A 
  WHERE A.FCardId IN(SELECT FCardId FROM #SaleCard)

 
SELECT A.FCardId,A.FBillId,B.FBillTime,
ISNULL((SELECT TOP 1 FEmpId FROM TMemberSaleEmployee AS E WHERE E.FBillId = A.FBillId ORDER BY FWorkType),0) FEmpId
INTO #SaleRchg
FROM TMemberSaleCard AS A,TMemberSaleBill AS B
WHERE A.FBillId = B.FBillId
 AND B.FBizType = ''CardRchg''
 AND A.FSalePrice > 0
 

UPDATE A
   SET A.FBizEmpId = ISNULL((SELECT TOP 1 FEmpId FROM #SaleRchg AS B WHERE B.FCardId = A.FCardId ORDER BY FBillTime DESC),A.FBizEmpId)
  FROM TMemberCard AS A 
 WHERE A.FCardId IN(SELECT FCardId FROM #SaleRchg)

UPDATE A
   SET A.FBizEmpId = B.FChargeEmpId
  FROM TMemberCard AS A,TMember AS B
 WHERE A.FMemId = B.FMemId
  AND A.FBizEmpId = 0')
