﻿UPDATE csro
SET csro.TOROLT = 'T'
FROM T_CSENGETESIRENDORA csro
INNER JOIN
  (SELECT C_CSENGETESIRENDID, C_ORASZAM, C_INTEZMENYID, C_TANEVID, COUNT(1) AS CNT, MIN(ID) AS minId
  FROM T_CSENGETESIRENDORA
  WHERE TOROLT = 'F'
  GROUP BY C_CSENGETESIRENDID, C_ORASZAM, C_INTEZMENYID, C_TANEVID
  HAVING COUNT(1) > 1
  ) x ON csro.C_CSENGETESIRENDID = x.C_CSENGETESIRENDID AND csro.C_ORASZAM = x.C_ORASZAM AND csro.ID <> x.minId
WHERE csro.TOROLT = 'F'


UPDATE oo
SET oo.C_CSENGETESIRENDORAID = x.csroId
FROM T_ORARENDIORA oo
INNER JOIN (
  SELECT TOP(3000) o.id AS ooId, cs.ID AS csroId
  FROM T_ORARENDIORA o
  INNER JOIN T_CSENGETESIRENDORA cs ON cs.C_ORASZAM = o.C_ORASZAM AND cs.C_CSENGETESIRENDID = o.C_CSENGETESIRENDID AND cs.TOROLT = 'F'
  WHERE o.C_CSENGETESIRENDORAID <> cs.ID
) x ON oo.ID = x.ooId

WHILE @@ROWCOUNT <> 0 BEGIN
  UPDATE oo
  SET oo.C_CSENGETESIRENDORAID = x.csroId
  FROM T_ORARENDIORA oo
  INNER JOIN (
	SELECT TOP(3000) o.id AS ooId, cs.ID AS csroId
	FROM T_ORARENDIORA o
	INNER JOIN T_CSENGETESIRENDORA cs ON cs.C_ORASZAM = o.C_ORASZAM AND cs.C_CSENGETESIRENDID = o.C_CSENGETESIRENDID AND cs.TOROLT = 'F'
	WHERE o.C_CSENGETESIRENDORAID <> cs.ID
  ) x ON oo.ID = x.ooId
END;
GO
