SET NOCOUNT ON;

DECLARE @CD_EMP INT, @CD_FILIAL INT, @CD_ORC INT;

DECLARE FILIAL_CURSOR CURSOR
    FOR SELECT CD_EMP, CD_FILIAL FROM PRC_FILIAL
OPEN FILIAL_CURSOR
FETCH NEXT FROM FILIAL_CURSOR INTO @CD_EMP, @CD_FILIAL;

	WHILE @@FETCH_STATUS = 0
	BEGIN

		PRINT 'PROCESSANDO CORRECAO DA FILIAL ' + CAST(@CD_FILIAL AS VARCHAR)

		UPDATE A
				  SET    A.CD_IT = B.CD_IT
				  FROM   EST_ORC_CPL A
						 INNER JOIN (SELECT CD_EMP,
											CD_FILIAL,
											CD_ORC,
											CD_PROD,
											ROW_NUMBER()
											  OVER (
												PARTITION BY CD_FILIAL, CD_ORC
												ORDER BY CD_ORC) AS CD_IT
									 FROM   EST_ORC_CPL) B
								 ON A.CD_EMP = B.CD_EMP
									AND A.CD_FILIAL = B.CD_FILIAL
									AND A.CD_ORC = B.CD_ORC
									AND A.CD_PROD = B.CD_PROD
							WHERE A.CD_EMP = @CD_EMP AND A.CD_FILIAL = @CD_FILIAL;


		FETCH NEXT FROM FILIAL_CURSOR INTO @CD_EMP, @CD_FILIAL;
	END

CLOSE FILIAL_CURSOR
DEALLOCATE FILIAL_CURSOR