-- Переводим Линии на полный адрес
---- Линия - AFTER UPDATE,DELETE ----
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AfterЛинияUpdate]') and xtype = N'TR')
drop trigger [dbo].[AfterЛинияUpdate]
GO
declare @table_name nvarchar(50)
declare @strSQL nvarchar(1024)

set @table_name=N'Линия'
set @strSQL=''
select @strSQL = @strSQL + ' ALTER TABLE ' + @table_name + ' DROP CONSTRAINT '+ object_name(FK_Tab.id) 
from sysobjects FK_Tab 
where (xtype = 'F') AND object_id(@table_name)=parent_obj
if @strSQL<>''  exec (@strSQL)
GO
SET IDENTITY_INSERT AddressExtraParts ON
INSERT INTO AddressExtraParts (ExtraPartID)
  SELECT BP.AddressID FROM AddressBaseParts BP
  INNER JOIN Линия ON Линия.AddressID = BP.AddressID
SET IDENTITY_INSERT AddressExtraParts OFF
GO
INSERT INTO Addresses (AddressID, ExtraPartID)
  SELECT BP.AddressID, BP.AddressID FROM AddressBaseParts BP
  INNER JOIN Линия ON Линия.AddressID = BP.AddressID
GO
ALTER TABLE Линия
        ADD FOREIGN KEY (Код_класса_напряжения)
                              REFERENCES Справочник_классов_напряжения

ALTER TABLE Линия WITH NOCHECK
        ADD FOREIGN KEY (Код_линии)
                              REFERENCES Объект
                              ON DELETE CASCADE

ALTER TABLE Линия ADD FOREIGN KEY (Код_типа_участка) REFERENCES Спр_типов_участков

alter table Линия add foreign key (AddressID) references Addresses
GO 
CREATE TRIGGER AfterЛинияUpdate ON [dbo].[Линия] 
AFTER UPDATE,DELETE
AS
  if (SELECT Count(AddressID) FROM DELETED) > 0
    DELETE FROM Addresses WHERE 
      AddressID in (select AddressID from DELETED)
      AND ((select count(AddressID) from inserted) = 0 OR   
      AddressID not in (select AddressID from INSERTED))  
GO
alter table SupplyContracts add Pmax float