UPDATE AKUZ.T_MOVEMENT m
SET m.FullMedCardNum = CAST(m.MedCardNumber as varchar(10)) + '/' + CAST(cr.ChildNumber as varchar(10))
FROM m
JOIN AKUZ.T_CHILD_REGISTRATION cr on cr.MovementID = m.MovementID;

UPDATE AKUZ.T_MOVEMENT m
SET m.FullMedCardNum = m.MedCardNumber
FROM m
WHERE m.FullMedCardNum is null and m.MedCardNumber is not null;


-- в AKUZ.T_GEN_NUMBERS проставление в EntityID и максимального значение в NextNumber для нынешнего года 
DO $$
DECLARE 
	_entityMRID integer := (SELECT e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'MEDICALCARD_REGISTRATION' And e.Schema = 'AKUZ' limit 1);
	_entityEEID integer := (SELECT e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'EMERGENCY_EVENT' And e.Schema = 'AKUZ' limit 1);

BEGIN
  UPDATE AKUZ.T_GEN_NUMBERS 
  SET EntityID = _entityEEID
  WHERE EntityID = _entityMRID and (LEN(NumberName) - LEN(REPLACE(NumberName, '/', ''))) = 2 and NumberName Like '%/2024/%';

CREATE TEMP table TMP_GN  
(
    GenNumbersID uniqueidentifier NOT NULL,
    EntityID integer NOT NULL,
    NumberName varchar(64) NOT NULL,
    NextNumber integer NOT NULL
) ;
  INSERT INTO TMP_GN
  SELECT gn.GenNumbersID, gn.EntityID, gn.NumberName, gn.NextNumber
  FROM AKUZ.T_GEN_NUMBERS gn
  WHERE gn.EntityID = _entityEEID and (LEN(gn.NumberName) - LEN(REPLACE(gn.NumberName, '/', ''))) = 2 and gn.NumberName Like '%/2024/%';

CREATE TEMP table TMP_PART_NAME  
(
	part varchar(64) NULL
) ;
  INSERT INTO TMP_PART_NAME
  SELECT t.c
  FROM (SELECT LEFT(gn.NumberName, LEN(gn.NumberName) - CHARINDEX('/', REVERSE(gn.NumberName))) as c
  FROM TMP_GN gn) as t
  GROUP BY c;

  CREATE TEMP table TMP_MAXNUM  
(
	maxNextNumber integer,
	partNumberName varchar(64)
) ;
  INSERT INTO TMP_MAXNUM
  SELECT max(gn.NextNumber), pn.part
  FROM TMP_GN gn
  RIGHT JOIN TMP_PART_NAME pn on gn.NumberName Like pn.part + '/%'
  GROUP BY pn.part;
  
DROP TABLE TMP_PART_NAME;
	


  DECLARE my_cur CURSOR FOR SELECT maxNextNumber, partNumberName FROM TMP_MAXNUM;
		  _entityID integer = (SELECT e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'EMERGENCY_EVENT' And e.Schema = 'AKUZ' limit 1);
		  record record;
  BEGIN
   OPEN my_cur;
   LOOP
		FETCH my_cur INTO record;
        EXIT WHEN NOT FOUND;

   		IF EXISTS (SELECT * FROM TMP_GN gn WHERE gn.NumberName = record.partNumberName + '/1') 
			UPDATE gn 
			SET gn.NextNumber = record.maxNextNumber
			FROM AKUZ.T_GEN_NUMBERS gn
			WHERE gn.EntityID = _entityID and gn.NumberName = record.partNumberName + '/1';
		ELSE
			INSERT INTO AKUZ.T_GEN_NUMBERS (
				 GenNumbersID
				,EntityID
				,NumberName
				,NextNumber)
			VALUES (NEWID(), _entityID, record.partNumberName + '/1', record.maxNextNumber);
   
   CLOSE my_cur
   DEALLOCATE my_cur
  END;


DROP TABLE TMP_MAXNUM;
DROP TABLE TMP_GN;
END;
$$;