---- GetAirLinePieceLength ----
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAirLinePieceLength]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetAirLinePieceLength]
GO
create function GetAirLinePieceLength(@ObjID integer)
returns float
as
begin
  declare @PieceLength float
  declare @SpanLength float

  select @PieceLength = Длина FROM Отрезок_ВЛЭП WHERE Код_отрезка = @ObjID
  if @PieceLength > 0
    return @PieceLength

  select @SpanLength = sum(span.Длина) FROM Пролет span INNER JOIN dbo.Дерево_объекта(@ObjID, 2) tree ON tree.id = span.Код_пролета
  if @SpanLength > 0
    return @SpanLength
  return 0
end
