UPDATE A SET A.FCompId = B.FCompId FROM TMemberCard AS A,_xiu..TMemberCard AS B WHERE A.FCardId = B.FCardId AND A.FCompId != B.FCompId SELECT * FROM TCompany DROP TABLE #Company CREATE TABLE #Company ( FCompId BIGINT, FCompNo VARCHAR(10) ) INSERT #Company SELECT FId,FNo FROM TCompany WHERE FNo IN('002','008','009','010') BEGIN TRAN DECLARE @CardId BIGINT DECLARE @CardNo VARCHAR(300) DECLARE List CURSOR FOR SELECT A.FCardId FROM TMemberSaleCard AS A,TMemberSaleBill AS B WHERE A.FBillId = B.FBilliD AND B.FState = 1 GROUP BY FCardId OPEN List FETCH List INTO @CardId WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @CompId BIGINT DECLARE @CardCompId BIGINT SELECT TOP 1 @CompId = T.FCompId ,@CardNo = B.FCardNo,@CardCompId = C.FCompId FROM TMemberSaleCard AS B,TMemberSaleBill AS T,TMemberCard AS C WHERE 1=1 AND T.FBillId = B.FBillId AND B.FSalePrice > 0 AND B.FCardId = @CardId AND C.FCardId = B.FCardId AND T.FState = 1 AND ((T.FWorkDate >= '2018-11-01' AND T.FCompId = 3472330288284041216) OR ( T.FCompId != 3472330288284041216)) ORDER BY T.FBillTime DESC PRINT @CardNo SELECT @CompId = ISNULL(@CompId,0) IF @CompId != @CardCompId AND (@CardCompId IN(SELECT FCompId FROM #Company) OR @CompId IN(SELECT FCompId FROM #Company)) UPDATE TMemberCard SET FCompId = @CompId WHERE FCardId = @CardId FETCH List INTO @CardId END CLOSE List DEALLOCATE LIST COMMIT TRAN