       WHERE referenced_relation = 'specimen_parts'
         AND record_id = part_id
         AND code_category = 'main'
-        AND full_code_order_by IN (recPartsDetails.main_code, recPartsDetails.rbins_code, recPartsDetails.inventory_code, recPartsDetails.batch_main_code);
+        AND (full_code_order_by IN (recPartsDetails.main_code, recPartsDetails.rbins_code, recPartsDetails.inventory_code, recPartsDetails.batch_main_code)
+             OR
+             CASE WHEN coalesce(new_code_id,0) = 0 THEN true ELSE id = new_code_id END
+            );
       GET DIAGNOSTICS code_count = ROW_COUNT;
       IF code_count = 0 THEN
         IF createCodes (new_part_id, recPartsDetails.old_main_code) < 0 THEN

end;
$$;

create or replace function createNewPart(IN part_id specimen_parts.id%TYPE, IN recPartsDetails recPartsDetail) RETURNS specimen_parts.id%TYPE language plpgsql AS
$$
DECLARE
  new_part_id specimen_parts.id%TYPE;


      IF coalesce(new_code_id,'') = '' THEN
        RAISE NOTICE 'No update occured for code: %', recPartsDetails.main_code;
        SELECT createNewPart(part_id, recPartsDetails) INTO new_part_id;
        IF new_part_id < 0 THEN
          return false;
        END IF;
      ELSE
        RAISE NOTICE 'At least one update occured for code: % ', recPartsDetails.main_code;
        SELECT createNewPart(part_id, recPartsDetails, new_code_id) INTO new_part_id;
        IF new_part_id < 0 THEN
          return false;
        END IF;
      END IF;
      select array_agg(coalesce(code_prefix, '') || case when code_prefix is null then '' else coalesce(code_prefix_separator, ' ') end || coalesce(code, '') || case when code_suffix is null then '' else coalesce(code_suffix_separator, ' ') end || coalesce(code_suffix, '')) into recActualCodes from codes where code_category = 'main' and referenced_relation = 'specimen_parts' and record_id = part_id;
      select array_agg(coalesce(code_prefix, '') || case when code_prefix is null then '' else coalesce(code_prefix_separator, ' ') end || coalesce(code, '') || case when code_suffix is null then '' else coalesce(code_suffix_separator, ' ') end || coalesce(code_suffix, '')) into recTransferedCodes from codes where code_category = 'main' and referenced_relation = 'specimen_parts' and record_id = new_part_id;
