IF OBJECT_ID('VCLib.T_GEN_NUMBERS', 'U') IS NULL
begin
  CREATE TABLE VCLib.T_GEN_NUMBERS 
  (
    GenNumbersID uniqueidentifier NOT NULL,
    EntityID int NOT NULL,
    NumberName varchar(64) NOT NULL,
    NextNumber bigint NOT NULL
	)
    ON [PRIMARY]
    ALTER TABLE VCLib.T_GEN_NUMBERS ADD CONSTRAINT PK_T_GEN_NUMBERS
    PRIMARY KEY CLUSTERED (GenNumbersID) ON [PRIMARY]
    ALTER TABLE VCLib.T_GEN_NUMBERS ADD CONSTRAINT FK_T_ENTITIES_T_GEN_NUMBERS_EntityID
    FOREIGN KEY(EntityID) REFERENCES VCLib.T_ENTITIES (EntityID)
end

insert into VCLib.T_GEN_NUMBERS (GenNumbersID, EntityID, NumberName, NextNumber)
select newid(), gen.EntityID, gen.NumberName, max(gen.NextNumber) as NextNumber
from RDS.T_GEN_NUMBERS gen
join VCLib.T_ENTITIES ent on ent.EntityID = gen.EntityID
where ent.[Schema] in ('STOR', 'PHARM', 'RDS') 
group by gen.NumberName, gen.EntityID