--- Перевешиваем тип с базового на реализацию
UPDATE STOR.T_ISSUE_PLACE ip
SET
    type_ = (
        SELECT entityid FROM VCLib.T_ENTITIES e WHERE e.EntName = 'LPU_MAIN_ISSUE_PLACE'
            )
WHERE
    EXISTS
    (
        SELECT
            1
        FROM AKUZ.T_LPU_ISSUE_PLACE L
        WHERE IP.IssuePlaceID = L.IssuePlaceID
    );


---T_BRANCH_ISSUE_PLACE
INSERT INTO
    AKUZ.T_LPU_ISSUE_PLACE(LpuMain, IssuePlaceID)
SELECT
    br.LpuMain,
    ip.IssuePlaceID
FROM AKUZ.T_BRANCH_ISSUE_PLACE ip
JOIN AKUZ.T_BRANCH br ON BR.LpuID = ip.Branch;


---DIVISION_ISSUE_PLACE
INSERT INTO
    AKUZ.T_LPU_ISSUE_PLACE(LpuMain, IssuePlaceID)
SELECT
        br.LpuMain,
    ip.IssuePlaceID
FROM AKUZ.T_DIVISION_ISSUE_PLACE ip
JOIN AKUZ.T_DIVISION div ON ip.Division = div.DivisionID
JOIN AKUZ.T_BRANCH br ON BR.LpuID = div.Branch;


---ROOM_ISSUE_PLACE
INSERT INTO
    AKUZ.T_LPU_ISSUE_PLACE(LpuMain, IssuePlaceID)
SELECT
    br.LpuMain,
    ip.IssuePlaceID
FROM AKUZ.T_ROOM_ISSUE_PLACE ip
JOIN AKUZ.T_RESOURCE res ON IP.Room = res.ResourceID
JOIN AKUZ.T_DIVISION div ON RES.Division = div.DivisionID
JOIN AKUZ.T_BRANCH br ON BR.LpuID = div.Branch;


---SENTRY_ISSUE_PLACE
INSERT INTO
    AKUZ.T_LPU_ISSUE_PLACE(LpuMain, IssuePlaceID)
SELECT
    br.LpuMain,
    ip.IssuePlaceID
FROM AKUZ.T_SENTRY_ISSUE_PLACE ip
JOIN AKUZ.T_RESOURCE res ON IP.Post = res.ResourceID
JOIN AKUZ.T_DIVISION div ON RES.Division = div.DivisionID
JOIN AKUZ.T_BRANCH br ON BR.LpuID = div.Branch;


---T_BRANCH_ISSUE_PLACE
ALTER TABLE AKUZ.T_BRANCH_ISSUE_PLACE
    DROP CONSTRAINT IF EXISTS FK_T_ISSUE_PLACE_T_BRANCH_ISSUE_PLACE_ISSUEPLACEID;


---T_DIVISION_ISSUE_PLACE
ALTER TABLE AKUZ.T_DIVISION_ISSUE_PLACE
    DROP CONSTRAINT IF EXISTS FK_T_ISSUE_PLACE_T_DIVISION_ISSUE_PLACE_ISSUEPLACEID;

---T_ROOM_ISSUE_PLACE
ALTER TABLE AKUZ.T_ROOM_ISSUE_PLACE
    DROP CONSTRAINT IF EXISTS FK_T_ISSUE_PLACE_T_ROOM_ISSUE_PLACE_IssuePlaceID;

---T_SENTRY_ISSUE_PLACE
ALTER TABLE AKUZ.T_SENTRY_ISSUE_PLACE
    DROP CONSTRAINT IF EXISTS FK_T_ISSUE_PLACE_T_SENTRY_ISSUE_PLACE_ISSUEPLACEID;


---T_BRANCH_ISSUE_PLACE
ALTER TABLE AKUZ.T_BRANCH_ISSUE_PLACE
    ADD CONSTRAINT FK_T_LPU_ISSUE_PLACE_T_BRANCH_ISSUE_PLACE_IssuePlaceID
        FOREIGN KEY (IssuePlaceID) REFERENCES AKUZ.T_LPU_ISSUE_PLACE (IssuePlaceID);


---T_DIVISION_ISSUE_PLACE
ALTER TABLE AKUZ.T_DIVISION_ISSUE_PLACE
    ADD CONSTRAINT FK_T_LPU_ISSUE_PLACE_T_DIVISION_ISSUE_PLACE_IssuePlaceID
        FOREIGN KEY (IssuePlaceID) REFERENCES AKUZ.T_LPU_ISSUE_PLACE (IssuePlaceID);


---T_ROOM_ISSUE_PLACE
ALTER TABLE AKUZ.T_ROOM_ISSUE_PLACE
    ADD CONSTRAINT FK_T_LPU_ISSUE_PLACE_T_ROOM_ISSUE_PLACE_IssuePlaceID
        FOREIGN KEY (IssuePlaceID) REFERENCES AKUZ.T_LPU_ISSUE_PLACE (IssuePlaceID);


---T_SENTRY_ISSUE_PLACE
ALTER TABLE AKUZ.T_SENTRY_ISSUE_PLACE
    ADD CONSTRAINT FK_T_LPU_ISSUE_PLACE_T_SENTRY_ISSUE_PLACE_IssuePlaceID
        FOREIGN KEY (IssuePlaceID) REFERENCES AKUZ.T_LPU_ISSUE_PLACE (IssuePlaceID);

