-- 3.5.30 Power 
-- 1.0.29 Power.TechnologicalConnection
-- Переименование PowerBuilding в PowerConstruction, Building в Construction, Housing в Building
---- Building -> Construction
if exists (select 1 from dbo.sysobjects where id = object_id(N'[dbo].[AfterСтроительное_сооружениеUpdate]') and xtype = N'TR')
  drop trigger [dbo].[AfterСтроительное_сооружениеUpdate]
GO
exec sp_rename 'Buildings.BuildingID', 'ConstructionID'
exec sp_rename 'Buildings', 'Constructions'
exec sp_rename 'BuildingTypes', 'ConstructionTypes'
exec sp_rename 'Дверь_строения.BuildingID', 'ConstructionID'
exec sp_rename 'Строительное_сооружение.BuildingID', 'ConstructionID'
GO
-- восстанавливаем триггеры
CREATE TRIGGER AfterСтроительное_сооружениеUpdate ON [dbo].[Строительное_сооружение] 
AFTER UPDATE,DELETE
AS
  if (SELECT Count(ConstructionID) FROM DELETED) > 0
    DELETE FROM Constructions WHERE 
      ConstructionID in (select ConstructionID from DELETED)
      AND ((select count(ConstructionID) from inserted) = 0 OR   
      ConstructionID not in (select ConstructionID from INSERTED))  
GO
---- Housing -> Building
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AfterHousingsUpdate]') and xtype = N'TR')
drop trigger [dbo].[AfterHousingsUpdate]
GO
exec sp_rename 'Housings.HousingID', 'BuildingID'
exec sp_rename 'Housings', 'Buildings'
exec sp_rename 'ConsumingObjects.HousingID', 'BuildingID' 
GO
CREATE TRIGGER AfterBuildingsUpdate ON [dbo].[Buildings] 
AFTER UPDATE,DELETE
AS
  SET NOCOUNT ON
  if (SELECT Count(AddressID) FROM DELETED) > 0
    DELETE FROM AddressBaseParts WHERE 
      AddressID in (select AddressID from DELETED)
      AND ((select count(AddressID) from inserted) = 0 OR   
      AddressID not in (select AddressID from INSERTED))  
  SET NOCOUNT OFF
GO
-- Поправим тригер ConsumingObjects и за одно удалим безхозные "дубли".
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AfterConsumingObjectsUpdate]') and xtype = N'TR')
drop trigger [dbo].[AfterConsumingObjectsUpdate]
GO
delete from ConsumingObjects where buildingid is null
GO
CREATE TRIGGER [dbo].[AfterConsumingObjectsUpdate] ON [dbo].[ConsumingObjects] 
AFTER UPDATE, DELETE
AS
  SET NOCOUNT ON 
  if (SELECT Count(AddressID) FROM DELETED) > 0
    DELETE FROM AddressExtraParts WHERE 
      ExtraPartID in (select AddressID from DELETED)
      AND ((select count(AddressID) from inserted) = 0 OR   
      ExtraPartID not in (select AddressID from INSERTED))
  SET NOCOUNT OFF
GO
-- нашли "мёртвое" поле 
alter table TCApplications drop column TCApplicationTemplateID
-- Увеличим размер поля могут быть длинные названия.
alter table TCActs alter column ProjectName nvarchar(500)
-- Добавляем индекс: когда много работ, без него не жить
CREATE INDEX Работа_Код_объекта
  ON Работа(Код_объекта)