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


---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
GO


---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
GO


---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
GO


---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
GO


---T_BRANCH_ISSUE_PLACE
ALTER TABLE AKUZ.T_BRANCH_ISSUE_PLACE
    DROP CONSTRAINT FK_T_ISSUE_PLACE_T_BRANCH_ISSUE_PLACE_ISSUEPLACEID
GO


---T_DIVISION_ISSUE_PLACE
ALTER TABLE AKUZ.T_DIVISION_ISSUE_PLACE
    DROP CONSTRAINT FK_T_ISSUE_PLACE_T_DIVISION_ISSUE_PLACE_ISSUEPLACEID
GO

---T_ROOM_ISSUE_PLACE
ALTER TABLE AKUZ.T_ROOM_ISSUE_PLACE
    DROP CONSTRAINT FK_T_ISSUE_PLACE_T_ROOM_ISSUE_PLACE_IssuePlaceID
GO

---T_SENTRY_ISSUE_PLACE
ALTER TABLE AKUZ.T_SENTRY_ISSUE_PLACE
    DROP CONSTRAINT FK_T_ISSUE_PLACE_T_SENTRY_ISSUE_PLACE_ISSUEPLACEID
GO


---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)
GO


---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)
GO


---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)
GO


---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)
GO
