ALTER TABLE BMS.CulvertInventory ADD ConstructionYear nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD PWDStoneCh int;
ALTER TABLE BMS.CulvertInventory ADD PWDStrNum nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD NearByPlace nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD Submersible bit;
ALTER TABLE BMS.CulvertInventory ADD SkewAngle nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD Bedmaterial nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD Type2SpansNo int;
ALTER TABLE BMS.CulvertInventory ADD Type2SpanWidth decimal(9,3);
ALTER TABLE BMS.CulvertInventory ADD Type2SpanHeight decimal(9,3);
ALTER TABLE BMS.CulvertInventory ADD SpacingBtwnPipes decimal(9,3);
ALTER TABLE BMS.CulvertInventory ADD Cushion decimal(9,3);
ALTER TABLE BMS.CulvertInventory ADD WRWallMtrlType nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD WRWallLength decimal(9,3);
ALTER TABLE BMS.CulvertInventory ADD CulverLength int;
ALTER TABLE BMS.CulvertInventory ADD Railingtype nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD IsFlorngProvd bit;
ALTER TABLE BMS.CulvertInventory ADD FlorngType nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD CurtainwallPRVD bit;
ALTER TABLE BMS.CulvertInventory ADD CurtainwallType nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD IsPichngProvd bit;
ALTER TABLE BMS.CulvertInventory ADD SdSlpPitchtype nvarchar(100);
ALTER TABLE BMS.CulvertInventory ADD Remarks nvarchar(100);
GO
ALTER TABLE BMS.CulvertCondition ADD SupStuctrCondition nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD HeadWallCond nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD WRWallCond nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD RailingCondition nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD SiltUS nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD SiltDS nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD ProtectionUS nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD ProtectionDS nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD CurtainWallCondUS nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD CurtainWallCondDS nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD SdSlpPitchCond nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD WideningReq bit;
ALTER TABLE BMS.CulvertCondition ADD OverallStrCond nvarchar(100);
ALTER TABLE BMS.CulvertCondition ADD LinkCode nvarchar(100);
go
alter table BMS.CulvertInventory drop column  Fill,ProtectionUS,ProtectionDS,ToeWallType, NoofPipesorVents,PipeDiameter
GO
alter table BMS.CulvertCondition drop column  [ConditionofDeckSlab],[ConditionofHeadWall],[ConditionofReturnWall]
,[ConditionofParapet],[Choked],[ConditionofWingWall],[Remarks],[SurveyYear]
go
alter table BMS.[CulvertInventory_Audit] drop column  Fill,ProtectionUS,ProtectionDS,ToeWallType, NoofPipesorVents,PipeDiameter
GO
EXEC sp_rename '[BMS].[CulvertInventory].WingWall','WRWallType','COLUMN'
GO
EXEC sp_rename '[BMS].[CulvertInventory_Audit].WingWall','WRWallType','COLUMN'
go
delete TableColumnDef where TableName='CulvertInventory';
go
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','RoadCode','CulvertInventory',1,'BMS','RoadCode');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Direction','CulvertInventory',2,'BMS','Direction');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','SurveyDate','CulvertInventory',3,'BMS','SurveyDate');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','ConstructionYear','CulvertInventory',4,'BMS','ConstructionYear');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','SurveyYear','CulvertInventory',5,'BMS','SurveyYear');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Latitude','CulvertInventory',6,'BMS','Latitude');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Longitude','CulvertInventory',7,'BMS','Longitude');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','CDNumber','CulvertInventory',8,'BMS','CDNumber');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','PWDStoneCh','CulvertInventory',9,'BMS','PWDStoneCh');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','PWDStrNum','CulvertInventory',10,'BMS','PWDStrNum');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','FlowDirection','CulvertInventory',11,'BMS','FlowDirection');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','NearByPlace','CulvertInventory',12,'BMS','NearByPlace');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','StructureType','CulvertInventory',13,'BMS','StructureType');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','TotalCulvertWidth','CulvertInventory',14,'BMS','TotalCulvertWidth');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','ClearRoadWidth','CulvertInventory',15,'BMS','ClearRoadWidth');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Submersible','CulvertInventory',16,'BMS','Submersible');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','SkewAngle','CulvertInventory',17,'BMS','SkewAngle');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Bedmaterial','CulvertInventory',18,'BMS','Bedmaterial');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','NoofSpans','CulvertInventory',19,'BMS','NoofSpans');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','SpanWidth','CulvertInventory',20,'BMS','SpanWidth');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','SpanHeight','CulvertInventory',21,'BMS','SpanHeight');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Type2SpansNo','CulvertInventory',22,'BMS','Type2SpansNo');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Type2SpanWidth','CulvertInventory',23,'BMS','Type2SpanWidth');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Type2SpanHeight','CulvertInventory',24,'BMS','Type2SpanHeight');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','DeckSlabThickness','CulvertInventory',25,'BMS','DeckSlabThickness');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','SpacingBtwnPipes','CulvertInventory',26,'BMS','SpacingBtwnPipes');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Cushion','CulvertInventory',27,'BMS','Cushion');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','HeadWallType','CulvertInventory',28,'BMS','HeadWallType');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','HeadWallThickness','CulvertInventory',29,'BMS','HeadWallThickness');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','WRWallType','CulvertInventory',30,'BMS','WRWallType');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','WRWallMtrlType','CulvertInventory',31,'BMS','WRWallMtrlType');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','WRWallLength','CulvertInventory',32,'BMS','WRWallLength');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','HeadWallLength','CulvertInventory',33,'BMS','HeadWallLength');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','CulverLength','CulvertInventory',34,'BMS','CulverLength');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Railingtype','CulvertInventory',35,'BMS','Railingtype');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','IsFlorngProvd','CulvertInventory',36,'BMS','IsFlorngProvd');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','FlorngType','CulvertInventory',37,'BMS','FlorngType');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','CurtainwallPRVD','CulvertInventory',38,'BMS','CurtainwallPRVD');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','CurtainwallType','CulvertInventory',39,'BMS','CurtainwallType');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','IsPichngProvd','CulvertInventory',40,'BMS','IsPichngProvd');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','SdSlpPitchtype','CulvertInventory',41,'BMS','SdSlpPitchtype');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Remarks','CulvertInventory',42,'BMS','Remarks');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','Chainage','CulvertInventory',43,'BMS','Chainage');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','LinkCode','CulvertInventory',44,'BMS','LinkCode');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','OldCode','CulvertInventory',45,'BMS','OldCode');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertInventory','BMS.CulvertInventory','CulvertCode','CulvertInventory',46,'BMS','CulvertCode');
go
delete TableColumnDef where TableName='CulvertCondition';
go
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','SupStuctrCondition','CulvertCondition',1,'BMS','SupStuctrCondition');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','HeadWallCond','CulvertCondition',2,'BMS','HeadWallCond');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','WRWallCond','CulvertCondition',3,'BMS','WRWallCond');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','RailingCondition','CulvertCondition',4,'BMS','RailingCondition');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','ScourUS','CulvertCondition',5,'BMS','ScourUS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','ScourDS','CulvertCondition',6,'BMS','ScourDS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','SiltUS','CulvertCondition',7,'BMS','SiltUS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','SiltDS','CulvertCondition',8,'BMS','SiltDS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','VegetationUS','CulvertCondition',9,'BMS','VegetationUS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','VegetationDS','CulvertCondition',10,'BMS','VegetationDS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','ProtectionUS','CulvertCondition',11,'BMS','ProtectionUS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','ProtectionDS','CulvertCondition',12,'BMS','ProtectionDS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','CurtainWallCondUS','CulvertCondition',13,'BMS','CurtainWallCondUS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','CurtainWallCondDS','CulvertCondition',14,'BMS','CurtainWallCondDS');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','SdSlpPitchCond','CulvertCondition',15,'BMS','SdSlpPitchCond');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','WideningReq','CulvertCondition',16,'BMS','WideningReq');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','WaterWayAdequacy','CulvertCondition',17,'BMS','WaterWayAdequacy');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','OverallStrCond','CulvertCondition',18,'BMS','OverallStrCond');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','LinkCode','CulvertCondition',19,'BMS','LinkCode');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','CulvertCode','CulvertCondition',20,'BMS','CulvertCode');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','OldCode','CulvertCondition',21,'BMS','OldCode');
INSERT INTO TableColumnDef(TableName,TableNameDescription,DBColumnName,Caption,Seq, SchemaName,ExcelCaption) 
VALUES('CulvertCondition','BMS.CulvertCondition','ConditionofPipe','CulvertCondition',22,'BMS','ConditionofPipe');
GO
CREATE TABLE BMS.LKPTScourCond(
	[ScourCondId] [int] IDENTITY(1,1) NOT NULL,
	[ScourCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTScourCond] PRIMARY KEY CLUSTERED 
(
	[ScourCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.LKPTSiltCond(
	[SiltCondId] [int] IDENTITY(1,1) NOT NULL,
	[SiltCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTSiltCond] PRIMARY KEY CLUSTERED 
(
	[SiltCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.LKPTVegCond(
	[VegCondId] [int] IDENTITY(1,1) NOT NULL,
	[VegCondCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTVegCond] PRIMARY KEY CLUSTERED 
(
	[VegCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.LKPTOvrlStructureCond(
	[OvrlStructureCondId] [int] IDENTITY(1,1) NOT NULL,
	[OvrlStructureCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTOvrlStructureCond] PRIMARY KEY CLUSTERED 
(
	[OvrlStructureCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.LKPTWallType(
	[WallTypeCondId] [int] IDENTITY(1,1) NOT NULL,
	[WallTypeCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTWallTypeCond] PRIMARY KEY CLUSTERED 
(
	[WallTypeCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.LKPTFloorType(
	[FloorTypeCondId] [int] IDENTITY(1,1) NOT NULL,
	[FloorTypeCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTFloorTypeCond] PRIMARY KEY CLUSTERED 
(
	[FloorTypeCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.LKPTCurtainType(
	[CurtainTypeCondId] [int] IDENTITY(1,1) NOT NULL,
	[CurtainTypeCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTCurtainTypeCond] PRIMARY KEY CLUSTERED 
(
	[CurtainTypeCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.LKPTPitchingType(
	[PitchingTypeCondId] [int] IDENTITY(1,1) NOT NULL,
	[PitchingTypeCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTPitchingTypeCond] PRIMARY KEY CLUSTERED 
(
	[PitchingTypeCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.[LKPTPipeCond](
	[PipeCondId] [int] IDENTITY(1,1) NOT NULL,
	[PipeCondType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTPipeCond] PRIMARY KEY CLUSTERED 
(
	[PipeCondId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
CREATE TABLE BMS.[LKPTFloorPrtctType](
	[FloorPrtctId] [int] IDENTITY(1,1) NOT NULL,
	[FloorPrtctType] [varchar](50) NULL,
	[Description] [varchar](100) NULL,
 CONSTRAINT [PK_LKPTFloorPrtct] PRIMARY KEY CLUSTERED (	[FloorPrtctId] ASC)
 WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, 
 OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
GO
INSERT [BMS].[LKPTScourCond] ([ScourCondType], [Description]) VALUES (N'1', N'None')
INSERT [BMS].[LKPTScourCond] ([ScourCondType], [Description]) VALUES (N'2', N'Nominal')
INSERT [BMS].[LKPTScourCond] ([ScourCondType], [Description]) VALUES (N'3', N'Severe')
go
INSERT [BMS].[LKPTSiltCond] ([SiltCondType], [Description]) VALUES (N'1', N'None')
INSERT [BMS].[LKPTSiltCond] ([SiltCondType], [Description]) VALUES (N'2', N'Partial')
INSERT [BMS].[LKPTSiltCond] ([SiltCondType], [Description]) VALUES (N'3', N'Fully Silted')
go
INSERT [BMS].[LKPTWallType] ([WallTypeCondType], [Description]) VALUES (N'1', N'Return Wall (RW)')
INSERT [BMS].[LKPTWallType] ([WallTypeCondType], [Description]) VALUES (N'2', N'Wing Wall (WW)')
go
INSERT [BMS].[LKPTFloorType] ([FloorTypeCondType], [Description]) VALUES (N'1', N'Stone Flooring')
INSERT [BMS].[LKPTFloorType] ([FloorTypeCondType], [Description]) VALUES (N'2', N'Concrete Block')
INSERT [BMS].[LKPTFloorType] ([FloorTypeCondType], [Description]) VALUES (N'3', N'Gabions')
go
INSERT [BMS].[LKPTCurtainType] ([CurtainTypeCondType], [Description]) VALUES (N'1', N'Masonry')
INSERT [BMS].[LKPTCurtainType] ([CurtainTypeCondType], [Description]) VALUES (N'2', N'Concrete')
INSERT [BMS].[LKPTCurtainType] ([CurtainTypeCondType], [Description]) VALUES (N'3', N'Gabions')
go
INSERT [BMS].[LKPTPitchingType] ([PitchingTypeCondType], [Description]) VALUES (N'1', N'Stone Pitching')
INSERT [BMS].[LKPTPitchingType] ([PitchingTypeCondType], [Description]) VALUES (N'2', N'Concrete Block')
INSERT [BMS].[LKPTPitchingType] ([PitchingTypeCondType], [Description]) VALUES (N'3', N'Gabions')
go
INSERT [BMS].[LKPTOvrlStructureCond] ([OvrlStructureCondType], [Description]) VALUES (N'1', N'Retain with Routine Maintainance')
INSERT [BMS].[LKPTOvrlStructureCond] ([OvrlStructureCondType], [Description]) VALUES (N'2', N'Retain with Repairs')
INSERT [BMS].[LKPTOvrlStructureCond] ([OvrlStructureCondType], [Description]) VALUES (N'3', N'Retain + Widen')
INSERT [BMS].[LKPTOvrlStructureCond] ([OvrlStructureCondType], [Description]) VALUES (N'4', N'Propose for Reconstruction')
go
INSERT [BMS].[LKPTVegCond] ([VegCondCondType], [Description]) VALUES (N'1', N'None')
INSERT [BMS].[LKPTVegCond] ([VegCondCondType], [Description]) VALUES (N'2', N'Light')
INSERT [BMS].[LKPTVegCond] ([VegCondCondType], [Description]) VALUES (N'3', N'Thick')
go
INSERT [BMS].[LKPTCondSev] ([CondSevType], [Description]) VALUES (N'1', N'No Defect')
INSERT [BMS].[LKPTCondSev] ([CondSevType], [Description]) VALUES (N'2', N'Low')
INSERT [BMS].[LKPTCondSev] ([CondSevType], [Description]) VALUES (N'3', N'Medium')
INSERT [BMS].[LKPTCondSev] ([CondSevType], [Description]) VALUES (N'4', N'High')
go
INSERT INTO [BMS].[LKPTPipeCond] (PipeCondType, Description) values('1','Good')
INSERT INTO [BMS].[LKPTPipeCond] (PipeCondType, Description) values('2','Fair')
INSERT INTO [BMS].[LKPTPipeCond] (PipeCondType, Description) values('3','Poor')
go
INSERT INTO [BMS].[LKPTFloorPrtctType] (FloorPrtctType, Description) values('1','Good')
INSERT INTO [BMS].[LKPTFloorPrtctType](FloorPrtctType, Description) values('2','Fair')
INSERT INTO [BMS].[LKPTFloorPrtctType] (FloorPrtctType, Description) values('3','Poor')
go
INSERT [BMS].[LKPTBrdgCatg] ([BrdgCatgType], [Description]) VALUES (N'1', N'High Level')
INSERT [BMS].[LKPTBrdgCatg] ([BrdgCatgType], [Description]) VALUES (N'2', N'Submersible')
go
INSERT [BMS].[LKPTCondExt] ([CondExtType], [Description]) VALUES (N'A', N'No Defect')
INSERT [BMS].[LKPTCondExt] ([CondExtType], [Description]) VALUES (N'B', N'Few (0% - 5%)')
INSERT [BMS].[LKPTCondExt] ([CondExtType], [Description]) VALUES (N'C', N'Moderate (5% - 25%)')
INSERT [BMS].[LKPTCondExt] ([CondExtType], [Description]) VALUES (N'D', N'Extensive (> 25%)')
go

/****** Object:  StoredProcedure [BMS].[CulvertConditionDetails]    Script Date: 24-01-2025 15:08:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [BMS].[CulvertConditionDetails]
--BMS.CulvertCondition 2019,'C',NULL,'demo'
@SurveyYear NVARCHAR(5),
@SearchType NVARCHAR(5), 
@SearchVal  NVARCHAR (50) =NULL,
@User NVARCHAR(100) =NULL,
@CName NVARCHAR(100) = NULL,
@DName NVARCHAR(100) = NULL,
@SubDivision NVARCHAR(100) = NULL
AS BEGIN 
declare @userType  varchar(20)

select @userType = CASE WHEN areatype = 'H' THEN 'HQ' ELSE areatype END  from  SSUM.[User] where  [UserName] =@user
  
--IF @Circle IS NULL AND @Division IS NULL AND @SubDivision IS NULL AND @MLAConstituency IS NULL AND @MPConstituency IS NULL
IF (@SearchType  = 'C' )
BEGIN
 IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN
      If (@userType = 'HQ' )
	   begin
	 
		SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
		from [BMS].[CulvertCondition] CC
		INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
		LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
		LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
		LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
		LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
		LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
		LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
		LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
		left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
		left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
		left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
		left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
		left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
		left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
		left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
		left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
		left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
		left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
		left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
		left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
	  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
	  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
	  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
	  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
	  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
	  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
	  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
	  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
	  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode

  where CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
	    end
		   else if (@userType = 'D' )
	     begin		  
		  SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		 WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		
   end
		else
		begin

	SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
    WHERE C.CircleCode    in (SELECT areaname FROM  SSUM.userareas WHERE username =@user)
	AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
    end


  END

   else if (@userType = 'D' )
	     begin		  
		  SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		 WHERE C.CircleCode = @SearchVal AND D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		
   end
  ELSE
  BEGIN
 SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks	
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
WHERE C.CircleCode = @SearchVal AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear) 
  END
END
ELSE
IF (@SearchType  = 'D' )
BEGIN
  IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN

   If (@userType = 'HQ' )
	   begin
	     SELECT  'Division'AS SEL,D.DivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType  
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			AND  Ci.SurveyYear= ISNULL(@SurveyYear,Ci.SurveyYear)
		  end
	   else if(@userType in ('C','W'))
	     begin		  
		 SELECT  'Division'AS SEL,D.DivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		 WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		end
   else
	     begin		  
		  SELECT  'Division'AS SEL,D.DivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks	
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode  
  INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode 
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		 WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		
   end
  END
  ELSE
    BEGIN
		 SELECT  'Division'AS SEL,D.DivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks	
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType 
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.linkmaster lm ON lm.RoadCode = CI.LinkCode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		 WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode =   @SearchVal AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear) 
		 
 END 
END
ELSE
IF (@SearchType  = 'S' )
BEGIN
 IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN
    
	 If (@userType = 'HQ' )
	   begin
		  SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  inner join NM.LinkMaster lm on lm.RoadCode=CI.LinkCode
		   INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
		   INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
           	 end
	   else if(@userType in ('C','W'))
	    begin
			SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  inner join nm.LinkMaster lm on lm.RoadCode=CI.LinkCode
			   INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			   INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			 WHERE C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
			 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
			 AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			 end 
	   else if(@userType='D')
	    begin
			SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  inner join NM.LinkMaster lm on lm.RoadCode=CI.LinkCode
			   INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			   INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			 WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
			 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
			 AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			end
	   else
	    begin
			SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
			   INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
			   INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode
			   INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			   INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			 WHERE SD.SubDivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
			 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
			 AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			 end 
   END
     ELSE
       BEGIN
			SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode  
  INNER JOIN NM.linkmaster lm ON lm.LinkCode = CI.LinkCode
			INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			WHERE SD.SubDivisionCode =  @SearchVal AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
			END
     END
  ELSE   IF (@SearchType  = 'MP' )
   BEGIN
		SELECT 'MP Constituency'AS SEL, MPC.Name AS 'Name',rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
		INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		INNER JOIN  NM.MPConstituencyRoad MPr ON MPr.RoadCode =  rm.RoadCode 
		AND CI.Chainage>=MPR.StartChainage And CI.Chainage<=MPR.EndChainage
			--AND CI.EndChainage>=MPR.StartChainage And CI.EndChainage<=MPR.EndChainage
		INNER JOIN NM.MPConstituency MPc ON  MPc.MpcId  = MPr.MPCode
		WHERE MPC.MpcId=  ISNULL (   @searchval   , MPC.MpcId ) AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		END 
	ELSE IF (@SearchType  = 'ML' )
	BEGIN
		SELECT 'MLA Constituency'AS SEL, MPC.Name AS 'Name',rm.RoadCategoryCode,rm.[Name] AS 'RoadName',
		CI.RoadCode,CI.Direction,CC.CulvertCode,CI.SurveyDate,CI.ConstructionYear,
		CI.SurveyYear,CI.Latitude,CI.Longitude,
		CI.CDNumber,CI.PWDStoneCh,CI.PWDStrNum,
		FL.description as 'FlowDirection',CI.NearByPlace,
		ST.description as 'StructureType',CI.TotalCulvertWidth, 
		CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,
		CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
		CI.Type2SpanHeight,CI.Type2SpanWidth,CI.DeckSlabThickness,CI.SpacingBtwnPipes,CI.Cushion,
		SSC.Description as 'SupStuctrCondition',
		WT.Description as 'WRWallMtrlType',
		HWT.Description as 'HeadWallType',
		HW1.Description as 'WRWallMtrlType', 
		CI.HeadWallLength,CI.HeadWallThickness,
		HWC.description as 'HeadWallCond',WT.Description as 'WRWallType',CI.WRWallLength,CI.WRWallMtrlType,
		wrwc.description as 'WRWallCond',CI.CulverLength,
		RT.Description as 'Railingtype',
		RC.Description as 'RailingCondition',
		sc1.description as 'ScourDS',
		sc.description as 'ScourUS',
		slt.description as 'SiltUS',
		slt1.description as 'SiltDS',
		vg.description as 'VegetationUS',vg1.description as 'VegetationDS',CI.IsFlorngProvd,
		flt.description as 'FlorngType',
		pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.CurtainwallPRVD,
		ct.description as 'CurtainwallType', CWUS.description as 'CurtainWallCondUS', 
		cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
		PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',
		CC.WideningReq,CC.WaterWayAdequacy,OSC.Description as 'OverallStrCond',CI.remarks		
from [BMS].[CulvertCondition] CC

  INNER JOIN bms.CulvertInventory CI on CC.CulvertCode=CI.CulvertCode
  LEFT JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN [BMS].[LKPTCulvCond] SSC on CC.SupStuctrCondition = SSC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
  LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
  left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
  left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
  left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
  left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
  left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
  left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
  left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
  left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
  left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
  left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
  left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
  left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
  left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
  left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
		INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		INNER JOIN NM.MLAConstituencyRoad MPr ON MPr.RoadCode =  rm.RoadCode 
		AND CI.Chainage>=MPR.StartChainage And CI.Chainage<=MPR.EndChainage
			   --AND CI.EndChainage>=MPR.StartChainage And CI.EndChainage<=MPR.EndChainage 
		INNER JOIN NM.MLAConstituency MPc ON  MPc.MLACId  = MPr.MLACode
		WHERE MPC.MLAcId=  ISNULL (@Searchval , MPC.MLAcId ) AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		END
END


/****** Object:  StoredProcedure [BMS].[CulvertInventoryDetails]    Script Date: 24-01-2025 09:47:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER PROCEDURE [BMS].[CulvertInventoryDetails]
--BMS.CulvertInventoryDetails 2019,'D','RBD02','saraswathin','Ahmedabad R&B Circle - 1',NULL,NULL
@SurveyYear NVARCHAR(5),
@SearchType NVARCHAR(5), 
@SearchVal  NVARCHAR (50) =NULL,
@User NVARCHAR(100) =NULL,
@CName NVARCHAR(100) = NULL,
@DName NVARCHAR(100) = NULL,
@SubDivision NVARCHAR(100) = NULL
AS BEGIN 
declare @userType  varchar(20)

select @userType = CASE WHEN areatype = 'H' THEN 'HQ' ELSE areatype END  from  SSUM.[User] where  [UserName] =@user
  
--IF @Circle IS NULL AND @Division IS NULL AND @SubDivision IS NULL AND @MLAConstituency IS NULL AND @MPConstituency IS NULL
IF (@SearchType  = 'C' )
BEGIN
 IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN
      If (@userType = 'HQ' )
	   begin

		SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
  where CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
	    end
		else  If (@userType = 'D' )
		   begin		  
		  SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		 WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)		
   end
		begin
		SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'
from [BMS].[CulvertInventory] CI 
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
    WHERE C.CircleCode    in (SELECT areaname FROM  SSUM.userareas WHERE username =@user)
	AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
    end
  END

 else  If (@userType = 'D' )
		   begin		  
		  SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype' 
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		 WHERE C.CircleCode = @SearchVal AND D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		
   end
  ELSE
  BEGIN
 SELECT 'Circle'as SEL,C.CirclesName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype' 
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
WHERE C.CircleCode = @SearchVal AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear) 
  END
END
ELSE
IF (@SearchType  = 'D' )
BEGIN
  IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN

   If (@userType = 'HQ' )
	   begin
	     SELECT 'Division'AS SEL,D.DivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype' 
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		  end
	   else if(@userType in ('C','W'))
	     begin		  
		  SELECT 'Division'AS SEL,D.DivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype' 
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode
		 WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		end
   else
	     begin		  
		  SELECT 'Division'AS SEL,D.DivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'  
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
		   INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
		   INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode
		 WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		
   end
  END
  ELSE
    BEGIN
		 SELECT 'Division'AS SEL,D.DivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'   
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode 
  INNER JOIN NM.Division D ON lm.Division=D.DivisionCode 
  INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode
		 WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode =   @SearchVal AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear) 
		 
 END 
END
ELSE
IF (@SearchType  = 'S' )
BEGIN
 IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN
    
	 If (@userType = 'HQ' )
	   begin
		  SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype' 
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
  INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
  INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
           	 end
	   else if(@userType in ('C','W'))
	    begin
			SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'  
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
  INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
  INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			 WHERE C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
			 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
			 AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			 end 
	   else if(@userType='D')
	    begin
			SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
  INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
  INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode
			 WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
			 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
			 AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			end
	   else
	    begin
			 SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'    
from [BMS].[CulvertInventory] CI
               INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
  INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
  INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode  
			 WHERE SD.SubDivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
			 AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
			 AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
			 end 
   END
     ELSE
       BEGIN
			 SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name', rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype' 
from [BMS].[CulvertInventory] CI
    INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
  INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
  INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
			WHERE SD.SubDivisionCode =  @SearchVal AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
			END
     END
  ELSE   IF (@SearchType  = 'MP' )
   BEGIN
		 SELECT 'MP Constituency'AS SEL, MPC.Name AS 'Name',rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'    
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
  INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
  INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode
	INNER JOIN  NM.MPConstituencyRoad MPr ON MPr.RoadCode =  rm.RoadCode 
	AND CI.Chainage>=MPR.StartChainage And CI.Chainage<=MPR.EndChainage
			   --AND CI.EndChainage>=MPR.StartChainage And CI.EndChainage<=MPR.EndChainage
		INNER JOIN NM.MPConstituency MPc ON  MPc.MpcId  = MPr.MPCode
		WHERE MPC.MpcId=  ISNULL (   @searchval   , MPC.MpcId ) AND  CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		END 
	ELSE IF (@SearchType  = 'ML' )
	BEGIN
		 SELECT 'MP Constituency'AS SEL, MPC.Name AS 'Name',rm.RoadCategoryCode,rm.[Name] AS 'RoadName',CI.RoadCode,CI.SurveyYear,CI.Latitude,CI.Longitude,CI.pwdstonech,CI.PWDStrNum, 
		CI.Direction,CI.SurveyYear,CI.CulvertCode,CI.CDNumber,ST.[Description] as 'StructureType',CI.NoofSpans,CI.SpanWidth,flow.Description as 'FlowDirection', CI.SpanHeight,CI.ClearRoadWidth,CI.TotalCulvertWidth,CI.DeckSlabThickness,HW.[description] as 'HeadWallType',CI.HeadWallLength,CI.HeadWallThickness,ci.nearbyplace, 
		WT.[Description] as 'WingWall',ci.submersible,ci.skewangle,ci.bedmaterial,ci.noofspans,ci.SpanWidth,ci.SpanHeight,CI.Type2SpanHeight,ci.Type2SpanWidth,ci.Type2SpansNo,
		ci.SpacingBtwnPipes,ci.Cushion,hw.Description as 'HeadWallType',ci.HeadWallThickness,WRHW.Description as 'WRWallMtrlType',ci.WRWallLength,CI.CulverLength,
		RT.Description as 'RailingType',FLT.Description as 'FlorngType',CT.description as 'CurtainwallType',PT.description as 'SdSlpPitchtype'     
from [BMS].[CulvertInventory] CI
  INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
  LEFT JOIN bms.LKPTHeadWallType HW on CI.HeadWallType = HW.headwalltype  
  LEFT JOIN bms.lkptwalltype WT on CI.WRWallType = WT.walltypecondtype  
  left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
  left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
  left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
  left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
  left join bms.LKPTFlowDir flow on flow.FlowDirType=ci.FlowDirection
  LEFT JOIN bms.LKPTHeadWallType WRHW on CI.wrwallmtrltype = wrhw.headwalltype
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
  INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
  INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode
		INNER JOIN  NM.MPConstituencyRoad MPr ON MPr.RoadCode =  rm.RoadCode 
		      AND CI.Chainage>=MPR.StartChainage And CI.Chainage<=MPR.EndChainage
			   --AND CI.EndChainage>=MPR.StartChainage And CI.EndChainage<=MPR.EndChainage
		INNER JOIN NM.MPConstituency MPc ON  MPc.MpcId  = MPr.MPCode
		WHERE
		--MPC.MLAcId=  ISNULL (@Searchval , MPC.MLAcId ) AND  
		CI.SurveyYear= ISNULL(@SurveyYear,CI.SurveyYear)
		END
END
/****** Object:  StoredProcedure [BMS].[GetCulvertInventoryDataDuplicateUpdate]    Script Date: 24-01-2025 11:39:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [BMS].[GetCulvertInventoryDataDuplicateUpdate]
AS
BEGIN
	SELECT [CulvertInventoryId]
	,[RoadCode]
	,[Chainage]
	,[LinkCode]
	,[Direction]
	,[SurveyYear]
	,RoadCode+CAST(Chainage as varchar(20))+Direction as CompositeKey
    FROM [BMS].[CulvertInventory]
END
GO
/****** Object:  StoredProcedure [BMS].[RoadwiseBridgeCount]    Script Date: 24-01-2025 15:35:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [BMS].[RoadwiseBridgeCount] 
--[BMS].[RoadwiseBridgeCount]'C',NULL,'satya',NULL,NULL,NULL
@SearchType NVARCHAR(5), 
@SearchVal  NVARCHAR (50) =NULL,
@User NVARCHAR(100) =NULL,
@CName NVARCHAR(100) = NULL,
@DName NVARCHAR(100) = NULL,
@SubDivision NVARCHAR(100) = NULL
AS BEGIN
declare @userType  varchar(20)

select @userType = CASE WHEN areatype = 'H' THEN 'HQ' ELSE areatype END  from  SSUM.[User] where  [UserName] =@user
  
--IF @Circle IS NULL AND @Division IS NULL AND @SubDivision IS NULL AND @MLAConstituency IS NULL AND @MPConstituency IS NULL
IF (@SearchType  = 'C' )
BEGIN
 IF (@SearchVal IS NULL or UPPER(@SearchVal) = 'NULL' )--or UPPER(@SearchVal) = 'NULL'
  BEGIN
      If (@userType = 'HQ' )
	   BEGIN
select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		 
union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  
	  union all
				  select
		'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where
ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		 
)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc

 end

 else IF (@userType = 'D' )
begin
select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',

rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
	
	  union all
				  select
		'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
 end
ELSE
BEGIN
select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode    in (SELECT areaname FROM  SSUM.userareas WHERE username =@user)

union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode    in (SELECT areaname FROM  SSUM.userareas WHERE username =@user)

	  union all
				  select
		'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode    in (SELECT areaname FROM  SSUM.userareas WHERE username =@user)

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
 end
 END
 else IF (@userType = 'D' )
begin
select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode = @SearchVal AND D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode = @SearchVal AND D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

	  union all
				  select 'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode, rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode and ci.chainage between rt.startchainage and rt.endchainage) bridge_cnt
					FROM ris.roadtype rt
					  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
					  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
					  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
					  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
					  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
					  WHERE C.CircleCode = @SearchVal AND D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
  END
  ELSE
  BEGIN
select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode = @SearchVal

union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode = @SearchVal

	  union all
				  select
		'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode = @SearchVal

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
  END
END

ELSE
IF (@SearchType  = 'D' )
BEGIN
    IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN

   IF (@userType = 'HQ')

 BEGIN
select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

	  union all
				  select
		'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
  END

else IF(@userType in ('C','W'))
begin
select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

	  union all
				  select
		'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
  END
   else
    BEGIN
	select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
	
	  union all
				  select
		'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
  END
END
 ELSE
    BEGIN
		select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode =   @SearchVal

union 
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode =   @SearchVal 

	  union all
				  select
		'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode =   @SearchVal 

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
  END
  END
  ELSE
IF (@SearchType  = 'S' )
BEGIN
 IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN
    
	 If (@userType = 'HQ' )
	   begin
	select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

union 
 
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

	  union all
				  
		SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
	INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
       	 end
	   else if(@userType in ('C','W'))
	    begin
		select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
	INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

union 
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

	  union all
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
	INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  AND C.CircleCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
		 end 
		 
	   else if(@userType='D')
	   BEGIN
		select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

union 
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

	  union all
	SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc
	end
	end

	   else
BEGIN
				select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		 INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		   WHERE SD.SubDivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

union 
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		    WHERE SD.SubDivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

	  union all
				 SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district
		,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,
(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode 
and ci.chainage between rt.startchainage and rt.endchainage
) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		 INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE SD.SubDivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		  AND C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)

)
b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc

		 end 
   END
     ELSE
       BEGIN
	   				select b.sel,b.name,b.Divisionname,b.district,b.RoadCode,b.RoadName,b.RoadCategoryCode,
b.RoadType,b.startchainage,b.endchainage,b.bridgetype,b.bridge_cnt
from
(
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,
NULL District,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Major' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where ld.roadcode= rm.RoadCode
and ld.typeofthebridge=1
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		 INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		WHERE SD.SubDivisionCode =  @SearchVal

union 
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district,
rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,rt.RoadType,rt.startchainage,rt.endchainage,'Minor' bridgetype,
(select count(BridgeID) from bms.locationdetails ld where roadcode= rm.RoadCode and ld.typeofthebridge=2
and ld.chainage between rt.startchainage and rt.endchainage) bridge_cnt
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		   WHERE SD.SubDivisionCode =  @SearchVal

	  union all
SELECT 'Sub Division'AS SEL,SD.SubDivisionName AS 'Name',d.Divisionname,null district,rm.RoadCode,rm.name as 'RoadName',rm.RoadCategoryCode,
rt.RoadType,rt.startchainage,rt.endchainage,'Culvert' bridgetype,(select count(culvertcode) from bms.culvertinventory ci where ci.roadcode= rm.RoadCode  and ci.chainage between rt.startchainage and rt.endchainage) bridge_cnt FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  INNER JOIN NM.SubDivision SD  ON SD.SubDivisionCode=lm.SubDivision
			INNER JOIN NM.Division D ON  sd.DivisionCode=D.DivisionCode 
			INNER JOIN NM.Circle C ON D.CircleCode=C.CircleCode 
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		  WHERE SD.SubDivisionCode =  @SearchVal)	b
order by  b.sel,b.Divisionname ,b.RoadCategoryCode,b.roadcode,b.startchainage,b.endchainage,b.bridgetype desc

END
END
GO
/****** Object:  StoredProcedure [BMS].[RoadwiseBridgeDet]    Script Date: 24-01-2025 15:49:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




ALTER PROCEDURE [BMS].[RoadwiseBridgeDet] 
--[RIS].[RoadwiseBridgeDet]'C',NULL,'satya'
@SearchType NVARCHAR(5), 
@SearchVal  NVARCHAR (50) =NULL,
@User NVARCHAR(100) =NULL,
@CName NVARCHAR(100) = NULL,
@DName NVARCHAR(100) = NULL,
@SubDivision NVARCHAR(100) = NULL
AS BEGIN
declare @userType  varchar(20)

select @userType = CASE WHEN areatype = 'H' THEN 'HQ' ELSE areatype END  from  SSUM.[User] where  [UserName] =@user
  
--IF @Circle IS NULL AND @Division IS NULL AND @SubDivision IS NULL AND @MLAConstituency IS NULL AND @MPConstituency IS NULL
IF (@SearchType  = 'C' )
BEGIN
 IF (@SearchVal IS NULL or UPPER(@SearchVal) = 'NULL' )--or UPPER(@SearchVal) = 'NULL'
  BEGIN
      If (@userType = 'HQ' )
	   BEGIN
select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 SELECT 'Culvert' bridgetype,lm.LinkCode,count(culvertcode) bridgecnt,ci.roadcode
    from [BMS].[CulvertInventory] CI
  INNER JOIN NM.linkmaster lm ON CI.RoadCode= lm.RoadCode
  INNER JOIN NM.roadmaster rm ON CI.RoadCode = rm.roadcode
  INNER JOIN NM.division d on d.DivisionCode = lm.Division
  INNER JOIN NM.Circle C ON d.CircleCode = C.CircleCode
  group by lm.LinkCode,ci.roadCode
  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
 end
 else IF (@userType = 'D' )
begin
select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		where  D.DivisionCode   in ( SELECT areaname FROM  SSUM.userareas WHERE username =@user  )
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 	 SELECT 'Culvert' bridgetype,ci.LinkCode,count(culvertcode) bridgecnt,ci.roadcode from [BMS].[CulvertInventory] CI
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode  group by ci.LinkCode,ci.roadCode  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
 end
ELSE
begin
select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		WHERE C.CircleCode in (SELECT areaname From  SSUM.userareas WHERE username =@user)
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 SELECT 'Culvert' bridgetype,ci.LinkCode,count(culvertcode) bridgecnt,ci.roadcode from [BMS].[CulvertInventory] CI INNER JOIN NM.linkmaster lm ON 
	 CI.LinkCode = lm.LinkCode group by ci.LinkCode,ci.roadCode
  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
 end
 END
 else IF (@userType = 'D' )
begin
select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		WHERE C.CircleCode = @SearchVal  AND D.DivisionCode   in ( SELECT areaname From  SSUM.userareas WHERE username =@user  )
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 SELECT 'Culvert' bridgetype,ci.LinkCode,count(culvertcode) bridgecnt,ci.roadcode
    from [BMS].[CulvertInventory] CI
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  group by ci.LinkCode,ci.roadCode
  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
  END
  ELSE
  BEGIN
select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Circle'as SEL,C.CirclesName AS 'Name',d.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		WHERE C.CircleCode = @SearchVal
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 SELECT 'Culvert' bridgetype,ci.LinkCode,count(culvertcode) bridgecnt,ci.roadcode
    from [BMS].[CulvertInventory] CI
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  group by ci.LinkCode,ci.roadCode
  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
  END
END
END

/*

ELSE
IF (@SearchType  = 'D' )
BEGIN
    IF (@searchVal IS NULL or UPPER(@SearchVal) = 'NULL' )
  BEGIN

   IF (@userType = 'HQ')

 BEGIN
select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Division'as SEL,Concat(D.DivisionCode,' - ',D.DivisionName) AS 'Name'd.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionName = ISNULL(@DName, D.DivisionName)
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
		-- AND LD.RoadCode='SH006'
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 SELECT 'Culvert' bridgetype,ci.LinkCode,count(culvertcode) bridgecnt,ci.roadcode
    from [BMS].[CulvertInventory] CI
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  where 1=1 --ci.RoadCode='SH006'
  group by ci.LinkCode,ci.roadCode
  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
  END

else IF(@userType in ('C','W'))
begin
select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Division'as SEL,Concat(D.DivisionCode,' - ',D.DivisionName) AS 'Name'd.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and C.CircleCode   in ( SELECT areaname From  SSUM.userareas WHERE username =@user  ) 
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
		-- AND LD.RoadCode='SH006'
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 SELECT 'Culvert' bridgetype,ci.LinkCode,count(culvertcode) bridgecnt,ci.roadcode
    from [BMS].[CulvertInventory] CI
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  where 1=1 --ci.RoadCode='SH006'
  group by ci.LinkCode,ci.roadCode
  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
  END
   else
    BEGIN
	select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Division'as SEL,Concat(D.DivisionCode,' - ',D.DivisionName) AS 'Name'd.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode   in ( SELECT areaname From  SSUM.userareas WHERE username =@user  )
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
		-- AND LD.RoadCode='SH006'
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 SELECT 'Culvert' bridgetype,ci.LinkCode,count(culvertcode) bridgecnt,ci.roadcode
    from [BMS].[CulvertInventory] CI
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  where 1=1 --ci.RoadCode='SH006'
  group by ci.LinkCode,ci.roadCode
  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
  END
END
 ELSE
    BEGIN
	select a.sel,a.name,a.divisionname,a.taluka,a.District,a.RoadName,a.RoadCategoryCode,
a.roadcode,a.roadtype,a.StartChainage,a.EndChainage,b.bridgetype,sum(b.bridgecnt),
b.bridgetype,a.roadcode
from
(
SELECT distinct
'Division'as SEL,Concat(D.DivisionCode,' - ',D.DivisionName) AS 'Name'd.Divisionname,lm.LinkCode,rt.RoadType,
NULL District,NULL Taluka ,rm.RoadCode,rm.name as 'RoadName',
rm.RoadCategoryCode,
rt.roadtype 'CarriagewayType',CONVERT(DECIMAL(10, 3),(SUM(abs(rt.StartChainage))/1000.00)) StartChainage,
CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage))/1000.00))  EndChainage
	--	 CONVERT(DECIMAL(10, 3),(SUM(abs(rt.EndChainage - rt.StartChainage))/1000.00)) AS [Length(km)]
		FROM ris.roadtype rt
		  INNER JOIN NM.linkmaster lm ON lm.LinkCode = rt.LinkCode 
		  INNER JOIN NM.roadmaster rm ON rt.RoadCode = rm.roadcode
		  inner JOIN NM.Division D on lm.Division=D.DivisionCode 
		  INNER JOIN NM.Circle C ON lm.circle=C.CircleCode
		  INNER JOIN nm.wing Wg on C.WingName = wg.WingName
		WHERE C.CirclesName = IsNULL(@CName,C.CirclesName) and D.DivisionCode =   @SearchVal
		group by C.CirclesName ,d.Divisionname,rm.RoadCode,rm.name,lm.LinkCode,
rm.RoadCategoryCode,rt.roadtype,rt.startchainage,rt.endchainage
)
a,
(SELECT BT.DESCRIPTION bridgetype ,LD.LinkCode,count(bridgecode) bridgecnt,ld.roadcode
		 from bms.BridgeDetails BD
		 INNER JOIN BMS.LocationDetails LD on BD.BridgeCode=LD.BridgeID
		 INNER JOIN BMS.LKPTBridgeType BT on LD.TypeoftheBridge=BT.BridgeType
		 and bt.Description in('Minor Bridge','Major Bridge')
		-- AND LD.RoadCode='SH006'
	 group by BT.DESCRIPTION ,LD.LinkCode,ld.roadcode
	 union
	 SELECT 'Culvert' bridgetype,ci.LinkCode,count(culvertcode) bridgecnt,ci.roadcode
    from [BMS].[CulvertInventory] CI
  INNER JOIN NM.linkmaster lm ON CI.LinkCode = lm.LinkCode
  where 1=1 --ci.RoadCode='SH006'
  group by ci.LinkCode,ci.roadCode
  )
  b
  where a.LinkCode=b.LinkCode
  and a.roadcode=b.roadcode
  group by a.sel,a.name,a.divisionname,b.bridgetype,a.roadcode,a.RoadType,a.Taluka,a.District,a.RoadName,
  a.RoadCategoryCode,a.StartChainage,a.EndChainage
  END
  END
  END
  GO
  ********************/

/****** Object:  StoredProcedure [dbo].[CulvertConditionEdit]    Script Date: 24-01-2025 16:04:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CulvertConditionEdit]
--EXEC [dbo].[CulvertConditionEdit] 1
(
@culvertConditionId int
)
AS

BEGIN
	SELECT  [CulvertConditionId], CC.[CulvertCode], [WaterWayAdequacy], [Remarks], 
			CI.[SurveyYear],Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
			FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
			CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
			CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
			WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
			CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
			sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
			flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
			CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
			OSC.Description as 'OverallStrCond',CI.Remarks
	FROM [BMS].[CulvertCondition] CC
		INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
		left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
		left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
		LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
		left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
		left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
		left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
		left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
		LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
		left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
		left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
		left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
		left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
		left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
		left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
		left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
		LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
		LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
		left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
		LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
		left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
		left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
		left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
		left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 
	WHERE CC.CulvertConditionId = @culvertConditionId		
END

/****** Object:  StoredProcedure [dbo].[CulvertInventoryEdit]    Script Date: 24-01-2025 17:40:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CulvertInventoryEdit]
--EXEC [dbo].[CulvertInventoryEdit] 2
(
@culvertInventoryId int
)
AS
--CONVERT(DATE, vd.GPSTime) as GPSTime
BEGIN
	SELECT CI.CulvertInventoryId, CI.RoadCode, CI.Chainage, CI.LinkCode, CI.Direction, CI.SurveyYear, CI.Latitude, CI.Longitude, 
	CI.CulvertCode, CI.CDNumber, CI.HeadWallLength, CI.HeadWallThickness, FL.Description as 'FlowDirection', 
	CONVERT(DATE, CI.SurveyDate) AS SurveyDate,CI.ConstructionYear,CI.PWDStoneCh,CI.PWDStrNum,CI.NearByPlace,ST.Description as 'StructureType',
	CI.TotalCulvertWidth,CI.ClearRoadWidth,CI.Submersible,CI.SkewAngle,CI.Bedmaterial,CI.NoofSpans,CI.SpanWidth,CI.SpanHeight,CI.Type2SpansNo,
	CI.Type2SpanWidth,CI.Type2SpanHeight,ci.DeckSlabThickness,ci.SpacingBtwnPipes,ci.Cushion,HWT.Description as 'HeadWallType',WT.Description as 'WRWallType',
	HW1.Description as 'WRWallMtrlType',CI.WRWallLength,CI.CulverLength,RT.description as 'Railingtype',CI.IsFlorngProvd,FLT.Description as 'FlorngType',
	CI.CurtainwallPRVD,CT.Description as 'CurtainwallType',CI.IsPichngProvd,PT.Description as 'SdSlpPitchtype',CI.Remarks,
	rm.NAME as roadName	 
	FROM [BMS].[CulvertInventory] CI
	INNER JOIN NM.ROADMASTER rm on CI.roadcode = rm.roadcode
	left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
	INNER JOIN bms.LKPTStructureType  ST on CI.StructureType=ST.StructureType
		left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
		left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
		left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
		left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
		left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
		left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
		left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType	
	WHERE CI.CulvertInventoryId = @culvertInventoryId		
END
GO
/****** Object:  StoredProcedure [dbo].[GetCulvertCodes]    Script Date: 24-01-2025 19:03:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetCulvertCodes]
--EXEC [dbo].[GetCulvertInventoryByFilter] NULL,'CI:MDR_PND06_001:0000.100',NULL,NULL,4
(
@user VARCHAR(50) = NULL,
@userType VARCHAR(10) = NULL,
@hType VARCHAR(10) = NULL,
@hTypeVal VARCHAR(MAX) = NULL
)
AS
BEGIN
	    IF @userType = 'C'
		BEGIN
			SELECT DISTINCT CulvertCode
			FROM [BMS].[CulvertInventory] LD
			INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
			LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
			LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
			LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
			--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
			WHERE ld.RoadCode IN(SELECT sdr.Roadcode  
					FROM NM.LinkMaster  sdr  WHERE Circle IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			ORDER BY CulvertCode
		END
	ELSE IF @userType = 'D'
		BEGIN
			SELECT DISTINCT CulvertCode
			FROM [BMS].[CulvertInventory] LD
			INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
			LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
			LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
			LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
			--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
			WHERE ld.RoadCode IN(SELECT sdr.Roadcode  
					FROM NM.LinkMaster  sdr  WHERE Division IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			ORDER BY CulvertCode
		END
	ELSE
		BEGIN
			IF @hType = 'C'
				BEGIN
					SELECT DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					WHERE ld.RoadCode IN(SELECT sdr.Roadcode FROM NM.LinkMaster  sdr  WHERE Circle = @hTypeVal)
					ORDER BY CulvertCode
				END
			ELSE IF @hType = 'D'
				BEGIN
					SELECT DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					WHERE ld.RoadCode IN(SELECT sdr.Roadcode FROM NM.LinkMaster  sdr  WHERE Division = @hTypeVal)
					ORDER BY CulvertCode
				END
			ELSE IF @hType = 'MLA'
				BEGIN
					SELECT DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					WHERE ld.RoadCode IN(SELECT sdr.Roadcode FROM [NM].[MLAConstituencyRoad] sdr Where MLACODE = @hTypeVal)
					ORDER BY CulvertCode
				END
			ELSE IF @hType = 'MP'
				BEGIN
					SELECT  DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					WHERE ld.RoadCode IN(SELECT sdr.Roadcode FROM [NM].[MPConstituencyRoad] sdr Where MPCODE = @hTypeVal)
					ORDER BY CulvertCode
				END	
			ELSE
				BEGIN
					SELECT DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					ORDER BY CulvertCode
				END	
		END
END
GO
/****** Object:  StoredProcedure [dbo].[ExecuteRMCndtSections]    Script Date: 27-01-2025 09:28:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Exec [dbo].[ExecuteRMCndtSections] 2019, NULL,0
--Exec [dbo].[ExecuteRMCndtSections] '2019','LI:MDR_PND01_002:0000.000'
--Exec [dbo].[ExecuteRMCndtSections] '2019',NULL,'satya',NULL,NULL,1
ALTER PROCEDURE [dbo].[ExecuteRMCndtSections] 
@Surveyyear VARCHAR(10)=NULL,
--@linkcode Varchar(max)=NULL,
@rdcatg varchar(50) = NULL, 
@userName VARCHAR(50) = NULL,
@hqTypeSel VARCHAR(10) = NULL,
@hTypeVal VARCHAR(MAX) = NULL,
@Network varchar(50) = NULL,     
@Src bit = 0      
As 
BEGIN 

declare @userType  varchar(20)

select @userType =  areatype  from  SSUM.[User] where  [UserName] =@userName

IF(UPPER(@rdcatg) = 'NULL')
begin
	set @rdcatg = NULL
end
IF (@rdcatg is not null )
begin
				delete [RMMS].[AssgnWrkCode]  where RMCndtSecID in (select RMCndtSecID from RMMS.RMCndtSec  where SurveyYear = ISNULL(@Surveyyear,SurveyYear) and RoadCatg = ISNULL(@rdcatg,RoadCatg) and NtWrk = ISNULL(@Network,NtWrk))
				delete from [RMMS].[RMCndtSec]  where SurveyYear=ISNULL(@Surveyyear,SurveyYear) and RoadCatg = ISNULL(@rdcatg,RoadCatg) and NtWrk = ISNULL(@Network,NtWrk)--and Linkcode=ISNULL(@linkcode,LinkCode)
				IF(@Src = 1)
				begin
					INSERT INTO [RMMS].[RMCndtSec]
				   ([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth,TrfCls,RghCls,DflctCls,Src,AddedBy,AddedOn)
					 SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType , PaveWidth,TrfCls,RghCls,DflctCls,'Decision Tree', @userName,GETDATE()
						FROM [RMMS].[SmplPMSSec] a
						where WrkCode Is Null and SurveyYear = ISNULL( @Surveyyear,SurveyYear) 
						and RoadCatg = ISNULL(@rdcatg,RoadCatg)
						and NtWrk = ISNULL(@Network,NtWrk)
						--and LinkCode= ISNULL(@linkcode,a.LinkCode)
						order by roadcode, StartCh
				end
				else if (@Src = 0)
				begin
				INSERT INTO [RMMS].[RMCndtSec]
			   ([Linkcode],[Roadcode],[StartCh],[EndCh],[SurveyYear],RoadCatg,NtWrk,PaveWidth,Src,AddedBy,AddedOn)
					select st.LINK_NAME
					,left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1)
					,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))
					,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], (charindex(':', st.[Sect_Name], 1))+1))))
					, @Surveyyear
					,rm.RoadCategoryCode
					,rm.IsCRN
					, st.CWAY_WIDTH
					,'HDM'
					,@userName
					,GETDATE()
					from SECTIONS st
					inner join NM.RoadMaster rm on left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1) = rm.RoadCode
					where  SECT_ID not in 
					(select distinct wp.SECT_ID from WorkProgramme wp
					inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
					where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> '0' and wp.SurveyCode = ISNULL(@Surveyyear,wp.SurveyCode))
					and st.ROAD_CLASS = ISNULL(@rdcatg,st.ROAD_CLASS) and rm.IsCRN = ISNULL(@Network, rm.ISCRN)
					order by left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))

					update a set a.RoadType = b.RoadType from RMMS.RMCndtSec a 
					inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
					where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) 
					and a.RoadCatg = ISNULL(@rdcatg, a.RoadCatg)
					and a.NtWrk = ISNULL(@Network, a.Ntwrk)
					--and a.LinkCode=ISNULL(@linkCode,a.Linkcode)
				end
end
else
BEGIN
	IF ((@userType = 'C' or @userType = 'W') and @hTypeVal is null)
		BEGIN
			delete [RMMS].[AssgnWrkCode]  where RMCndtSecID in (select RMCndtSecID from RMMS.RMCndtSec  where SurveyYear = ISNULL(@Surveyyear,SurveyYear) and RoadCatg = ISNULL(@rdcatg,RoadCatg) and NtWrk = ISNULL(@Network,NtWrk) 
			and Linkcode in (select LinkCode from NM.LinkMaster where Circle in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName)))
			delete from [RMMS].[RMCndtSec]  
			where SurveyYear=ISNULL(@Surveyyear,SurveyYear) 
			and Linkcode in (select LinkCode from NM.LinkMaster where Circle in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName))
			and RoadCatg = ISNULL(@rdcatg, RoadCatg)
			and NtWrk = ISNULL(@Network,NtWrk)
			--select @Surveyyear,@roadCode

			IF(@Src = 1)
				begin
					INSERT INTO [RMMS].[RMCndtSec]
				   	([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth,TrfCls,RghCls,DflctCls,Src,AddedBy,AddedOn)
					 SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType , PaveWidth,TrfCls,RghCls,DflctCls,'Decision Tree', @userName,GETDATE()
						FROM [RMMS].[SmplPMSSec] a
						where WrkCode Is Null and SurveyYear = ISNULL( @Surveyyear,SurveyYear) 
						and RoadCatg = ISNULL(@rdcatg,RoadCatg)
						and NtWrk = ISNULL(@Network,NtWrk)
						--and LinkCode= ISNULL(@linkcode,a.LinkCode)
						order by roadcode, StartCh
				end
				else if (@Src = 0)
				begin
				INSERT INTO [RMMS].[RMCndtSec]
			   ([Linkcode],[Roadcode],[StartCh],[EndCh],[SurveyYear],RoadCatg,NtWrk,PaveWidth,Src,AddedBy,AddedOn)
					select st.LINK_NAME
					,left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1)
					,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))
					,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], (charindex(':', st.[Sect_Name], 1))+1))))
					, @Surveyyear
					,rm.RoadCategoryCode
					,rm.IsCRN
					, st.CWAY_WIDTH
					,'HDM'
					,@userName
					,GETDATE()
					from SECTIONS st
					inner join NM.RoadMaster rm on left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1) = rm.RoadCode
					where  SECT_ID not in 
					(select distinct wp.SECT_ID from WorkProgramme wp
					inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
					where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> '0' 
					and wp.SurveyCode = ISNULL(@Surveyyear,wp.SurveyCode))
					and st.ROAD_CLASS = ISNULL(@rdcatg,st.ROAD_CLASS) and rm.IsCRN = ISNULL(@Network, rm.ISCRN)
					and st.LINK_NAME in (select LinkCode from NM.LinkMaster where Circle in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName))
					order by left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))

					update a set a.RoadType = b.RoadType from RMMS.RMCndtSec a 
					inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
					where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) 
					and a.RoadCatg = ISNULL(@rdcatg, a.RoadCatg)
					and a.NtWrk  = ISNULL(@Network,a.Ntwrk)
					and a.Linkcode in (select LinkCode from NM.LinkMaster where Circle in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName))
				end

		END

		else IF(@userType = 'D'  and @hTypeVal is null)
		BEGIN
		delete [RMMS].[AssgnWrkCode]  where RMCndtSecID in (select RMCndtSecID from RMMS.RMCndtSec  where SurveyYear = ISNULL(@Surveyyear,SurveyYear) and RoadCatg = ISNULL(@rdcatg,RoadCatg) and NtWrk = ISNULL(@Network,NtWrk)
		and Linkcode in (select LinkCode from NM.LinkMaster where Division in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName)))
			delete from [RMMS].[RMCndtSec]  
			where SurveyYear=ISNULL(@Surveyyear,SurveyYear) 
			and Linkcode in (select LinkCode from NM.LinkMaster where Division in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName))
			and RoadCatg = ISNULL(@rdcatg, RoadCatg)
			and NtWrk = ISNULL(@Network, NtWrk)
			--select @Surveyyear,@roadCode

			IF(@Src = 1)
				begin
					INSERT INTO [RMMS].[RMCndtSec]
				   	([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth,TrfCls,RghCls,DflctCls,Src,AddedBy,AddedOn)
					 SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType , PaveWidth,TrfCls,RghCls,DflctCls,'Decision Tree', @userName,GETDATE()
						FROM [RMMS].[SmplPMSSec] a
						where WrkCode Is Null and SurveyYear = ISNULL( @Surveyyear,SurveyYear) 
						and RoadCatg = ISNULL(@rdcatg,RoadCatg)
						and NtWrk = ISNULL(@Network,NtWrk)
						and a.Linkcode in (select LinkCode from NM.LinkMaster where Division in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName))
						--and LinkCode= ISNULL(@linkcode,a.LinkCode)
						order by roadcode, StartCh
				end
				else if (@Src = 0)
				begin
				INSERT INTO [RMMS].[RMCndtSec]
			   ([Linkcode],[Roadcode],[StartCh],[EndCh],[SurveyYear],RoadCatg,NtWrk,PaveWidth,Src,AddedBy,AddedOn)
					select st.LINK_NAME
					,left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1)
					,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))
					,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], (charindex(':', st.[Sect_Name], 1))+1))))
					, @Surveyyear
					,rm.RoadCategoryCode
					,rm.IsCRN
					, st.CWAY_WIDTH
					,'HDM'
					,@userName
					,GETDATE()
					from SECTIONS st
					inner join NM.RoadMaster rm on left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1) = rm.RoadCode
					where  SECT_ID not in 
					(select distinct wp.SECT_ID from WorkProgramme wp
					inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
					where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> '0' and wp.SurveyCode = ISNULL(@Surveyyear,wp.SurveyCode))
					and st.ROAD_CLASS = ISNULL(@rdcatg,st.ROAD_CLASS)
					and rm.IsCRN = ISNULL(@Network, rm.ISCRN)
					and st.LINK_NAME in (select LinkCode from NM.LinkMaster where Division in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName))
					order by left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))

					update a set a.RoadType = b.RoadType from RMMS.RMCndtSec a 
					inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
					where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) 
					and a.RoadCatg = ISNULL(@rdcatg, a.RoadCatg)
					and a.NtWrk = ISNULL(@Network, a.Ntwrk)
					and a.Linkcode in (select LinkCode from NM.LinkMaster where Division in (SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @userName))
				end

		END
		ELSE 
	BEGIN
			IF @hqTypeSel = 'C'
			BEGIN
				delete [RMMS].[AssgnWrkCode]  where RMCndtSecID in (select RMCndtSecID from RMMS.RMCndtSec  where SurveyYear = ISNULL(@Surveyyear,SurveyYear) and RoadCatg = ISNULL(@rdcatg,RoadCatg) --and NtWrk = ISNULL(@Network,NtWrk) 
				and Linkcode in (select LinkCode from NM.LinkMaster where Circle = @hTypeVal))
				delete from [RMMS].[RMCndtSec]  
				where SurveyYear=ISNULL(@Surveyyear,SurveyYear) 
				and Linkcode in (select LinkCode from NM.LinkMaster where Circle = @hTypeVal)
				and RoadCatg = ISNULL(@rdcatg, RoadCatg)
				and NtWrk = ISNULL(@Network,NtWrk)
				--select @Surveyyear,@roadCode

			IF(@Src = 1)
				begin
					INSERT INTO [RMMS].[RMCndtSec]
				   	([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth,TrfCls,RghCls,DflctCls,Src,AddedBy,AddedOn)
					 SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType , PaveWidth,TrfCls,RghCls,DflctCls,'Decision Tree', @userName,GETDATE()
						FROM [RMMS].[SmplPMSSec] a
						where WrkCode Is Null and SurveyYear = ISNULL( @Surveyyear,SurveyYear) 
						and RoadCatg = ISNULL(@rdcatg,RoadCatg)
						and NtWrk = ISNULL(@Network,NtWrk)
						and Linkcode in (select LinkCode from NM.LinkMaster where Circle = @hTypeVal)
						--and LinkCode= ISNULL(@linkcode,a.LinkCode)
						order by roadcode, StartCh
				end
				else if (@Src = 0)
				begin
				INSERT INTO [RMMS].[RMCndtSec]
			   ([Linkcode],[Roadcode],[StartCh],[EndCh],[SurveyYear],RoadCatg,NtWrk,PaveWidth,Src,AddedBy,AddedOn)
					select st.LINK_NAME
					,left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1)
					,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))
					,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], (charindex(':', st.[Sect_Name], 1))+1))))
					, @Surveyyear
					,rm.RoadCategoryCode
					,rm.IsCRN
					, st.CWAY_WIDTH
					,'HDM'
					,@userName
					,GETDATE()
					from SECTIONS st
					inner join NM.RoadMaster rm on left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1) = rm.RoadCode
					where  SECT_ID not in 
					(select distinct wp.SECT_ID from WorkProgramme wp
					inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
					where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> '0' and wp.SurveyCode = ISNULL(@Surveyyear,wp.SurveyCode))
					and st.ROAD_CLASS = ISNULL(@rdcatg,st.ROAD_CLASS)
					and rm.IsCRN = ISNULL(@Network,rm.IsCRN)
					and st.LINK_NAME in (select LinkCode from NM.LinkMaster where Circle = @hTypeVal)
					order by left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))

					update a set a.RoadType = b.RoadType from RMMS.RMCndtSec a 
					inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
					where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) 
					and a.RoadCatg = ISNULL(@rdcatg, a.RoadCatg)
					and a.NtWrk = ISNULL(@Network,a.Ntwrk)
					and a.Linkcode in (select LinkCode from NM.LinkMaster where Circle = @hTypeVal)
				end

			END
			IF @hqTypeSel = 'D'
			BEGIN
				delete [RMMS].[AssgnWrkCode]  where RMCndtSecID in (select RMCndtSecID from RMMS.RMCndtSec  where SurveyYear = ISNULL(@Surveyyear,SurveyYear) and RoadCatg = ISNULL(@rdcatg,RoadCatg) --and NtWrk = ISNULL(@Network,NtWrk) 
				and Linkcode in (select LinkCode from NM.LinkMaster where Division = @hTypeVal))
				delete from [RMMS].[RMCndtSec]  
				where SurveyYear=ISNULL(@Surveyyear,SurveyYear) 
				and Linkcode in (select LinkCode from NM.LinkMaster where Division = @hTypeVal)
				and RoadCatg = ISNULL(@rdcatg, RoadCatg)
				and NtWrk = ISNULL(@Network, NtWrk)
				--select @Surveyyear,@roadCode

			IF(@Src = 1)
				begin
					INSERT INTO [RMMS].[RMCndtSec]
				   	([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth,TrfCls,RghCls,DflctCls,Src,AddedBy,AddedOn)
					 SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType , PaveWidth,TrfCls,RghCls,DflctCls,'Decision Tree', @userName,GETDATE()
						FROM [RMMS].[SmplPMSSec] a
						where WrkCode Is Null and SurveyYear = ISNULL( @Surveyyear,SurveyYear) 
						and RoadCatg = ISNULL(@rdcatg,RoadCatg)
						and NtWrk = ISNULL(@Network,NtWrk)
						and Linkcode in (select LinkCode from NM.LinkMaster where Division = @hTypeVal)
						--and LinkCode= ISNULL(@linkcode,a.LinkCode)
						order by roadcode, StartCh
				end
				else if (@Src = 0)
				begin
				INSERT INTO [RMMS].[RMCndtSec]
			   ([Linkcode],[Roadcode],[StartCh],[EndCh],[SurveyYear],RoadCatg,NtWrk,PaveWidth,Src,AddedBy,AddedOn)
					select st.LINK_NAME
					,left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1)
					,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))
					,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], (charindex(':', st.[Sect_Name], 1))+1))))
					, @Surveyyear
					,rm.RoadCategoryCode
					,rm.IsCRN
					, st.CWAY_WIDTH
					,'HDM'
					,@userName
					,GETDATE()
					from SECTIONS st
					inner join NM.RoadMaster rm on left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1) = rm.RoadCode
					where  SECT_ID not in 
					(select distinct wp.SECT_ID from WorkProgramme wp
					inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
					where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> '0' and wp.SurveyCode = ISNULL(@Surveyyear,wp.SurveyCode))
					and st.ROAD_CLASS = ISNULL(@rdcatg,st.ROAD_CLASS)
					and rm.IsCRN = ISNULL(@Network, rm.IsCRN)
					and st.LINK_NAME in (select LinkCode from NM.LinkMaster where Division = @hTypeVal)
					order by left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))

					update a set a.RoadType = b.RoadType from RMMS.RMCndtSec a 
					inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
					where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) 
					and a.RoadCatg = ISNULL(@rdcatg, a.RoadCatg)
					and a.NtWrk = ISNULL(@Network, a.NtWrk)
					and a.Linkcode in (select LinkCode from NM.LinkMaster where Division = @hTypeVal)
				end

			END

			IF @hqTypeSel = 'W'
			BEGIN
				delete [RMMS].[AssgnWrkCode]  where RMCndtSecID in 
				(select RMCndtSecID from RMMS.RMCndtSec  
				where SurveyYear = ISNULL(@Surveyyear,SurveyYear) 
				and RoadCatg = ISNULL(@rdcatg,RoadCatg) 
				and NtWrk = ISNULL(@Network,NtWrk)
				and Linkcode in (select LinkCode from NM.LinkMaster where Circle in (select CircleCode from NM.Circle where WingName = @hTypeVal)))
				
				delete from [RMMS].[RMCndtSec]  
				where SurveyYear=ISNULL(@Surveyyear,SurveyYear) 
				and Linkcode in (select LinkCode from NM.LinkMaster where Circle in (select CircleCode from NM.Circle where WingName = @hTypeVal))
				and RoadCatg = ISNULL(@rdcatg, RoadCatg)
				and NtWrk = ISNULL(@Network, NtWrk)

				--select @Surveyyear,@roadCode

			IF(@Src = 1)
				begin
					INSERT INTO [RMMS].[RMCndtSec]
				   ([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth,TrfCls,RghCls,DflctCls,Src,AddedBy,AddedOn)
					 SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType , PaveWidth,TrfCls,RghCls,DflctCls,'Decision Tree', @userName,GETDATE()
					 	FROM [RMMS].[SmplPMSSec] a
						where WrkCode Is Null and SurveyYear = ISNULL( @Surveyyear,SurveyYear) 
						and RoadCatg = ISNULL(@rdcatg,RoadCatg)
						and NtWrk = ISNULL(@Network,NtWrk)
						and Linkcode in (select LinkCode from NM.LinkMaster where Circle in (select CircleCode from NM.Circle where WingName = @hTypeVal))
						--and LinkCode= ISNULL(@linkcode,a.LinkCode)
						order by roadcode, StartCh
				end
				else if (@Src = 0)
				begin
				INSERT INTO [RMMS].[RMCndtSec]
			   ([Linkcode],[Roadcode],[StartCh],[EndCh],[SurveyYear],RoadCatg,NtWrk,PaveWidth,Src,AddedBy,AddedOn)
					select st.LINK_NAME
					,left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1)
					,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))
					,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], (charindex(':', st.[Sect_Name], 1))+1))))
					, @Surveyyear
					,rm.RoadCategoryCode
					,rm.IsCRN
					, st.CWAY_WIDTH
					,'HDM'
					,@userName
					,GETDATE()
					from SECTIONS st
					inner join NM.RoadMaster rm on left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1) = rm.RoadCode
					where  SECT_ID not in 
					(select distinct wp.SECT_ID from WorkProgramme wp
					inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
					where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> '0' and wp.SurveyCode = ISNULL(@Surveyyear,wp.SurveyCode))
					and st.ROAD_CLASS = ISNULL(@rdcatg,st.ROAD_CLASS)
					and rm.IsCRN = ISNULL(@Network, rm.IsCRN)
					and st.LINK_NAME in (select LinkCode from NM.LinkMaster where Circle in (select CircleCode from NM.Circle where WingName = @hTypeVal))
					order by left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))

					update a set a.RoadType = b.RoadType from RMMS.RMCndtSec a 
					inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
					where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) 
					and a.RoadCatg = ISNULL(@rdcatg, a.RoadCatg)
					and a.NtWrk = ISNULL(@Network, a.NtWrk)
					and a.Linkcode in (select LinkCode from NM.LinkMaster where Circle in (select CircleCode from NM.Circle where WingName = @hTypeVal))
				end

			END
		ELSE
		BEGIN
				delete [RMMS].[AssgnWrkCode]  where RMCndtSecID in (select RMCndtSecID from RMMS.RMCndtSec  where SurveyYear = ISNULL(@Surveyyear,SurveyYear) and RoadCatg = ISNULL(@rdcatg,RoadCatg))-- and NtWrk = ISNULL(@Network, NtWrk)
				delete from [RMMS].[RMCndtSec]  where SurveyYear=ISNULL(@Surveyyear,SurveyYear) and RoadCatg = ISNULL(@rdcatg,RoadCatg) --and NtWrk = ISNULL(@Network, NtWrk)--and Linkcode=ISNULL(@linkcode,LinkCode)
				IF(@Src = 1)
				begin
					INSERT INTO [RMMS].[RMCndtSec]
				   	([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth,TrfCls,RghCls,DflctCls,Src,AddedBy,AddedOn)
					 SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType , PaveWidth,TrfCls,RghCls,DflctCls,'Decision Tree', @userName,GETDATE()
						FROM [RMMS].[SmplPMSSec] a
						where WrkCode Is Null and SurveyYear = ISNULL( @Surveyyear,SurveyYear) 
						and RoadCatg = ISNULL(@rdcatg,RoadCatg)
						and NtWrk = ISNULL(@Network,NtWrk)
						--and LinkCode= ISNULL(@linkcode,a.LinkCode)
						order by roadcode, StartCh
				end
				else if (@Src = 0)
				begin
				INSERT INTO [RMMS].[RMCndtSec]
			   ([Linkcode],[Roadcode],[StartCh],[EndCh],[SurveyYear],RoadCatg,NtWrk,PaveWidth,Src,AddedBy,AddedOn)
					select st.LINK_NAME
					,left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1)
					,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))
					,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], (charindex(':', st.[Sect_Name], 1))+1))))
					, @Surveyyear
					,rm.RoadCategoryCode
					,rm.IsCRN
					, st.CWAY_WIDTH
					,'HDM'
					,@userName
					,GETDATE()
					from SECTIONS st
					inner join NM.RoadMaster rm on left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1) = rm.RoadCode
					where  SECT_ID not in 
					(select distinct wp.SECT_ID from WorkProgramme wp
					inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
					where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> '0' and wp.SurveyCode = ISNULL(@Surveyyear,wp.SurveyCode))
					and st.ROAD_CLASS = ISNULL(@rdcatg,st.ROAD_CLASS)
					and rm.IsCRN = ISNULL(@Network, rm.IsCRN)
					order by left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))

					update a set a.RoadType = b.RoadType from RMMS.RMCndtSec a 
					inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
					where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) 
					and a.RoadCatg = ISNULL(@rdcatg, a.RoadCatg)
					and a.NtWrk = ISNULL(@Network, a.NtWrk)
					--and a.LinkCode=ISNULL(@linkCode,a.Linkcode)
				end
		END
	end
	--declare @lnkCd varchar(max) , @Whr nvarchar(max)
	-- If @linkcode is not null 
	-- begin 
	--	 set @lnkCd = '''' +REPLACE(@linkcode,  ',', ''',''') + ''''
	--	 set @Whr = ' a.LinkCode in ('+@lnkCd+')';
	-- End	

	 --print @SurveyYear
	 --Print @linkcode

	 --If @linkcode is not null 
		-- begin 
	 --			declare @Str nvarchar(max)
		--		set @Str='delete a from [RMMS].[RMCndtSec] a where a.SurveyYear=ISNULL('+@Surveyyear+',a.SurveyYear) and'+@Whr
		--		Print @Str 
		--		exec sp_executesql @Str
		--		--Print 'test'
		--		IF (@Src = 1)
		--		begin
		--			declare @Str1 nvarchar(max)
	 --  	   	   		Set @Str1='INSERT INTO [RMMS].[RMCndtSec]([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth)
		--			SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType ,PaveWidth
		--			FROM [RMMS].[SmplPMSSec] a
		--			where WrkCode Is Null and SurveyYear = ISNULL( '+@Surveyyear+',SurveyYear) and'+@Whr+ 
		--			'order by roadcode, StartCh'
		--			exec sp_executesql @Str1
		--			--Print @Str1
		--		end
		--		else IF(@Src = 0)
		--		begin
		--			declare @Str1_H nvarchar(max)
		--			declare @Whr1 nvarchar(max)
		--			set @Whr1 = ' a.Link_Name in ('+@lnkCd+')';
	 --  	   	   		Set @Str1='INSERT INTO [RMMS].[RMCndtSec]([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],PaveWidth)
		--			select st.LINK_NAME
		--			,left(st.Sect_Name,charindex('':'',st.[Sect_Name], 1)-1)
		--			,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex('':'',st.[Sect_Name], 1))),charindex('':'',right (st.Sect_Name,len(st.Sect_Name)-(charindex('':'', st.[Sect_Name], 1))))-1))
		--			,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex('':'', st.[Sect_Name], (charindex('':'', st.[Sect_Name], 1))+1))))
		--			, '+@Surveyyear+'
		--			,rm.RoadCategoryCode
		--			,rm.IsCRN
		--			, st.CWAY_WIDTH
		--			from SECTIONS st
		--			inner join NM.RoadMaster rm on left(st.Sect_Name,charindex('':'',st.[Sect_Name], 1)-1) = rm.RoadCode
		--			where  SECT_ID not in 
		--			(select distinct wp.SECT_ID from WorkProgramme wp
		--			inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
		--			where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> ''0'') and'+@Whr1+ 
		--			' order by left(st.Sect_Name,charindex('':'',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex('':'',st.[Sect_Name], 1))),charindex('':'',right (st.Sect_Name,len(st.Sect_Name)-(charindex('':'', st.[Sect_Name], 1))))-1))'
		--			exec sp_executesql @Str1_H

		--			declare @Str2_H nvarchar(max)
		--		    Set @Str2_H='update a set RoadType = b.RoadType from RMMS.RMCndtSec a 
		--			inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
		--			where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr1
		--			exec sp_executesql @Str2_H
		--		end
      
		--	   declare @Str1_1 nvarchar(max)
		--   	   Set @Str1_1='Update a Set a.Crk= (case  when c.Code>4 then 4 else c.Code end) from [RMMS].[RMCndtSec] a 
	 --             INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and b.StartChainage=a.StartCh and b.EndChainage=a.EndCh
		--		  INNER JOIN RIS.LKPTCracking C on b.VisualConditionManual_Summary_Cracking >= c.[Min] and b.VisualConditionManual_Summary_Cracking < c.[Max]
		--		  where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--	   exec sp_executesql @Str1_1

		--	   declare @Str2 nvarchar(max)
		--   	   Set @Str2='Update a Set Rav= (case  when c.Code>4 then 4 else c.Code end)  from [RMMS].[RMCndtSec] a 
	 --             INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and a.StartCh >= b.StartChainage and a.StartCh < b.EndChainage
		--		  INNER JOIN RIS.LKPTRavelling C on b.VisualConditionManual_Summary_Raveling >= C.[Min] and b.VisualConditionManual_Summary_Raveling < C.[Max]
		--		  where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--	   exec sp_executesql @Str2
       
		--	   declare @Str3 nvarchar(max)
		--   	   Set @Str3='Update a Set Poth= (case  when c.Code>4 then 4 else c.Code end)  from [RMMS].[RMCndtSec] a 
	 --            INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and b.StartChainage=a.StartCh and b.EndChainage=a.EndCh
		--		 INNER JOIN RIS.LKPTPotholes C on b.VisualConditionManual_Summary_Pothole >= C.[MIN] and b.VisualConditionManual_Summary_Pothole < C.[Max]
		--		 where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--				 exec sp_executesql @Str3

		--	   declare @Str4 nvarchar(max)
		--   	   Set @Str4='Update a Set Vegt=(case  when b.Vegtn_Condition>4 then 4 else b.Vegtn_Condition end)  from [RMMS].[RMCndtSec] a 
	 --            INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and b.StartChainage=a.StartCh and b.EndChainage=a.EndCh
		--		 where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--				 exec sp_executesql @Str4

		--	   declare @Str5 nvarchar(max)
		--   	   Set @Str5='Update a Set ShldCond=(case  when c.Code>4 then 4 else c.Code end) from [RMMS].[RMCndtSec] a 
	 --            INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and b.StartChainage=a.StartCh and b.EndChainage=a.EndCh
		--		 INNER JOIN RIS.LKPTShoulderCondition C on b.VisualConditionManual_Summary_ShoulderCondition =c.Code
		--		 where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--				 exec sp_executesql @Str5

		--		declare @Str6 nvarchar(max)
		--   	   Set @Str6='Update a Set a.PaveWidth =b.PavementWidth_PavementWidthValue, a.NumLanes = CONVERT(decimal(9,1),c.Class) from [RMMS].[RMCndtSec] a 
	 --            INNER JOIN EditSec b ON b.LinkCode=a.Linkcode and a.StartCh =b.StartChainage 
		--		 INNER JOIN RIS.LKPTPavementWidth C on b.PavementWidth_PavementWidthValue = c.PavementWidthValue
		--		 where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--				 exec sp_executesql @Str6

		--		declare @Str7 nvarchar(max)
		--   	   Set @Str7='update a set a.CulvCnt = z.Cnt, a.CulvCond = z.CulvCond
		--		from RMMS.RMCndtSec a
		--		inner join
		--		(select rc.RMCndtSecId,c.[Description],count(cc.CulvertCode) [Cnt],MAX(case when cc.ConditionOfPipe IS NULL then cc.ConditionofDeckSlab else cc.ConditionofPipe end) [CulvCond]
		--			from  RMMS.RMCndtSec rc 
		--		inner join BMS.CulvertInventory ci on rc.RoadCode = ci.RoadCode and ci.Chainage between rc.StartCh and rc.EndCh
		--		inner join BMS.CulvertCondition cc on ci.CulvertCode = cc.CulvertCode 
		--		inner join BMS.LKPTCondSev c on (cc.ConditionofPipe = c.CondSevType or cc.ConditionofDeckSlab = c.CondSevType)
		--		group by rc.RMCndtSecId,c.[Description])z on a.RMCndtSecId = z.RMCndtSecId
		--		 where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--				 exec sp_executesql @Str7

		--		declare @Str8 nvarchar(max)
		--   	   Set @Str8='update a set a.KmStns = z.Cnt, a.KmStnCond = z.KmStnCond
		--		from RMMS.RMCndtSec a
		--		inner join
		--		(select rc.RMCndtSecId,c.[Descr],count(rf.RoadFurnitureId) [Cnt],MAX(case when rf.Condition>4 then 4 else rf.Condition end) [KmStnCond]
		--			from  RMMS.RMCndtSec rc 
		--		inner join RIS.RoadFurniture rf on rc.RoadCode = rf.RoadCode and rf.Chainage between rc.StartCh and rc.EndCh and rf.FurnitureType = 11
		--		inner join RIS.LKPTRdFurnCond c on rf.Condition = c.Code 
		--		group by rc.RMCndtSecId,c.[Descr])z on a.RMCndtSecId = z.RMCndtSecId
		--		 where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--				 exec sp_executesql @Str8

		--		declare @Str9 nvarchar(max)
		--   	   Set @Str9='update a set a.RdSgn = z.Cnt, a.RdSgnCond = z.RdSgnCond
		--		from RMMS.RMCndtSec a
		--		inner join
		--		(select rc.RMCndtSecId,c.[Descr],count(rf.RoadFurnitureId) [Cnt],MAX(case when rf.Condition>4 then 4 else rf.Condition end) [RdSgnCond]
		--			from  RMMS.RMCndtSec rc 
		--		inner join RIS.RoadFurniture rf on rc.RoadCode = rf.RoadCode and rf.Chainage between rc.StartCh and rc.EndCh and rf.FurnitureType in (9,13,17,23,24,21)
		--		inner join RIS.LKPTRdFurnCond c on rf.Condition = c.Code
		--		group by rc.RMCndtSecId,c.[Descr])z on a.RMCndtSecId = z.RMCndtSecId
		--		 where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--				 exec sp_executesql @Str9

		--		declare @Str10 nvarchar(max)
		--   	   Set @Str10='update a set a.RdMrkLn = z.Ln, a.RdMrkCond = (Case when z.RdMrkgCond>4 then 4 else z.RdMrkgCond end)
		--		from RMMS.RMCndtSec a
		--		inner join
		--		(select rc.RMCndtSecId,c.[Descr],Sum(abs((Case when rf.EndChainage> rc.EndCh then rc.EndCh else rf.EndChainage end) - (Case when rf.StartChainage< rc.StartCh then rc.StartCh else rf.StartChainage end))) [Ln],MAX(rf.Condition) [RdMrkgCond]
		--			from  RMMS.RMCndtSec rc 
		--		inner join RIS.RoadFurnitureSec rf on rc.RoadCode = rf.RoadCode and ((rf.StartChainage between rc.StartCh and rc.EndCh) or (rf.EndChainage between rc.StartCh and rc.EndCh)) and rf.FurnitureType =14
		--		inner join RIS.LKPTRdFurnCond c on rf.Condition = c.Code
		--		group by rc.RMCndtSecId,c.[Descr])z on a.RMCndtSecId = z.RMCndtSecId
		--		 where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
		--				 exec sp_executesql @Str10


				--declare @Str11 nvarchar(max)	
    --            Set @Str6='Update a set Prrty= (CASE WHEN (Rav> PotH) THEN Rav
    --     				  WHEN (PotH > Rav) THEN PotH
				--		  WHEN (Rav = PotH) THEN Rav
				--		  ELSE NULL
				--	END)  from [RMMS].[RMCndtSec] a
				--	where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
				--		 exec sp_executesql @Str11

				--declare @Str12 nvarchar(max)	
    --            Set @Str7='Update a set Prrty=Prrty+''.''+(CASE WHEN (Vegt> ShldCond) THEN Convert(Varchar(100),Vegt)
    --     							WHEN (ShldCond > Vegt) THEN Convert(Varchar(100),ShldCond)
				--					WHEN (Vegt = ShldCond) THEN Convert(Varchar(100),Vegt)
				--					ELSE NULL
				--				END) from [RMMS].[RMCndtSec] a
				--				where a.SurveyYear = ISNULL( '+@Surveyyear+',a.SurveyYear) and' +@Whr
				--		 exec sp_executesql @Str12
		 --END
	  --else if(@linkcode is null or @linkcode = '')
			-- begin
			-- --Print 'Test1'
			--	delete [RMMS].[AssgnWrkCode]  where RMCndtSecID in (select RMCndtSecID from RMMS.RMCndtSec where SurveyYear = ISNULL(@Surveyyear,SurveyYear))
			--	delete from [RMMS].[RMCndtSec]  where SurveyYear=ISNULL(@Surveyyear,SurveyYear) --and Linkcode=ISNULL(@linkcode,LinkCode)
			--	IF(@Src = 1)
			--	begin
			--		INSERT INTO [RMMS].[RMCndtSec]
			--	   ([Roadcode],[Linkcode],[StartCh],[EndCh],[SurveyYear],[RoadCatg],[NtWrk],[RoadType],PaveWidth)
			--		 SELECT  Roadcode, Linkcode , StartCh , EndCh ,  SurveyYear ,RoadCatg   ,NtWrk , RoadType , PaveWidth
			--			FROM [RMMS].[SmplPMSSec] a
			--			where WrkCode Is Null and SurveyYear = ISNULL( @Surveyyear,SurveyYear) and LinkCode= ISNULL(@linkcode,a.LinkCode)
			--			order by roadcode, StartCh
			--	end
			--	else if (@Src = 0)
			--	begin
			--	INSERT INTO [RMMS].[RMCndtSec]
			--   ([Linkcode],[Roadcode],[StartCh],[EndCh],[SurveyYear],RoadCatg,NtWrk,PaveWidth)
			--		select st.LINK_NAME
			--		,left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1)
			--		,convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))
			--		,convert(int,right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], (charindex(':', st.[Sect_Name], 1))+1))))
			--		, @Surveyyear
			--		,rm.RoadCategoryCode
			--		,rm.IsCRN
			--		, st.CWAY_WIDTH
			--		from SECTIONS st
			--		inner join NM.RoadMaster rm on left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1) = rm.RoadCode
			--		where  SECT_ID not in 
			--		(select distinct wp.SECT_ID from WorkProgramme wp
			--		inner join BudgetScenarios bs on wp.BUDGET_ID = bs.BUDGET_ID 
			--		where wp.YEAR_INDEX = 0 and bs.FnlFlag =1 and wp.FIN_COST <> '0')
			--		order by left(st.Sect_Name,charindex(':',st.[Sect_Name], 1)-1), convert(int,left(right (st.Sect_Name,len(st.Sect_Name)-(charindex(':',st.[Sect_Name], 1))),charindex(':',right (st.Sect_Name,len(st.Sect_Name)-(charindex(':', st.[Sect_Name], 1))))-1))

			--		update a set a.RoadType = b.RoadType from RMMS.RMCndtSec a 
			--		inner join RIS.RoadType b on a.RoadCode = b.RoadCode and  a.StartCh between b.StartChainage and b.EndChainage
			--		where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) and a.LinkCode=ISNULL(@linkCode,a.Linkcode)
			--	end
    Update a Set a.Crk= (case  when c.Code>4 then 4 else c.Code end) from [RMMS].[RMCndtSec] a 
	              INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and b.StartChainage=a.StartCh and b.EndChainage=a.EndCh
				  INNER JOIN RIS.LKPTCracking C on b.VisualConditionManual_Summary_Cracking >= c.[Min] and b.VisualConditionManual_Summary_Cracking < c.[Max]
				  where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) 
				  and a.RoadCatg = ISNULL(@rdCatg,a.RoadCatg) and a.NtWrk = ISNULL(@Network, a.NtWrk)--and a.LinkCode= ISNULL(@linkcode,a.LinkCode)
	  
     Update a Set Rav= (case  when c.Code>4 then 4 else c.Code end)  from [RMMS].[RMCndtSec] a 
	              INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and a.StartCh >= b.StartChainage and a.StartCh < b.EndChainage
				  INNER JOIN RIS.LKPTRavelling C on b.VisualConditionManual_Summary_Raveling >= C.[Min] and b.VisualConditionManual_Summary_Raveling < C.[Max]
				  where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) and a.RoadCatg = ISNULL(@rdCatg,a.RoadCatg) and a.NtWrk = ISNULL(@Network, a.NtWrk)--and a.LinkCode= ISNULL(@linkcode,a.LinkCode)

	Update a Set Poth=(case  when c.Code>4 then 4 else c.Code end)  from [RMMS].[RMCndtSec] a 
	             INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and b.StartChainage=a.StartCh and b.EndChainage=a.EndCh
				 INNER JOIN RIS.LKPTPotholes C on b.VisualConditionManual_Summary_Pothole >= C.[MIN] and b.VisualConditionManual_Summary_Pothole < C.[Max]
				 where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) and a.RoadCatg = ISNULL(@rdCatg,a.RoadCatg) and a.NtWrk = ISNULL(@Network, a.NtWrk)--and a.LinkCode= ISNULL(@linkcode,a.LinkCode)

	Update a Set Vegt=(case  when b.Vegtn_Condition>4 then 4 else b.Vegtn_Condition end)  from [RMMS].[RMCndtSec] a 
	             INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and b.StartChainage=a.StartCh and b.EndChainage=a.EndCh
				 --INNER JOIN RMMS.LKPTVegtnCond C on b.Vegtn_Condition = C.Code
				 where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) and a.RoadCatg = ISNULL(@rdCatg,a.RoadCatg) and a.NtWrk = ISNULL(@Network, a.NtWrk)--and a.LinkCode= ISNULL(@linkcode,a.LinkCode)

	Update a Set ShldCond=(case  when c.Code>4 then 4 else c.Code end) from [RMMS].[RMCndtSec] a 
	             INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and b.StartChainage=a.StartCh and b.EndChainage=a.EndCh
				 INNER JOIN RIS.LKPTShoulderCondition C on b.VisualConditionManual_Summary_ShoulderCondition =c.Code
				 where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) and a.RoadCatg = ISNULL(@rdCatg,a.RoadCatg) and a.NtWrk = ISNULL(@Network, a.NtWrk)--and a.LinkCode= ISNULL(@linkcode,a.LinkCode)

	Update a Set a.PaveWidth =c.PavementWidthValue, a.NumLanes = CONVERT(decimal(9,1),c.Class) from [RMMS].[RMCndtSec] a 
	             INNER JOIN EditSec b ON b.RoadCode=a.Roadcode and a.StartCh between b.StartChainage and b.EndChainage
				 INNER JOIN RIS.LKPTPavementWidth C on b.PavementWidth_PavementWidthValue=c.PavementWidthValue
				 where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) and a.RoadCatg = ISNULL(@rdCatg,a.RoadCatg) and a.NtWrk = ISNULL(@Network, a.NtWrk) --and a.LinkCode= ISNULL(@linkcode,a.LinkCode)
	

	update rc set rc.CulvCnt = z.Cnt, rc.CulvCond = z.CulvCond
		--select wc.RMCndtSecId, z.[Description],z.Cnt
		from RMMS.RMCndtSec rc
		inner join
		(select a.RMCndtSecId,count(cc.CulvertCode) 'Cnt',MAX(case when cc.ConditionOfPipe 
			--IS NULL then cc.ConditionofDeckSlab 
			IS NULL then 0 
			else cc.ConditionofPipe end) 'CulvCond'
			from  RMMS.RMCndtSec a 
		inner join BMS.CulvertInventory ci on a.RoadCode = ci.RoadCode and ci.Chainage between a.StartCh and a.EndCh
		inner join BMS.CulvertCondition cc on ci.CulvertCode = cc.CulvertCode 
		left join BMS.LKPTCondSev c on (cc.ConditionofPipe = c.CondSevType 
		--or cc.ConditionofDeckSlab = c.CondSevType
		)
		 group by a.RMCndtSecId)z on rc.RMCndtSecId = z.RMCndtSecId
		--inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.[Description] = d.Culv
		where rc.SurveyYear = ISNULL( @Surveyyear,rc.SurveyYear) 
		and rc.RoadCatg = ISNULL(@rdCatg,rc.RoadCatg)
		 and rc.NtWrk = ISNULL(@Network, rc.NtWrk)
		--and rc.LinkCode= ISNULL(@linkcode,rc.LinkCode)
	
	update rc set rc.KmStns = z.Cnt, rc.KmStnCond = z.KmStnCond
		--select wc.RMCndtSecId, z.[Description],z.Cnt
		from RMMS.RMCndtSec rc
		inner join
		(select a.RMCndtSecId,c.[Descr],count(rf.RoadFurnitureId) 'Cnt',MAX(case when rf.Condition>4 then 4 else rf.Condition end) 'KmStnCond'
			from  RMMS.RMCndtSec a 
		inner join RIS.RoadFurniture rf on a.RoadCode = rf.RoadCode and rf.Chainage between a.StartCh and a.EndCh and rf.FurnitureType = 11
		inner join RIS.LKPTRdFurnCond c on rf.Condition = c.Code 
		group by a.RMCndtSecId,c.[Descr])z on rc.RMCndtSecId = z.RMCndtSecId
		--inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.[Description] = d.Culv
		where rc.SurveyYear = ISNULL( @Surveyyear,rc.SurveyYear) and rc.RoadCatg = ISNULL(@rdCatg,rc.RoadCatg) 
		and rc.NtWrk = ISNULL(@Network, rc.NtWrk)--and rc.LinkCode= ISNULL(@linkcode,rc.LinkCode)

		update rc set rc.RdSgn = z.Cnt, rc.RdSgnCond = z.RdSgnCond
		--select wc.RMCndtSecId, z.[Description],z.Cnt
		from RMMS.RMCndtSec rc
		inner join
		(select a.RMCndtSecId,c.[Descr],count(rf.RoadFurnitureId) 'Cnt',MAX(case when rf.Condition>4 then 4 else rf.Condition end) 'RdSgnCond'
			from  RMMS.RMCndtSec a 
		inner join RIS.RoadFurniture rf on a.RoadCode = rf.RoadCode and rf.Chainage between a.StartCh and a.EndCh and rf.FurnitureType in (9,13,17,23,24,21)
		inner join RIS.LKPTRdFurnCond c on rf.Condition = c.Code
		group by a.RMCndtSecId,c.[Descr])z on rc.RMCndtSecId = z.RMCndtSecId
		--inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.[Description] = d.Culv
		where rc.SurveyYear = ISNULL( @Surveyyear,rc.SurveyYear) and rc.RoadCatg = ISNULL(@rdCatg,rc.RoadCatg) 
		and rc.NtWrk = ISNULL(@Network, rc.NtWrk)--and rc.LinkCode= ISNULL(@linkcode,rc.LinkCode)
		
		update rc set rc.RdMrkLn = z.Ln, rc.RdMrkCond = (Case when z.RdMrkgCond>4 then 4 else z.RdMrkgCond end)
		--select wc.RMCndtSecId, z.[Description],z.Cnt
		from RMMS.RMCndtSec rc
		inner join
		(select a.RMCndtSecId,c.[Descr],Sum(abs((Case when rf.EndChainage> a.EndCh then a.EndCh else rf.EndChainage end) - (Case when rf.StartChainage< a.StartCh then a.StartCh else rf.StartChainage end))) 'Ln',MAX(rf.Condition) 'RdMrkgCond'
			from  RMMS.RMCndtSec a 
		inner join RIS.RoadFurnitureSec rf on a.RoadCode = rf.RoadCode and ((rf.StartChainage between a.StartCh and a.EndCh) or (rf.EndChainage between a.StartCh and a.EndCh)) and rf.FurnitureType =14
		inner join RIS.LKPTRdFurnCond c on rf.Condition = c.Code
		group by a.RMCndtSecId,c.[Descr])z on rc.RMCndtSecId = z.RMCndtSecId
		--inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.[Description] = d.Culv
		where rc.SurveyYear = ISNULL( @Surveyyear,rc.SurveyYear) and rc.RoadCatg = ISNULL(@rdCatg,rc.RoadCatg) 
		and rc.NtWrk = ISNULL(@Network, rc.NtWrk)--and rc.LinkCode= ISNULL(@linkcode,rc.LinkCode)
			
	--Update a set Prrty= (CASE WHEN (Rav> PotH) THEN Rav
 --        				  WHEN (PotH > Rav) THEN PotH
	--					  WHEN (Rav = PotH) THEN Rav
	--					  ELSE NULL
	--				END)  from [RMMS].[RMCndtSec] a
	--				where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) and a.LinkCode= ISNULL(@linkcode,a.LinkCode)


 --   Update a set Prrty=Prrty+'.'+(CASE WHEN (Vegt> ShldCond) THEN Convert(Varchar(100),Vegt)
 --        							WHEN (ShldCond > Vegt) THEN Convert(Varchar(100),ShldCond)
	--								WHEN (Vegt = ShldCond) THEN Convert(Varchar(100),Vegt)
	--								ELSE NULL
	--							END) from [RMMS].[RMCndtSec] a
	--							where a.SurveyYear = ISNULL( @Surveyyear,a.SurveyYear) and a.LinkCode= ISNULL(@linkcode,a.LinkCode)
		 end 

	 
		
			 
		insert into [RMMS].[AssgnWrkCode] ([RMCndtSecID],[WrkCode])
		select distinct  a.RMCndtSecId,b.WrkCode
		from RMMS.RMCndtSec a,RMMS.LKPTWrkCodes b where Module = 'RMMS' order by a.RMCndtSecId,b.WrkCode
			 
			 
		update a set a.Qty = d.PothFact * abs(b.EndCh-b.StartCh)/1000.00 * b.NumLanes--(case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end)
		--select b.RoadCode,b.StartCh,b.EndCh,(b.EndCh-b.StartCh)/1000.00 'Length', case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'NumLanes'
		--,d.PothFact * (b.EndCh-b.StartCh)/1000.00 * case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'LaneKm'
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		inner join RIS.LKPTPotholes c on b.Poth = c.Code
		inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.Category = d.Poth
		inner join RIS.LKPTPavementWidth lpw on lpw.PavementWidthValue = b.PaveWidth
		where a.WrkCode in ('R01','R02','R03') and b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) 
		and b.RoadCatg = ISNULL(@rdCatg,b.RoadCatg) and b.NtWrk = ISNULL(@Network, b.NtWrk)--and b.LinkCode= ISNULL(@linkcode,b.LinkCode)

		update a set a.Qty = d.CrkFact * (abs(b.EndCh-b.StartCh)/1000.00) * b.NumLanes--(case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end)
		--select b.RoadCode,b.StartCh,b.EndCh,(b.EndCh-b.StartCh)/1000.00 'Length', case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'NumLanes'
		--,b.Crk,d.CrkFact * (b.EndCh-b.StartCh)/1000.00 * case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'LaneKm'
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		inner join RIS.LKPTCracking c on b.Crk = c.Code
		inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.Category = d.Crk
		inner join RIS.LKPTPavementWidth lpw on lpw.PavementWidthValue = b.PaveWidth
		where a.WrkCode in( 'R04','R05') and b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) 
		and b.RoadCatg = ISNULL(@rdCatg,b.RoadCatg) and b.NtWrk = ISNULL(@Network, b.NtWrk)--and b.LinkCode= ISNULL(@linkcode,b.LinkCode)

		update a set a.Qty = ISNULL(a.Qty,0) + (d.RavFact * (abs(b.EndCh-b.StartCh)/1000.00 )* b.NumLanes)--(case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end))
		--select b.RoadCode,b.StartCh,b.EndCh,(b.EndCh-b.StartCh)/1000.00 'Length', case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'NumLanes'
		--,b.Crk,d.CrkFact * (b.EndCh-b.StartCh)/1000.00 * case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'LaneKm'
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		inner join RIS.LKPTRavelling c on b.Rav = c.Code
		inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.Category = d.Rav
		inner join RIS.LKPTPavementWidth lpw on lpw.PavementWidthValue = b.PaveWidth
		where  a.WrkCode = 'R04' and b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) 
		and b.RoadCatg = ISNULL(@rdCatg,b.RoadCatg) and b.NtWrk = ISNULL(@Network, b.NtWrk)--and b.LinkCode= ISNULL(@linkcode,b.LinkCode)

		update a set a.Qty = d.ShldFact * (abs(b.EndCh-b.StartCh)/1000.00) * b.NumLanes--(case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end)
		--select b.RoadCode,b.StartCh,b.EndCh,(b.EndCh-b.StartCh)/1000.00 'Length', case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'NumLanes'
		--,b.Crk,d.CrkFact * (b.EndCh-b.StartCh)/1000.00 * case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'LaneKm'
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		inner join RIS.LKPTShoulderCondition c on b.ShldCond = c.Code
		inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.Category = d.Shld
		inner join RIS.LKPTPavementWidth lpw on lpw.PavementWidthValue = b.PaveWidth
		where  a.WrkCode = 'R10' and b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) 
		and b.RoadCatg = ISNULL(@rdCatg,b.RoadCatg) and b.NtWrk = ISNULL(@Network, b.NtWrk)--and b.LinkCode= ISNULL(@linkcode,b.LinkCode)

		update a set a.Qty = (d.VegtnFact * (abs(b.EndCh-b.StartCh)/1000.00) * b.NumLanes) --(case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end)
		--select b.RoadCode,b.StartCh,b.EndCh,(b.EndCh-b.StartCh)/1000.00 'Length', case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'NumLanes'
		--,b.Crk,d.CrkFact * (b.EndCh-b.StartCh)/1000.00 * case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'LaneKm'
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		inner join RMMS.LKPTVegtnCond c on b.Vegt = c.Code
		inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.Descr = d.Vegtn
		inner join RIS.LKPTPavementWidth lpw on lpw.PavementWidthValue = b.PaveWidth
		where  a.WrkCode = 'R11' and b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) 
		and b.RoadCatg = ISNULL(@rdCatg,b.RoadCatg) and b.NtWrk = ISNULL(@Network, b.NtWrk)--and b.LinkCode= ISNULL(@linkcode,b.LinkCode)

		--update a set a.Qty = d.CulvFact * (b.EndCh-b.StartCh)/1000.00 * b.NumLanes--(case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end)
		----select b.RoadCode,b.StartCh,b.EndCh,(b.EndCh-b.StartCh)/1000.00 'Length', case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'NumLanes'
		----,b.Crk,d.CrkFact * (b.EndCh-b.StartCh)/1000.00 * case when right(convert(decimal(9,1),Round(b.PaveWidth/3.5,1)),2)<> '.5' then Round(b.PaveWidth/3.5,0) else Round(b.PaveWidth/3.5,1) end 'LaneKm'
		--from RMMS.AssgnWrkCode a 
		--inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		--inner join RMMS.LKPTVegtnCond c on b.Vegt = c.Code
		--inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.Descr = d.Vegtn
		--inner join RIS.LKPTPavementWidth lpw on lpw.PavementWidthValue = b.PaveWidth
		--where  a.WrkCode = 'R20' and b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) and b.LinkCode= ISNULL(@linkcode,b.LinkCode)

		update wc set wc.Qty = z.CulvCnt * qs.CulvFact
		--select wc.RMCndtSecId, z.[Description],z.Cnt
		from RMMS.AssgnWrkCode wc
		inner join RMMS.LKPTRMQtyStnd qs on wc.WrkCode = qs.WrkCode
		inner join
		(select wc.RMCndtSecId, rc.CulvCnt,rc.CulvCond
		from RMMS.AssgnWrkCode wc
		inner join RMMS.LKPTRMQtyStnd qs on wc.WrkCode = qs.WrkCode
		inner join RMMS.RMCndtSec rc on wc.RMCndtSecID = rc.RMCndtSecId
		where wc.WrkCode ='R20' and
		 rc.SurveyYear = ISNULL( @Surveyyear,rc.SurveyYear) and rc.RoadCatg = ISNULL(@rdCatg,rc.RoadCatg) and rc.NtWrk = ISNULL(@Network, rc.NtWrk)--and rc.LinkCode= ISNULL(@linkcode,rc.LinkCode)		
		 )z on   wc.RMCndtSecId = z.RMCndtSecId
		inner join BMS.LKPTCondSev cs on z.CulvCond = cs.CondSevType and qs.Culv = cs.[Description]
		where  wc.WrkCode = 'R20' and wc.RMCndtSecId = z.RMCndtSecId
		
		update wc set wc.Qty = z.CulvCnt * qs.CulvFact
		--select wc.RMCndtSecId, z.CulvCnt * qs.CulvFact
		from RMMS.AssgnWrkCode wc
		inner join RMMS.LKPTRMQtyStnd qs on wc.WrkCode = qs.WrkCode 
		inner join
		(select wc.RMCndtSecId, rc.CulvCnt,rc.CulvCond
		from RMMS.AssgnWrkCode wc
		inner join RMMS.LKPTRMQtyStnd qs on wc.WrkCode = qs.WrkCode
		inner join RMMS.RMCndtSec rc on wc.RMCndtSecID = rc.RMCndtSecId
		where wc.WrkCode ='R21' and
		 rc.SurveyYear = ISNULL( @Surveyyear,rc.SurveyYear) 
		 and rc.RoadCatg = ISNULL(@rdcatg, rc.RoadCatg)
		 and rc.NtWrk = ISNULL(@Network, rc.NtWrk)--and rc.LinkCode= ISNULL(@linkcode,rc.LinkCode)		
		)z on   wc.RMCndtSecId = z.RMCndtSecId
		inner join BMS.LKPTCondSev cs on z.CulvCond = cs.CondSevType and qs.Culv = cs.[Description]
		where  wc.WrkCode = 'R21' and wc.RMCndtSecId = z.RMCndtSecId  

		--update wc set wc.Qty = z.Cnt
		----select wc.RMCndtSecId, z.[Description],z.Cnt
		--from RMMS.AssgnWrkCode wc
		--inner join RMMS.LKPTRMQtyStnd qs on wc.WrkCode = qs.WrkCode
		--inner join
		--(select a.RMCndtSecId,c.[Description],count(cc.CulvertCode) 'Cnt'
		--from RMMS.AssgnWrkCode a 
		--inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		--inner join BMS.CulvertInventory ci on b.RoadCode = ci.RoadCode and ci.Chainage between b.StartCh and b.EndCh
		--inner join BMS.CulvertCondition cc on ci.CulvertCode = cc.CulvertCode 
		--inner join BMS.LKPTCondSev c on (cc.ConditionofPipe = c.CondSevType or cc.ConditionofDeckSlab = c.CondSevType)
		--inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.[Description] = d.Culv
		--where b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) and b.LinkCode= ISNULL(@linkcode,b.LinkCode)				
		--group by a.RMCndtSecId,c.[Description])z on  qs.Culv = z.[Description] and wc.RMCndtSecId = z.RMCndtSecId
		--where  wc.WrkCode = 'R21' and wc.RMCndtSecId = z.RMCndtSecId

		update wc set wc.Qty = z.Cnt
		--select wc.RMCndtSecId, z.[Description],z.Cnt
		from RMMS.AssgnWrkCode wc
		inner join RMMS.LKPTRMQtyStnd qs on wc.WrkCode = qs.WrkCode
		inner join
		(select a.RMCndtSecId,c.[Descr],COUNT(rf.RoadFurnitureId) 'Cnt'
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		inner join RIS.RoadFurniture rf on b.RoadCode = rf.RoadCode and rf.Chainage between b.StartCh and b.EndCh and rf.FurnitureType = 11
		inner join RIS.LKPTRdFurnCond c on c.Code = b.KMStnCond
		inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.[Descr] = d.KmStn
		where b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) and b.RoadCatg = ISNULL(@rdCatg,b.RoadCatg) 
		and b.NtWrk = ISNULL(@Network, b.NtWrk)--and b.LinkCode= ISNULL(@linkcode,b.LinkCode)				
		group by a.RMCndtSecId,c.[Descr])z on  qs.Culv = z.[Descr] and wc.RMCndtSecId = z.RMCndtSecId
		where  wc.WrkCode = 'R30' and wc.RMCndtSecId = z.RMCndtSecId

		update wc set wc.Qty = z.Cnt
		--select wc.RMCndtSecId, z.[Description],z.Cnt
		from RMMS.AssgnWrkCode wc
		inner join RMMS.LKPTRMQtyStnd qs on wc.WrkCode = qs.WrkCode
		inner join
		(select a.RMCndtSecId,c.[Descr],COUNT(rf.RoadFurnitureId) 'Cnt'
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		inner join RIS.RoadFurniture rf on b.RoadCode = rf.RoadCode and rf.Chainage between b.StartCh and b.EndCh and rf.FurnitureType in (9,13,17,23,24,21)
		inner join RIS.LKPTRdFurnCond c on c.Code = b.RdSgnCond
		inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.[Descr] = d.SgnBrd		
		where b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) 
		and b.RoadCatg = ISNULL(@rdcatg, b.RoadCatg)
		and b.NtWrk = ISNULL(@Network, b.NtWrk)
		 --and b.LinkCode= ISNULL(@linkcode,b.LinkCode)		
		group by a.RMCndtSecId,c.[Descr])z on  qs.Culv = z.[Descr] and wc.RMCndtSecId = z.RMCndtSecId
		where  wc.WrkCode = 'R31' and wc.RMCndtSecId = z.RMCndtSecId

		update wc set wc.Qty = z.Ln
		--select wc.RMCndtSecId, z.[Description],z.Cnt
		from RMMS.AssgnWrkCode wc
		inner join RMMS.LKPTRMQtyStnd qs on wc.WrkCode = qs.WrkCode
		inner join
		(select a.RMCndtSecId,c.[Descr],Sum((Case when rf.EndChainage> b.EndCh then b.EndCh else rf.EndChainage end) - (Case when rf.StartChainage< b.StartCh then b.StartCh else rf.StartChainage end)) 'Ln'
		from RMMS.AssgnWrkCode a
		inner join  RMMS.RMCndtSec b on a.RMCndtSecId = b.RMCndtSecID
		inner join RIS.RoadFurnitureSec rf on b.RoadCode = rf.RoadCode and ((rf.StartChainage between b.StartCh and b.EndCh) or (rf.EndChainage between b.StartCh and b.EndCh)) and rf.FurnitureType =14
		inner join RIS.LKPTRdFurnCond c on rf.Condition = c.Code
		inner join RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode and c.[Descr] = d.RdMrkng
		where b.SurveyYear = ISNULL( @Surveyyear,b.SurveyYear) and b.RoadCatg = ISNULL(@rdCatg,b.RoadCatg) 
		and b.NtWrk = ISNULL(@Network, b.NtWrk)--and b.LinkCode= ISNULL(@linkcode,b.LinkCode)		
		group by a.RMCndtSecId,c.[Descr])z on  qs.Culv = z.[Descr] and wc.RMCndtSecId = z.RMCndtSecId
		where  wc.WrkCode = 'R32' and wc.RMCndtSecId = z.RMCndtSecId

		

		update a set a.Cost = (ISNULL(a.Qty,0) * b.UnitRate)
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec c on a.RMCndtSecID = c.RMCndtSecId
		inner join NM.LinkMaster lm on c.Linkcode = lm.LinkCode
		inner join RMMS.LKPTWrkCodes b on a.WrkCode = b.WrkCode  and lm.Division = b.Division
		and B.[Year] = (select MAX([Year]) from RMMS.LKPTWrkCodes wc where wc.Division = lm.Division and Convert(int,[Year]) <= CONVERT(int,@SurveyYear))
		where b.Module = 'RMMS' and b.Division = lm.Division
		
		
		update a set a.Cost = (d.Oth * b.cost)/100.00
		from RMMS.AssgnWrkCode a inner join 
		(select a.RMCndtSecId,  sum(ISNULL(a.Cost,0)) 'cost'
		from RMMS.AssgnWrkCode a
		inner join RMMS.RMCndtSec c on a.RMCndtSecID = c.RMCndtSecId
		inner join NM.LinkMaster lm on c.Linkcode = lm.LinkCode
		inner join RMMS.LKPTWrkCodes b on a.WrkCode = b.WrkCode and lm.Division = b.Division
		and B.[Year] = (select MAX([Year]) from RMMS.LKPTWrkCodes wc where wc.Division = lm.Division and Convert(int,[Year]) <= CONVERT(int,@SurveyYear))
		where a.WrkCode in ('R01','R02','R03','R04','R05','R06','R10','R11', 'R20', 'R21', 'R30','R31','R32')
		group by a.RMCndtSecId--,d.Oth
		)b on a.RMCndtSecID = b.RMCndtSecID 
		inner join  RMMS.LKPTRMQtyStnd d on a.WrkCode = d.WrkCode
		where a.WrkCode in ('R50','R60','R70')
		--print 1                                                                                                                                                                                         
		update a set a.TotCost = ISNULL(b.Cost ,0)/100000.00
		from RMMS.RMCndtSec a inner join (
		select a.RMCndtSecId,sum(ISNULL(a.Qty,0)) 'Qty',Sum(ISNULL(a.Cost,0)) 'Cost' 
		from RMMS.AssgnWrkCode a 
		inner join RMMS.RMCndtSec c on a.RMCndtSecID = c.RMCndtSecId
		inner join NM.LinkMaster lm on c.Linkcode = lm.LinkCode
		inner join RMMS.LKPTWrkCodes b on a.WrkCode = b.WrkCode  and lm.Division = b.Division
		and B.[Year] = (select MAX([Year]) from RMMS.LKPTWrkCodes wc where wc.Division = lm.Division and Convert(int,[Year]) <= CONVERT(int,@SurveyYear))
		group by a.RMCndtSecId)b on a.RMCndtSecId = b.RMCndtSecId
		where a.SurveyYear = ISNULL(@Surveyyear , a.SurveyYear) and a.RoadCatg = ISNULL(@rdCatg,a.RoadCatg)
		and a.NtWrk = ISNULL(@Network,a.NtWrk)


		--delete BAP.FnlSec where SurveyYear = @SurveyYear and WrkCatg = 'RM'

		--insert into BAP.FnlSec (RoadCode,LinkCode,StartCh,EndCh,SurveyYear,RoadCatg,InclSec,TrfCls,NtWrk,WrkCatg,Cost)
		--select Roadcode,Linkcode,StartCh,EndCh,SurveyYear,RoadCatg,1,TrfCls,NtWrk,'RM',TotCost 
		--from RMMS.RMCndtSec cndt
		--inner join NM.RoadCategory rc on cndt.RoadCatg = rc.RoadCategoryCode
		----where WrkCatg is not null
		--order by rc.Seq

		exec SpatialColumnUpdation  'RMMS.RMCndtSec',@rdCatg, NULL,NULL, @Surveyyear
     
END
GO
/****** Object:  StoredProcedure [dbo].[GetCulvertCodes]    Script Date: 27-01-2025 09:46:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetCulvertCodes]
--EXEC [dbo].[GetCulvertInventoryByFilter] NULL,'CI:MDR_PND06_001:0000.100',NULL,NULL,4
(
@user VARCHAR(50) = NULL,
@userType VARCHAR(10) = NULL,
@hType VARCHAR(10) = NULL,
@hTypeVal VARCHAR(MAX) = NULL
)
AS
BEGIN
	    IF @userType = 'C'
		BEGIN
			SELECT DISTINCT CulvertCode
			FROM [BMS].[CulvertInventory] LD
			INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
			LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
			LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
			LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
			--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
			WHERE ld.RoadCode IN(SELECT sdr.Roadcode  
					FROM NM.LinkMaster  sdr  WHERE Circle IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			ORDER BY CulvertCode
		END
	ELSE IF @userType = 'D'
		BEGIN
			SELECT DISTINCT CulvertCode
			FROM [BMS].[CulvertInventory] LD
			INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
			LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
			LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
			LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
			--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
			WHERE ld.RoadCode IN(SELECT sdr.Roadcode  
					FROM NM.LinkMaster  sdr  WHERE Division IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			ORDER BY CulvertCode
		END
	ELSE
		BEGIN
			IF @hType = 'C'
				BEGIN
					SELECT DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					WHERE ld.RoadCode IN(SELECT sdr.Roadcode FROM NM.LinkMaster  sdr  WHERE Circle = @hTypeVal)
					ORDER BY CulvertCode
				END
			ELSE IF @hType = 'D'
				BEGIN
					SELECT DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					WHERE ld.RoadCode IN(SELECT sdr.Roadcode FROM NM.LinkMaster  sdr  WHERE Division = @hTypeVal)
					ORDER BY CulvertCode
				END
			ELSE IF @hType = 'MLA'
				BEGIN
					SELECT DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					WHERE ld.RoadCode IN(SELECT sdr.Roadcode FROM [NM].[MLAConstituencyRoad] sdr Where MLACODE = @hTypeVal)
					ORDER BY CulvertCode
				END
			ELSE IF @hType = 'MP'
				BEGIN
					SELECT  DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					WHERE ld.RoadCode IN(SELECT sdr.Roadcode FROM [NM].[MPConstituencyRoad] sdr Where MPCODE = @hTypeVal)
					ORDER BY CulvertCode
				END	
			ELSE
				BEGIN
					SELECT DISTINCT CulvertCode
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					--LEFT JOIN BMS.LKPTFlowDir HWT ON LD.ToeWallType = HWT.FlowDirType
					ORDER BY CulvertCode
				END	
		END
END
GO
/****** Object:  StoredProcedure [dbo].[GetCulvertConditionByFilter]    Script Date: 27-01-2025 09:49:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetCulvertConditionByFilter]
--EXEC [dbo].[GetCulvertConditionByFilter] NULL,'ravis','C',NULL,null
(
@roadCode VARCHAR(100)=NULL,
@surveyYear VARCHAR(20)=NULL,
@structureType  VARCHAR(100)=NULL,
@culvertCode VARCHAR(100)=NULL,
@user VARCHAR(50) = NULL,
@userType VARCHAR(10) = NULL,
@hType VARCHAR(10) = NULL,
@hTypeVal VARCHAR(MAX) = NULL
)
AS
BEGIN
	IF (@userType = 'C' and @hType is NULL)
		BEGIN
			SELECT  [CulvertConditionId], CC.[CulvertCode], 			
			[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
			[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
			CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
			FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
			CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
			CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
			WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
			CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
			sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
			flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
			CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
			OSC.Description as 'OverallStrCond',CI.Remarks
			--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
			--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
			FROM
			[BMS].[CulvertCondition] CC
			INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
			left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
			left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
			LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
			left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
			left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
			left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
			LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
			left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
			left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
			left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
			left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
			left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
			left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
			left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
			left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
			left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
			left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
			left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
			left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType 

			/*LEFT JOIN [BMS].[LKPTCondSev]  DS ON CC.ConditionofDeckSlab =DS.CondSevType	
			LEFT JOIN [BMS].[LKPTCondSev]  HW ON CC.ConditionofHeadWall =HW.CondSevType	
			LEFT JOIN [BMS].[LKPTCondSev]  RW ON CC.ConditionofReturnWall =RW.CondSevType	
			LEFT JOIN [BMS].[LKPTCondSev]  PP ON CC.ConditionofParapet =PP.CondSevType	
			LEFT JOIN [BMS].[LKPTCondSev]  C ON CC.Choked =C.CondSevType*/
			WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
			AND CI.LinkCode IN(SELECT sdr.LinkCode  
					FROM NM.LinkMaster  sdr  WHERE Circle IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
			AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
			AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
			ORDER BY CulvertCode
		END
	ELSE IF (@userType = 'D' and @hType is NULL)
		BEGIN
			SELECT  [CulvertConditionId], CC.[CulvertCode], 			
			[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
			[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
			CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
			FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
			CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
			CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
			WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
			CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
			sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
			flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
			CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
			OSC.Description as 'OverallStrCond',CI.Remarks
			--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
			--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
			FROM
			[BMS].[CulvertCondition] CC
			INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
			left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
			left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
			LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
			left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
			left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
			left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
			LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
			left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
			left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
			left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
			left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
			left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
			left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
			left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
			left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
			left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
			left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
			left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
			left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
			WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
			AND CI.LinkCode IN(SELECT sdr.LinkCode  
					FROM NM.LinkMaster  sdr  WHERE Division IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
			AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
			AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
			ORDER BY CulvertCode
		END

		ELSE IF (@userType = 'W' and @hType is NULL)
		BEGIN
			SELECT  [CulvertConditionId], CC.[CulvertCode], 			
			[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
			[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
			CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
			FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
			CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
			CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
			WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
			CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
			sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
			flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
			CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
			OSC.Description as 'OverallStrCond',CI.Remarks
			--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
			--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
			FROM
			[BMS].[CulvertCondition] CC
			INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
			left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
			left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
			LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
			left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
			left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
			left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
			LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
			left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
			left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
			left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
			left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
			left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
			left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
			left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
			left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
			left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
			left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
			left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
			left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
			WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
			AND CI.RoadCode IN(SELECT sdr.Roadcode  
					FROM NM.LinkMaster  sdr  WHERE Circle IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
			AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
			AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
			ORDER BY CulvertCode
		END


	ELSE
		BEGIN
			IF @hType = 'C'
				BEGIN
					SELECT  [CulvertConditionId], CC.[CulvertCode], 			
			[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
			[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
			CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
			FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
			CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
			CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
			WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
			CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
			sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
			flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
			CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
			OSC.Description as 'OverallStrCond',CI.Remarks
			--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
			--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
			FROM
			[BMS].[CulvertCondition] CC
			INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
			left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
			left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
			LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
			left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
			left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
			left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
			LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
			left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
			left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
			left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
			left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
			left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
			left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
			left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
			left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
			left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
			left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
			left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
			left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
					WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
					AND CI.LinkCode IN(SELECT sdr.LinkCode FROM NM.LinkMaster  sdr  WHERE Circle = @hTypeVal)
					AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
					AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
					AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
					ORDER BY CulvertCode
				END
			ELSE IF @hType = 'D'
				BEGIN
					SELECT  [CulvertConditionId], CC.[CulvertCode], 			
			[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
			[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
			CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
			FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
			CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
			CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
			WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
			CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
			sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
			flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
			CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
			OSC.Description as 'OverallStrCond',CI.Remarks
			--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
			--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
			FROM
			[BMS].[CulvertCondition] CC
			INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
			left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
			left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
			LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
			left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
			left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
			left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
			LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
			left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
			left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
			left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
			left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
			left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
			left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
			left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
			left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
			left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
			left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
			left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
			left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
					WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
					AND CI.LinkCode IN(SELECT sdr.LinkCode FROM NM.LinkMaster  sdr  WHERE Division = @hTypeVal)
					AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
					AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
					AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
					ORDER BY CulvertCode
				END

			ELSE IF @hType = 'W'
				BEGIN
					SELECT  [CulvertConditionId], CC.[CulvertCode], 			
			[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
			[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
			CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
			FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
			CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
			CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
			WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
			CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
			sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
			flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
			CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
			OSC.Description as 'OverallStrCond',CI.Remarks
			--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
			--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
			FROM
			[BMS].[CulvertCondition] CC
			INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
			left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
			left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
			LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
			left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
			left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
			left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
			LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
			left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
			left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
			left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
			left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
			left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
			left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
			left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
			left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
			left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
			left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
			left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
			left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
					WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
					--AND CI.RoadCode IN(SELECT sdr.Roadcode FROM NM.LinkMaster  sdr  WHERE Division = @hTypeVal)		/* Commented on 11/26/2020*/
					AND CI.RoadCode IN (SELECT sdr.Roadcode FROM NM.LinkMaster  sdr  WHERE Circle IN(SELECT CircleCode FROM NM.Circle WHERE WingName= @hTypeVal))
					AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
					AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
					AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
					ORDER BY CulvertCode
				END

			ELSE IF @hType = 'MLA'
				BEGIN
					SELECT  [CulvertConditionId], CC.[CulvertCode], 			
			[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
			[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
			CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
			FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
			CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
			CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
			WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
			CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
			sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
			flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
			CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
			OSC.Description as 'OverallStrCond',CI.Remarks
			--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
			--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
			FROM
			[BMS].[CulvertCondition] CC
			INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
			left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
			left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
			LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
			left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
			left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
			left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
			LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
			left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
			left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
			left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
			left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
			left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
			left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
			left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
			LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
			left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
			LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
			left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
			left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
			left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
			left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
					WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
					AND CI.RoadCode IN(SELECT sdr.Roadcode FROM [NM].[MLAConstituencyRoad] sdr Where MLACODE = @hTypeVal)
					AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
					AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
					AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
					ORDER BY CulvertCode
				END
			ELSE IF @hType = 'MP'
				BEGIN
					SELECT  [CulvertConditionId], CC.[CulvertCode], 			
					[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
					[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
					CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
					FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
					CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
					CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
					WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
					CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
					sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
					flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
					CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
					OSC.Description as 'OverallStrCond',CI.Remarks
					--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
					--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
					FROM
					[BMS].[CulvertCondition] CC
					INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
					left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
					left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
					LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
					left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
					left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
					left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
					LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
					left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
					left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
					left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
					left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
					left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
					left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
					left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
					LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
					LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
					left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
					LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
					left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
					left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
					left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
					left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
					WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
					AND CI.RoadCode IN(SELECT sdr.Roadcode FROM [NM].[MPConstituencyRoad] sdr Where MPCODE = @hTypeVal)
					AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
					AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
					AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
					ORDER BY CulvertCode
				END	
			ELSE
				BEGIN
					SELECT  [CulvertConditionId], CC.[CulvertCode], 			
					[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
					[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
					CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
					FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
					CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
					CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
					WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
					CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
					sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
					flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
					CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
					OSC.Description as 'OverallStrCond',CI.Remarks
					--CC.[SurveyYear],DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,CC.[SurveyYear] 'SurveyCode'
					--DS.Description AS ConditionofDeckSlabDesc, HW.Description AS ConditionofHeadWallDesc, RW.Description AS ConditionofReturnWallDesc,PP.Description AS ConditionofParapetDesc, C.Description AS ChokedDesc
					FROM
					[BMS].[CulvertCondition] CC
					INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode		
					left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
					left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
					LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
					left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
					left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
					left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
					LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
					left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
					left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
					left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
					left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
					left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
					left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
					left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
					LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
					LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
					left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
					LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
					left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
					left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
					left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
					left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
					WHERE CC.culvertCode = ISNULL(@culvertCode,CC.culvertCode)
					AND CI.RoadCode = ISNULL(@roadCode, CI.RoadCode)
					AND CI.SurveyYear = ISNULL(@surveyYear, CI.SurveyYear)
					AND CI.StructureType = ISNULL(@structureType, CI.StructureType)
					ORDER BY CulvertCode
				END	
		END
	
END
GO
/****** Object:  StoredProcedure [dbo].[GetCulvertConditionForApprove]    Script Date: 27-01-2025 10:36:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetCulvertConditionForApprove]
--EXEC [dbo].[CulvertConditionEdit] 1
(
@roadCode VARCHAR(100)=NULL,
@culvertCode VARCHAR(100)=NULL
)
AS

BEGIN
	IF @roadCode = '' SET @roadCode = NULL 
	SELECT  [CulvertConditionId],CI.[RoadCode],CC.culvertCode, CI.[Chainage], CONVERT ( DECIMAL(18,3) ,(CI.Chainage/1000.00)) as 'Chainagekm',CI.[LinkCode]
			, CI.[Direction], 
			[VegetationUS], [VegetationDS], [ScourUS], [ScourDS], [WaterWayAdequacy],
					[ConditionofPipe], [Remarks], CI.LinkCode,CI.RoadCode,CI.Chainage,
					CI.[SurveyYear] as 'SurveyCode',Ci.RoadCode,CI.Direction,CI.SurveyDate,CI.ConstructionYear,CI.Latitude,CI.Longitude,ci.CDNumber,ci.PWDStoneCh,CI.PWDStrNum,
					FL.Description as 'FlowDirection',CI.NearByPlace,Ci.StructureType,CI.TotalCulvertWidth,CI.ClearRoadWidth,ci.Submersible,ci.SkewAngle,
					CI.Bedmaterial,ci.NoofSpans,ci.SpanWidth,CI.SpanHeight,ci.Type2SpanWidth,CI.Type2SpansNo,CI.Type2SpanHeight,ci.DeckSlabThickness,
					CI.SpacingBtwnPipes,CI.Cushion,cc.SupStuctrCondition,HWT.Description as 'HeadWallType',CI.HeadWallThickness,HWC.description as 'HeadWallCond',
					WT.description as 'WRWallType',CI.wrwalllength,HW1.description as 'WRWallMtrlType',CI.WRWallLength,wrwc.description as 'WRWallCond',
					CI.HeadWallLength,CI.CulverLength,RT.description as 'Railingtype',RC.description as 'RailingCondition',sc.description as 'ScourUS',
					sc1.description as 'ScourDS',slt.description as 'SiltUS',slt1.description as 'SiltDS',vg.description as 'VegetationUS',vg1.description as 'VegetationDS',
					flt.description as 'FlorngType',pus.description as 'ProtectionUS',pds.description as 'ProtectionDS',CI.IsFlorngProvd,CI.CurtainwallPRVD,
					CT.description as 'CurtainwallType',CWUS.description as 'CurtainWallCondUS', cwds.description as 'CurtainWallCondDS',CI.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',PC.description as 'SdSlpPitchCond',CC.WideningReq,CC.WaterWayAdequacy,
					OSC.Description as 'OverallStrCond',CI.Remarks

	FROM
	 [BMS].[CulvertCondition] CC
					INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode
					left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
					left join BMS.LKPTHeadWallType HWT on CI.HeadWallType=HWT.HeadWallType
					LEFT JOIN [BMS].[LKPTCulvCond] HWC on CC.HeadWallCond=HWC.CulvCondType
					left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on CI.WRWallMtrlType=HW1.HeadWallType
					left join [BMS].[LKPTCulvCond] WRWC on cc.wrwallcond=WRWC.CulvCondType
					left join BMS.LKPTRailType RT on CI.Railingtype=RT.RailType
					LEFT JOIN [BMS].[LKPTCulvCond] RC on CC.RailingCondition=RC.CulvCondType
					left join bms.LKPTScourCond SC on cc.SCourUS=sc.ScourCondType 
					left join bms.LKPTScourCond SC1 on cc.SCourDS=sc1.ScourCondType 
					left join BMS.LKPTSiltCond SLT on cc.SiltUS=SLT.SiltCondType
					left join BMS.LKPTSiltCond SLT1 on cc.SiltDS=SLT1.SiltCondType
					left join bms.LKPTVegCond VG on cc.VegetationUS=VG.VegCondCondType
					left join bms.LKPTVegCond VG1 on cc.VegetationDS=VG.VegCondCondType
					left join BMS.LKPTFloorType FLT on CI.FlorngType=FLT.FloorTypeCondType
					LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
					LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
					left join BMS.LKPTCurtainType CT on CI.CurtainwallType=CT.CurtainTypeCondType
					LEFT JOIN [BMS].[LKPTCulvCond] CWDS on cc.CurtainWallCondDS=CWDS.CulvCondType
					left join [BMS].[LKPTCulvCond] CWUS on cc.CurtainWallCondUS=CWUS.CulvCondType
					left join BMS.LKPTPitchingType PT on CI.SdSlpPitchtype=PT.PitchingTypeCondType
					left join [BMS].[LKPTCulvCond] PC on cc.SdSlpPitchCond=pc.CulvCondType
					left join [BMS].[LKPTOvrlStructureCond] OSC on cc.OverallStrCond=OSC.OvrlStructureCondType
	WHERE CI.RoadCode = ISNULL(@roadCode ,CI.RoadCode)
		AND CC.CulvertCode = ISNULL(@culvertCode,CC.CulvertCode)
	
END
GO
/****** Object:  StoredProcedure [dbo].[GetCulvertConditionStaging]    Script Date: 27-01-2025 10:53:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetCulvertConditionStaging]
--EXEC [dbo].[CulvertConditionEdit] 1
(
@roadCode VARCHAR(100)=NULL,
@culvertCode VARCHAR(100)=NULL
)
AS

BEGIN
IF @roadCode = '' SET @roadCode = null 
	SELECT  [CulvertConditionId],CI.[RoadCode],CC.culvertCode, CI.[Chainage], CONVERT ( DECIMAL(18,3) ,(CI.Chainage/1000.00)) as 'Chainagekm',CI.[LinkCode]
			, CI.[Direction], [ConditionofDeckSlab], [ConditionofHeadWall], [ConditionofReturnWall], [ConditionofParapet], 
			[VegetationUS], [VegetationDS], [Choked], [ScourUS], [ScourDS], [WaterWayAdequacy], [ConditionofPipe], [ConditionofWingWall], CI.[Remarks], 
			CC.[SurveyYear],
			DS.CondSevType AS DeckSlabDesc, HW.CondSevType AS HeadWallDesc, RW.CondSevType AS ReturnWallDesc, 
			PP.CondSevType AS ParapetDesc, C.CondSevType AS ChokedDesc,
			CC.culvertCode AS 'CompositeKey'
	FROM
	 [BMS].[CulvertCondition_Staging] CC
		INNER JOIN BMS.CulvertInventory CI ON CC.CulvertCode = CI.CulvertCode
		LEFT JOIN [BMS].[LKPTCondSev]  DS ON CC.ConditionofDeckSlab =DS.CondSevType	
		LEFT JOIN [BMS].[LKPTCondSev]  HW ON CC.ConditionofHeadWall =HW.CondSevType	
		LEFT JOIN [BMS].[LKPTCondSev]  RW ON CC.ConditionofReturnWall =RW.CondSevType	
		LEFT JOIN [BMS].[LKPTCondSev]  PP ON CC.ConditionofParapet =PP.CondSevType	
		LEFT JOIN [BMS].[LKPTCondSev]  C ON CC.Choked =C.CondSevType
	WHERE CI.RoadCode = ISNULL(roadCode ,CI.RoadCode)
		AND CC.CulvertCode = ISNULL(@culvertCode,CC.CulvertCode)
		AND CC.ApprovalStatus IS NULL		
END
GO
/****** Object:  StoredProcedure [dbo].[GetCulvertInventoryByFilter]    Script Date: 27-01-2025 10:55:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetCulvertInventoryByFilter]
--EXEC [dbo].[GetCulvertInventoryByFilter] NULL,'CI:MDR_RBD06_003:0000.100',NULL,NULL,4
(
@roadCode VARCHAR(100)=NULL,
@culvertCode VARCHAR(100)=NULL,
@StartChainage VARCHAR(100)=NULL,
@EndChainage VARCHAR(100)=NULL,
@structureType  VARCHAR(100)=NULL,
@user VARCHAR(50) = NULL,
@userType VARCHAR(10) = NULL,
@hType VARCHAR(10) = NULL,
@hTypeVal VARCHAR(MAX) = NULL
)
AS
BEGIN
	    IF (@userType = 'C' and @hType is NULL)
		BEGIN
			SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
			latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
			headWallLength,headWallThickness,flowDirection,surveyDate,
			BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
			LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
			LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
			LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
			LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
			WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
			LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
			flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
			CT.description as 'CurtainwallType',LD.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',LD.Remarks
			--, null 'ApprovalStatus'
			FROM [BMS].[CulvertInventory] LD
			INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
			LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
			LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
			LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
			left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
			left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
			left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
			left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
			left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
			left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
			WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
			AND ld.LinkCode IN(SELECT sdr.LinkCode  
					FROM NM.LinkMaster  sdr  WHERE Circle IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
			--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
			AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
			AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
			AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
			ORDER BY 2,3
		END
	ELSE IF (@userType = 'D' and @hType is NULL)
		BEGIN
			SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
			latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
			headWallLength,headWallThickness,flowDirection,surveyDate,
			BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
			LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
			LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
			LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
			LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
			WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
			LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
			flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
			CT.description as 'CurtainwallType',LD.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',LD.Remarks
			--, null 'ApprovalStatus'
			FROM [BMS].[CulvertInventory] LD
			INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
			LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
			LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
			LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
			left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
			left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
			left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
			left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
			left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
			left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
			WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
			AND ld.LinkCode IN(SELECT sdr.LinkCode  
					FROM NM.LinkMaster  sdr  WHERE Division IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
			--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
			AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
			AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
			AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
			ORDER BY 2,3
		END


		 ELSE IF (@userType = 'W' and @hType is NULL)
		BEGIN
			SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
			latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
			headWallLength,headWallThickness,flowDirection,surveyDate,
			BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
			LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
			LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
			LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
			LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
			WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
			LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
			flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
			CT.description as 'CurtainwallType',LD.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',LD.Remarks
			--, null 'ApprovalStatus'
			FROM [BMS].[CulvertInventory] LD
			INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
			LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
			LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
			LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
			left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
			left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
			left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
			left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
			left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
			left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
			WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
			AND ld.RoadCode IN(SELECT sdr.Roadcode  
					FROM NM.LinkMaster  sdr  WHERE Circle IN(SELECT AreaName FROM [SSUM].[UserAreas] WHERE UserName = @user))
			and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
			--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
			AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
			AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
			AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
			ORDER BY 2,3
		END

	ELSE
		BEGIN
			IF @hType = 'C'
				BEGIN
					SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
					latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
					headWallLength,headWallThickness,flowDirection,surveyDate,
					BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
					LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
					LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
					LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
					LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
					WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
					LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
					flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
					CT.description as 'CurtainwallType',LD.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',LD.Remarks
					--, null 'ApprovalStatus'
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
					left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
					left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
					left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
					left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
					left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
					WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
					AND ld.LinkCode IN(SELECT sdr.LinkCode FROM NM.LinkMaster  sdr  WHERE Circle = @hTypeVal)
					and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
					--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
					AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
					AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
					AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
					ORDER BY 2,3
				END
ELSE IF @hType = 'D'
				BEGIN
					SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
					latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
					headWallLength,headWallThickness,flowDirection,surveyDate,
					BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
					LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
					LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
					LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
					LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
					WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
					LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
					flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
					CT.description as 'CurtainwallType',LD.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',LD.Remarks
					--, null 'ApprovalStatus'
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
					left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
					left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
					left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
					left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
					left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
					WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
					AND ld.LinkCode IN(SELECT sdr.LinkCode FROM NM.LinkMaster  sdr  WHERE Division = @hTypeVal)
					and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
					--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
					AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
					AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
					AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
					ORDER BY 2,3
				END

				ELSE IF @hType = 'W'
				BEGIN
					SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
					latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
					headWallLength,headWallThickness,flowDirection,surveyDate,
					BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
					LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
					LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
					LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
					LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
					WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
					LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
					flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
					CT.description as 'CurtainwallType',LD.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',LD.Remarks
					--, null 'ApprovalStatus'
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
					left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
					left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
					left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
					left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
					left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
					WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
					--AND ld.RoadCode IN(SELECT sdr.Roadcode FROM NM.LinkMaster  sdr  WHERE Division = @hTypeVal)		/* Commented on 11/26/2020*/
					AND LD.RoadCode IN (SELECT sdr.Roadcode FROM NM.LinkMaster  sdr  WHERE Circle IN(SELECT CircleCode FROM NM.Circle WHERE WingName= @hTypeVal))
					and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
					--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
					AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
					AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
					AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
					ORDER BY 2,3
				END

			ELSE IF @hType = 'MLA'
				BEGIN
					SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
					latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
					headWallLength,headWallThickness,flowDirection,surveyDate,
					BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
					LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
					LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
					LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
					LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
					WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
					LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
					flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
					CT.description as 'CurtainwallType',LD.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',LD.Remarks
					--, null 'ApprovalStatus'
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
					left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
					left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
					left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
					left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
					left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
					WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
					AND ld.RoadCode IN(SELECT sdr.Roadcode FROM [NM].[MLAConstituencyRoad] sdr Where MLACODE = @hTypeVal)
					and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
					--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
					AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
					AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
					AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
					ORDER BY 2,3
				END
			ELSE IF @hType = 'MP'
				BEGIN
					SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
					latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
					headWallLength,headWallThickness,flowDirection,surveyDate,
					BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
					LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
					LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
					LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
					LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
					WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
					LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
					flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
					CT.description as 'CurtainwallType',LD.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',LD.Remarks
					--, null 'ApprovalStatus'
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
					left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
					left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
					left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
					left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
					left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
					WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
					AND ld.RoadCode IN(SELECT sdr.Roadcode FROM [NM].[MPConstituencyRoad] sdr Where MPCODE = @hTypeVal)
					and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
					--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
					AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
					AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
					AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
					ORDER BY 2,3
				END	
			ELSE
				BEGIN
					SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
					latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
					headWallLength,headWallThickness,flowDirection,surveyDate,
					BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
					LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
					LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
					LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
					LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
					WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
					LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
					flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
					CT.description as 'CurtainwallType',LD.IsPichngProvd,
					PT.description as 'SdSlpPitchtype',LD.Remarks
					--, null 'ApprovalStatus'
					FROM [BMS].[CulvertInventory] LD
					INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
					LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
					LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
					LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
					left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
					left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
					left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
					left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
					left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
					left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
					left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
					WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
					and ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
					--AND LinkCode = ISNULL(@linkCode, LD.linkCode)
					AND LD.Chainage >=ISNULL(@StartChainage, ld.Chainage)
					AND LD.Chainage <=ISNULL(@EndChainage, ld.Chainage)
					AND LD.StructureType = ISNULL(@structureType, LD.StructureType)
					ORDER BY 2,3
				END	
		END		
END
GO
/****** Object:  StoredProcedure [dbo].[GetCulvertInventoryForApprove]    Script Date: 27-01-2025 11:39:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetCulvertInventoryForApprove]
--EXEC [dbo].[GetCulvertInventory] NULL,NULL
(
@roadCode VARCHAR(100)=NULL,
@culvertCode VARCHAR(100)=NULL
)
AS
BEGIN
		IF @roadCode = '' SET @roadCode = null 
		SELECT   [culvertInventoryId], ld.[RoadCode], [Chainage], CONVERT ( DECIMAL(18,3) ,(Chainage/1000.00)) as 'Chainagekm',[LinkCode], [Direction], 
			latitude,longitude,culvertCode,cDNumber,LD.structureType,noofSpans,spanWidth,spanHeight,clearRoadWidth,totalCulvertWidth,deckSlabThickness,LD.headWallType,
			headWallLength,headWallThickness,flowDirection,surveyDate,
			BT.Description AS StructureTypeDesc, bg.Description as HeadWallTypeDesc, FD.Description as FlowDirTypeDesc, RD.NAME as roadName, [SurveyYear] 'SurveyCode',
			LD.RoadCode,LD.Direction,LD.SurveyDate,LD.ConstructionYear,LD.Latitude,LD.Longitude,LD.CDNumber,LD.PWDStoneCh,LD.PWDStrNum,
			LD.NearByPlace,LD.StructureType,LD.TotalCulvertWidth,LD.ClearRoadWidth,LD.Submersible,LD.SkewAngle,
			LD.Bedmaterial,LD.NoofSpans,LD.SpanWidth,LD.SpanHeight,LD.Type2SpanWidth,LD.Type2SpansNo,LD.Type2SpanHeight,LD.DeckSlabThickness,
			LD.SpacingBtwnPipes,LD.Cushion,HWT.Description as 'HeadWallType',LD.HeadWallThickness,
			WT.description as 'WRWallType',LD.wrwalllength,HW1.description as 'WRWallMtrlType',LD.WRWallLength,
			LD.HeadWallLength,LD.CulverLength,RT.description as 'Railingtype',
			flt.description as 'FlorngType',LD.IsFlorngProvd,LD.CurtainwallPRVD,
			CT.description as 'CurtainwallType',LD.IsPichngProvd,
			PT.description as 'SdSlpPitchtype',LD.Remarks
			--, null 'ApprovalStatus'
			FROM [BMS].[CulvertInventory] LD
			INNER JOIN NM.RoadMaster RD ON LD.RoadCode = RD.RoadCode
			LEFT JOIN BMS.LKPTStructureType BT ON LD.StructureType = BT.StructureType
			LEFT JOIN BMS.LKPTHeadWallType BG ON LD.HeadWallType = BG.HeadWallType
			LEFT JOIN BMS.LKPTFlowDir FD ON LD.FlowDirection = FD.FlowDirType
			left join BMS.LKPTHeadWallType HWT on LD.HeadWallType=HWT.HeadWallType
			left join BMS.LKPTWallType WT on LD.WRWallType= WT.WallTypeCondType
			left join BMS.LKPTHeadWallType HW1 on LD.WRWallMtrlType=HW1.HeadWallType
			left join BMS.LKPTRailType RT on LD.Railingtype=RT.RailType
			left join BMS.LKPTFloorType FLT on LD.FlorngType=FLT.FloorTypeCondType
			left join BMS.LKPTCurtainType CT on LD.CurtainwallType=CT.CurtainTypeCondType
			left join BMS.LKPTPitchingType PT on LD.SdSlpPitchtype=PT.PitchingTypeCondType
		WHERE ld.RoadCode = ISNULL(@roadCode,ld.RoadCode) 
		AND ld.CulvertCode = ISNULL(@culvertCode,ld.CulvertCode)
END
GO
/****** Object:  StoredProcedure [dbo].[MergeLinksNew]    Script Date: 27-01-2025 11:45:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MergeLinksNew] 
--EXEC MergeLinks 'LI:NH055:0000.000','LI:NH055:0000.200', '0','500'
@OLDLinkID VARCHAR(100),
@NewLinkID VARCHAR(100)
,@StartChainage VARCHAR(20)
,@EndChainage VARCHAR(20)

AS
BEGIN
	DECLARE @strReturn VARCHAR(20)
	SET @strReturn = 0 
	DECLARE @TABLE NVARCHAR(100) 
	SET NOCOUNT ON;
	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @Result NVARCHAR(MAX)='0'
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Merge'
	DECLARE @deleteCommand NVARCHAR(MAX) ='' 


		DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
		INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
		SELECT TableName,TableType FROM NM.SplitMergeTableList WHERE SplitColumn='1'
		DECLARE @COUNT INT
		SET @COUNT =1

		WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
			BEGIN
				SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
				IF @TABLE = 'TIS.Trafficstation'
					BEGIN
						INSERT INTO [TIS].[TrafficStation_Audit]
									([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
						SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
						FROM [TIS].[TrafficStation]
						WHERE LinkCode = @NewLinkID

						UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE LinkCode = @NewLinkID

						UPDATE TIS.Trafficstation SET LinkCode = @OLDLinkID WHERE LinkCode = @NewLinkID

						UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
						FROM tis.AxleLoad S
						INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

						UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
						FROM [TIS].[TrafficVolume] S
						INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

						UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
						FROM [TIS].[LinkTrafficDistribution] S
						INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode
					END
               ELSE IF @TABLE = 'RSAMS.Accident'
						BEGIN
							INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
							SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
										,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
										,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
							FROM [RSAMS].[Accident] 	WHERE LinkCode = @NewLinkID
						UPDATE RSAMS.Accident SET OldCode = AccidentCode WHERE LinkCode = @NewLinkID

						UPDATE RSAMS.Accident SET LinkCode = @OLDLinkID WHERE LinkCode = @NewLinkID

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVehicles] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVictims] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode
                        END
               ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
						BEGIN
							INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
							SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
										,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
										,[Direction],[OldCode],@Split
							FROM [RSAMS].[BlackspotExternal]
							WHERE LinkCode = @NewLinkID

							--UPDATE RSAMS.BlackspotExternal SET OldCode = BlackSpotCode WHERE LinkCode = @NewLinkID

						 --   UPDATE RSAMS.BlackspotExternal SET LinkCode = @OLDLinkID WHERE LinkCode = @NewLinkID

							UPDATE RSAMS.BlackspotExternal SET OldCode = BlackSpotCode WHERE LinkCode = @OLDLinkID
							UPDATE [RSAMS].BlackspotExternal   SET LinkCode = @OLDLinkID WHERE LinkCode = @NewLinkID
            				--UPDATE RSAMS.BlackspotExternal   SET EndChainage = @EndChainage WHERE LinkCode = @OLDLinkID

						    --Delete RSAMS.BlackspotExternal WHERE LinkCode = @NewLinkID 

							UPDATE S SET S.LocCode = A.BlackSpotCode
							FROM [RSAMS].[CntrMeasmt] S
							INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode
						END
               ELSE IF @TABLE = 'RSAMS.HazdLocation'
						BEGIN						

							INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
							SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
									,[EndPointLongitude],[Direction],[OldCode],@Split
							FROM [RSAMS].[HazdLocation]
							WHERE LinkCode = @NewLinkId 

                        UPDATE [RSAMS].[HazdLocation]   SET OldCode = HazdLocCode WHERE LinkCode = @OLDLinkID
						UPDATE [RSAMS].[HazdLocation]   SET LinkCode = @OLDLinkID WHERE LinkCode = @NewLinkID
						--UPDATE [RSAMS].[HazdLocation]   SET EndChainage = @EndChainage WHERE LinkCode = @OLDLinkID

						--Delete [RSAMS].[HazdLocation] WHERE LinkCode = @NewLinkID 

						UPDATE S SET S.LocCode = A.HazdLocCode
						FROM [RSAMS].[CntrMeasmt] S
						INNER JOIN [RSAMS].[HazdLocation] A ON S.LocCode = A.OldCode

	               
						END
               ELSE IF @TABLE = 'BMS.LocationDetails'
					BEGIN
						INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],[Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails]  
						
						WHERE LinkCode = @NewLinkID

						select @NewLinkID 
						select @OLDLinkID

						UPDATE [BMS].[LocationDetails]   SET OldCode = BridgeID WHERE LinkCode = @NewLinkID

						UPDATE [BMS].[LocationDetails]   SET LinkCode = @OLDLinkID WHERE LinkCode = @NewLinkID

				
						        UPDATE S SET S.BridgeCode = A.BridgeId 
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BCICondRating S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BridgeBoQ S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertCondition S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertInventory S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
					END
			   ELSE IF @TABLE = 'BMS.CulvertInventory'
					BEGIN
						INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
						WHERE CC.LinkCode = @NewLinkID

						UPDATE [BMS].[CulvertInventory] SET OldCode = CulvertCode WHERE LinkCode = @NewLinkID
							  
						UPDATE [BMS].[CulvertInventory] SET LinkCode = @OLDLinkID WHERE LinkCode = @NewLinkID

						UPDATE S SET S.CulvertCode = A.CulvertCode
						FROM [BMS].[CulvertCondition] S
						INNER JOIN [BMS].[CulvertInventory] A ON S.CulvertCode = A.OldCode					
					END
				
				SET @COUNT = @COUNT + 1;
			END
END
GO
/****** Object:  StoredProcedure [dbo].[MergeRoadsNew1]    Script Date: 27-01-2025 12:34:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MergeRoadsNew1] 
--EXEC MergeRoads 'NH068A','NH068', '600','600',0,0,0,'Increasing'
--EXEC MergeRoads 'NH068A','NH068', '600','600',0,0,2,'Decreasing' --IsReset = 2
--EXEC MergeRoads 'NH068A','NH068', '600','600',0,0,1,'Decreasing' --IsReset = 1
--EXEC MergeRoadsNew1 'NH714A','NH714', '100100','100100',120100,120100,2,'Increasing' --IsReset = 0
@OLDRoadCode VARCHAR(20), --Deleted Road
@NewRoadCode VARCHAR(20) --Contine Road
,@StartChainage1 VARCHAR(20)
,@EndChainage1 VARCHAR(20)
,@StartChainage2 VARCHAR(20)
,@EndChainage2 VARCHAR(20)
,@IsReset VARCHAR(10)
,@Direction VARCHAR(20)

AS
BEGIN
	DECLARE @strReturn VARCHAR(20)
	SET @strReturn = 0 
	DECLARE @TABLE NVARCHAR(100) 
	SET NOCOUNT ON;
	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @Result NVARCHAR(MAX)='0'
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Merge'
	DECLARE @NewLinkID NVARCHAR(50)
	DECLARE @Chainage VARCHAR(20)


		DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
		INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
		SELECT TableName,TableType FROM NM.SplitMergeTableList WHERE SplitColumn='1'
		DECLARE @COUNT INT
		DECLARE @PID NVARCHAR(20)
		DECLARE @PID1 NVARCHAR(20)
		SET @COUNT =1
		DECLARE @INNERCOUNT INT

		WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
			BEGIN
				SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
				IF @TABLE = 'TIS.Trafficstation'
					BEGIN
						INSERT INTO [TIS].[TrafficStation_Audit]
									([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
						SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
						FROM [TIS].[TrafficStation]
						WHERE RoadCode = @OLDRoadCode

						UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE RoadCode = @OLDRoadCode

						UPDATE TIS.Trafficstation SET LinkCode = REPLACE(LinkCode,@OLDRoadCode,@NewRoadCode), RoadCode = @NewRoadCode, TrafficStationCode = REPLACE(TrafficStationCode,@OLDRoadCode,@NewRoadCode)  WHERE RoadCode = @OLDRoadCode
						
						UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode, S.RoadCode = A.RoadCode
						FROM tis.AxleLoad S
						INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

						UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode, S.RoadCode = A.RoadCode
						FROM [TIS].[TrafficVolume] S
						INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

						UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
						FROM [TIS].[LinkTrafficDistribution] S
						INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode
					
					END
				ELSE IF @TABLE = 'RSAMS.Accident'
					BEGIN
						INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
						SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
									,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
									,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
						FROM [RSAMS].[Accident]
						WHERE RoadCode = @OLDRoadCode

						UPDATE [RSAMS].[Accident] SET OldCode = AccidentCode WHERE RoadCode = @OLDRoadCode

						UPDATE [RSAMS].[Accident] SET LinkCode = REPLACE(LinkCode,@OLDRoadCode,@NewRoadCode), RoadCode = @NewRoadCode, AccidentCode = REPLACE(AccidentCode,@OLDRoadCode,@NewRoadCode)  WHERE RoadCode = @OLDRoadCode

						UPDATE S SET S.AccidentCode = A.AccidentCode
						FROM [RSAMS].[AccVehicles] S
						INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode

						UPDATE S SET S.AccidentCode = A.AccidentCode
						FROM [RSAMS].[AccVictims] S
						INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode
					END
				ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
					BEGIN
						INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
						SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
									,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
									,[Direction],[OldCode],@Split
						FROM [RSAMS].[BlackspotExternal]
						WHERE RoadCode = @OLDRoadCode

						UPDATE [RSAMS].[BlackspotExternal] SET OldCode = BlackSpotCode WHERE RoadCode = @OLDRoadCode

						IF (@IsReset != '2')
							BEGIN
								UPDATE [RSAMS].[BlackspotExternal] SET StartChainage=StartChainage+@EndChainage1,EndChainage=EndChainage+@EndChainage1 WHERE RoadCode = @OLDRoadCode 
							END

						UPDATE [RSAMS].[BlackspotExternal] SET LinkCode = REPLACE(LinkCode,@OLDRoadCode,@NewRoadCode), RoadCode = @NewRoadCode, BlackSpotCode = REPLACE(BlackSpotCode,@OLDRoadCode,@NewRoadCode)  WHERE RoadCode = @OLDRoadCode

						UPDATE S
						SET LINKCODE=lm.LinkCode
						FROM [RSAMS].[BlackspotExternal] S
						INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
						WHERE S.RoadCode=@NewRoadCode
						AND S.StartChainage >= CONVERT(VARCHAR(20),lm.StartChainage) AND S.EndChainage <= CONVERT(VARCHAR(20),lm.EndChainage) 

						UPDATE S SET S.LocCode = A.BlackSpotCode
						FROM [RSAMS].[CntrMeasmt] S
						INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode
					END
				ELSE IF @TABLE = 'RSAMS.HazdLocation'
					BEGIN
						INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
						SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
								,[EndPointLongitude],[Direction],[OldCode],@Split
						FROM [RSAMS].[HazdLocation]
						WHERE RoadCode = @OLDRoadCode

						
						UPDATE [RSAMS].[HazdLocation] SET OldCode = HazdLocCode WHERE RoadCode = @OLDRoadCode 						
							
						IF (@IsReset != '2')
							BEGIN
								UPDATE [RSAMS].[HazdLocation] SET StartChainage=StartChainage+@EndChainage1,EndChainage=EndChainage+@EndChainage1 WHERE RoadCode = @OLDRoadCode 
							END

						UPDATE [RSAMS].[HazdLocation] SET LinkCode = REPLACE(LinkCode,@OLDRoadCode,@NewRoadCode), RoadCode = @NewRoadCode, HazdLocCode = REPLACE(HazdLocCode,@OLDRoadCode,@NewRoadCode)  WHERE RoadCode = @OLDRoadCode 

						UPDATE S
						SET LINKCODE=lm.LinkCode
						FROM [RSAMS].[HazdLocation] S
						INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
						WHERE S.RoadCode=@NewRoadCode
						AND S.StartChainage >= CONVERT(VARCHAR(20),lm.StartChainage) AND S.EndChainage <= CONVERT(VARCHAR(20),lm.EndChainage) 

						UPDATE S SET S.LocCode = A.HazdLocCode
						FROM [RSAMS].[CntrMeasmt] S
						INNER JOIN RSAMS.HazdLocation A ON S.LocCode = A.OldCode
					END
                ELSE IF @TABLE = 'BMS.LocationDetails'
					BEGIN
						INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],[Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails]  
						WHERE RoadCode = @OLDRoadCode

						UPDATE [BMS].[LocationDetails]  SET OldCode = BridgeID WHERE RoadCode = @OLDRoadCode

						UPDATE [BMS].[LocationDetails]  SET LinkCode = REPLACE(LinkCode,@OLDRoadCode,@NewRoadCode), RoadCode = @NewRoadCode, BridgeID = REPLACE(BridgeID,@OLDRoadCode,@NewRoadCode)  WHERE RoadCode = @OLDRoadCode

			
						        UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BCICondRating S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BridgeBoQ S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertCondition S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertInventory S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
					END
				ELSE IF @TABLE = 'BMS.CulvertInventory'
					BEGIN
						INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
						WHERE CC.LinkCode = @NewLinkID
					
						UPDATE [BMS].[CulvertInventory] SET OldCode = CulvertCode WHERE RoadCode = @OLDRoadCode

						UPDATE [BMS].[CulvertInventory] SET LinkCode = REPLACE(LinkCode,@OLDRoadCode,@NewRoadCode), RoadCode = @NewRoadCode, CulvertCode = REPLACE(CulvertCode,@OLDRoadCode,@NewRoadCode)  WHERE RoadCode = @OLDRoadCode

						UPDATE S SET S.CulvertCode = A.CulvertCode
						FROM [BMS].[CulvertCondition] S
						INNER JOIN [BMS].[CulvertInventory]  A ON S.CulvertCode = A.OldCode
						
					END
				SET @COUNT = @COUNT + 1;
			END
			SELECT @strReturn
END
GO
/****** Object:  StoredProcedure [dbo].[SplitLinksAllTablesNew]    Script Date: 27-01-2025 12:37:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SplitLinksAllTablesNew] 
--EXEC SplitLinksAllTablesNew 'LI:SH 00001:0000.000-OL','LI:SH 00001:0000.200','45','0','200','800','200'
@OldLinkID VARCHAR(100),
@NewLinkID VARCHAR(100),
@ModifiedBy VARCHAR(20),
@StartChainage1 VARCHAR(20),
@EndChainage1 VARCHAR(20),
@EndChainage2 VARCHAR(20),
@StartChainage2 VARCHAR(20)

AS
BEGIN
	--select @OldLinkID,@NewLinkID,@ModifiedBy,@StartChainage1,@EndChainage1,@EndChainage2,@StartChainage2,@YEAR
	DECLARE 
	@strReturn INT
	SET @strReturn = 0 
	SET NOCOUNT ON; 

	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @TABLE NVARCHAR(100)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @COLUMNLIST NVARCHAR(MAX)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Split'
	Declare @ec varchar(20)
	
	DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
			INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
			SELECT TableName,TableType FROM NM.SPLITMERGETABLELIST WHERE SplitColumn='1'
			DECLARE @COUNT INT
			DECLARE @PID NVARCHAR(20)
			DECLARE @PID1 NVARCHAR(20)
			SET @COUNT =1
			DECLARE @INNERCOUNT INT
			
			--select * from @QUERYTEMPTABLE

			WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
				BEGIN
					SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
					IF @TABLE = 'TIS.Trafficstation'
						BEGIN
							INSERT INTO [TIS].[TrafficStation_Audit]
									([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
							SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
							FROM [TIS].[TrafficStation]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE TIS.Trafficstation SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							INSERT INTO [TIS].[TrafficStation_Audit]
									([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
							SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
							FROM [TIS].[TrafficStation]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND LinkCode = @OldLinkID

							UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND LinkCode = @OldLinkID

							UPDATE TIS.Trafficstation SET LinkCode = @NewLinkID 
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND LinkCode = @OldLinkID

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
							FROM tis.AxleLoad S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode
							FROM tis.AxleVolCnt S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
							FROM [TIS].[TrafficVolume] S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
							FROM [TIS].[LinkTrafficDistribution] S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.Accident'
						BEGIN
							INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
							SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
										,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
										,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
							FROM [RSAMS].[Accident]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[Accident] SET OldCode = AccidentCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[Accident] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
							SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
										,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
										,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
							FROM [RSAMS].[Accident]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)  
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[Accident] SET OldCode = AccidentCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[Accident] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVehicles] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVictims] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
						BEGIN
						    
							Declare @TempBlackspotExternal TABLE( 
									[RoadCode] [varchar](20) NULL,[LinkCode] [varchar](30) NULL,[StartChainage] [int] NULL,
									[EndChainage] [int] NULL,[BSType] [varchar](50) NULL,[NoOfInjuredPersons] [int] NULL,
									[NoOfFatalPersons] [int] NULL,[MarkedYear] [int] NULL,[NoofAccident] [int] NULL,
									[StartPointLatitude] [numeric](8, 6) NULL,[StartPointLongitude] [numeric](8, 6) NULL,
									[EndPointLatitude] [numeric](8, 6) NULL,[EndPointLongitude] [numeric](8, 6) NULL,
									[SurveyCode] [varchar](50) NOT NULL,[AddedBy] [varchar](100) NULL,[AddedOn] [datetime] NULL,
									[ModifiedBy] [varchar](100) NULL,[ModifiedOn] [datetime] NULL,[BlackSpotCode] [varchar](50) NULL,
									[SourceType] [varchar](50) NULL,[Direction] [varchar](15) NULL,[OldCode] [varchar](50) NULL)

                            IF NOT EXISTS (SELECT * FROM [RSAMS].[BlackspotExternal]  WHERE StartChainage=@StartChainage1 and EndChainage=@EndChainage1 AND LinkCode = @OldLinkID)
								BEGIN
								INSERT INTO @TempBlackspotExternal
								           ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[BSType],[NoOfInjuredPersons],
										    [NoOfFatalPersons],[MarkedYear],[NoofAccident],[StartPointLatitude],[StartPointLongitude],
											[EndPointLatitude],[EndPointLongitude],[SurveyCode],[AddedBy],[AddedOn],[ModifiedBy],
											[ModifiedOn],[BlackSpotCode],[SourceType],[Direction],[OldCode])
								     SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[BSType],[NoOfInjuredPersons],
										    [NoOfFatalPersons],[MarkedYear],[NoofAccident],[StartPointLatitude],[StartPointLongitude],
											[EndPointLatitude],[EndPointLongitude],[SurveyCode],[AddedBy],[AddedOn],[ModifiedBy],
											[ModifiedOn],[BlackSpotCode],[SourceType],[Direction],[OldCode]
										FROM [RSAMS].[BlackspotExternal] 
										--WHERE StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2) AND LinkCode = @OldLinkID
											--WHERE   StartChainage=@StartChainage1 and EndChainage=@EndChainage2 AND LinkCode = @OldLinkID
											WHERE LinkCode = @OldLinkID AND (StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1))
							                AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)
								END

							INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
							SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
										,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
										,[Direction],[OldCode],@Split
							FROM [RSAMS].[BlackspotExternal]
							WHERE LinkCode = @OldLinkID AND StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)

							UPDATE [RSAMS].[BlackspotExternal] SET OldCode = BlackSpotCode WHERE StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[BlackspotExternal] SET LinkCode = @NewLinkID
							WHERE StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
							AND LinkCode = @OldLinkID

							INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
							SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
										,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
										,[Direction],[OldCode],@Split
							FROM [RSAMS].[BlackspotExternal]
							WHERE LinkCode = @OldLinkID AND (StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[BlackspotExternal] SET OldCode = BlackSpotCode WHERE (StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[BlackspotExternal] SET LinkCode = @NewLinkID
							WHERE (StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

					       --UPDATE [RSAMS].[BlackspotExternal]  SET StartChainage=@StartChainage2 where LinkCode = @NewLinkID

						  
						  set @ec=(select Endchainage from @TempBlackspotExternal)
						  UPDATE [RSAMS].[BlackspotExternal]  SET StartChainage=@StartChainage2 where LinkCode = @NewLinkID and Endchainage=@ec

						  UPDATE @TempBlackspotExternal  SET EndChainage=@EndChainage1 where LinkCode = @OldLinkID 

							INSERT INTO [RSAMS].[BlackspotExternal]
								           ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[BSType],[NoOfInjuredPersons],
										    [NoOfFatalPersons],[MarkedYear],[NoofAccident],[StartPointLatitude],[StartPointLongitude],
											[EndPointLatitude],[EndPointLongitude],[SurveyCode],[AddedBy],[AddedOn],[ModifiedBy],
											[ModifiedOn],[BlackSpotCode],[SourceType],[Direction],[OldCode])
								     SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[BSType],[NoOfInjuredPersons],
										    [NoOfFatalPersons],[MarkedYear],[NoofAccident],[StartPointLatitude],[StartPointLongitude],
											[EndPointLatitude],[EndPointLongitude],[SurveyCode],[AddedBy],[AddedOn],[ModifiedBy],
											[ModifiedOn],[BlackSpotCode],[SourceType],[Direction],[OldCode]
									FROM @TempBlackspotExternal 
										  --WHERE   StartChainage=@StartChainage1 and EndChainage=@EndChainage1 AND LinkCode = @OldLinkID
										--WHERE StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
									--AND LinkCode = @OldLinkID

							UPDATE S SET S.LocCode = A.BlackSpotCode
							FROM [RSAMS].[CntrMeasmt] S
							INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.HazdLocation'
						BEGIN

						Declare @TempHazdLoc TABLE( 					
						[HazdLocCode] [varchar](50) NULL,[RoadCode] [varchar](20) NULL,
						[LinkCode] [varchar](30) NULL,[StartChainage] [int] NULL,[EndChainage] [int] NULL,
						[HazdType] [varchar](50) NULL,[ASI] [decimal](18, 3) NULL,
						[SurveyCode] [varchar](20) NULL,[StartPointLatitude] [numeric](8, 6) NULL,
						[StartPointLongitude] [numeric](8, 6) NULL,[EndPointLatitude] [numeric](8, 6) NULL,
						[EndPointLongitude] [numeric](8, 6) NULL,[AddedBy] [varchar](100) NULL,[AddedOn] [datetime] NULL,
						[ModifiedBy] [varchar](100) NULL,[ModifiedOn] [datetime] NULL,[Direction] [varchar](15) NULL,
						[OldCode] [varchar](50) NULL)	

					 IF NOT EXISTS (SELECT * FROM [RSAMS].[HazdLocation]  WHERE StartChainage=@StartChainage1 and EndChainage=@EndChainage1 AND LinkCode = @OldLinkID)
					   BEGIN
						INSERT INTO @TempHazdLoc
							  ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],
							   [SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],
							   [AddedBy],[AddedOn],[ModifiedBy],[ModifiedOn],[Direction],[OldCode])
						SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],
							   [SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude]
							   ,[AddedBy],[AddedOn],[ModifiedBy],[ModifiedOn],[Direction],[OldCode]
								FROM [RSAMS].[HazdLocation] 
								--WHERE StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2) AND LinkCode = @OldLinkID
								--WHERE   StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2) AND LinkCode = @OldLinkID 
							
								--WHERE StartChainage=@StartChainage1 and EndChainage=@EndChainage2 AND LinkCode = @OldLinkID

								WHERE LinkCode = @OldLinkID AND (StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)
						END

							--select * from @TempHazdLoc 



							INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
							SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
									,[EndPointLongitude],[Direction],[OldCode],@Split
							FROM [RSAMS].[HazdLocation]
							WHERE LinkCode = @OldLinkID AND StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)


				     		UPDATE [RSAMS].[HazdLocation] SET OldCode = HazdLocCode WHERE StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[HazdLocation] SET LinkCode = @NewLinkID
							WHERE StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
							AND LinkCode = @OldLinkID

							INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
							SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
									,[EndPointLongitude],[Direction],[OldCode],@Split
							FROM [RSAMS].[HazdLocation]
							WHERE LinkCode = @OldLinkID AND (StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[HazdLocation] SET OldCode = HazdLocCode 
							WHERE LinkCode = @OldLinkID AND (StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[HazdLocation] SET LinkCode = @NewLinkID
							WHERE LinkCode = @OldLinkID AND (StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)
						
					        --UPDATE [RSAMS].[HazdLocation]  SET StartChainage=@StartChainage2 where LinkCode = @NewLinkID 
						  
						
						  set @ec=(select Endchainage from @TempHazdLoc)
						  UPDATE [RSAMS].[HazdLocation]  SET StartChainage=@StartChainage2 where LinkCode = @NewLinkID and Endchainage=@ec

						  UPDATE @TempHazdLoc  SET EndChainage=@EndChainage1 where LinkCode = @OldLinkID 

						  --select * from @TempHazdLoc

							INSERT INTO  [RSAMS].[HazdLocation]
								  ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],
								   [SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],
								   [AddedBy],[AddedOn],[ModifiedBy],[ModifiedOn],[Direction],[OldCode])
							SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],
								   [SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude]
								   ,[AddedBy],[AddedOn],[ModifiedBy],[ModifiedOn],[Direction],[OldCode]
									FROM @TempHazdLoc 
								    --WHERE StartChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2) AND LinkCode = @OldLinkID
						            --WHERE   StartChainage=@StartChainage1 and EndChainage=@EndChainage1 AND LinkCode = @OldLinkID

                           --UPDATE [RSAMS].[HazdLocation]  SET EndChainage=@EndChainage1 where LinkCode = @OldLinkID
						END
				    ELSE IF @TABLE = 'BMS.LocationDetails'
						BEGIN
						INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],
                                          [Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails]  
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[LocationDetails] SET OldCode = BridgeID WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							--select @NewLinkID '@newLinkId'					
							--SELECT @EndChainage1 '@EndChainage1'
							--select @EndChainage2 '@EndChainage2'

							UPDATE [BMS].[LocationDetails] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],[Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails]  
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)  
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[LocationDetails] SET OldCode = BridgeID WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							--select @NewLinkID '@newLinkId1'
							--SELECT @EndChainage1 '@EndChainage1'

							UPDATE [BMS].[LocationDetails] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID
							
							    UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BCICondRating S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BridgeBoQ S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertCondition S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertInventory S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
						END
					ELSE IF @TABLE = 'BMS.CulvertInventory'
					    BEGIN
							INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND CI.LinkCode = @OldLinkID

							UPDATE [BMS].[CulvertInventory] SET OldCode = CulvertCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[CulvertInventory] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND CI.LinkCode = @OldLinkID

							UPDATE [BMS].[CulvertInventory] SET OldCode = CulvertCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[CulvertInventory] SET LinkCode = @NewLinkID 
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND LinkCode = @OldLinkID

							UPDATE S SET S.CulvertCode = A.CulvertCode
							FROM [BMS].[CulvertCondition] S
							INNER JOIN [BMS].[CulvertInventory] A ON S.CulvertCode = A.OldCode
						END
					SET @COUNT = @COUNT + 1;
				END
END
GO
/****** Object:  StoredProcedure [dbo].[SplitLinksDecAllTablesNeW]    Script Date: 27-01-2025 12:40:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SplitLinksDecAllTablesNeW] 
--EXEC SplitLinksDecAllTablesNew 'LD:NH050:0000.500','LD:NH050:0000.200','45','500','200','0','200'
@OldLinkID VARCHAR(100),
@NewLinkID VARCHAR(100),
@ModifiedBy VARCHAR(20),
@StartChainage1 VARCHAR(20),
@EndChainage1 VARCHAR(20),
@EndChainage2 VARCHAR(20),
@StartChainage2 VARCHAR(20)

AS
BEGIN
	--select @OldLinkID,@NewLinkID,@ModifiedBy,@StartChainage1,@EndChainage1,@EndChainage2,@StartChainage2,@YEAR
	DECLARE 
	@strReturn INT
	SET @strReturn = 0 
	SET NOCOUNT ON; 

	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @TABLE NVARCHAR(100)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @COLUMNLIST NVARCHAR(MAX)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Split'
				
	
	DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
			INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
			SELECT TableName,TableType FROM NM.SPLITMERGETABLELIST WHERE SplitColumn='1'
			DECLARE @COUNT INT
			DECLARE @PID NVARCHAR(20)
			DECLARE @PID1 NVARCHAR(20)
			SET @COUNT =1
			DECLARE @INNERCOUNT INT
			

			WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
				BEGIN
					SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
					IF @TABLE = 'TIS.Trafficstation'
						BEGIN
							INSERT INTO [TIS].[TrafficStation_Audit]
									([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
							SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
							FROM [TIS].[TrafficStation]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE TIS.Trafficstation SET LinkCode = @NewLinkID WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							INSERT INTO [TIS].[TrafficStation_Audit]
									([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
							SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
							FROM [TIS].[TrafficStation]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND LinkCode = @NewLinkID

							UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND LinkCode = @NewLinkID

							UPDATE TIS.Trafficstation SET LinkCode = @NewLinkID WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND LinkCode = @NewLinkID

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
							FROM tis.AxleLoad S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode
							FROM tis.AxleVolCnt S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
							FROM [TIS].[TrafficVolume] S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
							FROM [TIS].[LinkTrafficDistribution] S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode
					END
					ELSE IF @TABLE = 'RSAMS.Accident'
						BEGIN
							INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
							SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
										,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
										,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
							FROM [RSAMS].[Accident]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[Accident] SET OldCode = AccidentCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[Accident] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
										SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
													,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
													,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
										FROM [RSAMS].[Accident]
										WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)  
										AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[Accident] SET OldCode = AccidentCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[Accident] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVehicles] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVictims] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
						BEGIN
							INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
							SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
										,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
										,[Direction],[OldCode],@Split
							FROM [RSAMS].[BlackspotExternal]
							WHERE LinkCode = @OldLinkID AND StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)

							UPDATE [RSAMS].[BlackspotExternal] SET OldCode = BlackSpotCode WHERE StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[BlackspotExternal] SET LinkCode = @NewLinkID
							WHERE StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
							AND LinkCode = @OldLinkID

							INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
							SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
										,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
										,[Direction],[OldCode],@Split
							FROM [RSAMS].[BlackspotExternal]
							WHERE LinkCode = @OldLinkID AND (StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[BlackspotExternal] SET OldCode = BlackSpotCode WHERE (StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[BlackspotExternal] SET LinkCode = @NewLinkID
							WHERE (StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE S SET S.LocCode = A.BlackSpotCode
							FROM [RSAMS].[CntrMeasmt] S
							INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.HazdLocation'
						BEGIN
							INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
							SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
									,[EndPointLongitude],[Direction],[OldCode],@Split
							FROM [RSAMS].[HazdLocation]
							WHERE LinkCode = @OldLinkID AND StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)

							UPDATE [RSAMS].[HazdLocation] SET OldCode = HazdLocCode WHERE StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
							AND LinkCode = @OldLinkID

							UPDATE [RSAMS].[HazdLocation] SET LinkCode = @NewLinkID
							WHERE StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage2)
							AND LinkCode = @OldLinkID

							INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
							SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
									,[EndPointLongitude],[Direction],[OldCode],@Split
							FROM [RSAMS].[HazdLocation]
							WHERE LinkCode = @OldLinkID AND (StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[HazdLocation] SET OldCode = HazdLocCode 
							WHERE LinkCode = @OldLinkID AND (StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[HazdLocation] SET LinkCode = @NewLinkID
							WHERE LinkCode = @OldLinkID AND (StartChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1))
							AND StartChainage != CONVERT(VARCHAR(20),@EndChainage1) AND EndChainage != CONVERT(VARCHAR(20),@EndChainage1)
						END
                    ELSE IF @TABLE = 'BMS.LocationDetails'
						BEGIN
							INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],
                                          [Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails]  
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[LocationDetails] SET OldCode = BridgeID WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[LocationDetails] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

							INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],
                                          [Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                            FROM [BMS].[LocationDetails]  
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)  
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[LocationDetails] SET OldCode = BridgeID WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[LocationDetails] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID
							
							UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BCICondRating S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BridgeBoQ S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertCondition S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertInventory S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
						END
					ELSE IF @TABLE = 'BMS.CulvertInventory'
						BEGIN
							INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
							
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND CI.LinkCode = @OldLinkID

							UPDATE [BMS].[CulvertInventory] SET  OldCode = CulvertCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) AND 
							LinkCode = @OldLinkID

							UPDATE [BMS].[CulvertInventory] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage2) 
							AND LinkCode = @OldLinkID

					INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
							
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
							AND CI.LinkCode = @OldLinkID

							UPDATE [BMS].[CulvertInventory] SET OldCode = CulvertCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

							UPDATE [BMS].[CulvertInventory] SET LinkCode = @NewLinkID
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@EndChainage1) AND CONVERT(VARCHAR(20),@EndChainage1)
							AND LinkCode = @OldLinkID

								UPDATE S SET S.CulvertCode = A.CulvertCode
								FROM BMS.[CulvertCondition] S
								INNER JOIN [BMS].[CulvertInventory] A ON S.CulvertCode = A.OldCode
						END
					SET @COUNT = @COUNT + 1;
				END
END
GO
/****** Object:  StoredProcedure [dbo].[SplitRoadLinkAllTablesNew1]    Script Date: 27-01-2025 12:45:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SplitRoadLinkAllTablesNew1] 
--EXEC SplitRoadLinkAllTablesNew1 'NH056','NH056A','500','1000','0','Increasing',null
--EXEC SplitRoadLinkAllTablesNew1 'NH056','NH056A','500','1000','1','Increasing',0,500
--EXEC SplitRoadLinkAllTablesNew1 'VR_PND06_006','VR_PND06_014','500','2000','False','Increasing',null,null
--EXEC SplitRoadLinkAllTablesNew1 'NH714','NH714A','100100','120100','False','Increasing',null,null
@OldRoadCode VARCHAR(100),
@NewRoadCode VARCHAR(100),
@StartChainage1 VARCHAR(20),
@EndChainage1 VARCHAR(20),
@IsReset VARCHAR(10),
@Direction VARCHAR(20),
@StartChainage2 VARCHAR(20)=null,
@EndChainage2 VARCHAR(20)=NULL

AS
BEGIN
	--select @OldLinkID,@NewLinkID,@ModifiedBy,@StartChainage1,@EndChainage1,@EndChainage2,@StartChainage2,@YEAR
	DECLARE 
	@strReturn INT
	SET @strReturn = 0 
	SET NOCOUNT ON; 

	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @TABLE NVARCHAR(100)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @COLUMNLIST NVARCHAR(MAX)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Split'
	DECLARE @NewLinkID NVARCHAR(50)
	DECLARE @Chainage VARCHAR(20)
	DECLARE @sc varchar(20)

	DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
			INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
			SELECT TableName,TableType FROM NM.SPLITMERGETABLELIST WHERE SplitColumn='1'
			DECLARE @COUNT INT
			DECLARE @PID NVARCHAR(20)
			DECLARE @PID1 NVARCHAR(20)
			SET @COUNT =1
			DECLARE @INNERCOUNT INT


			WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
				BEGIN
					SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
					IF @TABLE = 'TIS.Trafficstation'
						BEGIN
							INSERT INTO [TIS].[TrafficStation_Audit]
										([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
							SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
							FROM [TIS].[TrafficStation]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							UPDATE TIS.Trafficstation SET  OldCode = TrafficStationCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 
							IF	(@IsReset = 'True')
								BEGIN
									UPDATE TIS.Trafficstation 
									SET RoadCode = @NewRoadCode, Chainage = Chainage - @StartChainage1 , LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,TrafficStationCode = REPLACE(TrafficStationCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode

									UPDATE TIS.Trafficstation 
									SET TrafficstationCode = 'TC:'+RoadCode+':' + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode
								END
							ELSE
								BEGIN
									UPDATE TIS.Trafficstation 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')								
									,TrafficStationCode = REPLACE(TrafficStationCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END                          
						

							--Below code is used for updating LinkCode with specific chainage 							
								UPDATE S
								SET LINKCODE=lm.LinkCode
								FROM TIS.Trafficstation S
								INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
								WHERE S.RoadCode=@NewRoadCode
								AND chainage BETWEEN CONVERT(VARCHAR(20),StartChainage) AND CONVERT(VARCHAR(20),EndChainage)

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode, S.RoadCode = A.RoadCode
							FROM tis.AxleLoad S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode
							FROM tis.AxleVolCnt S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode, S.RoadCode = A.RoadCode
							FROM [TIS].[TrafficVolume] S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
							FROM [TIS].[LinkTrafficDistribution] S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.Accident'
						BEGIN
							INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
							SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
										,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
										,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
							FROM [RSAMS].[Accident]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							UPDATE RSAMS.Accident SET  OldCode = AccidentCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 
							IF	(@IsReset = 'True')
								BEGIN
									UPDATE [RSAMS].[Accident] 
									SET RoadCode = @NewRoadCode, Chainage = Chainage - @StartChainage2 , LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,AccidentCode = REPLACE(AccidentCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END
							ELSE
								BEGIN
									UPDATE [RSAMS].[Accident] 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,AccidentCode = REPLACE(AccidentCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode

									UPDATE [RSAMS].[Accident] 
									SET AccidentCode = 'AC:'+RoadCode+':' + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode
								END

							--Below code is used for updating LinkCode with specific chainage 							
								UPDATE S
								SET LINKCODE=lm.LinkCode
								FROM [RSAMS].[Accident] S
								INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
								WHERE S.RoadCode=@NewRoadCode
								AND chainage BETWEEN CONVERT(VARCHAR(20),StartChainage) AND CONVERT(VARCHAR(20),EndChainage)

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVehicles] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVictims] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
						BEGIN
							INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
							SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
										,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
										,[Direction],[OldCode],@Split
							FROM [RSAMS].[BlackspotExternal]
							WHERE RoadCode = @OldRoadCode AND StartChainage >= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[BlackspotExternal] SET  OldCode = BlackSpotCode WHERE StartChainage >= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 

							IF	(@IsReset = 'True')
								BEGIN
									UPDATE [RSAMS].[BlackspotExternal]
									SET RoadCode = @NewRoadCode, StartChainage = StartChainage - @StartChainage1,  EndChainage = EndChainage - @EndChainage2, LinkCode = @NewLinkID + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,BlackSpotCode = REPLACE(BlackSpotCode,@OldRoadCode,@NewRoadCode)
									WHERE StartChainage >= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode AND Direction=@Direction
								END
							ELSE
								BEGIN
									UPDATE [RSAMS].[BlackspotExternal] 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,BlackSpotCode = REPLACE(BlackSpotCode,@OldRoadCode,@NewRoadCode)
									WHERE StartChainage >= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode AND Direction=@Direction
								END

							    UPDATE S
								SET LINKCODE=lm.LinkCode
								FROM [RSAMS].[BlackspotExternal]  S
								INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
								WHERE S.RoadCode=@NewRoadCode
								AND S.StartChainage >= CONVERT(VARCHAR(20),lm.StartChainage) AND S.EndChainage <= CONVERT(VARCHAR(20),lm.EndChainage) 


								UPDATE S SET S.LocCode = A.BlackSpotCode
								FROM [RSAMS].[CntrMeasmt] S
								INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.HazdLocation'
						BEGIN
							INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
							SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
									,[EndPointLongitude],[Direction],[OldCode],@Split
							FROM [RSAMS].[HazdLocation]
							WHERE RoadCode = @OldRoadCode AND StartChainage >= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[HazdLocation] SET  OldCode = HazdLocCode WHERE StartChainage >= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 

							IF	(@IsReset = 'True')
								BEGIN
									UPDATE [RSAMS].[HazdLocation]
									SET RoadCode = @NewRoadCode, StartChainage = StartChainage - @StartChainage1,  EndChainage = EndChainage - @EndChainage2, LinkCode = @NewLinkID + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,HazdLocCode = REPLACE(HazdLocCode,@OldRoadCode,@NewRoadCode)
									WHERE StartChainage >= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode	AND Direction=@Direction							
								END
							ELSE
								BEGIN
									UPDATE [RSAMS].[HazdLocation] 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,HazdLocCode = REPLACE(HazdLocCode,@OldRoadCode,@NewRoadCode)
									WHERE StartChainage >= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage <= CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode	 AND Direction=@Direction														
							     END

								UPDATE S
								SET LINKCODE=lm.LinkCode
								FROM [RSAMS].[HazdLocation] S
								INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
								WHERE S.RoadCode=@NewRoadCode
								AND S.StartChainage >= CONVERT(VARCHAR(20),lm.StartChainage) AND S.EndChainage <= CONVERT(VARCHAR(20),lm.EndChainage) 

								UPDATE S SET S.LocCode = A.HazdLocCode
								FROM [RSAMS].[CntrMeasmt] S
								INNER JOIN [RSAMS].[HazdLocation] A ON S.LocCode = A.OldCode
						END
                    ELSE IF @TABLE = 'BMS.LocationDetails'
						BEGIN
						     INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],
                                          [Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails]  
						     							
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							UPDATE [BMS].[LocationDetails] SET  OldCode = BridgeId WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode
							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 

						   IF (@IsReset = 'True')
								BEGIN
									UPDATE [BMS].[LocationDetails] 
									SET RoadCode = @NewRoadCode, Chainage = Chainage - @StartChainage2 , LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,BridgeID = REPLACE(BridgeID,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END
							ELSE
								BEGIN
									UPDATE [BMS].[LocationDetails]
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,BridgeID = REPLACE(BridgeID,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END

							 --  Update [BMS].[LocationDetails] 
								--SET
								--LinkCode= CASE   WHEN  (StartChainage <= CONVERT(VARCHAR(20),Chainage) AND EndChainage >= CONVERT(VARCHAR(20),Chainage))
								--				 THEN  (@NewLinkID+  FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')) 
								--		  END
								--  From [BMS].[LocationDetails]  TF INNER  JOIN
								-- NM.LinkMaster  LM ON LM.RoadCode=TF.RoadCode where TF.RoadCode=@NewRoadCode
								UPDATE S
								SET LINKCODE=lm.LinkCode
								FROM [BMS].[LocationDetails] S
								INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
								WHERE S.RoadCode=@NewRoadCode
								AND chainage BETWEEN CONVERT(VARCHAR(20),StartChainage) AND CONVERT(VARCHAR(20),EndChainage)
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BCICondRating S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BridgeBoQ S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertCondition S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertInventory S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

						END
					ELSE IF @TABLE = 'BMS.CulvertInventory'
						BEGIN
							INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							UPDATE BMS.CulvertInventory SET  OldCode = CulvertCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 
							IF	(@IsReset = 'True')
								BEGIN
									UPDATE BMS.CulvertInventory 
									SET RoadCode = @NewRoadCode, Chainage = Chainage - @StartChainage1 , LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,CulvertCode = REPLACE(CulvertCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode

									UPDATE BMS.CulvertInventory
									SET CulvertCode = 'CI:'+RoadCode+':' + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode
								END
							ELSE
								BEGIN
									UPDATE BMS.CulvertInventory
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')								
									,CulvertCode = REPLACE(CulvertCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END 
						
						--Below code is used for updating LinkCode with specific chainage 							
								UPDATE S
								SET LINKCODE=lm.LinkCode
								FROM BMS.CulvertInventory S
								INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
								WHERE S.RoadCode=@NewRoadCode
								AND chainage BETWEEN CONVERT(VARCHAR(20),StartChainage) AND CONVERT(VARCHAR(20),EndChainage)  

							UPDATE S SET S.CulvertCode = A.CulvertCode
							FROM BMS.CulvertCondition S
							INNER JOIN BMS.CulvertInventory A ON S.CulvertCode = A.OldCode
						END
					SET @COUNT = @COUNT + 1;
				END
				SELECT @strReturn
END
GO
/****** Object:  StoredProcedure [dbo].[SplitRoadLinkDecAllTablesNew1]    Script Date: 27-01-2025 12:57:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SplitRoadLinkDecAllTablesNew1] 
--EXEC SplitRoadLinkDecAllTables1 'NH057','NH57A','1000','400',0,'Decreasing',NULL,NULL
--EXEC SplitRoadLinkDecAllTables1 'NH057','NH57A','1000','400',1,'Decreasing',600,0
--EXEC SplitRoadLinkDecAllTables1 'NH056','NH056A','1000','500',1,'Decreasing',0,500
@OldRoadCode VARCHAR(25),
@NewRoadCode VARCHAR(25),
@StartChainage1 VARCHAR(20),
@EndChainage1 VARCHAR(20),
@IsReset VARCHAR(10),
@Direction VARCHAR(20),
@StartChainage2 VARCHAR(20)=null,
@EndChainage2 VARCHAR(20)=NULL

AS
BEGIN
	--select @OldLinkID,@NewLinkID,@ModifiedBy,@StartChainage1,@EndChainage1,@EndChainage2,@StartChainage2,@YEAR
	DECLARE 
	@strReturn INT
	SET @strReturn = 0 
	SET NOCOUNT ON; 

	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @TABLE NVARCHAR(100)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @COLUMNLIST NVARCHAR(MAX)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Split'
	DECLARE @NewLinkID NVARCHAR(50)
	DECLARE @Chainage VARCHAR(20)
				
	
	DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
			INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
			SELECT TableName,TableType FROM NM.SPLITMERGETABLELIST WHERE SplitColumn='1'
			DECLARE @COUNT INT
			DECLARE @PID NVARCHAR(20)
			DECLARE @PID1 NVARCHAR(20)
			SET @COUNT =1
			DECLARE @INNERCOUNT INT
			
			WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
				BEGIN
					SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
					IF @TABLE = 'TIS.Trafficstation'
						BEGIN
							INSERT INTO [TIS].[TrafficStation_Audit]
										([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
							SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
							FROM [TIS].[TrafficStation]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							UPDATE TIS.Trafficstation SET  OldCode = TrafficStationCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 
							IF	(@IsReset = 'True')
								BEGIN
									UPDATE TIS.Trafficstation 
									SET RoadCode = @NewRoadCode, Chainage = Chainage - @EndChainage1 , LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									, TrafficStationCode = REPLACE(TrafficStationCode,@OLDRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode

									UPDATE TIS.Trafficstation 
									SET TrafficstationCode = 'TC:'+RoadCode+':' + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode
								END
							ELSE
								BEGIN
									UPDATE TIS.Trafficstation 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									, TrafficStationCode = REPLACE(TrafficStationCode,@OLDRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode, S.RoadCode = A.RoadCode
							FROM tis.AxleLoad S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode
							FROM tis.AxleVolCnt S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode, S.RoadCode = A.RoadCode
							FROM [TIS].[TrafficVolume] S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

							UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
							FROM [TIS].[LinkTrafficDistribution] S
							INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.Accident'
						BEGIN
							INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
							SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
										,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
										,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
							FROM [RSAMS].[Accident]
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							UPDATE RSAMS.Accident SET  OldCode = AccidentCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 
							IF	(@IsReset = 'True')
								BEGIN
									UPDATE [RSAMS].[Accident] 
									SET RoadCode = @NewRoadCode, Chainage = Chainage - @EndChainage1 , LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,AccidentCode = REPLACE(AccidentCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode

								    UPDATE [RSAMS].[Accident] 
									SET AccidentCode = 'AC:'+RoadCode+':' + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode
								END
							ELSE
								BEGIN
									UPDATE [RSAMS].[Accident] 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,AccidentCode = REPLACE(AccidentCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVehicles] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode

							UPDATE S SET S.AccidentCode = A.AccidentCode
							FROM [RSAMS].[AccVictims] S
							INNER JOIN [RSAMS].[Accident]  A ON S.AccidentCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
						BEGIN
							INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
							SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
										,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
										,[Direction],[OldCode],@Split
							FROM [RSAMS].[BlackspotExternal]
							WHERE RoadCode = @OldRoadCode AND StartChainage <= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[BlackspotExternal] SET  OldCode = BlackSpotCode WHERE StartChainage <= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 

							IF	(@IsReset = 'True')
								BEGIN
									UPDATE [RSAMS].[BlackspotExternal]
									SET RoadCode = @NewRoadCode, StartChainage = StartChainage - @EndChainage1,  EndChainage = EndChainage - @EndChainage2, LinkCode = @NewLinkID + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,BlackSpotCode = REPLACE(BlackSpotCode,@OldRoadCode,@NewRoadCode)
									WHERE StartChainage <= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode AND Direction=@Direction

									UPDATE [RSAMS].[BlackspotExternal] 
									SET BlackSpotCode = 'BS:'+RoadCode+':' + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode
								END
							ELSE
								BEGIN
									UPDATE [RSAMS].[BlackspotExternal] 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,BlackSpotCode = REPLACE(BlackSpotCode,@OldRoadCode,@NewRoadCode)
									WHERE StartChainage <= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode AND Direction=@Direction
								END

								UPDATE S
								SET LINKCODE=lm.LinkCode
								FROM [RSAMS].[BlackspotExternal]  S
								INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
								WHERE S.RoadCode=@NewRoadCode
								AND S.StartChainage >= CONVERT(VARCHAR(20),lm.StartChainage) AND S.EndChainage <= CONVERT(VARCHAR(20),lm.EndChainage) 

								UPDATE S SET S.LocCode = A.BlackSpotCode
								FROM [RSAMS].[CntrMeasmt] S
								INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode
						END
					ELSE IF @TABLE = 'RSAMS.HazdLocation'
						BEGIN
							INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
							SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
									,[EndPointLongitude],[Direction],[OldCode],@Split
							FROM [RSAMS].[HazdLocation]
							WHERE RoadCode = @OldRoadCode AND StartChainage <= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1)

							UPDATE [RSAMS].[HazdLocation] SET  OldCode = HazdLocCode WHERE StartChainage <= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 

							IF	(@IsReset = 'True')
								BEGIN
									UPDATE [RSAMS].[HazdLocation]
									SET RoadCode = @NewRoadCode, StartChainage = StartChainage - @EndChainage1,  EndChainage = EndChainage - @EndChainage2, LinkCode = @NewLinkID + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,HazdLocCode = REPLACE(HazdLocCode,@OldRoadCode,@NewRoadCode)
									WHERE StartChainage <= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode AND Direction=@Direction

									UPDATE [RSAMS].[HazdLocation]
									SET HazdLocCode = 'HZ:'+RoadCode+':' + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode		
								END
							ELSE
								BEGIN
									UPDATE [RSAMS].[HazdLocation] 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((StartChainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,HazdLocCode = REPLACE(HazdLocCode,@OldRoadCode,@NewRoadCode)
									WHERE StartChainage <= CONVERT(VARCHAR(20),@StartChainage1) AND EndChainage >= CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode AND Direction=@Direction
								END

							    UPDATE S
								SET LINKCODE=lm.LinkCode
								FROM [RSAMS].[HazdLocation] S
								INNER JOIN NM.LINKMASTER lm ON S.RoadCode=lm.RoadCode
								WHERE S.RoadCode=@NewRoadCode
								AND S.StartChainage >= CONVERT(VARCHAR(20),lm.StartChainage) AND S.EndChainage <= CONVERT(VARCHAR(20),lm.EndChainage) 


								UPDATE S SET S.LocCode = A.HazdLocCode
								FROM [RSAMS].[CntrMeasmt] S
								INNER JOIN [RSAMS].[HazdLocation] A ON S.LocCode = A.OldCode
						END
                    ELSE IF @TABLE = 'BMS.LocationDetails'
						BEGIN
							INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],
                                          [Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails]  
							WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							UPDATE [BMS].[LocationDetails] SET  OldCode = BridgeId WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 
							IF	(@IsReset = 'True')
								BEGIN
									UPDATE [BMS].[LocationDetails]  
									SET RoadCode = @NewRoadCode, Chainage = Chainage - @EndChainage1 , LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,BridgeId = REPLACE(BridgeId,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode

									UPDATE [BMS].[LocationDetails]
									SET BridgeID = 'BR:'+RoadCode+':' + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode	
								END
							ELSE
								BEGIN
									UPDATE [BMS].[LocationDetails]  
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,BridgeId = REPLACE(BridgeId,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END						

							    UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BCICondRating S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BridgeBoQ S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertCondition S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertInventory S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
						END
					 ELSE IF @TABLE = 'BMS.CulvertInventory'
						BEGIN
							INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
							
							  WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							UPDATE [BMS].[CulvertInventory] SET  OldCode = CulvertCode WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) AND RoadCode = @OldRoadCode

							SET @NewLinkID = 'LI:' + @NewRoadCode + ':' 
							IF	(@IsReset = 'True')
								BEGIN
									UPDATE [BMS].[CulvertInventory]  
									SET RoadCode = @NewRoadCode, Chainage = Chainage - @EndChainage1 , LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,CulvertCode = REPLACE(CulvertCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode

									UPDATE [BMS].[CulvertInventory]
									SET CulvertCode = 'CI:'+RoadCode+':' + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									WHERE RoadCode = @NewRoadCode	
								END
							ELSE
								BEGIN
									UPDATE [BMS].[CulvertInventory] 
									SET RoadCode = @NewRoadCode, LinkCode = @NewLinkID + FORMAT((Chainage/CONVERT(decimal(11,3), 1000)),'#0000.000')
									,CulvertCode = REPLACE(CulvertCode,@OldRoadCode,@NewRoadCode)
									WHERE Chainage BETWEEN CONVERT(VARCHAR(20),@StartChainage1) AND CONVERT(VARCHAR(20),@EndChainage1) 
									AND RoadCode = @OldRoadCode
								END	

								UPDATE S SET S.CulvertCode = A.CulvertCode
								FROM BMS.[CulvertCondition] S
								INNER JOIN [BMS].[CulvertInventory] A ON S.CulvertCode = A.OldCode
						END
					SET @COUNT = @COUNT + 1;
				END
				SELECT @strReturn
END
GO
/****** Object:  StoredProcedure [dbo].[UpdateTablesNewByRoadCalibration]    Script Date: 27-01-2025 12:59:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[UpdateTablesNewByRoadCalibration]
--exec [dbo].[UpdateTablesNewByRoadCalibration] 'NH_MNR',1000,'Inc'
(
@roadCode VARCHAR(25),
@endChainage VARCHAR(20)=null,
@changeType VARCHAR(10)=NULL
)
AS
BEGIN
	DECLARE 
	@strReturn INT
	SET @strReturn = 0 
	SET NOCOUNT ON; 

	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @TABLE NVARCHAR(100)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @COLUMNLIST NVARCHAR(MAX)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Calib'
	DECLARE @NewLinkID NVARCHAR(MAX)
	DECLARE @NewLinkQuery NVARCHAR(MAX)
	DECLARE @Chainage VARCHAR(20)
	DECLARE @SChainage NVARCHAR(MAX)
	DECLARE @EChainage NVARCHAR(MAX)
	DECLARE @Direct NVARCHAR(MAX)
	DECLARE @SDirect NVARCHAR(MAX)
	DECLARE @SQuery NVARCHAR(MAX)
	DECLARE @EQuery NVARCHAR(MAX)
	DECLARE @COLUMNDIRECTIONSIDE NVARCHAR(MAX)
	DECLARE @CheckDirectionSide NVARCHAR(MAX)
	DECLARE @SIGN NVARCHAR(MAX)
	DECLARE @Code NVARCHAR(MAX)
	DECLARE @Seq NVARCHAR(MAX)


	DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
			INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
			SELECT TableName,TableType FROM NM.SPLITMERGETABLELIST WHERE SplitColumn='1' ORDER BY TableName
			DECLARE @COUNT INT
			DECLARE @PID NVARCHAR(20)
			DECLARE @PID1 NVARCHAR(20)
			SET @COUNT =1
			DECLARE @INNERCOUNT INT
			--SELECT * FROM @QUERYTEMPTABLE
			WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
				BEGIN
					SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
					IF @TABLE = 'RSAMS.Accident'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.Accident WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
									SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
											FROM [RSAMS].[Accident]
									WHERE RoadCode = @roadCode
									UPDATE RSAMS.Accident SET OldCode = AccidentCode WHERE RoadCode = @roadCode

									IF OBJECT_ID('tempdb..#tempTable1') IS NOT NULL
									DROP TABLE #tempTable1
									CREATE TABLE #tempTable1(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TID INT)
									INSERT INTO #tempTable1 SELECT AccidentId FROM RSAMS.Accident WHERE RoadCode = @roadCode
									--SELECT * FROM #tempTable1
									SET @INNERCOUNT =1
									WHILE (@INNERCOUNT <= (SELECT MAX(ID) FROM #tempTable1))
										BEGIN
											SELECT @PID = TID FROM #tempTable1 WHERE ID = @INNERCOUNT
											IF @changeType = 'Inc'
												BEGIN
													SET @SChainage = (SELECT Chainage + @endChainage FROM [RSAMS].[Accident] WHERE AccidentId = @PID)
												END
											ELSE 
												BEGIN
													SET @SChainage = (SELECT Chainage - @endChainage FROM [RSAMS].[Accident] WHERE AccidentId = @PID)
												END	
											
											SET @NewLinkID = (SELECT LinkCode FROM NM.LinkMaster WHERE RoadCode = @roadCode AND @SChainage BETWEEN StartChainage AND EndChainage AND Direction='Increasing')
											--SELECT @SChainage,@NewLinkID
											IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
											DROP TABLE #tempTable
											CREATE TABLE #tempTable(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TName VARCHAR(MAX))
											SET @TABLE = (SELECT AccidentCode FROM [RSAMS].[Accident] WHERE AccidentId = @PID)
											INSERT INTO #tempTable
											SELECT (Items) FROM dbo.Split(@TABLE, ':')
											SELECT @Code = TName FROM #tempTable WHERE ID =1
											SELECT @Seq = TName FROM #tempTable WHERE ID =4
											SET @Chainage= (SELECT RIGHT('000'+CONVERT(VARCHAR, CONVERT(DECIMAL(18,3),(@SChainage/1000.00))),8))
											--SELECT @Code, @Seq,@Chainage
											--SELECT @Code + ':' + @roadCode + ':' + @Chainage + ':' + @Seq 'NewCode'
											UPDATE [RSAMS].[Accident] SET AccidentCode = @Code + ':' + @roadCode + ':' + @Chainage + ':' + @Seq, LinkCode = @NewLinkID, Chainage = @SChainage WHERE AccidentId = @PID
											
											UPDATE S SET S.AccidentCode = A.AccidentCode
											FROM [RSAMS].[AccVehicles] S
											INNER JOIN [RSAMS].[Accident] A ON S.AccidentCode = A.OldCode

											UPDATE S SET S.AccidentCode = A.AccidentCode
											FROM [RSAMS].[AccVictims] S
											INNER JOIN [RSAMS].[Accident] A ON S.AccidentCode = A.OldCode

											SET @INNERCOUNT = @INNERCOUNT + 1
										END
								END
						END
					ELSE IF @TABLE = 'TIS.Trafficstation'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM TIS.Trafficstation WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [TIS].[TrafficStation_Audit]
											   ([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
									SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
									FROM [TIS].[TrafficStation]
									WHERE RoadCode = @roadCode
									UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE RoadCode = @roadCode

									IF OBJECT_ID('tempdb..#tempTable2') IS NOT NULL
									DROP TABLE #tempTable2
									CREATE TABLE #tempTable2(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TID INT)
									INSERT INTO #tempTable2 SELECT TrafficStationId FROM TIS.Trafficstation WHERE RoadCode = @roadCode
									--SELECT * FROM #tempTable1
									SET @INNERCOUNT =1
									WHILE (@INNERCOUNT <= (SELECT MAX(ID) FROM #tempTable2))
										BEGIN
											SELECT @PID = TID FROM #tempTable2 WHERE ID = @INNERCOUNT
											IF @changeType = 'Inc'
												BEGIN
													SET @SChainage = (SELECT Chainage + @endChainage FROM TIS.Trafficstation WHERE TrafficStationId = @PID)
												END
											ELSE 
												BEGIN
													SET @SChainage = (SELECT Chainage - @endChainage FROM TIS.Trafficstation WHERE TrafficStationId = @PID)
												END	
											
											SET @NewLinkID = (SELECT LinkCode FROM NM.LinkMaster WHERE RoadCode = @roadCode AND @SChainage BETWEEN StartChainage AND EndChainage AND Direction='Increasing')
											--SELECT @SChainage,@NewLinkID
											IF OBJECT_ID('tempdb..#tempTableTraffic') IS NOT NULL
											DROP TABLE #tempTableTraffic
											CREATE TABLE #tempTableTraffic(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TName VARCHAR(MAX))
											SET @TABLE = (SELECT TrafficStationCode FROM TIS.Trafficstation WHERE TrafficStationId = @PID)
											INSERT INTO #tempTableTraffic
											SELECT (Items) FROM dbo.Split(@TABLE, ':')
											SELECT @Code = TName FROM #tempTableTraffic WHERE ID =1
											--SELECT @Seq = TName FROM #tempTable WHERE ID =4
											SET @Chainage= (SELECT RIGHT('000'+CONVERT(VARCHAR, CONVERT(DECIMAL(18,3),(@SChainage/1000.00))),8))
											--SELECT @Code, @Seq,@Chainage
											--SELECT @Code + ':' + @roadCode + ':' + @Chainage + ':' + @Seq 'NewCode'
											UPDATE TIS.Trafficstation SET TrafficStationCode = @Code + ':' + @roadCode + ':' + @Chainage, LinkCode = @NewLinkID, Chainage = @SChainage WHERE TrafficStationId = @PID
											SET @INNERCOUNT = @INNERCOUNT + 1
										END
										UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
										FROM tis.AxleLoad S
										INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

										UPDATE S SET S.TrafficStationCode = A.TrafficStationCode
										FROM tis.AxleVolCnt S
										INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

										UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
										FROM [TIS].[TrafficVolume] S
										INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

										UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
										FROM [TIS].[LinkTrafficDistribution] S
										INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode
								END
						END
					ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.BlackspotExternal WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
									SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],@Split
									FROM [RSAMS].[BlackspotExternal]
									WHERE RoadCode = @roadCode
									
									UPDATE RSAMS.BlackspotExternal SET OldCode = BlackSpotCode WHERE RoadCode = @roadCode

									IF OBJECT_ID('tempdb..#tempTable3') IS NOT NULL
									DROP TABLE #tempTable3
									CREATE TABLE #tempTable3(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TID INT)
									INSERT INTO #tempTable3 SELECT BlackspotId FROM RSAMS.BlackspotExternal WHERE RoadCode = @roadCode
									--SELECT * FROM #tempTable1
									SET @INNERCOUNT =1
									WHILE (@INNERCOUNT <= (SELECT MAX(ID) FROM #tempTable3))
										BEGIN
											SELECT @PID = TID FROM #tempTable3 WHERE ID = @INNERCOUNT
											IF @changeType = 'Inc'
												BEGIN
													SET @SChainage = (SELECT StartChainage + @endChainage FROM RSAMS.BlackspotExternal WHERE BlackspotId = @PID)
													SET @EChainage = (SELECT EndChainage + @endChainage FROM RSAMS.BlackspotExternal WHERE BlackspotId = @PID)
												END
											ELSE 
												BEGIN
													SET @SChainage = (SELECT StartChainage - @endChainage FROM RSAMS.BlackspotExternal WHERE BlackspotId = @PID)
													SET @EChainage = (SELECT EndChainage - @endChainage FROM RSAMS.BlackspotExternal WHERE BlackspotId = @PID)
												END	
											
											SET @NewLinkID = (SELECT LinkCode FROM NM.LinkMaster WHERE RoadCode = @roadCode AND StartChainage >= @SChainage AND EndChainage <= @EChainage AND Direction='Increasing')

											IF @NewLinkID = '' OR @NewLinkID IS NULL
												BEGIN
													SET @NewLinkID = (SELECT LinkCode FROM NM.LinkMaster WHERE RoadCode = @roadCode AND StartChainage <= @SChainage AND EndChainage >= @EChainage AND Direction='Increasing')
												END
											--SELECT @SChainage,@NewLinkID
											IF OBJECT_ID('tempdb..#tempTableBlackspot') IS NOT NULL
											DROP TABLE #tempTableBlackspot
											CREATE TABLE #tempTableBlackspot(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TName VARCHAR(MAX))
											SET @TABLE = (SELECT BlackSpotCode FROM RSAMS.BlackspotExternal WHERE BlackspotId = @PID)
											INSERT INTO #tempTableBlackspot
											SELECT (Items) FROM dbo.Split(@TABLE, ':')
											SELECT @Code = TName FROM #tempTableBlackspot WHERE ID =1
											--SELECT @Seq = TName FROM #tempTable WHERE ID =4
											SET @Chainage= (SELECT RIGHT('000'+CONVERT(VARCHAR, CONVERT(DECIMAL(18,3),(@SChainage/1000.00))),8))
											--SELECT @Code + ':' + @roadCode + ':' + @Chainage
											UPDATE RSAMS.BlackspotExternal SET BlackSpotCode = @Code + ':' + @roadCode + ':' + @Chainage, LinkCode = @NewLinkID, StartChainage = @SChainage, EndChainage = @EChainage WHERE BlackspotId = @PID
											
											UPDATE S SET S.LocCode = A.BlackSpotCode
											FROM [RSAMS].[CntrMeasmt] S
											INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode

											SET @INNERCOUNT = @INNERCOUNT + 1
										END
								END
						END
					ELSE IF @TABLE = 'RSAMS.HazdLocation'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.HazdLocation WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
									SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
											,[EndPointLongitude],[Direction],[OldCode],@Split
									FROM [RSAMS].[HazdLocation]
									WHERE RoadCode = @roadCode
									
									UPDATE RSAMS.HazdLocation SET OldCode = HazdLocCode WHERE RoadCode = @roadCode

									IF OBJECT_ID('tempdb..#tempTable4') IS NOT NULL
									DROP TABLE #tempTable4
									CREATE TABLE #tempTable4(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TID INT)
									INSERT INTO #tempTable4 SELECT HazdLocId FROM RSAMS.HazdLocation WHERE RoadCode = @roadCode
									--SELECT * FROM #tempTable1
									SET @INNERCOUNT =1
									WHILE (@INNERCOUNT <= (SELECT MAX(ID) FROM #tempTable4))
										BEGIN
											SELECT @PID = TID FROM #tempTable4 WHERE ID = @INNERCOUNT
											IF @changeType = 'Inc'
												BEGIN
													SET @SChainage = (SELECT StartChainage + @endChainage FROM RSAMS.HazdLocation WHERE HazdLocId = @PID)
													SET @EChainage = (SELECT EndChainage + @endChainage FROM RSAMS.HazdLocation WHERE HazdLocId = @PID)
												END
											ELSE 
												BEGIN
													SET @SChainage = (SELECT StartChainage - @endChainage FROM RSAMS.HazdLocation WHERE HazdLocId = @PID)
													SET @EChainage = (SELECT EndChainage - @endChainage FROM RSAMS.HazdLocation WHERE HazdLocId = @PID)
												END	
											
											SET @NewLinkID = (SELECT LinkCode FROM NM.LinkMaster WHERE RoadCode = @roadCode AND StartChainage >= @SChainage AND EndChainage <= @EChainage AND Direction='Increasing')

											IF @NewLinkID = '' OR @NewLinkID IS NULL
												BEGIN
													SET @NewLinkID = (SELECT LinkCode FROM NM.LinkMaster WHERE RoadCode = @roadCode AND StartChainage <= @SChainage AND EndChainage >= @EChainage AND Direction='Increasing')
												END
											--SELECT @SChainage,@NewLinkID
											IF OBJECT_ID('tempdb..#tempTableHazd') IS NOT NULL
											DROP TABLE #tempTableHazd
											CREATE TABLE #tempTableHazd(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TName VARCHAR(MAX))
											SET @TABLE = (SELECT HazdLocCode FROM RSAMS.HazdLocation WHERE HazdLocId = @PID)
											INSERT INTO #tempTableHazd
											SELECT (Items) FROM dbo.Split(@TABLE, ':')
											SELECT @Code = TName FROM #tempTableHazd WHERE ID =1
											--SELECT @Seq = TName FROM #tempTable WHERE ID =4
											SET @Chainage= (SELECT RIGHT('000'+CONVERT(VARCHAR, CONVERT(DECIMAL(18,3),(@SChainage/1000.00))),8))
											--SELECT @Code + ':' + @roadCode + ':' + @Chainage
											UPDATE RSAMS.HazdLocation SET HazdLocCode = @Code + ':' + @roadCode + ':' + @Chainage, LinkCode = @NewLinkID, StartChainage = @SChainage, EndChainage = @EChainage WHERE HazdLocId = @PID
											
											UPDATE S SET S.LocCode = A.HazdLocCode
											FROM [RSAMS].[CntrMeasmt] S
											INNER JOIN RSAMS.HazdLocation A ON S.LocCode = A.OldCode

											SET @INNERCOUNT = @INNERCOUNT + 1
										END
								END
						END
                    ELSE IF @TABLE = 'BMS.LocationDetails'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM BMS.LocationDetails WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],
                                          [Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails]  
									WHERE RoadCode = @roadCode
									UPDATE BMS.LocationDetails SET OldCode = BridgeID WHERE RoadCode = @roadCode

									IF OBJECT_ID('tempdb..#tempTable5') IS NOT NULL
									DROP TABLE #tempTable5
									CREATE TABLE #tempTable5(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TID INT)
									INSERT INTO #tempTable5 SELECT LocationId FROM BMS.LocationDetails WHERE RoadCode = @roadCode
									--SELECT * FROM #tempTable5
									SET @INNERCOUNT =1
									WHILE (@INNERCOUNT <= (SELECT MAX(ID) FROM #tempTable5))
										BEGIN
											SELECT @PID = TID FROM #tempTable5 WHERE ID = @INNERCOUNT
											IF @changeType = 'Inc'
												BEGIN
													SET @SChainage = (SELECT Chainage + @endChainage FROM BMS.LocationDetails WHERE LocationId = @PID)
												END
											ELSE 
												BEGIN
													SET @SChainage = (SELECT Chainage - @endChainage FROM BMS.LocationDetails WHERE LocationId = @PID)
												END	
											
											SET @NewLinkID = (SELECT LinkCode FROM NM.LinkMaster WHERE RoadCode = @roadCode AND @SChainage BETWEEN StartChainage AND EndChainage AND Direction='Increasing')
											--SELECT @SChainage,@NewLinkID
											IF OBJECT_ID('tempdb..#tempTableLocationDetails') IS NOT NULL
											DROP TABLE #tempTableLocationDetails
											CREATE TABLE #tempTableLocationDetails(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TName VARCHAR(MAX))
											SET @TABLE = (SELECT BridgeID FROM BMS.LocationDetails WHERE LocationId = @PID)

											SELECT @Table 'table value'

											INSERT INTO #tempTableLocationDetails
											SELECT (Items) FROM dbo.Split(@TABLE, ':')
											SELECT @Code = TName FROM #tempTableLocationDetails WHERE ID =1  
											--SELECT @Seq = TName FROM #tempTableLocationDetails WHERE ID =4   
											SET @Chainage= (SELECT RIGHT('000'+CONVERT(VARCHAR, CONVERT(DECIMAL(18,3),(@SChainage/1000.00))),8))
										
										--select * from #tempTableLocationDetails
										--    select @PID
										--	SELECT @Code, @Seq,@Chainage
										--select @Code '@Code'
										--select @roadCode '@roadCode'
										--select @Chainage '@Chainage'
										--select @Seq '@Seq'
										--	SELECT @Code + ':' + @roadCode + ':' + @Chainage + ':'  'NewCode'
											
								--UPDATE BMS.LocationDetails SET BridgeID = @Code + ':' + @roadCode + ':' + @Chainage + ':' + @Seq, LinkCode = @NewLinkID, Chainage = @SChainage WHERE LocationId = @PID
								UPDATE BMS.LocationDetails SET BridgeID = @Code + ':' + @roadCode + ':' + @Chainage , LinkCode = @NewLinkID, Chainage = @SChainage WHERE LocationId = @PID
											
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BCICondRating S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BridgeBoQ S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertCondition S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertInventory S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode


											SET @INNERCOUNT = @INNERCOUNT + 1
										END
								END
						END
					ELSE IF @TABLE = 'BMS.CulvertInventory'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM BMS.CulvertInventory WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType
									   WHERE RoadCode = @roadCode

									UPDATE [BMS].[CulvertInventory] SET OldCode = CulvertCode WHERE RoadCode = @roadCode

									
									IF OBJECT_ID('tempdb..#tempTable6') IS NOT NULL
									DROP TABLE #tempTable6
									CREATE TABLE #tempTable6(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TID INT)
									INSERT INTO #tempTable6 SELECT CulvertInventoryId FROM BMS.CulvertInventory WHERE RoadCode = @roadCode
									SELECT * FROM #tempTable6
									SET @INNERCOUNT =1
									WHILE (@INNERCOUNT <= (SELECT MAX(ID) FROM #tempTable6))
										BEGIN
											SELECT @PID = TID FROM #tempTable6 WHERE ID = @INNERCOUNT
											IF @changeType = 'Inc'
												BEGIN
													SET @SChainage = (SELECT Chainage + @endChainage FROM BMS.CulvertInventory WHERE CulvertInventoryId = @PID)
												END
											ELSE 
												BEGIN
													SET @SChainage = (SELECT Chainage - @endChainage FROM BMS.CulvertInventory WHERE CulvertInventoryId = @PID)
												END	
											
											SET @NewLinkID = (SELECT LinkCode FROM NM.LinkMaster WHERE RoadCode = @roadCode AND @SChainage BETWEEN StartChainage AND EndChainage AND Direction='Increasing')
											--SELECT @SChainage,@NewLinkID
											IF OBJECT_ID('tempdb..#tempTableCulvert') IS NOT NULL
											DROP TABLE #tempTableCulvert
											CREATE TABLE #tempTableCulvert(ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, TName VARCHAR(MAX))
											SET @TABLE = (SELECT CulvertCode FROM BMS.CulvertInventory WHERE CulvertInventoryId = @PID)
											INSERT INTO #tempTableCulvert
											SELECT (Items) FROM dbo.Split(@TABLE, ':')
											SELECT @Code = TName FROM #tempTableCulvert WHERE ID =1
											--SELECT @Seq = TName FROM #tempTableCulvert WHERE ID =4
											SET @Chainage= (SELECT RIGHT('000'+CONVERT(VARCHAR, CONVERT(DECIMAL(18,3),(@SChainage/1000.00))),8))
											--SELECT @Code, @Seq,@Chainage
											--SELECT @Code + ':' + @roadCode + ':' + @Chainage + ':' + @Seq 'NewCode'
											UPDATE BMS.CulvertInventory SET CulvertCode = @Code + ':' + @roadCode + ':' + @Chainage , LinkCode = @NewLinkID, Chainage = @SChainage WHERE CulvertInventoryId = @PID
											
											UPDATE S SET S.CulvertCode = A.CulvertCode
											FROM BMS.CulvertCondition S
											INNER JOIN BMS.CulvertInventory A ON S.CulvertCode = A.OldCode
										

											SET @INNERCOUNT = @INNERCOUNT + 1
										END
								END
						END
					SET @COUNT = @COUNT + 1;
				END
				SELECT @strReturn
END
GO
/****** Object:  StoredProcedure [dbo].[UpdateTablesNewByRoadCodeLengthChange]    Script Date: 27-01-2025 13:01:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[UpdateTablesNewByRoadCodeLengthChange]
--exec [dbo].[UpdateTablesNewByRoadCodeLengthChange] 'NH100','500','LD:NH100:0000.500'
(
@roadCode VARCHAR(25),
@endChainage VARCHAR(20)=null,
@linkCode VARCHAR(50) = NULL
)
AS
BEGIN
	DECLARE 
	@strReturn INT
	SET @strReturn = 0 
	SET NOCOUNT ON; 

	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @deleteCommand NVARCHAR(MAX) =''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @TABLE NVARCHAR(100)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @COLUMNLIST NVARCHAR(MAX)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Length'
	DECLARE @NewLinkID NVARCHAR(50)
	DECLARE @Chainage VARCHAR(20)
	DECLARE @COLUMNDIRECTIONSIDE NVARCHAR(MAX)
	DECLARE @CheckDirectionSide NVARCHAR(MAX)

	DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
			INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
			SELECT TableName,TableType FROM NM.SPLITMERGETABLELIST WHERE SplitColumn='1' ORDER BY TableName
			DECLARE @COUNT INT
			DECLARE @PID NVARCHAR(20)
			DECLARE @PType NVARCHAR(20)
			SET @COUNT =1
			DECLARE @INNERCOUNT INT

			WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
				BEGIN
					SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
					IF @TABLE = 'RSAMS.Accident'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.Accident WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
									SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
											FROM [RSAMS].[Accident]
									WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)

									UPDATE RSAMS.Accident SET OldCode = AccidentCode WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)

									DELETE S 
									FROM [RSAMS].[AccVehicles] S
									INNER JOIN [RSAMS].[Accident] A ON S.AccidentCode = A.OldCode

									DELETE S
									FROM [RSAMS].[AccVictims] S
									INNER JOIN [RSAMS].[Accident] A ON S.AccidentCode = A.OldCode

									DELETE FROM RSAMS.Accident WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)
								END
						END
					ELSE IF @TABLE = 'TIS.Trafficstation'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM TIS.Trafficstation WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [TIS].[TrafficStation_Audit]
											   ([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
									SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split 
									FROM [TIS].[TrafficStation]
									WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)
									
									UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)

									DELETE S 
									FROM tis.AxleLoad S
									INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

									DELETE S 
									FROM tis.AxleVolCnt S
									INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

									DELETE S
									FROM [TIS].[TrafficVolume] S
									INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

									DELETE S
									FROM [TIS].[LinkTrafficDistribution] S
									INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

									DELETE FROM TIS.Trafficstation WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)
								END
						END
					ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.BlackspotExternal WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
									SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],@Split 
									FROM [RSAMS].[BlackspotExternal]
									WHERE RoadCode = @roadCode AND StartChainage > CONVERT(VARCHAR(20),@endChainage)

									UPDATE RSAMS.BlackspotExternal SET OldCode = BlackSpotCode WHERE RoadCode = @roadCode AND StartChainage > CONVERT(VARCHAR(20),@endChainage)

									DELETE S
									FROM [RSAMS].[CntrMeasmt] S
									INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode

									--DELETE FROM RSAMS.BlackspotExternal WHERE RoadCode = @roadCode AND StartChainage > CONVERT(VARCHAR(20),@endChainage)
									DELETE FROM RSAMS.BlackspotExternal WHERE RoadCode = @roadCode AND ((StartChainage > CONVERT(VARCHAR(20),@endChainage)) OR (EndChainage > CONVERT(VARCHAR(20),@endChainage)))
								END
						END
					ELSE IF @TABLE = 'RSAMS.HazdLocation'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.HazdLocation WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
									SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
											,[EndPointLongitude],[Direction],[OldCode],@Split
									FROM [RSAMS].[HazdLocation]
									WHERE RoadCode = @roadCode AND StartChainage > CONVERT(VARCHAR(20),@endChainage)

									UPDATE RSAMS.HazdLocation SET OldCode = HazdLocCode WHERE RoadCode = @roadCode AND StartChainage > CONVERT(VARCHAR(20),@endChainage)

									DELETE S
									FROM [RSAMS].[CntrMeasmt] S
									INNER JOIN RSAMS.HazdLocation A ON S.LocCode = A.OldCode

									DELETE FROM RSAMS.HazdLocation WHERE RoadCode = @roadCode AND ((StartChainage > CONVERT(VARCHAR(20),@endChainage)) OR (EndChainage > CONVERT(VARCHAR(20),@endChainage)))
									--DELETE FROM RSAMS.HazdLocation WHERE RoadCode = @roadCode AND StartChainage > CONVERT(VARCHAR(20),@endChainage)
								END
						END
                    ELSE IF @TABLE = 'BMS.LocationDetails'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM BMS.LocationDetails WHERE RoadCode = @roadCode)
								BEGIN
									 INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],
                                          [Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
									     [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails] 
									WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)

									UPDATE BMS.LocationDetails SET OldCode = BridgeID WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)

								DELETE S 
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								DELETE S 
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								DELETE S 
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode								

								DELETE S 
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								DELETE S 
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								DELETE S 
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								DELETE S 
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								DELETE S 
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								DELETE S 
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								DELETE S 
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode


								DELETE FROM [BMS].[LocationDetails] WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)
							END
						END
					ELSE IF @TABLE = 'BMS.CulvertInventory'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM [BMS].[CulvertInventory] WHERE RoadCode = @roadCode)
								BEGIN
									INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType						
									WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)

									UPDATE [BMS].[CulvertInventory] SET OldCode = CulvertCode WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)

									DELETE S 
									FROM [BMS].[CulvertCondition] S
									INNER JOIN [BMS].[CulvertInventory] A ON S.CulvertCode = A.OldCode
								
									DELETE FROM [BMS].[CulvertInventory] WHERE RoadCode = @roadCode AND Chainage > CONVERT(VARCHAR(20),@endChainage)
								END
						END

					SET @COUNT = @COUNT + 1;
				END

				SELECT @strReturn
END
GO
/****** Object:  StoredProcedure [dbo].[UpdateTablesNewByRoadRename]    Script Date: 27-01-2025 13:02:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER  PROCEDURE [dbo].[UpdateTablesNewByRoadRename]
--exec [dbo].[UpdateTablesNewByRoadRename] 'NH100','SH100'
(
@roadCode VARCHAR(25),
@oldRoadCode VARCHAR(25)=NULL
)
AS
BEGIN
	DECLARE 
	@strReturn INT
	SET @strReturn = 0 
	SET NOCOUNT ON; 

	DECLARE @sqlCommand NVARCHAR(MAX)=''
	DECLARE @updateCommand NVARCHAR(MAX) =''
	DECLARE @sqlupdateCommand NVARCHAR(MAX) =''
	DECLARE @TABLE NVARCHAR(100)
	DECLARE @COLUMN NVARCHAR(100)
	DECLARE @TName NVARCHAR(100)
	DECLARE @SchemaName NVARCHAR(100)
	DECLARE @SCOPEID NVARCHAR(20)
	DECLARE @COLUMNLIST NVARCHAR(MAX)
	DECLARE @TableType NVARCHAR(50)
	DECLARE @COLUMNLISTMAIN NVARCHAR(MAX)
	DECLARE @COLUMNLISTAUDIT NVARCHAR(MAX)
	DECLARE @Split NVARCHAR(10) = 'Rename'
	DECLARE @NewLinkID NVARCHAR(50)
	DECLARE @Chainage VARCHAR(20)

	DECLARE @QUERYTEMPTABLE TABLE(ID INT IDENTITY(1,1),TABLENAME VARCHAR(MAX), TABLETYPE VARCHAR(50))
			INSERT INTO @QUERYTEMPTABLE(TABLENAME,TABLETYPE)
			SELECT TableName,TableType FROM NM.SPLITMERGETABLELIST WHERE SplitColumn='1'
			DECLARE @COUNT INT
			DECLARE @PID NVARCHAR(20)
			DECLARE @PID1 NVARCHAR(20)
			SET @COUNT =1
			DECLARE @INNERCOUNT INT

			WHILE (@COUNT <= (SELECT MAX(ID) FROM @QUERYTEMPTABLE))
				BEGIN
					SET @TABLE = (SELECT TableName FROM @QUERYTEMPTABLE WHERE ID = @COUNT)
					IF @TABLE = 'RSAMS.Accident'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.Accident WHERE RoadCode = @oldRoadCode)
								BEGIN
									INSERT INTO [RSAMS].[Accident_Audit]
											   ([AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],[Action])
									SELECT [AccidentCode],[RoadCode],[LinkCode],[Chainage],[Direction],[AccidentDate],[AccidentTime],[AccidentLocation],[FactorsInvoled]
												,[InspectingOfficer],[Designation],[PoliceStation],[VehicleInvolved],[NoOfInjuredPersons],[NoOfFatalPersons],[AccidentType],[PrimaryReason]
												,[Remarks],[Latitude],[Longitude],[FIRNo],[OldCode],@Split
											FROM [RSAMS].[Accident]
									WHERE RoadCode = @oldRoadCode
									UPDATE RSAMS.Accident SET OldCode = AccidentCode WHERE RoadCode = @oldRoadCode

									UPDATE RSAMS.Accident SET RoadCode = @roadCode , AccidentCode = REPLACE(AccidentCode,@oldRoadCode,@roadCode), LinkCode = REPLACE(LinkCode,@oldRoadCode,@roadCode) WHERE RoadCode = @oldRoadCode

									UPDATE S SET S.AccidentCode = A.AccidentCode
									FROM [RSAMS].[AccVehicles] S
									INNER JOIN [RSAMS].[Accident] A ON S.AccidentCode = A.OldCode

									UPDATE S SET S.AccidentCode = A.AccidentCode
									FROM [RSAMS].[AccVictims] S
									INNER JOIN [RSAMS].[Accident] A ON S.AccidentCode = A.OldCode
								END
						END
					ELSE IF @TABLE = 'TIS.Trafficstation'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM TIS.Trafficstation WHERE RoadCode = @oldRoadCode)
								BEGIN
									INSERT INTO [TIS].[TrafficStation_Audit]
											   ([TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],[Action])
									SELECT [TrafficStationCode],[StationName],[RoadCode],[LinkCode],[Chainage],[Latitude],[Longitude],[OldCode],[Direction],@Split
									FROM [TIS].[TrafficStation]
									WHERE RoadCode = @oldRoadCode
									UPDATE TIS.Trafficstation SET OldCode = TrafficStationCode WHERE RoadCode = @oldRoadCode

									UPDATE TIS.Trafficstation SET RoadCode = @roadCode , TrafficStationCode = REPLACE(TrafficStationCode,@oldRoadCode,@roadCode), LinkCode = REPLACE(LinkCode,@oldRoadCode,@roadCode) WHERE RoadCode = @oldRoadCode

									UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode, S.RoadCode = A.RoadCode
									FROM tis.AxleLoad S
									INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

									UPDATE S SET S.TrafficStationCode = A.TrafficStationCode
									FROM tis.AxleVolCnt S
									INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

									UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode, S.RoadCode = A.RoadCode
									FROM [TIS].[TrafficVolume] S
									INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode

									UPDATE S SET S.TrafficStationCode = A.TrafficStationCode, S.LinkCode = A.LinkCode
									FROM [TIS].[LinkTrafficDistribution] S
									INNER JOIN TIS.Trafficstation A ON S.TrafficStationCode = A.OldCode
								END
						END
					ELSE IF @TABLE = 'RSAMS.BlackspotExternal'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.BlackspotExternal WHERE RoadCode = @oldRoadCode)
								BEGIN
									INSERT INTO [RSAMS].[BlackspotExternal_Audit]
											   ([RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],[Action])
									SELECT [RoadCode],[LinkCode],[StartChainage],[EndChainage],[NoOfInjuredPersons],[NoOfFatalPersons],[MarkedYear],[NoofAccident]
												,[StartPointLatitude],[StartPointLongitude],[EndPointLatitude],[EndPointLongitude],[SurveyCode],[BlackSpotCode],[SourceType]
												,[Direction],[OldCode],@Split
									FROM [RSAMS].[BlackspotExternal]
									WHERE RoadCode = @oldRoadCode

									UPDATE RSAMS.BlackspotExternal SET OldCode = BlackSpotCode WHERE RoadCode = @oldRoadCode

									UPDATE RSAMS.BlackspotExternal SET RoadCode = @roadCode , BlackSpotCode = REPLACE(BlackSpotCode,@oldRoadCode,@roadCode), LinkCode = REPLACE(LinkCode,@oldRoadCode,@roadCode) WHERE RoadCode = @oldRoadCode

									UPDATE S SET S.LocCode = A.BlackSpotCode
									FROM [RSAMS].[CntrMeasmt] S
									INNER JOIN RSAMS.BlackspotExternal A ON S.LocCode = A.OldCode
								END
						END
					ELSE IF @TABLE = 'RSAMS.HazdLocation'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM RSAMS.HazdLocation WHERE RoadCode = @oldRoadCode)
								BEGIN
									INSERT INTO [RSAMS].[HazdLocation_Audit]
											   ([HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
												,[EndPointLongitude],[Direction],[OldCode],[Action])
									SELECT [HazdLocCode],[RoadCode],[LinkCode],[StartChainage],[EndChainage],[HazdType],[ASI],[SurveyCode],[StartPointLatitude],[StartPointLongitude],[EndPointLatitude]
											,[EndPointLongitude],[Direction],[OldCode],@Split
									FROM [RSAMS].[HazdLocation]
									WHERE RoadCode = @oldRoadCode

									UPDATE RSAMS.HazdLocation SET OldCode = HazdLocCode WHERE RoadCode = @oldRoadCode

									UPDATE RSAMS.HazdLocation SET RoadCode = @roadCode , HazdLocCode = REPLACE(HazdLocCode,@oldRoadCode,@roadCode), LinkCode = REPLACE(LinkCode,@oldRoadCode,@roadCode) WHERE RoadCode = @oldRoadCode

									UPDATE S SET S.LocCode = A.HazdLocCode
									FROM [RSAMS].[CntrMeasmt] S
									INNER JOIN RSAMS.HazdLocation A ON S.LocCode = A.OldCode
								END
						END
                    ELSE IF @TABLE = 'BMS.LocationDetails'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM BMS.LocationDetails WHERE RoadCode = @oldRoadCode)
								BEGIN
								  INSERT INTO [BMS].[LocationDetails_Audit] 
							             ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
										  [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										  [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
										  [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],[OldCode],
                                          [Action])
                                  SELECT [RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[BridgeID],[CDNumber],
                                         [BridgeNameNo],[NameofRiverNallah],[FunctionofBridge],[TypeoftheBridge],[YearofConstruction],
										 [Nameofnearbyplace],[DateofInspection],[ContractorFirm],[SupervisedConsultant],[DesignConsultant],
                                         [State],[District],[Circle],[Division],[SubDivision],[Remarks],[IsProcess],OldCode,@Split
                                         FROM [BMS].[LocationDetails] 
									WHERE RoadCode = @oldRoadCode
									UPDATE BMS.LocationDetails SET OldCode = BridgeID WHERE RoadCode = @oldRoadCode

									UPDATE BMS.LocationDetails SET RoadCode = @roadCode , BridgeID = REPLACE(BridgeID,@oldRoadCode,@roadCode), LinkCode = REPLACE(LinkCode,@oldRoadCode,@roadCode) WHERE RoadCode = @oldRoadCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.AbutmentDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ApproachProtectionInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCI S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BCICondRating S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BCIElementCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BearingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.BridgeBoQ S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeCostRepair S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.BridgeDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.CrossGirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertCondition S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								--UPDATE S SET S.BridgeCode = A.BridgeId
								--FROM BMS.CulvertInventory S
								--INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSlabCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DeckSurfaceCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.DrainSpoutCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationAbutmentInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.FoundationPierInventory S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.GirderCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.HydraulicDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								

								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.JointCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.PierDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.ProtectionWorksCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.RailingCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode
								
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.SuperStructureDetails S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode							
																
								UPDATE S SET S.BridgeCode = A.BridgeId
								FROM BMS.WallCondition S
								INNER JOIN [BMS].[LocationDetails] A ON S.BridgeCode = A.OldCode

								END
						END
					ELSE IF @TABLE = 'BMS.CulvertInventory'
						BEGIN
							IF EXISTS(SELECT TOP 1 * FROM BMS.CulvertInventory WHERE RoadCode = @oldRoadCode)
								BEGIN
									INSERT INTO [BMS].[CulvertInventory_Audit]
											 ([RoadCode],[Chainage],[LinkCode],[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,[CulvertCode],[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight],
											  [ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType
											 ,[SurveyDate],OldCode,[Action])
       
									   SELECT [RoadCode],[Chainage],CI.LinkCode,[Direction],[SurveyYear],[Latitude],[Longitude]
											 ,CI.CulvertCode,[CDNumber],[StructureType],[NoofSpans],[SpanWidth],[SpanHeight]
											 ,[ClearRoadWidth],[TotalCulvertWidth],[DeckSlabThickness],[HeadWallType]
											 ,[HeadWallLength],[HeadWallThickness],WRWallType,[SurveyDate],CI.OldCode,@Split
                                       FROM [BMS].[CulvertInventory] CI inner join [BMS].[CulvertCondition] CC on CC.CulvertCode=CI.CulvertCode 
									   LEFT JOIN [BMS].[LKPTCulvCond] PUS on CC.ProtectionUS=PUS.CulvCondType
									   LEFT JOIN [BMS].[LKPTCulvCond] PDS on CC.ProtectionDS=PDS.CulvCondType
									   left join bms.LKPTFlowDir FL on CI.FlowDirection=FL.FlowDirType
									   left join BMS.LKPTWallType WT on CI.WRWallType= WT.WallTypeCondType	
							         WHERE RoadCode = @oldRoadCode
									
									UPDATE [BMS].[CulvertInventory] SET OldCode = CulvertCode WHERE RoadCode = @oldRoadCode

									UPDATE [BMS].[CulvertInventory] SET RoadCode = @roadCode , CulvertCode = REPLACE(CulvertCode,@oldRoadCode,@roadCode), LinkCode = REPLACE(LinkCode,@oldRoadCode,@roadCode) WHERE RoadCode = @oldRoadCode

									UPDATE S SET S.CulvertCode = A.CulvertCode
									FROM [BMS].[CulvertCondition] S
									INNER JOIN [BMS].[CulvertInventory] A ON S.CulvertCode = A.OldCode

									
								END
						END
					SET @COUNT = @COUNT + 1;
				END

				SELECT @strReturn
END
GO
alter table BMS.CulvertInventory alter column CulvertCode nvarchar(100);
alter table BMS.CulvertInventory alter column LinkCode nvarchar(100);
alter table BMS.CulvertInventory alter column OldCode nvarchar(100);
go
alter table BMS.CulvertInventory_Audit alter column CulvertCode nvarchar(100);
alter table BMS.CulvertInventory_Audit alter column LinkCode nvarchar(100);
alter table BMS.CulvertInventory_Audit alter column OldCode nvarchar(100);
go
alter table BMS.CulvertCondition_Audit alter column CulvertCode nvarchar(100);
alter table BMS.CulvertCondition_Audit alter column OldCode nvarchar(100);
alter table BMS.CulvertCondition_Audit alter column ConditionofPipe nvarchar(100);
go
alter table BMS.CulvertCondition alter column CulvertCode nvarchar(100);
alter table BMS.CulvertCondition alter column LinkCode nvarchar(100);
alter table BMS.CulvertCondition alter column OldCode nvarchar(100);
alter table BMS.CulvertCondition alter column ConditionofPipe nvarchar(100);
go