/*
  材料用途和材料编码来源字段
  PipeArea: 1=工厂预制，2=现场安装
*/
IF COL_LENGTH(N'dbo.HJGL_PipeLineMat', N'PipeArea') IS NULL
BEGIN
    ALTER TABLE dbo.HJGL_PipeLineMat ADD PipeArea NCHAR(1) NULL;
END;
GO

IF COL_LENGTH(N'dbo.HJGL_MaterialCodeLib', N'DesignInstitute') IS NULL
BEGIN
    ALTER TABLE dbo.HJGL_MaterialCodeLib ADD DesignInstitute NVARCHAR(200) NULL;
END;
GO

/* 历史材料按所属管线区域回填；无法关联管线的历史数据保留为空。 */
UPDATE mat
SET mat.PipeArea = pipe.PipeArea
FROM dbo.HJGL_PipeLineMat mat
INNER JOIN dbo.HJGL_Pipeline pipe ON pipe.PipelineId = mat.PipelineId
WHERE mat.PipeArea IS NULL
  AND pipe.PipeArea IN (N'1', N'2');
GO
 