
/********************************************************************************************** *
User should be able to initiate a downgrade operation via a utility outside of the Touchstone
application, to downgrade the exposure DB from 10.0 to 9.0 
Requires with the provided AIRDowngradeHelper DB.

#region tags are recognized by SSMSBoost plugin.
************************************************************************************************/
--#region Pre Downgrade Validation
BEGIN TRY

	DECLARE @Msg VARCHAR(200)
	DECLARE @DbExpectedVersion VARCHAR(10) = '10.0.0'
	DECLARE @DbVersion VARCHAR(10) 
	DECLARE @DbType VARCHAR(10) 


	-- make sure that the Database is not a system database.
	IF    DB_NAME() IN ('master','model','msdb','tempdb') 
	   OR EXISTS(SELECT * FROM master.sys.databases WHERE name=DB_NAME() AND is_distributor=1)
	     THROW 60000,'Current database is a system database.',1
		
	IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = 'tDBVersion') 
		THROW 60000, 'Current database is missing tDBVersion.', 1 

    SELECT TOP 1
	       @DbVersion= Version 
	      ,@DbType = DataSourceTypeCode
	FROM tDBVersion
	
	SELECT @DbVersion '@DbVersion', @DbType '@DbType'

	IF @DbVersion <> @DbExpectedVersion BEGIN
		SET @Msg = 'Current database is at a wrong version. Required: ' + @DbExpectedVersion + ' Found: '+ @DbVersion + '';
		THROW 60000, @Msg, 1 
	END

	IF @DbType <> 'EXP' BEGIN
		SET @Msg = 'Current database is not an Exposure database ' + @DbType + '. EXP required';
		THROW 60000, @Msg, 1 
	END

	IF DATABASEPROPERTYEX(DB_NAME(), 'Updateability') = 'READ_ONLY' 
		THROW 60000, 'Current database is not updateable.', 1 

    IF NOT EXISTS(SELECT 1 FROM sys.databases WHERE name = 'AIRDowngradeHelper') BEGIN
		SET @Msg = 'This environment does not have the required AIRDowngradeHelper database to continue with the downgrade.';
		THROW 60000, @Msg, 1 
	END
	
	--this one should be uppdate each release	
	IF NOT EXISTS(SELECT 1 FROM AIRDowngradeHelper.sys.Tables WHERE name = 'tGeography_90_JP') BEGIN
		SET @Msg = 'The available AIRDowngradeHelper does not support this version.';
		THROW 60000, @Msg, 1 
	END
		
END TRY
BEGIN CATCH
	SELECT ERROR_MESSAGE()
	PRINT ERROR_MESSAGE()
	SET NOEXEC ON; --safeguard against further execution even if there are GOs further down.
END CATCH
GO
--#endregion Pre Downgrade Validation

--#region Rollback Packages
/**********************************************************************************************************
Rollback Packages
	Execute rollback code for all current version packages. This is a simplied version of pDS_RollbackPackages
	This help bring DB in line with RTM X.0.0 db as a good basis for downgrade

	It is possible that an ignoreable package is skipped by downgrade, so we have to be vigilant.

	Any not ignoreable update should be handled using the downgrade hook:

	  dbo.pDS_Downgrade_8x_80

**********************************************************************************************************/
	 
DECLARE @rollbackSQL NVARCHAR(MAX)
DECLARE @name NVARCHAR(255)
DECLARE @desc NVARCHAR(MAX)
DECLARE @notes NVARCHAR(MAX)
DECLARE @packageSID INT
DECLARE @contentID INT
DECLARE @PackageType VARCHAR(10)
DECLARE @DbHistoryID INT
		

DECLARE HFCursor CURSOR LOCAL FORWARD_ONLY STATIC FOR
SELECT RollbackScript
		,PackageName
		,PackageDescription
		,ContentNotes
		,b.PackageSID
		,ContentID
		,PackageType
		,DbHistoryID
	FROM tDBVersion a
	JOIN tDbHistory b ON a.Version = b.StartVersion
	WHERE b.IsRolledBack = 0
	AND b.RollbackScript IS NOT NULL
	ORDER BY b.DbHistoryID DESC
		
OPEN HFCursor
		    
FETCH NEXT FROM HFCursor INTO @rollbackSQL, @name, @desc, @notes, @packageSID, @contentID, @PackageType, @DbHistoryID
		    
WHILE @@FETCH_STATUS = 0 BEGIN
				   
	EXEC sp_executesql @rollbackSQL
		
	UPDATE dbo.tDBHistory SET IsRolledBack = 1 WHERE DbHistoryID = @DbHistoryID
		
	INSERT INTO dbo.tDBHistory (
		HistoryType
		,SystemVersion
		,SystemCodeVersion
		,StartVersion
		,EndVersion
		,StartCodeVersion
		,EndCodeVersion
		,PackageSID
		,PackageType
		,PackageName
		,PackageDescription
		,ContentID
		,ContentNotes
	)
	SELECT 
		'PACKAGE ROLLBACK'
		,(SELECT version FROM tDBVersion)
		,(SELECT CodeVersion FROM tDBVersion)
		,Version --note: Packages don't change the version
		,Version
		,CodeVersion
		,CodeVersion
		,@packageSID
		,@PackageType
		,@Name
		,'ROLLBACK' --@Desc
		,@ContentID
		,NULL--@Notes
	FROM tDBVersion dbv
	FETCH NEXT FROM HFCursor INTO @rollbackSQL, @name, @desc, @notes, @packageSID, @contentID, @PackageType, @DbHistoryID
END
		    
GO
--#endregion

--#region pDS_Downgrade Hook
--Post 10.0 packages that have downgrade impact may include code to remove themselves.
--That will be accessed during downgrade using pDS_Downgrade_10x_100.
--pDS_Downgrade will not exist in a baseline 10.0 exposure db
IF EXISTS(SELECT 1 FROM sys.procedures WHERE name = 'pDS_Downgrade_10x_100')
    EXEC dbo.pDS_Downgrade_10x_100

GO
--#endregion


--#region Install Index Reset Helper Proc
/******************************************************************************************************
Object: dbo.pDS_ResetExposureIndexes
Description: 
Use the master copy of indexes in AirDowngradeHelper. These are copied from AirDbAdmin.
We stoppped purposely touching keys in 7.0, so not worrying about those.

USAGE
Downgrade installs in target DB and removes after use.
Call before and after downgrade to fix up any indexes.

Example:

--assuming a db already in R7 state
create index id_tloc_geosid on Tlocation(geographysid)
drop index IDX_filter_Country_Data on [tAggregateExposure]
drop index [fk_Contract_Currency] on tContract
create index fk_Contract_Currency on tContract(currencycode) include (statuscode)

EXEC pDS_ResetExposureIndexes  @debug = 1
EXEC pDS_ResetExposureIndexes '10.0.0', @debug = 1
EXEC pDS_ResetExposureIndexes '9.0.0', @debug = 1
EXEC pDS_ResetExposureIndexes '7.0.0', @debug = 1
*******************************************************************************************************/
CREATE OR ALTER PROC dbo.pDS_ResetExposureIndexes 
	@TargetVersion VARCHAR(10) = NULL
	,@Debug BIT = 0 
AS BEGIN

SET NOCOUNT ON

DECLARE @Result INT
DECLARE @SPName NVARCHAR(392) = DB_NAME() + '.' + SCHEMA_NAME() + '.' + OBJECT_NAME(@@PROCID)
IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ': START OF ', @SPName

BEGIN TRY
--@TargetVersion VARCHAR(10) = NULL
IF @TargetVersion IS NULL
	--SELECT @TargetVersion = SUBSTRING(Version,0,LEN(Version)-CHARINDEX('.',REVERSE(Version),0)+1) FROM dbo.tDBVersion
	SELECT @TargetVersion = Version FROM dbo.tDBVersion

--DECLARE @Debug BIT = 1 
DECLARE @DbName_Quoted NVARCHAR(MAX) = QUOTENAME(DB_NAME())
DROP TABLE IF EXISTS #tExposureIndex

--Note: We are little loose with is_unique vs is_unique_contraint, but so far it isn't important in AirExposure. R8.
CREATE TABLE #tExposureIndex (
	PartitionCount INT NULL
	,PartitionNum INT NULL
	,PartitionCommand NVARCHAR(128) NULL
	,SchemaName NVARCHAR(128) NULL
	,TableName NVARCHAR(128) NULL
	,ObjectCode TINYINT NULL
	,ObjectName NVARCHAR(128) NULL
	,ObjectType NVARCHAR(128) NULL
	,ObjectColumns NVARCHAR(max) NULL
	,FKObjectID INT NULL
	,ReferenceSchemaName NVARCHAR(128) NULL
	,ReferenceTableName NVARCHAR(128) NULL
	,ReferenceColumns NVARCHAR(max) NULL
	,FKDeleteAction NVARCHAR(128) NULL
	,FKUpdateAction NVARCHAR(128) NULL
	,EnteredDate DATETIME NULL
	,IsUnique BIT NULL 
	,IsUniqueConstraint BIT NULL
	,DbVersion VARCHAR(10) NULL
	,FilterDefinition NVARCHAR(max) NULL
)

INSERT INTO #tExposureIndex
EXEC AirDownGradeHelper.dbo.pDS_GetExposureKeysAndIndexes @DbName_Quoted,1
IF @Debug = 1 SELECT '#tExposureIndex' TempTable, * FROM #tExposureIndex ORDER BY TableName,ObjectName

DECLARE @sqlCmd NVARCHAR(MAX) = N''''

--DECLARE @TargetVersion VARCHAR(10) = NULL
--IF @TargetVersion IS NULL
	--SELECT @TargetVersion = SUBSTRING(Version,0,LEN(Version)-CHARINDEX('.',REVERSE(Version),0)+1) FROM dbo.tDBVersion
	--SELECT @TargetVersion = Version FROM dbo.tDBVersion
--PRINT @TargetVersion
SELECT @TargetVersion TargetVersion
      ,COUNT(1) CountIndexesToDrop
  FROM #tExposureIndex a
  LEFT JOIN AIRDowngradeHelper..tExposureKeyAndIndex b 
         ON 1=1
		AND a.TableName = b.TableName
		AND a.SchemaName = b.SchemaName
		AND a.ObjectColumns = b.ObjectColumns
		AND a.ObjectName = b.ObjectName
		AND a.IsUnique = b.IsUnique
		AND ISNULL(a.FilterDefinition,'') = ISNULL(b.FilterDefinition,'')
		--AND a.PartitionCommand = b.PartitionCommand
		AND @TargetVersion = b.DbVersion
		--AND '7.0.0' = b.DbVersion
    WHERE a.ObjectCode = 2
	 AND b.ObjectName IS NULL

DECLARE DropIndexCursor CURSOR LOCAL FORWARD_ONLY STATIC FOR
SELECT SqlCmd = IIF(a.IsUniqueConstraint = 1, '
	ALTER TABLE ' + a.TableName + ' DROP CONSTRAINT ' + a.ObjectName,'
	DROP INDEX ' + a.TableName + '.' + a.ObjectName)
  FROM #tExposureIndex a
  LEFT JOIN AIRDowngradeHelper..tExposureKeyAndIndex b 
         ON 1=1
		AND a.TableName = b.TableName
		AND a.SchemaName = b.SchemaName
		AND a.ObjectColumns = b.ObjectColumns
		AND a.ObjectName = b.ObjectName
		AND a.IsUnique = b.IsUnique
		AND ISNULL(a.FilterDefinition,'') = ISNULL(b.FilterDefinition,'')
		--AND a.PartitionCommand = b.PartitionCommand
		AND @TargetVersion = b.DbVersion
		--AND '7.0.0' = b.DbVersion
    WHERE a.ObjectCode = 2
	 AND b.ObjectName IS NULL

OPEN DropIndexCursor

FETCH NEXT FROM DropIndexCursor INTO @sqlCmd
		    
WHILE @@FETCH_STATUS = 0 BEGIN
	
	PRINT @sqlCmd
	EXEC sp_executesql @sqlCmd
			
	FETCH NEXT FROM DropIndexCursor INTO @sqlCmd
END

--create any missing index from master
SELECT @TargetVersion TargetVersion
      ,COUNT(1) CountIndexesToCreate
FROM #tExposureIndex a
 RIGHT JOIN AIRDowngradeHelper..tExposureKeyAndIndex b 
         ON a.TableName = b.TableName
	    AND a.ObjectColumns = b.ObjectColumns
	    AND a.ObjectName = b.ObjectName
        AND a.IsUnique = b.IsUnique
	    AND ISNULL(a.FilterDefinition,'') = ISNULL(b.FilterDefinition,'')
		--AND a.PartitionCommand = b.PartitionCommand
 WHERE b.ObjectCode = 2 --only dealing with 2s now
   AND a.ObjectName IS NULL
   AND @TargetVersion = b.DbVersion
   --AND '7.0.0' = b.DbVersion

DECLARE CreateIndexCursor CURSOR LOCAL FORWARD_ONLY STATIC FOR
SELECT SqlCmd =  '
IF NOT EXISTS(SELECT 1 FROM sys.dm_exec_sessions WHERE session_id = @@SPID AND [quoted_identifier] = 1)
	SET QUOTED_IDENTIFIER ON
CREATE ' + IIF(b.IsUnique=1,'UNIQUE ','') + b.ObjectType + ' INDEX ' + b.ObjectName + 
' ON  ' + b.SchemaName + '.' + b.TableName + ' (' + b.ObjectColumns + ')' 
+ IIF(b.FilterDefinition IS NOT NULL, ' WHERE ' + b.FilterDefinition, '')
+ ISNULL(b.PartitionCommand,'')
  FROM #tExposureIndex a
 RIGHT JOIN AIRDowngradeHelper..tExposureKeyAndIndex b 
         ON a.TableName = b.TableName
	    AND a.ObjectColumns = b.ObjectColumns
	    AND a.ObjectName = b.ObjectName
        AND a.IsUnique = b.IsUnique
	    AND ISNULL(a.FilterDefinition,'') = ISNULL(b.FilterDefinition,'')
		--AND a.PartitionCommand = b.PartitionCommand
 WHERE b.ObjectCode = 2 --only dealing with 2s now
   AND a.ObjectName IS NULL
   AND @TargetVersion = b.DbVersion
   --AND '7.0.0' = b.DbVersion
OPEN CreateIndexCursor

FETCH NEXT FROM CreateIndexCursor INTO @sqlCmd
		    
WHILE @@FETCH_STATUS = 0 BEGIN
	
	PRINT @sqlCmd
	EXEC sp_executesql @sqlCmd
			
	FETCH NEXT FROM CreateIndexCursor INTO @sqlCmd

END
	   
	
SET @Result = 0

END TRY
BEGIN CATCH			
    EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
END CATCH;

IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ': END OF ', @SPName
RETURN @Result

END
 
GO
--#endregion Install Index Reset Helper Proc

EXEC pDS_ResetExposureIndexes  @debug = 0

--#region Revert Schema and Code Changes
--<Redgate Generated>

SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping extended properties'
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_18', 'SCHEMA', N'dbo', 'TABLE', N'tCompanyLossAssociation', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_18', 'SCHEMA', N'dbo', 'TABLE', N'tCompanyLossAssociation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_19', 'SCHEMA', N'dbo', 'TABLE', N'tCompany', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_19', 'SCHEMA', N'dbo', 'TABLE', N'tCompany', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_20', 'SCHEMA', N'dbo', 'TABLE', N'tCompany', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_20', 'SCHEMA', N'dbo', 'TABLE', N'tCompany', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_22', 'SCHEMA', N'dbo', 'TABLE', N'tExposureSet', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_22', 'SCHEMA', N'dbo', 'TABLE', N'tExposureSet', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithRoles_29', 'SCHEMA', N'dbo', 'TABLE', N'tLayerCondition', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithRoles_29', 'SCHEMA', N'dbo', 'TABLE', N'tLayerCondition', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithRoles_27', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithRoles_27', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithRoles_28', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithRoles_28', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_13', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolioFilter', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_13', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolioFilter', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_15', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolio', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_15', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolio', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_25', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceEPCurveSet', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_25', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceEPCurveSet', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_26', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceEPCurve', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_26', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceEPCurve', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_16', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_16', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_17', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_17', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_23', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_23', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_14', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceTreaty', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_14', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceTreaty', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_24', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceTreaty', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithoutRoles_24', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceTreaty', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithRoles_32', 'SCHEMA', N'dbo', 'TABLE', N'tStepFunction', NULL, NULL))
EXEC sp_dropextendedproperty N'NavPropWithRoles_32', 'SCHEMA', N'dbo', 'TABLE', N'tStepFunction', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping constraints from [dbo].[tReinsuranceProgramSourceInure]'
GO
IF EXISTS (SELECT 1 FROM sys.columns WHERE name = N'IsInuringNextProgramFlow' AND object_id = OBJECT_ID(N'[dbo].[tReinsuranceProgramSourceInure]', 'U') AND default_object_id = OBJECT_ID(N'[dbo].[df_tReinsuranceProgramSourceInure_IsInuringNextProgramFlow]', 'D'))
ALTER TABLE [dbo].[tReinsuranceProgramSourceInure] DROP CONSTRAINT [df_tReinsuranceProgramSourceInure_IsInuringNextProgramFlow]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_tCompany_CompanyName_BusinessUnitSID_StatusCode] from [dbo].[tCompany]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tCompany_CompanyName_BusinessUnitSID_StatusCode' AND object_id = OBJECT_ID(N'[dbo].[tCompany]'))
DROP INDEX [ix_tCompany_CompanyName_BusinessUnitSID_StatusCode] ON [dbo].[tCompany]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping statistics [BusinessUnitSID] from [dbo].[tCompany]'
GO
IF EXISTS (SELECT 1 FROM sys.stats WHERE name = N'BusinessUnitSID' AND object_id = OBJECT_ID(N'[dbo].[tCompany]'))
DROP STATISTICS [dbo].[tCompany].[BusinessUnitSID]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping statistics [StatusCode] from [dbo].[tCompany]'
GO
IF EXISTS (SELECT 1 FROM sys.stats WHERE name = N'StatusCode' AND object_id = OBJECT_ID(N'[dbo].[tCompany]'))
DROP STATISTICS [dbo].[tCompany].[StatusCode]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_tContract_ContractID] from [dbo].[tContract]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tContract_ContractID' AND object_id = OBJECT_ID(N'[dbo].[tContract]'))
DROP INDEX [ix_tContract_ContractID] ON [dbo].[tContract]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_tContract_ExposureSetSID2] from [dbo].[tContract]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tContract_ExposureSetSID2' AND object_id = OBJECT_ID(N'[dbo].[tContract]'))
DROP INDEX [ix_tContract_ExposureSetSID2] ON [dbo].[tContract]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_tContract_ExposureSetSID_ContractID_ContractTypeCode2] from [dbo].[tContract]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tContract_ExposureSetSID_ContractID_ContractTypeCode2' AND object_id = OBJECT_ID(N'[dbo].[tContract]'))
DROP INDEX [ix_tContract_ExposureSetSID_ContractID_ContractTypeCode2] ON [dbo].[tContract]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Contract_Status] from [dbo].[tContract]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Contract_Status' AND object_id = OBJECT_ID(N'[dbo].[tContract]'))
DROP INDEX [fk_Contract_Status] ON [dbo].[tContract]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Contract_SubmitStatus] from [dbo].[tContract]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Contract_SubmitStatus' AND object_id = OBJECT_ID(N'[dbo].[tContract]'))
DROP INDEX [fk_Contract_SubmitStatus] ON [dbo].[tContract]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_Contract_UserLineOfBusiness] from [dbo].[tContract]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_Contract_UserLineOfBusiness' AND object_id = OBJECT_ID(N'[dbo].[tContract]'))
DROP INDEX [ix_Contract_UserLineOfBusiness] ON [dbo].[tContract]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_ExposureSet_Status] from [dbo].[tExposureSet]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_ExposureSet_Status' AND object_id = OBJECT_ID(N'[dbo].[tExposureSet]'))
DROP INDEX [fk_ExposureSet_Status] ON [dbo].[tExposureSet]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_LayerConditionLocationXref_Location] from [dbo].[tLayerConditionLocationXref]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_LayerConditionLocationXref_Location' AND object_id = OBJECT_ID(N'[dbo].[tLayerConditionLocationXref]'))
DROP INDEX [fk_LayerConditionLocationXref_Location] ON [dbo].[tLayerConditionLocationXref]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_LayerCondition_Contract] from [dbo].[tLayerCondition]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_LayerCondition_Contract' AND object_id = OBJECT_ID(N'[dbo].[tLayerCondition]'))
DROP INDEX [fk_LayerCondition_Contract] ON [dbo].[tLayerCondition]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_LayerCondition_LayerConditionType] from [dbo].[tLayerCondition]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_LayerCondition_LayerConditionType' AND object_id = OBJECT_ID(N'[dbo].[tLayerCondition]'))
DROP INDEX [fk_LayerCondition_LayerConditionType] ON [dbo].[tLayerCondition]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_LayerCondition_Layer] from [dbo].[tLayerCondition]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_LayerCondition_Layer' AND object_id = OBJECT_ID(N'[dbo].[tLayerCondition]'))
DROP INDEX [fk_LayerCondition_Layer] ON [dbo].[tLayerCondition]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_LayerCondition_LayerCondition] from [dbo].[tLayerCondition]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_LayerCondition_LayerCondition' AND object_id = OBJECT_ID(N'[dbo].[tLayerCondition]'))
DROP INDEX [fk_LayerCondition_LayerCondition] ON [dbo].[tLayerCondition]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Layer_Contract] from [dbo].[tLayer]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Layer_Contract' AND object_id = OBJECT_ID(N'[dbo].[tLayer]'))
DROP INDEX [fk_Layer_Contract] ON [dbo].[tLayer]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Locfeature_IBHSFortifiedCode] from [dbo].[tLocFeature]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Locfeature_IBHSFortifiedCode' AND object_id = OBJECT_ID(N'[dbo].[tLocFeature]'))
DROP INDEX [fk_Locfeature_IBHSFortifiedCode] ON [dbo].[tLocFeature]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_LocStepFuncXref_Location] from [dbo].[tLocStepFunctionXref]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_LocStepFuncXref_Location' AND object_id = OBJECT_ID(N'[dbo].[tLocStepFunctionXref]'))
DROP INDEX [fk_LocStepFuncXref_Location] ON [dbo].[tLocStepFunctionXref]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_LocStepFuncXref_StepFunction] from [dbo].[tLocStepFunctionXref]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_LocStepFuncXref_StepFunction' AND object_id = OBJECT_ID(N'[dbo].[tLocStepFunctionXref]'))
DROP INDEX [fk_LocStepFuncXref_StepFunction] ON [dbo].[tLocStepFunctionXref]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Locterm_Contract] from [dbo].[tLocTerm]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Locterm_Contract' AND object_id = OBJECT_ID(N'[dbo].[tLocTerm]'))
DROP INDEX [fk_Locterm_Contract] ON [dbo].[tLocTerm]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_LocTerm_Location] from [dbo].[tLocTerm]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_LocTerm_Location' AND object_id = OBJECT_ID(N'[dbo].[tLocTerm]'))
DROP INDEX [fk_LocTerm_Location] ON [dbo].[tLocTerm]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Location_Contract] from [dbo].[tLocation]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Location_Contract' AND object_id = OBJECT_ID(N'[dbo].[tLocation]'))
DROP INDEX [fk_Location_Contract] ON [dbo].[tLocation]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_Location_CountryCode] from [dbo].[tLocation]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_Location_CountryCode' AND object_id = OBJECT_ID(N'[dbo].[tLocation]'))
DROP INDEX [ix_Location_CountryCode] ON [dbo].[tLocation]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Location_ExposureSet] from [dbo].[tLocation]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Location_ExposureSet' AND object_id = OBJECT_ID(N'[dbo].[tLocation]'))
DROP INDEX [fk_Location_ExposureSet] ON [dbo].[tLocation]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_Location_GeographySID] from [dbo].[tLocation]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_Location_GeographySID' AND object_id = OBJECT_ID(N'[dbo].[tLocation]'))
DROP INDEX [ix_Location_GeographySID] ON [dbo].[tLocation]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_Location_LocationID] from [dbo].[tLocation]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_Location_LocationID' AND object_id = OBJECT_ID(N'[dbo].[tLocation]'))
DROP INDEX [ix_Location_LocationID] ON [dbo].[tLocation]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Location_ParentLocation] from [dbo].[tLocation]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Location_ParentLocation' AND object_id = OBJECT_ID(N'[dbo].[tLocation]'))
DROP INDEX [fk_Location_ParentLocation] ON [dbo].[tLocation]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_Location_Status] from [dbo].[tLocation]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_Location_Status' AND object_id = OBJECT_ID(N'[dbo].[tLocation]'))
DROP INDEX [fk_Location_Status] ON [dbo].[tLocation]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_ReinsAppliesToExp_ExposureSet] from [dbo].[tReinsAppliesToExp]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_ReinsAppliesToExp_ExposureSet' AND object_id = OBJECT_ID(N'[dbo].[tReinsAppliesToExp]'))
DROP INDEX [fk_ReinsAppliesToExp_ExposureSet] ON [dbo].[tReinsAppliesToExp]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_ReinsAppliesToExp_ReinsTargetSID] from [dbo].[tReinsAppliesToExp]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_ReinsAppliesToExp_ReinsTargetSID' AND object_id = OBJECT_ID(N'[dbo].[tReinsAppliesToExp]'))
DROP INDEX [ix_ReinsAppliesToExp_ReinsTargetSID] ON [dbo].[tReinsAppliesToExp]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_ReinsAppliesToExp_ReinsTargetType] from [dbo].[tReinsAppliesToExp]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_ReinsAppliesToExp_ReinsTargetType' AND object_id = OBJECT_ID(N'[dbo].[tReinsAppliesToExp]'))
DROP INDEX [fk_ReinsAppliesToExp_ReinsTargetType] ON [dbo].[tReinsAppliesToExp]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_ReinsAppliesToExp_ReinsuranceType] from [dbo].[tReinsAppliesToExp]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_ReinsAppliesToExp_ReinsuranceType' AND object_id = OBJECT_ID(N'[dbo].[tReinsAppliesToExp]'))
DROP INDEX [fk_ReinsAppliesToExp_ReinsuranceType] ON [dbo].[tReinsAppliesToExp]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [ix_ReinsuranceProgram_CompanySID] from [dbo].[tReinsuranceProgram]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_ReinsuranceProgram_CompanySID' AND object_id = OBJECT_ID(N'[dbo].[tReinsuranceProgram]'))
DROP INDEX [ix_ReinsuranceProgram_CompanySID] ON [dbo].[tReinsuranceProgram]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [IX_NC_U_tReinsuranceTreatySavedResults_1] from [dbo].[tReinsuranceTreatySavedResults]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_NC_U_tReinsuranceTreatySavedResults_1' AND object_id = OBJECT_ID(N'[dbo].[tReinsuranceTreatySavedResults]'))
DROP INDEX [IX_NC_U_tReinsuranceTreatySavedResults_1] ON [dbo].[tReinsuranceTreatySavedResults]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_StepFunctionDetail_StepFunction] from [dbo].[tStepFunctionDetail]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_StepFunctionDetail_StepFunction' AND object_id = OBJECT_ID(N'[dbo].[tStepFunctionDetail]'))
DROP INDEX [fk_StepFunctionDetail_StepFunction] ON [dbo].[tStepFunctionDetail]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [fk_StepFunction_Contract] from [dbo].[tStepFunction]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'fk_StepFunction_Contract' AND object_id = OBJECT_ID(N'[dbo].[tStepFunction]'))
DROP INDEX [fk_StepFunction_Contract] ON [dbo].[tStepFunction]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[rvDELETE_ReGetCompanyLossSets]'
GO
IF OBJECT_ID(N'[dbo].[rvDELETE_ReGetCompanyLossSets]', 'V') IS NOT NULL
DROP VIEW [dbo].[rvDELETE_ReGetCompanyLossSets]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[pDELETE_ReGetCompanyLossSets]'
GO
IF OBJECT_ID(N'[dbo].[pDELETE_ReGetCompanyLossSets]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[pDELETE_ReGetCompanyLossSets]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[pCOMMON_UpdatetSIDControl]'
GO
IF OBJECT_ID(N'[dbo].[pCOMMON_UpdatetSIDControl]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[pCOMMON_UpdatetSIDControl]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pDELETE_VacuumReinsuranceTreatyUDCClassification_Xref]'
GO
IF OBJECT_ID(N'[dbo].[pDELETE_VacuumReinsuranceTreatyUDCClassification_Xref]', 'P') IS NOT NULL
EXEC sp_executesql N'  /*****************************************************************************************************
Object: pDELETE_VacuumReinsuranceTreatyUDCClassification_Xref
Description: Removes rows on table tReinsuranceTreatyUDCClassification_Xref.
SPExposedToEntities: NO
ResultView: NA
******************************************************************************************************/
ALTER --ALTER
PROCEDURE [dbo].[pDELETE_VacuumReinsuranceTreatyUDCClassification_Xref]
	@BatchSize INT = 5000,
	@MaxRetries TINYINT = 3,
	@RetryWait VARCHAR(10) = ''00:00:05'',
	@Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT=0
	DECLARE @SPName NVARCHAR(392)=DB_NAME()+''.''+SCHEMA_NAME()+''.'' +OBJECT_NAME(@@PROCID)   
	DECLARE @RetryCount TINYINT=0  
	DECLARE @LastRowCount INT
	DECLARE @ErrorMsg VARCHAR(MAX)
    
	IF @Debug=1 EXEC dbo.pCOMMON_PrintVariable '': START OF '',@SPName
	
	BEGIN TRY
		BEGIN
			
			SET @LastRowCount = @BatchSize
			WHILE @LastRowCount = @BatchSize
			BEGIN
				
				SET @RetryCount = 0
				WHILE @RetryCount <= @MaxRetries
				BEGIN
					BEGIN TRY      
						DELETE TOP (@BatchSize) f
						  FROM tReinsuranceTreatyUDCClassification_Xref f /*HINT:Delete*/WITH (TABLOCK)/*HINT_End*/  
						  JOIN tReinsuranceTreaty e /*HINT:Delete*/WITH (TABLOCK)/*HINT_End*/ ON f.ReinsuranceTreatySID =e.ReinsuranceTreatySID
						  JOIN #DELETE_ReinsuranceProgramSID de /*HINT:Delete_Temp*/WITH (NOLOCK)/**HINT_End*/ ON e.ReinsuranceProgramSID = de.ReinsuranceProgramSID
						  JOIN tReinsuranceProgram p /*HINT:Delete_Temp*/WITH (NOLOCK)/**HINT_End*/ ON p.ReinsuranceProgramSID	=de.ReinsuranceProgramSID
						  			
						SET @lastRowCount = @@ROWCOUNT
						BREAK
					END TRY 
					BEGIN CATCH
						IF ERROR_NUMBER() IN (1205)
						BEGIN
							--Locking stuff, other retryable, etc.
							IF @RetryCount < @MaxRetries
							BEGIN
								SET @RetryCount = @RetryCount+1
								IF @Debug=1 PRINT ''Retry counter: '' + CAST(@RetryCount AS varchar)
								WAITFOR DELAY @RetryWait
								CONTINUE
							END
							ELSE
							BEGIN                   
								IF @Debug=1 PRINT @SPName +'': Retry counter exceeds maximum''
								EXECUTE @Result=dbo.pReThrowError @SPName, @Debug
								SET @LastRowCount = 0
								BREAK
							END
						END
						ELSE
						BEGIN
							EXECUTE @Result=dbo.pReThrowError @SPName, @Debug
							SET @LastRowCount = 0
							BREAK
						END					
					END CATCH                 
				END 
			END
		END 
	SET @Result = 0
	END TRY
	BEGIN CATCH
		EXECUTE @Result=dbo.pReThrowError @SPName, @Debug
	END CATCH;
	IF @Debug=1 EXEC dbo.pCOMMON_PrintVariable '': END OF '',@SPName
	RETURN @Result
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tReinsuranceProgramSourceInure]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tReinsuranceProgramSourceInure]', N'IsInuringNextProgramFlow') IS NOT NULL
ALTER TABLE [dbo].[tReinsuranceProgramSourceInure] DROP COLUMN [IsInuringNextProgramFlow]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tReinsuranceProgramStructure]'
GO
IF OBJECT_ID(N'[dbo].[tReinsuranceProgramStructure]', 'U') IS NULL
CREATE TABLE [dbo].[tReinsuranceProgramStructure]
(
[ReinsuranceProgramStructureSID] [int] NOT NULL,
[BusinessUnitSID] [int] NOT NULL,
[CompanySID] [int] NOT NULL,
[ReinsuranceProgramStructureName] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[StatusCode] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[EnteredDate] [datetime] NULL,
[EditedDate] [datetime] NULL,
[Author] [char] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Description] [varchar] (4000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[LayoutStructure] [xml] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [pk_tReinsuranceProgramStructure] on [dbo].[tReinsuranceProgramStructure]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'pk_tReinsuranceProgramStructure' AND object_id = OBJECT_ID(N'[dbo].[tReinsuranceProgramStructure]'))
ALTER TABLE [dbo].[tReinsuranceProgramStructure] ADD CONSTRAINT [pk_tReinsuranceProgramStructure] PRIMARY KEY CLUSTERED  ([ReinsuranceProgramStructureSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tReinsuranceProgramStructureXRef]'
GO
IF OBJECT_ID(N'[dbo].[tReinsuranceProgramStructureXRef]', 'U') IS NULL
CREATE TABLE [dbo].[tReinsuranceProgramStructureXRef]
(
[ReinsuranceProgramStructureSID] [int] NOT NULL,
[ReinsuranceProgramSID] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [pk_tReinsuranceProgramStructureXRef] on [dbo].[tReinsuranceProgramStructureXRef]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'pk_tReinsuranceProgramStructureXRef' AND object_id = OBJECT_ID(N'[dbo].[tReinsuranceProgramStructureXRef]'))
ALTER TABLE [dbo].[tReinsuranceProgramStructureXRef] ADD CONSTRAINT [pk_tReinsuranceProgramStructureXRef] PRIMARY KEY CLUSTERED  ([ReinsuranceProgramStructureSID], [ReinsuranceProgramSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating statistics [ReinsuranceProgramSID] on [dbo].[tReinsuranceProgramStructureXRef]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.stats WHERE name = N'ReinsuranceProgramSID' AND object_id = OBJECT_ID(N'[dbo].[tReinsuranceProgramStructureXRef]'))
CREATE STATISTICS [ReinsuranceProgramSID] ON [dbo].[tReinsuranceProgramStructureXRef] ([ReinsuranceProgramSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pEPTOULF_ReGetModeInfo]'
GO
IF OBJECT_ID(N'[dbo].[pEPTOULF_ReGetModeInfo]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
DATE :					mm-yyyy
OBJECT:					dbo.pEPTOULF_ReGetModeInfo 
DESCRIPTION:			Get Model information for given ActivitySID for EP to ULF feature
ExposedToEntities:		YES
ResultView:				rvEPTOULF_ReGetModeInfo
Usage:					
						DECLARE @ActivitySID INT = 1;
						
						DECLARE @Debug BIT = 1;
						EXECUTE AIRExposureRe.dbo.pEPTOULF_ReGetModeInfo @ActivitySID = @ActivitySID,
																		   
																		   @Debug = @Debug;
						
******************************************************************************************************/
ALTER   PROCEDURE [dbo].[pEPTOULF_ReGetModeInfo]
    @ActivitySID INT,
    @Debug BIT = 0
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        -- DECLARE VARIABLES
        DECLARE @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
                @Result INT = 0;
        DECLARE @ReinsuranceEPCurveSetSID INT;
        DECLARE @ReinsuranceEventSetSID INT;
        DECLARE @BusinessUnitSID INT;
        DECLARE @CatalogTypeCode INT = 2;
        DECLARE @SQLStmt VARCHAR(MAX);
        DECLARE @SQLStmt2 VARCHAR(MAX);
        DECLARE @TableSuffix_Adjusted sysname = N''EPTOULF_Adjusted'';
        -- SET VARIABLES
        EXEC @BusinessUnitSID = AIRProject.dbo.pCOMMON_ReGetBusinessUnitSID;
        -- DECLARE TABLE VARIABLES
        -- DECLARE TEMP TABLES
        --/*******************************************************************************
        --Start
        --*******************************************************************************/
        -- PRINT START OF PROC
        IF @Debug = 1
            EXEC @Result = dbo.pCOMMON_PrintVariable '': START OF '', @SPName;
        --/*******************************************************************************
        --Some cleanup on AdvancedJobOption to make this XML column readable to downstream ( unit Test) 
        --*******************************************************************************/
        UPDATE AIRProject.dbo.tActivity
        SET AdvancedJobOption = REPLACE(
                                           CONVERT(VARCHAR(MAX), AdvancedJobOption),
                                           ''xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"'',
                                           ''''
                                       )
        --OUTPUT deleted.AdvancedJobOption,
        --       inserted.AdvancedJobOption
        WHERE ActivitySID = @ActivitySID;
        --/*******************************************************************************
        --Get CurveSet data
        --*******************************************************************************/
        SELECT @ReinsuranceEPCurveSetSID
            = AdvancedJobOption.value(''(/ArrayOfKeyValueOfstringstring/KeyValueOfstringstring/Value)[1]'', ''int'')
        FROM AIRProject.dbo.tActivity
        WHERE ActivitySID = @ActivitySID;
        SELECT ReinsuranceEPCurveSetSID,
               CurrencyCode,
               CurrencyExchangeRateSetSID,
               ReinsuranceEventSetSID,
               ULFFileName,
               ULFComments,
               ULFGeoResolution,
               CompanySID,
               IsGenerateLMS,
               ULFCurrencyCode,
               ULFCurrencyExchangeRateSetSID,
               IsDemandSurgeOn
        INTO #tReinsuranceEPCurveSet
        FROM AIRExposureRe.dbo.tReinsuranceEPCurveSet
        WHERE ReinsuranceEPCurveSetSID = @ReinsuranceEPCurveSetSID;
        SELECT TOP 1
               @ReinsuranceEventSetSID = ReinsuranceEventSetSID
        FROM #tReinsuranceEPCurveSet;
        IF @Debug = 1
        BEGIN
            SELECT @SPName ''@SPName'',
                   @ReinsuranceEPCurveSetSID ''@ReinsuranceEPCurveSetSID'',
                   @ReinsuranceEventSetSID ''@ReinsuranceEventSetSID'';
            SELECT @SPName ''@SPName'',
                   ''#tReinsuranceEPCurveSet'';
            SELECT @SPName ''@SPName'',
                   ''#tReinsuranceEPCurveSet'',
                   *
            FROM #tReinsuranceEPCurveSet;
        END;
        --/*******************************************************************************
        --Get event set data 
        --*******************************************************************************/
        SELECT ModelCode,
               BaseName,
               EventMax,
               YearMax,
               ModelVersion,
               Version AS FileVersion,
               PerilSetCode,
               CatalogTypeCode,
               CatalogSubTypeCode
        INTO #tReinsuranceCatalog
        FROM AIRUserSetting.dbo.tReinsuranceCatalog cgg
            JOIN AIRUserSetting.dbo.tReinsuranceEventSetCatalogXRef cgx
                ON cgx.CatalogSID = cgg.CatalogSID
        WHERE cgg.CatalogTypeCode = @CatalogTypeCode
              AND cgx.ReinsuranceEventSetSID = @ReinsuranceEventSetSID
              AND cgg.BusinessUnitSID = @BusinessUnitSID;
        --/*******************************************************************************
        --Build and get final data for all curves 
        --*******************************************************************************/
        SET @SQLStmt = '''';
        SELECT @SQLStmt += '' 
		    
			SELECT ReinsuranceEPCurveSID,
                   ModelCode,
                   COUNT(DISTINCT YearID) AS YearCount,
                   COUNT(DISTINCT EventID) AS EventCount
            FROM '' + AIRProject.dbo.fEPToULF_GetTableNameWithDB(
                                                                   @ActivitySID,
                                                                   ReinsuranceEPCurveSID,
                                                                   NULL,
                                                                   @TableSuffix_Adjusted
                                                               )
                           + ''
            GROUP BY ReinsuranceEPCurveSID,
                     ModelCode
		'' + ''UNION ALL''
        FROM AIRExposureRe.dbo.tReinsuranceEPCurve
        WHERE ReinsuranceEPCurveSetSID = @ReinsuranceEPCurveSetSID;
        SET @SQLStmt = SUBSTRING(@SQLStmt, 1, LEN(@SQLStmt) - LEN(''UNION ALL''));
        SET @SQLStmt2
            = ''
		SELECT 
		   cs.ReinsuranceEPCurveSetSID,
		   c.ReinsuranceEPCurveSID,
		   cs.CurrencyCode,
		   cs.CurrencyExchangeRateSetSID,
		   cs.ReinsuranceEventSetSID,
		   cs.ULFFileName,
		   cs.ULFComments,
		   cs.ULFGeoResolution,
		   cs.CompanySID,
		   cs.IsGenerateLMS,
		   cs.ULFCurrencyCode,
		   cs.ULFCurrencyExchangeRateSetSID,
		   cs.IsDemandSurgeOn,
		   c.YearCount,
		   c.EventCount,
		   cg.ModelCode,
		   cg.BaseName,
		   cg.EventMax,
		   cg.YearMax,
		   cg.ModelVersion,
		   cg.FileVersion,
		   cg.PerilSetCode,
		   cg.CatalogTypeCode,
		   cg.CatalogSubTypeCode
        FROM
        (
			'' + @SQLStmt
              + ''
        ) c
            JOIN #tReinsuranceCatalog cg
                ON c.ModelCode = cg.ModelCode 
			CROSS JOIN 
			#tReinsuranceEPCurveSet cs	
				
				'';
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable '': @SqlStmt '', @SQLStmt2;
        EXECUTE (@SQLStmt2);
        --/*****************************************************************************************************
        --End
        --******************************************************************************************************/
        -- PRINT END OF PROC
        IF @Debug = 1
            EXEC @Result = dbo.pCOMMON_PrintVariable '': END OF '', @SPName;
        SET @Result = 0;
    END TRY
    BEGIN CATCH
        SET @Result = 1;
        -- re-raise the error to be caught in the calling process
        EXECUTE @Result = dbo.pReThrowError @SPName, @Debug;
    END CATCH;
    RETURN @Result;
END; -- OF PROC
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pEPTOULF_ReGetModelsFromCurveSet]'
GO
IF OBJECT_ID(N'[dbo].[pEPTOULF_ReGetModelsFromCurveSet]', 'P') IS NOT NULL
EXEC sp_executesql N' /******************************************************************************************************
Object:					pEPTOULF_ReGetModelsFromCurveSet
Description:				Get Model from CurveSetSID
SPExposedToEntities :		02/15/2021
ResultView:					rvReGetModelsFromCurveSet ?
Usage :
DECLARE	@return_value int
EXEC	@return_value = [dbo].[pEPTOULF_ReGetModelsFromCurveSet]
		@ReinsuranceEPCurveSetSID = 1,
		@Debug = 1
SELECT	''Return Value'' = @return_value
Notes : Name Changed
*******************************************************************************************************/
ALTER 
--ALTER
PROCEDURE [dbo].[pEPTOULF_ReGetModelsFromCurveSet]
(
	@ReinsuranceEPCurveSetSID BIGINT, 
	@Debug BIT=0
)
AS BEGIN
SET NOCOUNT ON
DECLARE 
	@SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
	@Result INT=0
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
	BEGIN TRY
			/*
		 --Get models when only parentGeograhySID is selected (Models by Country)
		 --Get models when special Area is selected  For Example Hawaii or Alaska : They have their own models
		  Example : 
			  All US
			  Hawaii/Alaska
			  AIR Earthquake Model for Hawaii
			  AIR Earthquake Model for Alaska
			  AIR Hurricane Model for Hawaii
		  */
		SELECT t.ReinsuranceEPCurveSID,
		   t.ModelCode,
		   t.BaseName
		FROM
		(
			SELECT DISTINCT
				   epcr.ReinsuranceEPCurveSID,
				   CONVERT(INT, c.ModelCode) AS ModelCode,
				   c.BaseName,
			   CASE
				   WHEN c.ModelCode = 41
						AND
						(
							(epcr.PerilSetCode & 1) > 0
							OR (epcr.PerilSetCode & 64) > 0
						) THEN
					   1
				   ELSE
					   c.PerilSetCode & epcr.PerilSetCode
			   END PerilValue
			FROM dbo.tReinsuranceEPCurveSet epcs (NOLOCK)
				INNER JOIN dbo.tReinsuranceEPCurve epcr (NOLOCK)
					ON epcr.ReinsuranceEPCurveSetSID = epcs.ReinsuranceEPCurveSetSID
				INNER JOIN AIRExposureRe.dbo.tAppliesToAreaGeoXRef gxref (NOLOCK)
					ON gxref.AppliesToAreaSID = epcr.AppliesToAreaSID
				INNER JOIN AIRReference.dbo.tModelGeographyXref mgxref
					ON mgxref.GeographySID = gxref.GeographySID
				INNER JOIN AIRUserSetting.dbo.tReinsuranceCatalog c (NOLOCK)
					ON c.ModelCode = mgxref.ModelCode
				INNER JOIN AIRUserSetting.dbo.tReinsuranceEventSetCatalogXRef cxref (NOLOCK)
					ON cxref.CatalogSID = c.CatalogSID
					   AND cxref.ReinsuranceEventSetSID = epcs.ReinsuranceEventSetSID
			WHERE epcs.ReinsuranceEPCurveSetSID = @ReinsuranceEPCurveSetSID
				  AND c.CatalogTypeCode = 2
		) t
		WHERE t.PerilValue > 0
		/*
		 --Get models for parent geographysids excluding special models for example Hawaii and Alaska?
		 --Get models for parent geographysids when only one child is selected (Example : In US, only one area is selected in appliestoarea)
		*/
		UNION
	SELECT t1.ReinsuranceEPCurveSID,
		   t1.ModelCode,
		   t1.BaseName
	FROM
	(
		SELECT DISTINCT
			   epcr.ReinsuranceEPCurveSID,
			   CONVERT(INT, c.ModelCode) AS ModelCode,
			   c.BaseName,
			   CASE
				   WHEN c.ModelCode = 41
						AND
						(
							(epcr.PerilSetCode & 1) > 0
							OR (epcr.PerilSetCode & 64) > 0
						) THEN
					   1
				   ELSE
					   c.PerilSetCode & epcr.PerilSetCode
			   END PerilValue
		FROM dbo.tReinsuranceEPCurveSet epcs (NOLOCK)
			INNER JOIN dbo.tReinsuranceEPCurve epcr (NOLOCK)
				ON epcr.ReinsuranceEPCurveSetSID = epcs.ReinsuranceEPCurveSetSID
			INNER JOIN AIRExposureRe.dbo.tAppliesToAreaGeoXRef gxref (NOLOCK)
				ON gxref.AppliesToAreaSID = epcr.AppliesToAreaSID
			INNER JOIN AIRGeography.dbo.tReinsuranceGeography g
				ON g.GeographySID = gxref.GeographySID
			INNER JOIN AIRReference.dbo.tModelGeographyXref mgxref
				ON (mgxref.GeographySID = g.ParentGeographySID)
			INNER JOIN AIRUserSetting.dbo.tReinsuranceCatalog c (NOLOCK)
				ON c.ModelCode = mgxref.ModelCode
			INNER JOIN AIRUserSetting.dbo.tReinsuranceEventSetCatalogXRef cxref (NOLOCK)
				ON cxref.CatalogSID = c.CatalogSID
				   AND cxref.ReinsuranceEventSetSID = epcs.ReinsuranceEventSetSID
		WHERE epcs.ReinsuranceEPCurveSetSID = @ReinsuranceEPCurveSetSID
			  AND c.CatalogTypeCode = 2
			  AND gxref.GeographySID NOT IN
				  (
					  SELECT x1.GeographySID
					  FROM AIRReference.dbo.tModelGeographyXref x1
					  WHERE x1.GeographySID = gxref.GeographySID
				  )
			  AND
			--Exclude Hawaii and Alaska Models
			NOT (
					g.CountryCode IN ( ''US'' )
					AND c.ModelCode IN ( 13, 14, 23 )
				)
) t1
WHERE t1.PerilValue > 0
ORDER BY t.ReinsuranceEPCurveSID;
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName;
		RETURN @Result; 
		END TRY
		BEGIN CATCH	
			-- re-raise the error to be caught in the calling process
			EXECUTE @Result = dbo.pReThrowError @SPName, @Debug;
		END CATCH;
	
END	
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLOSS_GenerateLocationStagingTable]'
GO
IF OBJECT_ID(N'[dbo].[pLOSS_GenerateLocationStagingTable]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
DESCRIPTION:	Creates and populates Tile Loss Staging table with list of Locations to analize.
******************************************************************************************************/
ALTER   --ALTER
PROCEDURE [dbo].[pLOSS_GenerateLocationStagingTable]
	@AnalysisSID INT
	,@ChunkID SMALLINT
	,@ExposureDataSourceSID INT
	,@DisaggregatedLocationRecords INT
	,@Debug BIT = FALSE
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
	BEGIN TRY
		DECLARE @SQLStmt NVARCHAR(MAX) = N''''
		DECLARE @SQLUnion NVARCHAR(20) = N''SELECT''
		DECLARE @LossStagingTable NVARCHAR(392)
		DECLARE @LocationMappingTable NVARCHAR(392)
		DECLARE @ContractMappingTable NVARCHAR(392)
		DECLARE @LocTermMappingTable NVARCHAR(392)
		DECLARE @ConObjectType CHAR(1) = ''5''	-- ObjectType of the Contract
		DECLARE @LocObjectType CHAR(1) = ''7''	-- ObjectType of the Location
	--	DECLARE @LConObjectType CHAR(1) = ''9''	-- ObjectType of the LayerCondition
		DECLARE @TargetCurrencyRate VARCHAR(30)
		DECLARE @TargetCurrencyCode CHAR(3)
		DECLARE @TargetCurrencyRateSetSID INT
		DECLARE @sExposureDataSourceSID VARCHAR(10) = CONVERT(VARCHAR(10), @ExposureDataSourceSID)
		DECLARE @ApplyDisaggregation BIT
		DECLARE @SourceTargetTableCount INT = 0
		DECLARE @OldCountryCode INT
		DECLARE @SourceTargetTable NVARCHAR(392)
		DECLARE @SourceTargetJoin NVARCHAR(MAX) = N''''
		DECLARE @AnalysisTypeCode VARCHAR(10)
		DECLARE @AuditStatusCode NVARCHAR(20) = N''1056964608''
		DECLARE @BusinessUnitSID INT
		DECLARE @AnyOffshoreLocs BIT = 0;
		DECLARE @EventSetTypeCode INT = 0
		DECLARE @CatalogTypeTag NVARCHAR(255)
		
		CREATE TABLE #SourceTargetTables (
			ID INT IDENTITY(1, 1) PRIMARY KEY
			,OldCountryCode INT
			,TableName NVARCHAR(392)
		)
		SET @LossStagingTable = AIRProject.dbo.fLOSS_GetStagingTableName (@AnalysisSID, @ChunkID, ''Location'')
		SET @LocationMappingTable = AIRProject.dbo.fLOSS_GetStagingTableName (@AnalysisSID, NULL, ''MLocation'')
		SET @ContractMappingTable = AIRProject.dbo.fLOSS_GetStagingTableName (@AnalysisSID, NULL, ''MContract'')
		SET @LocTermMappingTable = AIRProject.dbo.fLOSS_GetStagingTableName(@AnalysisSID, NULL, ''MLocTerm'')
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': @LossStagingTable '', @LossStagingTable
		-- Collect Currency conversion related variable
		SELECT 
			@TargetCurrencyRate = CONVERT(VARCHAR(30), TargetCurrencyRate)
			,@TargetCurrencyCode = TargetCurrencyCode
			,@TargetCurrencyRateSetSID = TargetCurrencyRateSetSID
		FROM AIRProject.dbo.fCOMMON_GetAnalysisCurrencyConversionInfo(@AnalysisSID)
		SELECT
			@ApplyDisaggregation = ApplyDisaggregation
		FROM AIRProject.dbo.tLossAnalysisOption
		WHERE AnalysisSID = @AnalysisSID
		---Getting UserSetting DB Name
		DECLARE @UserSettingDBName NVARCHAR(392)
        SET @UserSettingDBName = AirProject.dbo.fGetUserSettingDBName(1) 
		--Set Audit Status Code
		SELECT
			@AnalysisTypeCode = a.AnalysisTypeCode,
			@EventSetTypeCode = ISNULL(es.EventSetTypeCode,0),
			@CatalogTypeTag = es.CatalogTypeTag				
		FROM AIRProject.dbo.tAnalysis a
			INNER JOIN AIRProject.dbo.tAnalysisTargetXref atx ON atx.AnalysisSID = a.AnalysisSID
			LEFT OUTER JOIN AIRProject.dbo.tLossAnalysisOption ao ON ao.AnalysisSID = a.AnalysisSID
			LEFT OUTER JOIN AIRUserSetting.dbo.tEventSet es ON es.EventSetSID = ao.EventSetSID
		WHERE a.AnalysisSID = @AnalysisSID
		
		IF (@AnalysisTypeCode = ''EC'') OR (@AnalysisTypeCode = ''LOSS'' AND ( @EventSetTypeCode IN (6,10) OR @CatalogTypeTag=''MDLBDR'')) BEGIN --IDT loss and user event set, 10 is Model builder Event Set.
			SET @AuditStatusCode = N''0''
			END
		IF @AnalysisTypeCode = ''EC'' 
			BEGIN
				SET @SQLStmt = N''SELECT TOP 1 @AnyOffshoreLocs=1 FROM '' +  @LocationMappingTable + N'' LM 
					INNER JOIN dbo.tLocation (NOLOCK) LOC on LM.LocationSID = LOC.LocationSID
					INNER JOIN AirReference.dbo.tCountry CTY ON LOC.CountryCode = CTY.CountryCode
					WHERE CTY.IsOffshore=1'' 
				EXEC sp_executesql @SQLStmt, N''@AnyOffshoreLocs BIT OUTPUT'', @AnyOffshoreLocs OUTPUT
				IF @Debug = 1 AND @AnyOffshoreLocs = 1 EXEC dbo.pCOMMON_PrintVariable '': Offshore Locations  ''  
			END
		-- If disaggregation is turned off get list of countries and their respective SourceTarget tables to populate empty L3 and L4 fields
		IF @ApplyDisaggregation = 0 BEGIN
			SET @SQLStmt = N''
			;WITH DisaggregatableCountries AS (
				SELECT DISTINCT
					oae.intLevel1
				FROM '' + @LocationMappingTable + N'' LM
					INNER JOIN dbo.tLocation (NOLOCK) L ON L.LocationSID = LM.LocationSID
					INNER JOIN AIRGeography.dbo.TblAreaExternal oae (NOLOCK) ON L.GeographySID=oae.GeographySID
				WHERE (1=1)
					AND (LM.ChunkID = '' + CONVERT(VARCHAR(10), @ChunkID) + N'')
					AND (LM.ExposureDataSourceSID = '' + @sExposureDataSourceSID + N'')
					AND (L.AuditStatusCode >= '' + @AuditStatusCode + '')
					AND (LM.DisaggregationSID = 0)
			)
			INSERT INTO #SourceTargetTables (
				OldCountryCode
				,TableName
			)
			SELECT
				gpx.intAreaLevel1
				,''''AIRGeography.dbo.TblSourceTargetMap'''' + strTableSuffix
			FROM DisaggregatableCountries dc
				INNER JOIN AIRGeography.dbo.TblGridPartitionRef gpx (NOLOCK) ON gpx.intAreaLevel1 = dc.intLevel1
			WHERE blIgnoreDisagg = 0
			
			SET @SourceTargetTableCount = @@ROWCOUNT''
			IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Get list of SourceTarget tables:'', @SQLStmt
			EXEC sp_executesql @SQLStmt, N''@SourceTargetTableCount INT OUTPUT'', @SourceTargetTableCount OUTPUT
		END
		
		-- Getting the BusinessUnitSID for the Analysis. This BusinessUnitSID will be used for getting right DefaultLossAnalysisOptions
		-- from AIRUserSetting
		SELECT 
			@BusinessUnitSID = tP.BusinessUnitSID
		FROM
			AIRProject.dbo.tAnalysis tA
			INNER JOIN AIRProject.dbo.tProject tP
		ON 
			tA.ProjectSID = tP.ProjectSID
		WHERE
			tA.AnalysisSID = @AnalysisSID
		
		-- Statement to get data for Primary locations (Non-Disaggregated)
		SET @SQLStmt = N''
		WITH ForestryLandPrice AS (
		SELECT
			tG.CountryCode
		   ,UnitPrice 
           
		FROM
			[AIRUserSetting].[dbo].[tForestryLandPrice] tF
			INNER JOIN [AIRGeography].[dbo].[tGeography] tG ON tF.GeographySID = tG.GeographySID
			INNER JOIN [AIRUserSetting].[dbo].[tDefaultLossAnalysisOption] tD ON tF.DefaultLossAnalysisOptionSID = tD.DefaultLossAnalysisOptionSID
			
		WHERE
			tD.BusinessUnitSID = @BusinessUnitSID
			
		) 
		
		INSERT INTO '' + @LossStagingTable + N'' (
			guidLocation
			,guidContract
			,LocationID
			,Latitude
			,Longitude
			,GeocoderCode
			,GeocoderAccountId
			,RiskCount
			,ReplacementValueA
			,ReplacementValueB
			,ReplacementValueC
			,ReplacementValueD
			,AIRConstructionCodeA
			,AIRConstructionCodeB
			,AIROccupancyCode
			,YearBuilt
			,Stories
			,Premium
			,OldCountryCode
			,OldAreaCode
			,OldSubareaCode
			,OldPostalCode
			,LocationInceptionDate
			,LocationExpirationDate
			,ReplacementValueDaysCovered
			,guidAreaExternal
--			,GeographySID
			,LocationTypeCode
			,ChildLocationCount
			,guidLocationParent
			,CurrencyCode
			,OldGeoMatchLevelCode
			,ExposureDataSourceSID
			,LocationSID
			,DisaggregationSID
			,GrossArea
			,guidExposureAttribute 
			,UserDefined1
			,UserDefined5
			,UserGeoMatchLevel 
			,DamageFunctionID
		)''
		SET @SQLStmt += N''
		SELECT
			CAST(CAST(CAST(LM.ExposureDataSourceSID AS BINARY(8)) AS NVARCHAR) +
				CAST(CAST('' + @LocObjectType + N'' AS BINARY(4)) AS NVARCHAR) +
				CAST(CAST(LM.LocationSID AS BINARY(4)) AS NVARCHAR) AS BINARY(16)) AS guidLocation
			,CAST(CAST(CAST(LM.ExposureDataSourceSID AS BINARY(8)) AS NVARCHAR) +
				CAST(CAST('' + @ConObjectType + N'' AS BINARY(4)) AS NVARCHAR) +
				CAST(CAST(LM.ContractSID AS BINARY(4)) AS NVARCHAR) AS BINARY(16)) AS guidContract
			,L.LocationID 
			,CONVERT(REAL, LM.Latitude) AS Latitude
			,CONVERT(REAL, LM.Longitude) AS Longitude ''
			
	   SET @SQLStmt += N''
			,L.GeocoderCode AS GeocoderCode
			,L.GeocoderAccountId AS GeocoderAccountId
	        ,L.RiskCount
			,( CASE WHEN f.CountryCode is NULL THEN L.ReplacementValueA 
			   ELSE 
				CASE WHEN L.AIROccupancyCode = 375 AND L.ReplacementValueA = 0 THEN				
				L.GrossArea * 
				CASE WHEN L.GrossAreaUnitCode = ''''SQM'''' THEN  0.0001   --Converting the Gross Area(square meters) to Hectares
				ELSE  0.092903 * 0.0001 END  * f.UnitPrice --Converting the Gross Area(square feet) to square meters and then to Hectares
				ELSE L.ReplacementValueA END
				END
			  ) * CUR.ExchangeRate / '' + @TargetCurrencyRate + N'' AS ReplacementValueA '' 
		IF @AnalysisTypeCode = ''EC'' AND @AnyOffshoreLocs=1
			SET @SQLStmt += N''
				,(CASE WHEN CTY.IsOffshore = 1 THEN LTO.Limit2 ELSE L.ReplacementValueB END) * CUR.ExchangeRate / '' + @TargetCurrencyRate + N'' AS ReplacementValueB
				,(CASE WHEN CTY.IsOffshore = 1 THEN LTO.Limit3 ELSE L.ReplacementValueC END) * CUR.ExchangeRate / '' + @TargetCurrencyRate + N'' AS ReplacementValueC
				,(CASE WHEN CTY.IsOffshore = 1 THEN LTO.Limit4 ELSE L.ReplacementValueD END) * CUR.ExchangeRate / '' + @TargetCurrencyRate + N'' AS ReplacementValueD ''
		ELSE
			SET @SQLStmt += N''
				,L.ReplacementValueB * CUR.ExchangeRate / '' + @TargetCurrencyRate + N'' AS ReplacementValueB
				,L.ReplacementValueC * CUR.ExchangeRate / '' + @TargetCurrencyRate + N'' AS ReplacementValueC
				,L.ReplacementValueD * CUR.ExchangeRate / '' + @TargetCurrencyRate + N'' AS ReplacementValueD ''
		SET @SQLStmt += N''
			,L.AIRConstructionCodeA
			,L.AIRConstructionCodeB
			,L.AIROccupancyCode
			,L.YearBuilt
			,L.Stories
			,L.Premium * CUR.ExchangeRate / '' + @TargetCurrencyRate + N'' AS Premium
			,oae.intLevel1 OldCountryCode
			,ISNULL(oae.StrLevel2, ''''0'''') OldAreaCode
			,CASE WHEN am.intUserLevel1 is not null then am.strModelLevel3 ELSE ISNULL(oae.strLevel3, jm.strLevel3) END OldSubareaCode
			,CASE WHEN am.intUserLevel1 is not null then am.strModelLevel4 ELSE ISNULL(oae.strLevel4, jm.strLevel4) END OldPostalCode 
			,L.InceptionDate AS LocationInceptionDate
			,L.ExpirationDate AS LocationExpirationDate
			,L.ReplacementValueDaysCovered
			,CASE WHEN am.intUserLevel1 is not null then am.guidModel ELSE  oae.GuidExternal END GuidExternal
--			,L.GeographySID
			,CASE
				WHEN L.IsPrimaryLocation = 1 THEN ''''P''''				-- Primary Location
				WHEN L.ParentLocationSID IS NOT NULL THEN ''''S''''		-- Site (or Secondary) Location
				ELSE ''''R''''											-- Regular location
			 END AS LocationTypeCode
			,CASE
				WHEN '' + CASE @DisaggregatedLocationRecords WHEN 0 THEN N''(L.IsPrimaryLocation = 1) AND '' ELSE N'''' END + N''(L.ParentLocationSID IS NULL) THEN (SELECT COUNT(*) FROM dbo.tLocation (NOLOCK) chL WHERE chL.ParentLocationSID = L.LocationSID)
				ELSE 0
			 END AS ChildLocationCount
			,CAST(CAST(CAST(LM.ExposureDataSourceSID AS BINARY(8)) AS NVARCHAR) +
				CAST(CAST('' + @LocObjectType + N'' AS BINARY(4)) AS NVARCHAR) +
				CAST(CAST(L.ParentLocationSID AS BINARY(4)) AS NVARCHAR) AS BINARY(16)) AS guidLocationParent
			,CurrencyCode = '''''' + @TargetCurrencyCode + N''''''
			,gml.OldGeoMatchLevelCode
			,LM.ExposureDataSourceSID
			,LM.LocationSID
			,LM.DisaggregationSID
			,L.GrossArea * 
				CASE WHEN L.GrossAreaUnitCode = ''''SQM'''' THEN 10.763910
				ELSE 1 END AS GrossArea
			, CAST (LM. ExposureAttributeSID AS BINARY (16)) AS guidExposureAttribute 
			, L.UserDefined1 AS UserDefined1
			, L.UserDefined5 AS UserDefined5
			,L.UserGeoMatchLevel AS UserGeoMatchLevel 
			,L.DamageFunctionID AS DamageFunctionID ''			
			SET @SQLStmt += N''
			FROM '' + @LocationMappingTable + N'' LM
				INNER JOIN dbo.tLocation (NOLOCK) L ON L.LocationSID = LM.LocationSID
				INNER JOIN ''+@UserSettingDBName+''.dbo.tCurrencyExchangeRateSetConversion CUR (NOLOCK) ON CUR.CurrencyCode = L.CurrencyCode AND CUR.CurrencyExchangeRateSetSID = '' + CONVERT(VARCHAR(10), @TargetCurrencyRateSetSID) + 
				CASE WHEN @AnalysisTypeCode = ''EC'' then '' LEFT OUTER JOIN '' ELSE '' INNER JOIN '' END + N'' AIRGeography.dbo.TblAreaExternal oae (NOLOCK) ON L.GeographySID=oae.GeographySID  				
				LEFT OUTER JOIN ForestryLandPrice f ON f.CountryCode = L.CountryCode
				LEFT OUTER JOIN AIRGeography.dbo.TblAreaModel am (NOLOCK) ON oae.guidExternal = am.guidUser and am.intUserLevel1 in ( 1, 18)
				LEFT OUTER JOIN AIRReference.dbo.tConvertCL2GeoMatchLevel gml (NOLOCK) ON gml.GeoMatchLevelCode = L.GeoMatchLevelCode '' 
				IF @AnalysisTypeCode = ''EC'' AND @AnyOffshoreLocs=1 -- Outer Join to Get the MAX Limits for Offshore Locations
					SET @SQLStmt += N''
						LEFT JOIN (SELECT LocationSID, ISNULL(MAX(Limit2),0) Limit2, ISNULL(MAX(Limit3),0) Limit3, ISNULL(MAX(Limit4),0) Limit4
						FROM dbo.tLocTerm (NOLOCK) WHERE LimitTypeCode=''''C'''' GROUP BY LocationSID) LTO ON L.LocationSID = LTO.LocationSID 
						LEFT OUTER JOIN AIRReference.dbo.tCountry CTY ON L.CountryCode = CTY.CountryCode ''
			SET @SQLStmt += N''
			OUTER APPLY (
					SELECT
						ae.strLevel3
						,ae.strLevel4
					FROM [AIRReference].[dbo].[tAIROccupancyWeightTypeXref] (NOLOCK) owtx
						INNER JOIN AIRGeography.dbo.TblAreaDistribution_xref (NOLOCK) adx ON (adx.intWeightTypeId = owtx.AIROccupancyWeightTypeCode) AND (adx.guidExternalAgg = oae.guidExternal)
						INNER JOIN AIRGeography.dbo.tblAreaExternal (NOLOCK) ae ON ae.guidExternal = adx.guidExternalDetail  					
					WHERE (L.CountryCode IN (''''JP'''', ''''MX''''))
						AND (oae.strLevel4 IS NULL)
						AND (owtx.AIROccupancyCode = L.AIROccupancyCode)
				) jm
			WHERE (1=1)
				AND (LM.ChunkID = '' + CONVERT(VARCHAR(10), @ChunkID) + N'')
				AND (LM.ExposureDataSourceSID = '' + @sExposureDataSourceSID + N'')
				AND (L.AuditStatusCode >= '' + @AuditStatusCode + '')
				AND (LM.DisaggregationSID = 0)
			ORDER BY
				LM.ContractSID, LM.LocationSID
			OPTION (RECOMPILE)''
			IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate Non-Disaggregated LocationStaging:'', @SQLStmt
			IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate Non-Disaggregated LocationStaging:'', @SQLStmt
		EXEC sp_executesql @SQLStmt, N''@BusinessUnitSID INT'',@BusinessUnitSID 
		-- Backfill L3 and L4 fields for non-disaggregated locations in certain countries based on SourceTarget tables
		WHILE @SourceTargetTableCount > 0 BEGIN
			SELECT
				@OldCountryCode = OldCountryCode
				,@SourceTargetTable = TableName
			FROM #SourceTargetTables
			WHERE ID = @SourceTargetTableCount
			SET @SQLStmt = N''
			UPDATE L SET
				OldSubareaCode = E.strLevel3
				,OldPostalCode = E.strLevel4
			FROM '' + @LossStagingTable + N'' L
				INNER JOIN [AIRReference].[dbo].[tAIROccupancyWeightTypeXref] W (NOLOCK) ON W.AIROccupancyCode = L.AIROccupancyCode
				INNER JOIN AIRGeography.dbo.TblSourceDefaultTarget_Xref A (NOLOCK) ON A.guidExternalSource = L.guidAreaExternal AND A.intWeightTypeId = W.AIROccupancyWeightTypeCode
				INNER JOIN '' + @SourceTargetTable + '' E (NOLOCK) ON E.guidExternalSource = A.guidExternalSource AND E.intWeightTypeId = A.intWeightTypeId AND E.intGridID = A.intGridIdDefault
			WHERE L.OldCountryCode = '' + CONVERT(NVARCHAR(20), @OldCountryCode) + N''
				AND L.OldSubareaCode IS NULL''
			IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''UPDATE L3 and L4 fields for non-disaggregated locations:'', @SQLStmt
			EXEC sp_executesql @SQLStmt
			SET @SourceTargetTableCount -= 1
		END
		IF @DisaggregatedLocationRecords > 0 BEGIN
			SET @SQLStmt = N''
			UPDATE STATISTICS '' + @LossStagingTable
			IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': UPDATE STATISTICS on Location Staging Table:'', @SQLStmt
			EXEC sp_executesql @SQLStmt
			-- Statement to get data for Disaggregated locations
			SET @SQLStmt = N''
			INSERT INTO '' + @LossStagingTable + N'' (
				guidLocation
				,guidContract
				,LocationId
				,Latitude
				,Longitude
				,GeocoderCode
				,GeocoderAccountId
				,RiskCount
				,ReplacementValueA
				,ReplacementValueB
				,ReplacementValueC
				,ReplacementValueD
				,AIRConstructionCodeA
				,AIRConstructionCodeB
				,AIROccupancyCode
				,YearBuilt
				,Stories
				,Premium
				,OldCountryCode
				,OldAreaCode
				,OldSubareaCode
				,OldPostalCode
				,LocationInceptionDate
				,LocationExpirationDate
				,ReplacementValueDaysCovered
				,guidAreaExternal
--				,GeographySID
				,LocationTypeCode
				,ChildLocationCount
				,guidLocationParent
				,CurrencyCode
				,OldGeoMatchLevelCode
				,ExposureDataSourceSID
				,LocationSID
				,DisaggregationSID
				,GrossArea
			)''
			SET @SQLStmt += N''
			SELECT
				CAST(CAST(CAST(LM.LocationSID AS BINARY(4)) AS NVARCHAR) +
					CAST(CAST(LM.ExposureDataSourceSID AS BINARY(4)) AS NVARCHAR) +
					CAST(CAST('' + @LocObjectType + N'' AS BINARY(4)) AS NVARCHAR) +
					CAST(CAST(LM.DisaggregationSID AS BINARY(4)) AS NVARCHAR) AS BINARY(16)) AS guidLocation
				,CAST(CAST(CAST(LM.ExposureDataSourceSID AS BINARY(8)) AS NVARCHAR) +
					CAST(CAST('' + @ConObjectType + N'' AS BINARY(4)) AS NVARCHAR) +
					CAST(CAST(LM.ContractSID AS BINARY(4)) AS NVARCHAR) AS BINARY(16)) AS guidContract 
					,L.LocationId 
					,LM.Latitude
					,LM.Longitude
					,LM.GeocoderCode
					,LM.GeocoderAccountId''
			
	   SET @SQLStmt += N''
				,L.RiskCount
				,L.ReplacementValueA * LM.DisaggregationRatio AS ReplacementValueA		-- Financial fields for Disaggregated locations do not need to be converted to different currency because they derrived from already converted Parent values ''
		IF @AnalysisTypeCode = ''EC'' AND @AnyOffshoreLocs =1
			SET @SQLStmt += N''
				,(CASE WHEN CTY.IsOffshore = 1 THEN LTO.Limit2 ELSE L.ReplacementValueB END) * LM.DisaggregationRatio AS ReplacementValueB
				,(CASE WHEN CTY.IsOffshore = 1 THEN LTO.Limit3 ELSE L.ReplacementValueC END) * LM.DisaggregationRatio AS ReplacementValueC
				,(CASE WHEN CTY.IsOffshore = 1 THEN LTO.Limit4 ELSE L.ReplacementValueD END) * LM.DisaggregationRatio AS ReplacementValueD ''
		ELSE
			SET @SQLStmt += N''
				,L.ReplacementValueB * LM.DisaggregationRatio AS ReplacementValueB
				,L.ReplacementValueC * LM.DisaggregationRatio AS ReplacementValueC
				,L.ReplacementValueD * LM.DisaggregationRatio AS ReplacementValueD ''
			SET @SQLStmt += N''
				,L.AIRConstructionCodeA
				,L.AIRConstructionCodeB
				,L.AIROccupancyCode
				,L.YearBuilt
				,L.Stories
				,L.Premium * LM.DisaggregationRatio AS Premium
				,oae.intLevel1 OldCountryCode
				,oae.StrLevel2 OldAreaCode
				,oae.strLevel3 OldSubareaCode
				,oae.strLevel4 OldPostalCode
				,L.LocationInceptionDate
				,L.LocationExpirationDate
				,L.ReplacementValueDaysCovered
				,g.GuidExternal
--				,LM.GeographySID
				,''''D'''' AS LocationTypeCode	-- Disaggregated Location
				,0 AS ChildLocationCount
				,L.guidLocation AS guidLocationParent
				,L.CurrencyCode
				,OldGeoMatchLevelCode = 9999		-- This is artificial Disaggregated locations Geocode value
				,LM.ExposureDataSourceSID
				,LM.LocationSID
				,LM.DisaggregationSID	
				,(CASE WHEN LM.Countrycode=''''US'''' THEN L.GrossArea ELSE NULL END)
				FROM '' + @LocationMappingTable + N'' LM
				INNER JOIN '' + @LossStagingTable + N'' L ON (L.ExposureDataSourceSID = LM.ExposureDataSourceSID) AND (L.LocationSID = LM.LocationSID)
				INNER JOIN AIRGeography.dbo.tGeography g (NOLOCK) ON g.GeographySID = LM.GeographySID
				INNER JOIN AIRGeography.dbo.TblAreaExternal oae (NOLOCK) ON oae.guidExternal = g.GuidExternal '' 				
			IF @AnalysisTypeCode = ''EC'' AND @AnyOffshoreLocs=1 -- Outer Join to Get the MAX Limits for Offshore Locations
			SET @SQLStmt += N''
				JOIN dbo.tLocation LOC on L.LocationSID = LOC.LocationSID
				LEFT JOIN (SELECT LocationSID, ISNULL(MAX(Limit2),0) Limit2, ISNULL(MAX(Limit3),0) Limit3, ISNULL(MAX(Limit4),0) Limit4
				FROM dbo.tLocTerm (NOLOCK) WHERE LimitTypeCode=''''C'''' GROUP BY LocationSID) LTO ON LOC.LocationSID = LTO.LocationSID 
				LEFT OUTER JOIN AIRReference.dbo.tCountry CTY ON LOC.CountryCode = CTY.CountryCode ''
									
			SET @SQLStmt += N''
			WHERE (1=1)
				AND (LM.ChunkID = '' + CONVERT(VARCHAR(10), @ChunkID) + N'')
				AND (LM.ExposureDataSourceSID = '' + @sExposureDataSourceSID + N'')
				AND (LM.DisaggregationSID > 0)
			ORDER BY
				LM.ContractSID, LM.LocationSID''
			IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LocationStaging with Disaggregated locations:'', @SQLStmt
			EXEC sp_executesql @SQLStmt
		END
		-- Calculate number of Child locations (Disaggregated and Site) per Primary location
		SET @SQLStmt = N''
		;WITH ParentLocations AS (
			SELECT
				P.guidLocation
				,ChildrenCount = COUNT(*)
			FROM '' + @LossStagingTable + N'' P
				INNER JOIN '' + @LossStagingTable + N'' Ch ON Ch.guidLocationParent = P.guidLocation
			WHERE P.LocationTypeCode IN (''''P'''', ''''R'''')
				AND P.ChildLocationCount = 0
			GROUP BY P.guidLocation
			HAVING COUNT(*) > 0
		)
		UPDATE LS SET
			ChildLocationCount = P.ChildrenCount
		FROM '' + @LossStagingTable + N'' LS
			INNER JOIN ParentLocations P ON P.guidLocation = LS.guidLocation''
        
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update LocationStaging with Child locations Count:'', @SQLStmt
		EXEC sp_executesql @SQLStmt
		
		-- Setting the Replacement values of Secondry Location to 0 when it is dissagregated .
		SET @SQLStmt =N'' 
		UPDATE LS SET
			LS.ReplacementValueA = 0
			,LS.ReplacementValueB = 0
			,LS.ReplacementValueC = 0
			,LS.ReplacementValueD = 0
		FROM '' + @LossStagingTable + N'' LS	
		INNER JOIN (SELECT [LocationSID], ExposureDataSourceSID 
			FROM '' + @LossStagingTable + N''
			WHERE LocationTypeCode=''''D'''') LS2		
		ON LS.[LocationSID] = LS2.[LocationSID]  AND LS.ExposureDataSourceSID=LS2.ExposureDataSourceSID
		WHERE LS.LocationTypeCode = ''''S''''''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update LocationStaging Secondary Location RV to 0 when dissagregated:'', @SQLStmt
		EXEC sp_executesql @SQLStmt
		SET @Result = 0
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
	RETURN @Result
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pGet_CLASizeByCompany]'
GO
IF OBJECT_ID(N'[dbo].[pGet_CLASizeByCompany]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
Object: [dbo].[pGet_CLASizeByCompany]
Description: This Stored Procedure will Calculate the CLA size for each company in one or more than one AIRCompanyLoss DB''s in one instance.
******************************************************************************************************/
ALTER PROCEDURE [dbo].[pGet_CLASizeByCompany] 
@Debug BIT = FALSE
AS 
BEGIN
	SET NOCOUNT ON    
	DECLARE @Result INT
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
    
	BEGIN TRY  
	DECLARE @SQLStmt NVARCHAR(MAX) 
	DECLARE @Counter INT = 1
	DECLARE @Count INT 
	DECLARE @CurrentDBName VARCHAR(256)
	CREATE TABLE #CompanyandLossSets (CompanySID INT,LossSetSID INT, DBName VARCHAR(256))
	CREATE TABLE #DistinctAIRCompanyLossDBList (RWID INT IDENTITY(1,1),DBName VARCHAR(256))
	CREATE TABLE #CompanyCLASizes (CompanySID INT, DBName VARCHAR(256), CLASizeinMB FLOAT,Table_Name  VARCHAR(256), CompanyLossSetSID INT)	
	CREATE TABLE #CompanyCLASizeswithModel (CompanySID INT,LossSetSID INT, DBName VARCHAR(256), CLASizeinMB FLOAT,Table_Name  VARCHAR(256), Modelcode INT, Modelversion VARCHAR(10) )	
		
	INSERT INTO #CompanyandLossSets
		SELECT DISTINCT CLA.CompanySID, CLA.CompanyLossSetSID ,  CLA.DataSourceName   FROM  [tCompanyLossAssociation] CLA
		INNER JOIN [tCompany] C ON C.CompanySID = CLA.CompanySID
		LEFT JOIN tCompanyCLASizes CLAS ON CLAS.CompanySID = C.CompanySID and CLAS.DataSourceName = CLA.DataSourceName AND CLAS.CompanyLossSetSID = CLA.CompanyLossSetSID						
		WHERE C.StatusCode = ''A'' AND CLA.StatusCode = ''A''  AND LossTypeCode = ''DB'' AND CLAS.CompanyLossSetSID IS NULL 
	INSERT INTO #DistinctAIRCompanyLossDBList (DBName)				
						SELECT DISTINCT CLS.DBName FROM #CompanyandLossSets CLS
						
						
	IF @Debug = 1	EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt =  '',@SQLStmt
	EXEC sp_executesql @SQLStmt
	
	SELECT @Count = MAX(RWID) FROM #DistinctAIRCompanyLossDBList
	WHILE @Counter <= @Count
	BEGIN
		SELECT @CurrentDBName = DBName FROM #DistinctAIRCompanyLossDBList WHERE RWID = @Counter
		IF EXISTS(SELECT 1 FROM sys.databases WHERE name = @CurrentDBName)
		BEGIN
		SET @SQLStmt = N'' DROP TABLE IF EXISTS #CompanyTables;
							CREATE TABLE #CompanyTables (CompanySID INT, object_id INT,Table_Name  VARCHAR(256), CompanyLossSetSID INT)	
		
						 ;WITH TableNameSuffix
							AS
							(
							SELECT DISTINCT CALS.CompanySID, CAST(ActivitySID AS NVARCHAR(10))+''''_''''+CAST(AnalysisSID AS NVARCHAR(10)) ActivitySID_AnalysisSID, tCLS.CompanyLossSetSID
							FROM [''+@CurrentDBName+''].dbo.tCompanyLossSet tCLS
							INNER JOIN #CompanyandLossSets CALS ON tCLS.CompanyLossSetSID = CALS.LossSetSID							
							WHERE CALS.DBName = ''''''+@CurrentDBName+''''''							
							)
							INSERT INTO #CompanyTables (CompanySID,object_id,Table_Name,CompanyLossSetSID )
							SELECT 
							TNS.CompanySID
							,T.object_id  
							,T.Name
							,CompanyLossSetSID
							FROM TableNameSuffix TNS
							INNER JOIN [''+@CurrentDBName+''].sys.tables T ON T.Name LIKE ''''tCLEXPORT%'''' AND T.Name LIKE ''''%''''+ ActivitySID_AnalysisSID
							''
		SET @SQLStmt += N'' INSERT INTO #CompanyCLASizes (CompanySID,DBName,CLASizeinMB, Table_Name, CompanyLossSetSID )
							SELECT 
							TNS.CompanySID
							,''''''+@CurrentDBName+''''''
							,CAST(ROUND(((SUM(AU.total_pages) * 8) / 1024.00), 2) AS Float) AS CLASizeinMB
							, TNS.Table_Name AS Table_Name
							, CompanyLossSetSID
							FROM #CompanyTables TNS
							INNER JOIN [''+@CurrentDBName+''].sys.indexes I ON TNS.object_id = I.object_id 
							INNER JOIN [''+@CurrentDBName+''].sys.partitions P ON I.object_id = P.object_id AND I.index_id = P.index_id
							INNER JOIN [''+@CurrentDBName+''].sys.allocation_units AU ON P.partition_id = AU.container_id
							GROUP BY
							TNS.CompanySID
							,TNS.Table_Name
							,CompanyLossSetSID
							''
		SET @SQLStmt += N'' INSERT INTO #CompanyCLASizeswithModel (CompanySID,LossSetSID,DBName,CLASizeinMB, Table_Name, Modelcode , Modelversion)
							SELECT 
							DISTINCT 
							CLA.CompanySID,CLC.CompanyLossSetSID, CLA.DBName,CLA.CLASizeinMB, CLA.Table_Name,CLC.Modelcode,CLC.Modelversion
							FROM #CompanyCLASizes CLA
							INNER JOIN [''+@CurrentDBName+''].dbo.tCompanyLossCatalog CLC ON CLC.[TableName] = CLA.Table_Name
							AND CLC.CompanyLossSetSID = CLA.CompanyLossSetSID ''
		IF @Debug = 1	EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt =  '',@SQLStmt
		EXEC sp_executesql @SQLStmt
		END
		SET @Counter = @Counter + 1
	END
	DELETE CLA  FROM tCompanyCLASizes CLA 
	INNER JOIN #CompanyCLASizes CLAT ON CLAT.CompanySID = CLA.CompanySID AND CLAT.DBName = CLA.DataSourceName
	INSERT INTO tCompanyCLASizes
	SELECT DISTINCT CLS.CompanySID, CLS.LossSetSID,Table_Name, CLS.DBName, CLASizeinMB,Modelcode,Modelversion FROM #CompanyandLossSets CLS
						INNER JOIN #CompanyCLASizeswithModel CLA ON CLS.CompanySID = CLA.CompanySID and CLA.DBName = CLS.DBName and CLA.LossSetSID = CLS.LossSetSID 
	
	SET @Result = 0
	END TRY
	BEGIN CATCH
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH
	RETURN @Result
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pGetAggregateExposureByCountry]'
GO
IF OBJECT_ID(N'[dbo].[pGetAggregateExposureByCountry]', 'P') IS NOT NULL
EXEC sp_executesql N'  /**********************************************************************************************************
OBJECT:				dbo.pGetAggregateExposureByCountry
DESCRIPTION:		Returns aggregate exposure on Country level filtered according to input parameters
ExposedToEntities:	Yes
ResultView:			rvGetAggregateExposureByCountry
Usage:				EXEC dbo.pGetAggregateExposureByCountry 
						@ExposureSetSID = 8, 
						@YearID = 2016, 
						@PerilSetCode = 67, 
						@Debug = 0
**********************************************************************************************************/
ALTER 
-- ALTER
 PROCEDURE [dbo].[pGetAggregateExposureByCountry]
	@ExposureSetSID INT, 
	@YearID INT, 
	@PerilSetCode INT, 
	@Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
	declare @companySID INT = 0
	DECLARE @Result INT = 0
	DECLARE @SPName SYSNAME = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	BEGIN TRY
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		IF EXISTS (SELECT 1 FROM [dbo].[tExposureSet] WHERE [ExposureSetSID]=@ExposureSetSID AND StatusCode!=''A'')
			RETURN 0;
		 select @companySID= companysid from tExposureSet where ExposureSetSID = @ExposureSetSID;
		 /*
			Start: Get a list of Custom LOB per Exposureset and Country
		 */
		 DECLARE @OutputExposureSet TABLE
            (
                ExposureSetSID		INT,
                CountryCode			VARCHAR(10),
                CountryID			INT,
                LOBCode				INT
            )
       ;WITH cte_LOB
            AS (
				SELECT LOBCode,
                       LOB,
                       CustomLOBIndex					= ROW_NUMBER() OVER (ORDER BY LOBCode)
                FROM 
					AIRReference.dbo.tReinsuranceLOB
                WHERE 
					LOBcode								BETWEEN 148 AND 167
				)
            INSERT INTO @OutputExposureSet
            (
                ExposureSetSID,
                CountryCode,
                CountryID,
                LOBCode
            )
            SELECT tae.ExposureSetSID,
                   tcl.CountryCode,
                   tcl.CountryID,
                   cte.LOBCode
            FROM 
				AIRUserSetting.dbo.tCustomLOB			tcl
            INNER JOIN 
				cte_LOB									cte  ON 
				(
					tcl.CustomLOBIndex					= cte.CustomLOBIndex
				)
            INNER JOIN 
				AIRExposureRe.dbo.tAggregateExposure	tae ON 
					(
						tae.CountryCode					= tcl.CountryCode
					AND tae.LOBCode						= cte.LOBCode
                    )
			WHERE 
				tae.ExposureSetSID						= @ExposureSetSID
            GROUP BY 
				tae.ExposureSetSID,
				tcl.CountryCode,
				tcl.CountryID,
				cte.LOBCode;
			/*
			End: Get a list of Custom LOB per Exposureset and Country
			*/
		;WITH AggExp AS (
			SELECT ExposureSetSID,
						PerilSetCode,
						YearID,
						MAX(IntAreaScheme) AS IntAreaScheme,
						MAX(GeographySID) AS GeographySID,
						CountryCode,
						CountryName,
						MAX(CurrencyCode) AS CurrencyCode
			FROM  dbo.tAggregateExposure
			WHERE 
				ExposureSetSID = @ExposureSetSID
				AND YearID = @YearID 
				AND PerilSetCode = @PerilSetCode
			GROUP BY 
				ExposureSetSID,
				PerilSetCode,
				YearID,
				CountryCode,
				CountryName
		) 
		SELECT  
			ExposureSetSID,
			PerilSetCode,
			YearID,
			IntAreaScheme,
			GeographySID,
			a.CountryCode,
			CountryName,
			CurrencyCode,
			b.TotalInsuredValue,
			RiskCount,
			Premium,
			Payroll,
			Rates, 
			UserSpecifiedMarketShare,
			cast(0 as bit) as IsLossMarketShare,
            ISNULL(d.TotalInsuredValue, 0) AS CustomSumsInsured
		FROM AggExp a
		LEFT JOIN (
			SELECT countrycode,
				ISNULL(SUM(TotalInsuredValue), 0) AS TotalInsuredValue,
				ISNULL(SUM(RiskCount),0) AS RiskCount,
				ISNULL(SUM(Premium),0) AS Premium,
				ISNULL(SUM(Payroll),0) AS Payroll
			FROM  dbo.tAggregateExposure
			WHERE 
				ExposureSetSID = @ExposureSetSID
				AND YearID = @YearID 
				AND PerilSetCode = @PerilSetCode 
				AND lobcode NOT BETWEEN 148 AND 167
				AND GeoLevelCode = ''COUN''
			GROUP BY countrycode
		
			) b ON a.countrycode = b.countrycode
		LEFT JOIN (
			SELECT countrycode,
				ISNULL(MAX(Rates),0) AS Rates, 
				ISNULL(MAX(UserSpecifiedMarketShare),0) AS UserSpecifiedMarketShare
			FROM  dbo.tAggregateExposure
			WHERE 
				ExposureSetSID = @ExposureSetSID
				AND YearID = @YearID 
				AND PerilSetCode = @PerilSetCode
				AND lobcode NOT BETWEEN 148 AND 167 
			GROUP BY countrycode				
		
		) c on a.CountryCode = c.CountryCode
		LEFT JOIN (
                     SELECT  
							tae.countrycode,
							ISNULL(SUM(tae.TotalInsuredValue), 0) AS TotalInsuredValue
                     FROM  
							dbo.tAggregateExposure	tae
						INNER JOIN
							@OutputExposureSet		o on
							(
								tae.ExposureSetSID	= o.ExposureSetSID
							AND tae.CountryCode		= o.CountryCode
							AND tae.LOBCode			= o.LOBCode
							)
                     WHERE 
						 tae.ExposureSetSID			= @ExposureSetSID
                     AND tae.YearID					= @YearID 
                     AND tae.PerilSetCode			= @PerilSetCode 
                     AND tae.GeoLevelCode			= ''COUN''
                     AND tae.lobcode				BETWEEN 148 AND 167
                     GROUP BY 
						tae.countrycode
              ) d on a.CountryCode = d.CountryCode 
		UNION ALL
		SELECT  
			@ExposureSetSID as ExposureSetSID
			,MAX(TLM.[PerilSetCode]) AS [PerilSetCode]
			,cast (@YearID as smallint) AS [YearID]
			,MAX( TG.[AreaScheme]) as IntAreaScheme 
			,MAX(TLM.[CountrySID]) AS [GeographySID]
			,MAX(TLM.[CountryCode]) AS [CountryCode]
			,MAX(TLM.[CountryName]) AS [CountryName]
			,MAX(TLM.[CurrencyCode]) AS [CurrencyCode]
			,0 as TotalInsuredValue 
			,0 as RiskCount 
			,0 as Premium 
			,0 as Payroll 
			,0 as Rates 
			,0 as UserSpecifiedMarketShare 
			,cast(1 as bit) AS  [IsLossMarketShare],
            0 AS CustomSumsInsured
		FROM [AIRExposureRe].[dbo].[tCompanyLossMarketShare] TLM
		inner join tCompanyLossAssociation cla on cla.CompanyLossAssociationSID = tlm.CompanyLossAssociationSID
		LEFT JOIN  [AIRGeography].[dbo].[tGeography] TG
		ON TLM.[CountrySID] = TG.GeographySID
		WHERE 
			--YearID = @YearID  AND 
			cla.statuscode = ''A'' and
			ROUND(TLM.LossMarketShare* 100,2) > 0 and 
			CASE WHEN PerilSetCode IN ( 3, 67 ) THEN 67
                                  ELSE PerilSetCode
                             END = @PerilSetCode AND
							 cla.companySid = @companySID
		GROUP BY TLM.[CountryCode]
		
		ORDER BY 
			a.CountryCode, 
			ExposureSetSID,
			PerilSetCode,
			YearID		
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
		RETURN @Result
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
END		-- Proc
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Refreshing [dbo].[rvGetContractListByGeoFilter]'
GO
IF OBJECT_ID(N'[dbo].[rvGetContractListByGeoFilter]', 'V') IS NOT NULL
EXEC sp_refreshview N'[dbo].[rvGetContractListByGeoFilter]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pGetAggregateExposureMaxYearByReinsuranceProgramSID]'
GO
IF OBJECT_ID(N'[dbo].[pGetAggregateExposureMaxYearByReinsuranceProgramSID]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
DATE :					02-06-2018
OBJECT:					dbo.pGetAggregateExposureMaxYearByReinsuranceProgramSID 
DESCRIPTION:			Get AggExposure Max Year 
ExposedToEntities:		YES
ResultView:				None
Usage		:			DECLARE @ReinsuranceProgramSID INT = 1
						DECLARE @Debug BIT = 1
						EXECUTE [dbo].pGetAggregateExposureMaxYearByReinsuranceProgramSID @ReinsuranceProgramSID,@Debug
						
******************************************************************************************************/
ALTER
--ALTER 
PROCEDURE [dbo].[pGetAggregateExposureMaxYearByReinsuranceProgramSID] 
(
	 @ReinsuranceProgramSID INT 
	,@Debug BIT = 0
)		
AS
BEGIN
	SET NOCOUNT ON
	DECLARE 
	@Result INT=0,
	@SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	BEGIN TRY
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		SELECT   CASE WHEN pt.YearSID IS NULL THEN MAX(CAST(ae.YearID AS INT))
					  ELSE pt.YearSID
				 END AS MaxYear
		FROM     AIRExposureRe.dbo.tAggregateExposure ae
				 INNER JOIN AIRExposureRe.dbo.tExposureSet es ON es.ExposureSetSID = ae.ExposureSetSID
				 INNER JOIN AIRExposureRe.dbo.tReinsuranceProgram rp ON rp.CompanySID = es.CompanySID
				 INNER JOIN AIRExposureRe.dbo.tReinsuranceProgramTargetXRef pt ON pt.ReinsuranceProgramSID = rp.ReinsuranceProgramSID
																				  AND pt.ExposureSetSID = ae.ExposureSetSID
		WHERE    pt.ReinsuranceProgramSID = @ReinsuranceProgramSID
				 AND pt.ExposureSetSID IS NOT NULL
		GROUP BY pt.YearSID
				
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
	RETURN @Result 
	END TRY
	BEGIN CATCH	
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH
	
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pGetCatBondAttributeData]'
GO
IF OBJECT_ID(N'[dbo].[pGetCatBondAttributeData]', 'P') IS NOT NULL
EXEC sp_executesql N' /******************************************************************************************************
Object: dbo.pGetCatBondAttributeData  
Description:	Get Cat Bond Attribute Data
SPExposedToEntities : 08-12-2016
ResultView: None
Usage:
DECLARE @RC int
DECLARE @ReinsuranceProgramSID int
DECLARE @Debug bit
SET @ReinsuranceProgramSID = 0
SET @Debug = 1
EXECUTE @RC = [dbo].[pGetCatBondAttributeData] 
   @ReinsuranceProgramSID
  ,@Debug
Notes : Name Changed
*******************************************************************************************************/
ALTER 
-- ALTER
PROCEDURE [dbo].[pGetCatBondAttributeData]  
	@ReinsuranceProgramSID INT,
	@Debug BIT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT
	    DECLARE @ReBusinessUnitSID INT
       EXEC @ReBusinessUnitSID = AIRProject.[dbo].[pCOMMON_ReGetBusinessUnitSID]
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
	BEGIN TRY
	
	IF(@ReinsuranceProgramSID =-1)
		    SELECT tca.CatBondAttributeSID AS CatBondAttributeSID, CatBondAttributeName, CatBondAttributeDataType, ISNULL(tcv.ReinsuranceProgramSID, 0) AS ReinsuranceProgramSID , CatBondAttributeValue
			FROM AIRUserSetting..tCatBondAttribute tca 
			JOIN AIRExposureRe..tCatBondAttributeValue tcv ON tca.CatBondAttributeSID = tcv.CatBondAttributeSid 
			JOIN  AIRExposureRe..tReinsuranceProgram p ON tcv.ReinsuranceProgramSID=p.ReinsuranceProgramSID AND p.StatusCode=''A''
			WHERE tca.businessunitsid = @ReBusinessUnitSID   
			ORDER BY ISNULL(tcv.ReinsuranceProgramSID, 0), CatBondAttributeSID;
	ELSE IF @ReinsuranceProgramSID IS NULL 
		SELECT CatBondAttributeSID, CatBondAttributeName, CatBondAttributeDataType, 0 AS ReinsuranceProgramSID, NULL AS CatBondAttributeValue
			FROM AIRUserSetting..tCatBondAttribute 
			WHERE BusinessUnitSID = @ReBusinessUnitSID
			ORDER BY CatBondAttributeSID;
	ELSE 
		SELECT tca.CatBondAttributeSID AS CatBondAttributeSID, CatBondAttributeName, CatBondAttributeDataType, ISNULL(tcv.ReinsuranceProgramSID, 0) AS ReinsuranceProgramSID , CatBondAttributeValue
			FROM AIRUserSetting..tCatBondAttribute tca LEFT JOIN AIRExposureRe..tCatBondAttributeValue tcv
			ON tca.CatBondAttributeSID = tcv.CatBondAttributeSid and ReinsuranceProgramSID = @ReinsuranceProgramSID
			JOIN  AIRExposureRe..tReinsuranceProgram p ON tcv.ReinsuranceProgramSID=p.ReinsuranceProgramSID AND p.StatusCode=''A''
			WHERE tca.businessunitsid = @ReBusinessUnitSID  
			ORDER BY CatBondAttributeSID;
				
		SET @Result = 0
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pGetCompanySummaryInfo]'
GO
IF OBJECT_ID(N'[dbo].[pGetCompanySummaryInfo]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT:				dbo.pGetCompanySummaryInfo
DESCRIPTION:		Returns all company summary info
ExposedToEntities:	Yes
ResultView:			rvGetCompanySummaryInfo
Usage:				EXEC dbo.pGetCompaniesInfo 
						
**********************************************************************************************************/
ALTER
--ALTER
PROCEDURE [dbo].[pGetCompanySummaryInfo]
    @Debug BIT = 0
AS
    BEGIN
        SET NOCOUNT ON;
        DECLARE @Result INT = 0;
        DECLARE @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID);
        IF @Debug = 1
            PRINT ''Begin: '' + @SPName;
        BEGIN TRY
            --IF OBJECT_ID(''tempdb.dbo.#xxx'') IS NOT NULL
            --    DROP TABLE #xxx
            --IF OBJECT_ID(''tempdb.dbo.#CTE_Company'') IS NOT NULL
            --    DROP TABLE #CTE_Company
            --IF OBJECT_ID(''tempdb.dbo.#udc'') IS NOT NULL
            --    DROP TABLE #udc
            SELECT      DISTINCT a.CompanySID,
                        a.CompanyName,
						a.CompanyTypeCode,
                        a.CompanyID,
                        (
                            SELECT
                                COUNT(ExposureSetSID) AS ExposureSetCount
                            FROM  dbo.tExposureSet te WITH (NOLOCK)
                            WHERE te.CompanySID = a.CompanySID
                                  AND te.StatusCode = ''A''
                        ) AS ExposureSetCount,
                        (
                            SELECT
                                CAST(MAX(ia.YearID) AS INT) LatestYear
                            FROM  dbo.tAggregateExposure ia WITH (NOLOCK, INDEX(IDX_filter_Country_Data))
                            JOIN  dbo.tExposureSet b
                                ON ia.ExposureSetSID = b.ExposureSetSID
                            WHERE ia.ExposureSetSID = a.DefaultExposureSetSID
                                  AND ia.IntAreaScheme = 1006
                                  AND b.StatusCode = ''A''
                        ) AS LatestYear,
                        (
                            SELECT
                                COUNT(DISTINCT CompanyLossSetName) AS CLFSetsCount
                            FROM  dbo.tCompanyLossAssociation WITH (NOLOCK)
                            WHERE CompanySID = a.CompanySID
                                  AND StatusCode = ''A''
                        ) AS CompanyLossAssociationsCount,
                        x.AnalysisSID AS LatestResultSID,
                        x.AnalysisName AS LatestResultName,
                        x.LatestResultTime,
                        w.LastActivity AS LastActivityType,
                        w.EnteredDate AS lastactivityTime,
                        (
                            SELECT
                                 COUNT(DISTINCT t1.ReinsuranceProgramSID) AS programcount
                            FROM      dbo.tReinsuranceProgram t1 WITH (NOLOCK)
                            JOIN      dbo.tReinsuranceProgramTargetXRef t2 WITH (NOLOCK)
                                ON t1.ReinsuranceProgramSID = t1.ReinsuranceProgramSID
                            LEFT JOIN dbo.tExposureSet c WITH (NOLOCK)
                                ON t2.ExposureSetSID = c.ExposureSetSID
                            LEFT JOIN dbo.tCompanyLossAssociation d WITH (NOLOCK)
                                ON t2.CompanyLossAssociationSID = d.CompanyLossAssociationSID
                            WHERE     t1.CompanySID = a.CompanySID
                                      AND t1.StatusCode = ''A''
                                      AND (
                                              c.ExposureSetSID IS NULL
                                              OR c.StatusCode = ''A''
                                          )
                                      AND (
                                              d.CompanyLossAssociationSID IS NULL
                                              OR d.StatusCode = ''A''
                                          )
                        ) AS programcount,
                        (
                            SELECT
                                 COUNT(DISTINCT t1.ReinsuranceProgramStructureSID) AS structurecount
                            FROM      dbo.tReinsuranceProgramStructure t1 WITH (NOLOCK)
                            JOIN      dbo.tReinsuranceProgramStructureXRef t2
                                ON t1.ReinsuranceProgramStructureSID = t2.ReinsuranceProgramStructureSID
                            JOIN      dbo.tReinsuranceProgram t3 WITH (NOLOCK)
                                ON t3.ReinsuranceProgramSID = t2.ReinsuranceProgramSID
                            JOIN      dbo.tReinsuranceProgramTargetXRef t4 WITH (NOLOCK)
                                ON t4.ReinsuranceProgramSID = t3.ReinsuranceProgramSID
                            LEFT JOIN dbo.tExposureSet c WITH (NOLOCK)
                                ON t4.ExposureSetSID = c.ExposureSetSID
                            LEFT JOIN dbo.tCompanyLossAssociation d WITH (NOLOCK)
                                ON t4.CompanyLossAssociationSID = d.CompanyLossAssociationSID
                            WHERE     t1.CompanySID = a.CompanySID
                                      AND t3.StatusCode = ''A''
                                      AND (
                                              c.ExposureSetSID IS NULL
                                              OR c.StatusCode = ''A''
                                          )
                                      AND (
                                              d.CompanyLossAssociationSID IS NULL
                                              OR d.StatusCode = ''A''
                                          )
                        ) AS structurecount,
                        a.AuthorEntered,
                        a.AuthorEdited
            INTO
                        #CTE_Company
            FROM        dbo.tCompany a WITH (NOLOCK)
            OUTER APPLY (
                            SELECT
                                 w.*,
                                 ann.AnalysisName
                            FROM (
                                     SELECT
                                           FIRST_VALUE(ac.CompletedDate) OVER (PARTITION BY
                                                                                   ao.CompanySID
                                                                               ORDER BY ac.CompletedDate DESC
                                                                              ) AS LatestResultTime,
                                           FIRST_VALUE(an.AnalysisSID) OVER (PARTITION BY
                                                                                 ao.CompanySID
                                                                             ORDER BY ac.CompletedDate DESC
                                                                            ) AS AnalysisSID
                                     FROM  AIRProject.dbo.tActivity ac WITH (NOLOCK)
                                     JOIN  AIRProject.dbo.tAnalysis an WITH (NOLOCK)
                                         ON ac.AnalysisSID = an.AnalysisSID
                                            AND ac.ActivityStatusCode = ''COM''
                                     JOIN  AIRProject.dbo.tAggregateLossAnalysisOption ao WITH (NOLOCK)
                                         ON ao.AnalysisSID = an.AnalysisSID
                                     WHERE ao.CompanySID = a.CompanySID
                                           AND an.StatusCode = ''A''
                                 ) w
                            JOIN AIRProject.dbo.tAnalysis ann WITH (NOLOCK)
                                ON w.AnalysisSID = ann.AnalysisSID
                        ) x
            OUTER APPLY (
                            SELECT
                                 CONCAT(ap.ActionType, '' '', at.AuditTargetType) AS LastActivity,
                                 y.EnteredDate
                            FROM (
                                     SELECT
                                           MAX(AuditHistorySID) AS AuditHistorySID
                                     FROM  AIRProject.dbo.tAuditHistoryParentObjectXRef WITH (NOLOCK)
                                     WHERE ParentObjectTypeCode = ''CPY''
                                           AND a.CompanySID = ParentObjectSID
                                 ) u
                            JOIN AIRProject.dbo.tAuditHistory y WITH (NOLOCK)
                                ON u.AuditHistorySID = y.AuditHistorySID
                            JOIN AIRReference.dbo.tAuditActionType ap WITH (NOLOCK)
                                ON ap.ActionTypeCode = y.ActionTypeCode
                            JOIN AIRReference.dbo.tAuditTargetType at WITH (NOLOCK)
                                ON y.AuditTargetTypeCode = at.AuditTargetTypeCode
                        ) w
            WHERE       a.StatusCode = ''A'';
            SELECT
                 *
            INTO
                 #udc
            FROM (
                     SELECT
                               xuc.CompanySID,
                               SystemUserDefinedCategoryCode,
                               UDCClassificationName
                     FROM      #CTE_Company AS rt
                     LEFT JOIN dbo.tCompanyUDCClassification_Xref xuc WITH (NOLOCK)
                         ON xuc.CompanySID = rt.CompanySID
                     LEFT JOIN AIRUserSetting.dbo.tUDCClassification udcc WITH (NOLOCK)
                         ON udcc.UDCClassificationSID = xuc.UDCClassificationSID
                     LEFT JOIN AIRUserSetting.dbo.tUserDefinedCategory udcac WITH (NOLOCK)
                         ON udcac.UserDefinedCategorySID = udcc.UserDefinedCategorySID
                 ) AS SourceTable
            PIVOT (
                      MAX(UDCClassificationName)
                      FOR SystemUserDefinedCategoryCode IN (COMUDC1, COMUDC2, COMUDC3, COMUDC4, COMUDC5)
                  ) AS PivotTable
            SELECT
                      rt.CompanySID,
                      rt.CompanyName,
					  rt.CompanyTypeCode,
                      rt.CompanyID,
                      rt.ExposureSetCount,
                      rt.LatestYear,
                      NULL AS regionlist,
                      rt.CompanyLossAssociationsCount,
                      rt.LatestResultSID,
                      rt.LatestResultName,
                      rt.LatestResultTime,
                      rt.LastActivityType,
                      rt.lastactivityTime,
                      rt.programcount,
                      rt.structurecount,
                      rt.AuthorEntered,
                      rt.AuthorEdited,
                      rc.COMUDC1,
                      rc.COMUDC2,
                      rc.COMUDC3,
                      rc.COMUDC4,
                      rc.COMUDC5
            FROM      #CTE_Company rt
            LEFT JOIN #udc rc
                ON rc.CompanySID = rt.CompanySID
            --ORDER BY rt.CompanySID
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName;
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = dbo.pReThrowError
                @SPName,
                0;
        END CATCH;
    END;
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pGetLMSByCountryAreaSubarea]'
GO
IF OBJECT_ID(N'[dbo].[pGetLMSByCountryAreaSubarea]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT:				dbo.pGetAggregateExposureByCountryAreaSubarea
DESCRIPTION:		Returns LMS for aggregated exposure on Country, Area and Subarea levels filtered according to input parameters
ExposedToEntities:	Yes
ResultView:			rvGetLMSByCountryAreaSubarea
Usage:				EXEC dbo.pGetLMSByCountryAreaSubarea 
						@CountryCode VARCHAR(15)=''US'',
						@PerilSetCode INT = 8,
						@YearID INT = 2018,
						@CompanyLossAssociationSID INT =  1,
						@ModelSID INT= 5,
						@geolevelcode VARCHAR(10)= ''SUBA'' ,   --''AREA'' --						
						@Debug BIT = 0
**********************************************************************************************************/
ALTER
--ALTER
 PROCEDURE [dbo].[pGetLMSByCountryAreaSubarea]
			@CountryCode VARCHAR(15),
			@PerilSetCode INT ,
			@YearID INT ,
			@CompanyLossAssociationSID INT ,
			@ModelSID INT ,
			@Geolevelcode VARCHAR(10) = ''SUBA'' ,   --default is suba ''AREA'' --						
			@Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT = 0
	DECLARE @SPName SYSNAME = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	BEGIN TRY
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		--IF EXISTS (SELECT 1 FROM [dbo].[tCompanyLossMarketShare] WHERE CompanyLossAssociationSID=@CompanyLossAssociationSID )
		--	RETURN 0;
			
			
	
		
		SELECT 
			MAX(lms.GeographySID) AS GeographySID,
			MAX(geo.AreaScheme) AS AreaScheme,
			MAX(geo.geolevelcode) AS geolevelcode,
			MAX(geo.AreaName) AS AreaName,
			MAX(geo.SubareaName) AS SubareaName,
			lms.LOBCode AS LOBCode,
			MAX(lms.CurrencyCode) AS CurrencyCode,
			ROUND(lms.LossMarketShare* 100,2) AS LossMarketShare
		--SELECT * --228
		FROM [AIRExposureRe].[dbo].[tCompanyLossMarketShare] lms
		INNER  JOIN airgeography.dbo.tGeography geo 
		ON geo.geographysid = lms.GeographySID
		WHERE 
		ROUND(lms.LossMarketShare* 100,2) > 0 and 
		CASE WHEN lms.PerilSetCode IN ( 3, 67 ) THEN 67
                                  ELSE lms.PerilSetCode
                             END =  @PerilSetCode AND
			geo.geolevelcode = @geolevelcode  AND 
			lms.[CompanyLossAssociationSID] = @CompanyLossAssociationSID AND
			lms.modelcode = @ModelSID 
			
		GROUP BY lms.LOBCode, lms.LossMarketShare, geo.AreaName,geo.SubareaName , lms.modelcode, lms.PerilSetCode
		union
		SELECT 
			MAX(lms.GeographySID) AS GeographySID,
			MAX(geo.AreaScheme) AS AreaScheme,
			MAX(geo.geolevelcode) AS geolevelcode,
			MAX(geo.CRESTACode) AS AreaName,
			MAX(geo.CRESTAName) AS SubareaName,
			lms.LOBCode AS LOBCode,
			MAX(lms.CurrencyCode) AS CurrencyCode,
			ROUND(lms.LossMarketShare* 100,2) AS LossMarketShare
		--SELECT * --228
		FROM [AIRExposureRe].[dbo].[tCompanyLossMarketShare] lms
		INNER  JOIN airgeography.dbo.tGeography geo 
		ON geo.geographysid = lms.GeographySID
		WHERE 
		ROUND(lms.LossMarketShare* 100,2) > 0 and 
		CASE WHEN lms.PerilSetCode IN ( 3, 67 ) THEN 67
                                  ELSE lms.PerilSetCode
                             END =  @PerilSetCode AND
			geo.geolevelcode = ''CRES''  AND 
			lms.[CompanyLossAssociationSID] = @CompanyLossAssociationSID AND
			lms.modelcode = @ModelSID 
		GROUP BY lms.LOBCode, lms.LossMarketShare,  geo.CRESTACode,geo.CRESTAName , lms.modelcode, lms.PerilSetCode
		union
		SELECT 
			geo.GeographySID AS GeographySID,
			geo.AreaScheme AS AreaScheme,
			geo.geolevelcode AS geolevelcode,
			geo.CountryCode AS AreaName,
			geo.CountryName AS SubareaName,
			lms.LOBCode AS LOBCode,
			lms.CurrencyCode AS CurrencyCode,
			ROUND(lms.LossMarketShare* 100,2) AS LossMarketShare
		--SELECT * --228
		FROM [AIRExposureRe].[dbo].[tCompanyLossMarketShare] lms
		INNER  JOIN airgeography.dbo.tGeography geo 
		ON geo.geographysid = lms.GeographySID
		WHERE 
		ROUND(lms.LossMarketShare* 100,2) > 0 and 
		CASE WHEN lms.PerilSetCode IN ( 3, 67 ) THEN 67
                                  ELSE lms.PerilSetCode
                             END =  @PerilSetCode AND
			geo.geolevelcode = ''COUN''  AND 
			lms.[CompanyLossAssociationSID] = @CompanyLossAssociationSID AND
			lms.modelcode = @ModelSID 
			
		ORDER BY MAX(geo.AreaName),MAX(geo.SubareaName)
		
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
		--RETURN @Result
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
END		-- Proc
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLOSS_GenerateGeoStagingTable_NGM]'
GO
IF OBJECT_ID(N'[dbo].[pLOSS_GenerateGeoStagingTable_NGM]', 'P') IS NOT NULL
EXEC sp_executesql N' /****** Object:  StoredProcedure [dbo].[pLOSS_GenerateGeoStagingTable_NGM]    Script Date: 3/24/2020 9:38:38 AM ******/
/*****************************************************************************************************
DESCRIPTION:	This SP is called from engine to expand all events after result tables are generated with clustered events
Change history :
initials		Date	       Desciption
NB			03/2018			Orginal code
NB/SK		02/20/2020		Added code to populate contractriskgeosid for by treatybylobbygeo. 
NB/SK		02/27/2020		Reinsurance table can have multiple records for same reinsurance target type code so we are getting the count and making sure its processed one for each tgttypecode.
NB/SK		03/24/2020		Changed Riskgeosid to Identity column so commenting out the insert for that column. 
NB			03/24/2020		Added risktype filter in update stmts for staging location tables.  						  
NB			09/04/2020		Change made for ticket Leo00052984
SK			09/15/2020		Modifications to the code changing the alias name SQLStmt_LYR variable
*****************************************************************************************************/
ALTER PROCEDURE [dbo].[pLOSS_GenerateGeoStagingTable_NGM]
	@AnalysisSID INT
	,@ChunkID SMALLINT
	,@Debug BIT = FALSE
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT
	DECLARE @DBName NVARCHAR(392)
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
	BEGIN TRY
		DECLARE @SQLStmt NVARCHAR(MAX) = N''''
		DECLARE @SQLStmt_LYR NVARCHAR(MAX) = N''''
		DECLARE @SQLStmt_CON NVARCHAR(MAX) = N''''
		
		DECLARE @SQLInsertPortGeo NVARCHAR(MAX) = N''''
		DECLARE @SQLInsertLobGeo NVARCHAR(MAX) = N''''
		DECLARE @SQLInsertConGeo NVARCHAR(MAX) = N''''
		DECLARE @SQLInsertLayGeo NVARCHAR(MAX) = N''''
		DECLARE @SQLInsertLayGeoToLocXRef NVARCHAR(MAX) = N''''
		
		DECLARE @SQLUpdateLocationRiskGeoPartial NVARCHAR(MAX) = N''''
		DECLARE @SQLUpdateLocationContractRiskGeoPartial NVARCHAR(MAX) = N''''
		DECLARE @SQLUpdatePortGeoBase NVARCHAR(MAX) = N''''
		DECLARE @SQLUpdateLobGeoBase NVARCHAR(MAX) = N''''
		DECLARE @SQLUpdateConGeoBase NVARCHAR(MAX) = N''''
		DECLARE @GeoSidType NVARCHAR(MAX) = N''''
		DECLARE @CREATEtbl  NVARCHAR(MAX) 
		DECLARE @LossLocationStagingTable NVARCHAR(MAX) = N''''
		DECLARE @LossContractStagingTable NVARCHAR(MAX) = N''''
		DECLARE @LossLayerSublimitStagingTable NVARCHAR(MAX) = N''''
		DECLARE @GeolevelCode VARCHAR(10)
		DECLARE @ResultTypeCode VARCHAR(10)
		DECLARE @OldCountryCode INT
		DECLARE @AnalysisTypeCode VARCHAR(10)
		DECLARE @LossGeoStagingTable NVARCHAR(MAX) = N''''
		DECLARE @GeographyMappingTable NVARCHAR(MAX) = N''''
		DECLARE @tmpGeoRiskSIDS_tblnm NVARCHAR(392)
		DECLARE @LocRiskGeoXrefTable NVARCHAR(MAX) = N''''
		DECLARE @TreatyLOBGeoTable NVARCHAR(392)
		DECLARE @TreatyConTable NVARCHAR(392)
		DECLARE @AnalysisUID NVARCHAR(392)
		DECLARE @ProgramSID  VARCHAR(10) -- NB check its datatype 
		DECLARE @SQLUpdateStmt NVARCHAR(MAX) = N''''
		DECLARE @tablecount int
		DECLARE @ContractTreatyCount INT 
		DECLARE @LayerTreatyCount INT 
		-- This is going to be NULL for now. This is for the option of save results by Geo and another option, for example Layer
		DECLARE @RiskSID	INT	
		SET @DBName = AIRProject.dbo.fCOMMON_GetDBName_NGM(@AnalysisSID, ''STAGE'')
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''***** DataBase '', @DBName
		
						
		SET @LossLocationStagingTable = AIRProject.dbo.fLOSS_GetStagingTableName_NGM (@AnalysisSID, @ChunkID, ''Location'')
		SET @LossContractStagingTable = AIRProject.dbo.fLOSS_GetStagingTableName_NGM (@AnalysisSID, @ChunkID, ''Contract'')
		SET @LossLayerSublimitStagingTable = AIRProject.dbo.fLOSS_GetStagingTableName_NGM (@AnalysisSID, @ChunkID, ''LayerSublimit'')
		SET @GeographyMappingTable = AIRProject.dbo.fLOSS_GetStagingTableName_NGM (@AnalysisSID, NULL, ''MGeography'')
		SET @LossGeoStagingTable = AIRProject.dbo.fLOSS_GetStagingTableName_NGM(@AnalysisSID, @ChunkID, ''Geography'')
		--TODO add this table to GetStagingTableName_NGM, CreateExposureChunkStagingTables, etc
		SELECT @AnalysisUID = AnalysisUID
		FROM AIRProject..tAnalysis
        WHERE AnalysisSID = @AnalysisSID 
		
		SET @LocRiskGeoXrefTable = ''[AIRWork]..[t''+CONVERT(VARCHAR(10),@AnalysisSID)+''_c''+CONVERT(VARCHAR(100),COALESCE(@ChunkID,0))+''_LOSS_StagingLocationRiskGeoXref_''+CONVERT(VARCHAR(100),@AnalysisUID)+'']''
		
		IF OBJECT_ID(@LocRiskGeoXrefTable) IS NOT NULL 
		BEGIN 
			SET @SQLStmt = ''DROP TABLE ''+@LocRiskGeoXrefTable
								
			IF @DEBUG = 1 EXEC dbo.pCOMMON_PrintVariable ''Dropping Location Risk Geo Xref table if exists '',@SQLStmt
			EXEC dbo.sp_executesql @SQLStmt 
		END
		--End TODO
		IF @Debug = 1 
			BEGIN
				EXEC dbo.pCOMMON_PrintVariable ''***** LossLocationStagingTable '', @LossLocationStagingTable
				EXEC dbo.pCOMMON_PrintVariable ''***** LossGeographyMappingTable '', @GeographyMappingTable
				EXEC dbo.pCOMMON_PrintVariable ''***** LossGeoStagingTable '', @LossGeoStagingTable
			END
	
		DECLARE @KeyFields NVARCHAR(MAX)
		DECLARE @DynamicFields NVARCHAR(MAX)
--		Check what kind of LOSS analysis is run by
--		If under Geography, is eventTotal, this table is not being populated
--								By Country, only country info is populated, all other columns are null
--								By Area,  country & area info is populated, all other columns are null
--								By Subarea,  country * area and Subarea info is populated, all other columns are null
--								By postalcode,  all  columns are populated
        
		 
-- lets separate these two tables. We are expecting multiple records so it wont work.
		SELECT
		@GeolevelCode = a.GeolevelCode
		,@ResultTypeCode = a.OutputTypeCode
		,@ProgramSID = A.programsid
		FROM AIRProject.dbo.tLossAnalysisOption a
		WHERE a.AnalysisSID = @AnalysisSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''**** GeolevelCode is :'', @GeolevelCode
		---Getting UserSetting DB Name
		DECLARE @UserSettingDBName NVARCHAR(392)
        SET @UserSettingDBName = AirProject.dbo.fGetUserSettingDBName_NGM(1) 
       
        
		IF @GeolevelCode IS NOT NULL 
		BEGIN
		
			SELECT  @ContractTreatyCount = count(*)
			FROM  AIRReinsurance.[dbo].[tReinsurance] 
			WHERE ProgramSID = @programsid
			AND reinstargettypecode = ''CON''
        
			SELECT  @LayerTreatyCount = count(*)
			FROM  AIRReinsurance.[dbo].[tReinsurance] 
			WHERE ProgramSID = @programsid
			AND reinstargettypecode in (''LYR'',''LOCLYR'')
			SET @GeoSidType = CASE
				WHEN @GeoLevelCode = ''COUN'' THEN ''tg.CountryGeographySID''
				WHEN @GeoLevelCode = ''AREA'' THEN ''ISNULL(tg.AreaGeographySID, tg.CRESTAGeographySID)''
				WHEN @GeoLevelCode = ''SUBA'' THEN ''ISNULL(tg.SubareaGeographySID, ISNULL(tg.AreaGeographySID, tg.CRESTAGeographySID))''
				WHEN @GeoLevelCode = ''POST'' THEN ''ISNULL(tg.PostalGeographySID, ISNULL(tg.SubareaGeographySID, ISNULL(tg.AreaGeographySID, tg.CRESTAGeographySID)))''
				ELSE ''UnrecognizedGeoLevelCode''
			END 
			SET @SQLInsertPortGeo = N''
				INSERT INTO '' + @LossGeoStagingTable + ''
				SELECT Z.*
				FROM
					( SELECT DISTINCT NULL AS RiskSID
					, '' + @GeoSidType + '' AS GeographySID
					, 1 AS RiskType
					FROM ''+@LossLocationStagingTable+'' Loc											                                              
					JOIN AIRGeography..tGeography tg
					ON Loc.GeographySID = tg.GeographySID 
				)Z; ''
			SET @SQLInsertLobGeo = N''
				INSERT INTO '' + @LossGeoStagingTable + '' 
				SELECT Z.*
				FROM
					( SELECT DISTINCT CONVERT(INT, Con.guidUserLineOfBusiness, 2) AS RiskSID
					, '' + @GeoSidType + '' AS GeographySID
					, 3 AS RiskType
					FROM '' + @LossLocationStagingTable + '' Loc
					JOIN '' + @LossContractStagingTable + '' Con
					ON Con.guidContract = Loc.guidContract 
					JOIN AIRGeography..tGeography tg
					ON Loc.GeographySID = tg.GeographySID 
				)Z; ''  
			SET @SQLInsertConGeo = N'' 
				INSERT INTO '' + @LossGeoStagingTable + '' 
				SELECT Z.*
				FROM
					( SELECT DISTINCT CONVERT(INT, Con.guidContract, 2) AS RiskSID
					, '' + @GeoSidType + '' AS GeographySID
					, 2 AS RiskType
					FROM '' + @LossLocationStagingTable + '' Loc
					JOIN '' + @LossContractStagingTable + '' Con
					ON Con.guidContract = Loc.guidContract 
					JOIN AIRGeography..tGeography tg
					ON Loc.GeographySID = tg.GeographySID 
				)Z; ''
			SET @SQLInsertLayGeo = N''  
				INSERT INTO '' + @LossGeoStagingTable + '' 
				SELECT Z.*
				FROM
					( SELECT DISTINCT CONVERT(INT, Lyr.guidCondition, 2) AS RiskSID
					, '' + @GeoSidType + '' AS GeographySID
					, 4 AS RiskType
					FROM ''+@LossLocationStagingTable+'' Loc											 
					JOIN ''+@LossLayerSublimitStagingTable+'' Lyr 
					ON Loc.guidContract = Lyr.guidContract
					JOIN AIRGeography..tGeography tg
					ON Loc.GeographySID = tg.GeographySID 
					WHERE Lyr.OldConditionTypeCode = 10 
					)Z ORDER BY RiskSID; ''     
			SET @SQLInsertLayGeoToLocXRef = N'' 
				SELECT Loc.LocationSID,
				sg.RiskGeoSID,
				sg.RiskSID
				INTO '' + @LocRiskGeoXrefTable + ''
				FROM '' + @LossLocationStagingTable + '' Loc
				INNER JOIN '' + @LossLayerSublimitStagingTable + '' Lay
				ON Loc.guidContract = Lay.guidContract
				INNER JOIN AIRGeography..tGeography tg
				ON Loc.GeographySID = tg.GeographySID 
				INNER JOIN '' + @LossGeoStagingTable + '' sg     
				ON sg.RiskSID = CONVERT( INT,Lay.guidCondition,2)
				AND '' + @GeoSidType + '' = sg.GeographySID
				WHERE Lay.OldConditionTypeCode = 10 ''            
							
			SET @SQLUpdateLocationRiskGeoPartial = N''
				USE [AIRWork]
				UPDATE '' + @LossLocationStagingTable + '' 
				SET RiskGeoSID = StageGeo.RiskGeoSID ''
				
			SET @SQLUpdateLocationContractRiskGeoPartial = N''
				USE [AIRWork]
				UPDATE '' + @LossLocationStagingTable + '' 
				SET ContractRiskGeoSID = StageGeo.RiskGeoSID ''
			
			SET @SQLUpdatePortGeoBase = N''
				FROM '' + @LossLocationStagingTable + '' Loc
				JOIN AIRGeography..tGeography tg
				ON Loc.GeographySID = tg.GeographySID
				JOIN '' + @LossGeoStagingTable + '' StageGeo
				ON StageGeo.GeographySID = '' + @GeoSidType + '' 
				AND StageGeo.RiskType = 1 ''
			SET @SQLUpdateLobGeoBase = N''
				FROM '' + @LossLocationStagingTable + '' Loc
				JOIN '' + @LossContractStagingTable + '' Con
				ON Con.guidContract = Loc.guidContract 
				JOIN AIRGeography..tGeography tg
				ON Loc.GeographySID = tg.GeographySID
				JOIN '' + @LossGeoStagingTable + '' StageGeo
				ON CONVERT(INT, Con.guidUserLineOfBusiness, 2) = StageGeo.RiskSID 
				AND StageGeo.Risktype = 3
				AND StageGeo.GeographySID = '' +	@GeoSidType + '' ''	
			SET @SQLUpdateConGeoBase = N''
				FROM '' + @LossLocationStagingTable + '' Loc
				JOIN '' + @LossContractStagingTable + '' Con
				ON Con.guidContract = Loc.guidContract 
				JOIN AIRGeography..tGeography tg
				ON Loc.GeographySID = tg.GeographySID
				JOIN '' + @LossGeoStagingTable + '' StageGeo
				ON CONVERT(INT, Con.guidContract, 2) = StageGeo.RiskSID 
				AND StageGeo.GeographySID = '' +	@GeoSidType + '' 
				AND StageGeo.RiskType = 2 ''
            IF @ResultTypeCode = ''EA'' OR @ResultTypeCode = ''EAGEOL'' 
			BEGIN
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with LOB Geo : '', @SQLInsertLobGeo
				EXEC dbo.sp_executesql @SQLInsertLobGeo
					
				SET @SQLStmt = @SQLUpdateLocationRiskGeoPartial + @SQLUpdateLobGeoBase
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update Location Staging Table RiskGeoSID for LOB Geo : '', @SQLStmt
				EXEC dbo.sp_executesql @SQLStmt              
				
				IF @ContractTreatyCount > 0
				BEGIN
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Contract Geo for Contract Treaty LOB Geo : '', @SQLInsertConGeo
					EXEC dbo.sp_executesql @SQLInsertConGeo 
					
					SET @SQLStmt = @SQLUpdateLocationContractRiskGeoPartial + @SQLUpdateConGeoBase
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update Location Staging Table ContractRiskGeoSID for Contract Treaty LOB Geo : '', @SQLStmt
					EXEC dbo.sp_executesql @SQLStmt      
				END 
                   
				IF @LayerTreatyCount > 0 
				BEGIN  
					SET @SQLStmt_LYR = @SQLInsertLayGeo
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Layer Geo for Layer Treaty LOB Geo: '', @SQLInsertLayGeo
					EXEC dbo.sp_executesql @SQLInsertLayGeo	
									  
					SET @SQLStmt_LYR = @SQLInsertLayGeoToLocXRef
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate Location Risk Geo Layer Xref for Layer Treaty LOB Geo: '', @SQLInsertLayGeoToLocXRef
					EXEC dbo.sp_executesql @SQLInsertLayGeoToLocXRef	
				END				
			END 
			IF @ResultTypeCode = ''CON'' OR @ResultTypeCode = ''CONGEOL'' 
			BEGIN
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Contract Geo : '', @SQLInsertConGeo
				EXEC dbo.sp_executesql @SQLInsertConGeo
				SET @SQLStmt = @SQLUpdateLocationRiskGeoPartial + @SQLUpdateConGeoBase
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update Location Staging Table RiskGeoSID for Contract Geo : '', @SQLStmt
				EXEC dbo.sp_executesql @SQLStmt 
					
				IF @ContractTreatyCount > 0
				BEGIN					
					SET @SQLStmt = @SQLUpdateLocationContractRiskGeoPartial + @SQLUpdateConGeoBase
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update Location Staging Table ContractRiskGeoSID for Contract Treaty Contract Geo : '', @SQLStmt
					EXEC dbo.sp_executesql @SQLStmt 
				END 
                   
				IF @LayerTreatyCount > 0 
				BEGIN  
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Layer Geo for Layer Treaty Contract Geo: '', @SQLInsertLayGeo
					EXEC dbo.sp_executesql @SQLInsertLayGeo	
									  
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate Location Risk Geo Layer Xref for Layer Treaty Contract Geo: '', @SQLInsertLayGeoToLocXRef
					EXEC dbo.sp_executesql @SQLInsertLayGeoToLocXRef	
				END		
			END
            IF @ResultTypeCode = ''LYR'' OR @ResultTypeCode = ''LYRGEOL'' OR @ResultTypeCode = ''CONGEOLYR''
			BEGIN
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Layer Geo for Layer Geo: '', @SQLInsertLayGeo
				EXEC dbo.sp_executesql @SQLInsertLayGeo	
									  
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate Location Risk Geo Layer Xref for Layer Treaty Layer Geo: '', @SQLInsertLayGeoToLocXRef
				EXEC dbo.sp_executesql @SQLInsertLayGeoToLocXRef	
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Contract Geo : '', @SQLInsertConGeo
				EXEC dbo.sp_executesql @SQLInsertConGeo
				
				SET @SQLStmt = @SQLUpdateLocationRiskGeoPartial + @SQLUpdateConGeoBase
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update Location Staging Table RiskGeoSID for Contract Geo : '', @SQLStmt
				EXEC dbo.sp_executesql @SQLStmt 
				IF @ContractTreatyCount > 0
				BEGIN					
					SET @SQLStmt = @SQLUpdateLocationContractRiskGeoPartial + @SQLUpdateConGeoBase
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update Location Staging Table ContractRiskGeoSID for Contract Treaty Layer Geo : '', @SQLStmt
					EXEC dbo.sp_executesql @SQLStmt      
				END 
			END
            IF @ResultTypeCode = ''GEOL'' OR @ResultTypeCode = ''LOC'' OR @ResultTypeCode = ''PORT''
			BEGIN
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Portfolio Geo : '', @SQLInsertPortGeo
				EXEC dbo.sp_executesql @SQLInsertPortGeo
				SET @SQLStmt = @SQLUpdateLocationRiskGeoPartial + @SQLUpdatePortGeoBase
				IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update Location Staging Table RiskGeoSID for Portfolio Geo : '', @SQLStmt
				EXEC dbo.sp_executesql @SQLStmt 
				IF @ContractTreatyCount > 0
				BEGIN
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Contract Geo for Contract Treaty Portfolio Geo : '', @SQLInsertConGeo
					EXEC dbo.sp_executesql @SQLInsertConGeo 
					
					SET @SQLStmt = @SQLUpdateLocationContractRiskGeoPartial + @SQLUpdateConGeoBase
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Update Location Staging Table ContractRiskGeoSID for Contract Treaty Portfolio Geo : '', @SQLStmt
					EXEC dbo.sp_executesql @SQLStmt      
				END 
                   
				IF @LayerTreatyCount > 0 
				BEGIN  
					SET @SQLStmt_LYR = @SQLInsertLayGeo
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate LossGeoStagingTable with Layer Geo for Layer Treaty Portfolio Geo: '', @SQLInsertLayGeo
					EXEC dbo.sp_executesql @SQLInsertLayGeo	
									  
					SET @SQLStmt_LYR = @SQLInsertLayGeoToLocXRef
					IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': Populate Location Risk Geo Layer Xref for Layer Treaty Portfolio Geo: '', @SQLInsertLayGeoToLocXRef
					EXEC dbo.sp_executesql @SQLInsertLayGeoToLocXRef	
				END	
			END	 
		END
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
	RETURN @Result
END    -- Proc
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLOSS_ReCreatePortfolioByProgramSIDList]'
GO
IF OBJECT_ID(N'[dbo].[pLOSS_ReCreatePortfolioByProgramSIDList]', 'P') IS NOT NULL
EXEC sp_executesql N' --DROP PROCEDURE dbo.pLOSS_ReCreatePortfolioByProgramSIDList
/*****************************************************************************************************
DATE :					08-2019
OBJECT:					dbo.pLOSS_ReCreatePortfolioByProgramSIDList 
DESCRIPTION:			Creates an inactive portfolio given list of program SIDs
ExposedToEntities:		Yes 
ResultView:				rvLOSS_ReCreatePortfolioByProgramSIDList
Usage:					
DECLARE @ReinsuranceProgramSIDList VARCHAR(MAX),
        @Debug BIT = 0;
EXECUTE dbo.pLOSS_ReCreatePortfolioByProgramSIDList @ReinsuranceProgramSIDList,
                                                        @Debug;
						
*****************************************************************************************************/
ALTER
--ALTER 
PROCEDURE [dbo].[pLOSS_ReCreatePortfolioByProgramSIDList]
    @ReinsuranceProgramSIDList VARCHAR(MAX),
    @Debug BIT = 0
AS
BEGIN
    -- DECLARE VARIABLES
    DECLARE @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
            @Result INT = 0;
    DECLARE @PortfolioSID INT,
            @PortfolioFilterSID INT,
            @PortfolioName VARCHAR(255),
            @BusinessUnitSID INT,
            @CompanyName VARCHAR(100),
            @Author VARCHAR(25),
            @Expression VARCHAR(MAX),
            @SqlString VARCHAR(MAX);
    SET NOCOUNT ON;
    BEGIN TRY
        -- PRINT START OF PROC
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName;
        --/*******************************************************************************
        --Convert list of SIDS to table 
        --*******************************************************************************/
        SELECT CONVERT(INT, strValue) AS ReinsuranceProgramSID
        INTO #ReinsuranceProgramSIDList
        FROM dbo.fCOMMON_ListToTable(@ReinsuranceProgramSIDList);
        IF @Debug = 1
            SELECT @SPName ''@SPName'',
                   ''#ReinsuranceProgramSIDList'' TableName,
                   *
            FROM #ReinsuranceProgramSIDList;
        --/*******************************************************************************
        --Get portfolio data  
        --*******************************************************************************/
        EXEC @BusinessUnitSID = AIRProject.[dbo].[pCOMMON_ReGetBusinessUnitSID];
        SELECT @CompanyName = c.CompanyName
        FROM dbo.tCompany c
            JOIN dbo.tReinsuranceProgram p
                ON p.CompanySID = c.CompanySID
            JOIN
            (
                SELECT TOP 1
                       ReinsuranceProgramSID
                FROM #ReinsuranceProgramSIDList
                ORDER BY ReinsuranceProgramSID
            ) rp
                ON rp.ReinsuranceProgramSID = p.ReinsuranceProgramSID;
        SET @Author = CURRENT_USER;
        --/*******************************************************************************
        --prepare portfolio filter data for insert 
        --<	->	&lt;
        -->	->	&gt;
        --"	->	&quot;
        --''	->	&apos;
        --&	->	&amp;
        --*******************************************************************************/
        SELECT @Expression
            = ''<FilterExpression xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="AIR.Services.Common.Filter.Data" i:type="CompositeExpression">
				  <Tag i:nil="true" />
				  <FilterExpressions>
					<FilterExpression i:type="CompositeExpression">
					  <Tag i:nil="true" />
					  <FilterExpressions>
						<FilterExpression i:type="SimpleExpression">
						  <Tag i:nil="true" />
						  <AppliedEntity>ViewReinsuranceTreatyDetails</AppliedEntity>
						  <Operator>IsEqualTo</Operator>
						  <PropertyName>CompanyName</PropertyName>
						  <Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:string">''
              +
-- SQL Prompt formatting off
			  REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@CompanyName, ''&'', ''&amp;''), ''>'', ''&gt;''), ''<'', ''&lt;''), ''"'', ''&quot;''), '''''''', ''&apos;'')
-- SQL Prompt formatting on
              +           ''</Value>
						</FilterExpression>
						<FilterExpression i:type="CompositeExpression">
          <Tag i:nil="true" />
          <FilterExpressions>'';
        SELECT @Expression += ''<FilterExpression i:type="SimpleExpression">
              <Tag i:nil="true" />
              <AppliedEntity>ViewReinsuranceTreatyDetails</AppliedEntity>
              <Operator>IsEqualTo</Operator>
              <PropertyName>ProgramName</PropertyName>
              <Value xmlns:d8p1="http://www.w3.org/2001/XMLSchema" i:type="d8p1:string">''
-- SQL Prompt formatting off
                              + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(p.ProgramID, ''&'', ''&amp;''), ''>'', ''&gt;''), ''<'', ''&lt;''), ''"'', ''&quot;''), '''''''', ''&apos;'')
-- SQL Prompt formatting on
+           ''</Value>
            </FilterExpression>''
        FROM dbo.fCOMMON_ListToTable(@ReinsuranceProgramSIDList) t
            JOIN AIRExposureRe.dbo.tReinsuranceProgram p
                ON p.ReinsuranceProgramSID = t.strValue;
        SELECT @Expression += ''</FilterExpressions>
							  <LogicalOperator>Or</LogicalOperator>
							</FilterExpression>
						  </FilterExpressions>
						  <LogicalOperator>And</LogicalOperator>
						</FilterExpression>
					  </FilterExpressions>
					  <LogicalOperator>Or</LogicalOperator>
					</FilterExpression>'';
        SELECT @SqlString
            = '' (   ViewReinsuranceTreatyDetails.ReinsuranceProgramSID  IN ( '' + @ReinsuranceProgramSIDList + '')  )  '';
        --/*******************************************************************************
        --open a nested transaction
        --*******************************************************************************/		
        BEGIN TRAN ReCreatePortfolio;
        --/*******************************************************************************
        --Get SIDs 
        --*******************************************************************************/	
        EXEC dbo.pGetSIDRange @TableName = ''tPortfolio'',
                              @Amount = 1,
                              @NextSID = @PortfolioSID OUTPUT;
        EXEC dbo.pGetSIDRange @TableName = ''tPortfolioFilter'',
                              @Amount = 1,
                              @NextSID = @PortfolioFilterSID OUTPUT;
        IF @Debug = 1
            SELECT @SPName ''@SPName'',
                   @PortfolioSID ''Next @PortfolioSID'',
                   @PortfolioFilterSID ''Next @PortfolioFilterSID'';
        --/*******************************************************************************
        --insert Portfolio Filter  
        --*******************************************************************************/
        INSERT INTO dbo.tPortfolioFilter
        (
            PortfolioFilterSID,
            Expression,
            SqlString,
            EnteredDate,
            EditedDate
        )
        VALUES
        (   @PortfolioFilterSID, -- PortfolioFilterSID - int
            @Expression,         -- Expression - varchar(max)
            @SqlString,          -- SqlString - varchar(max)
            GETDATE(),           -- EnteredDate - datetime
            GETDATE()            -- EditedDate - datetime
            );
        --/*******************************************************************************
        --insert portfolio  
        --*******************************************************************************/
        --CustomSet: CompanyName
        SET @PortfolioName = ''CustomSet: '' + @CompanyName;
        INSERT INTO dbo.tPortfolio
        (
            PortfolioSID,
            PortfolioFilterSID,
            PortfolioName,
            BusinessUnitSID,
            TotalInvestmentAmount,
            ReinsuranceLayerCount,
            RiskRatio,
            StatusCode,
            Description,
            EnteredDate,
            EditedDate,
            Author,
            PortfolioTypeCode
        )
        VALUES
        (   @PortfolioSID,       -- PortfolioSID - int
            @PortfolioFilterSID, -- PortfolioFilterSID - int
            @PortfolioName,      -- PortfolioName - varchar(255)
            @BusinessUnitSID,    -- BusinessUnitSID - int
            0.0,                 -- TotalInvestmentAmount - float
            0,                   -- ReinsuranceLayerCount - int
            NULL,                -- RiskRatio - float
            ''INA'',               -- StatusCode - varchar(10)
            NULL,                -- Description - varchar(4000)
            GETDATE(),           -- EnteredDate - datetime
            GETDATE(),           -- EditedDate - datetime
            @Author,             -- Author - varchar(255)
            ''DYN''                -- PortfolioTypeCode - varchar(10)
            );
        --/*******************************************************************************
        --insert tPortfolioReinsuranceTreaty  
        --*******************************************************************************/
        INSERT INTO dbo.tPortfolioReinsuranceTreaty
        (
            ReinsuranceTreatySID,
            PortfolioSID,
            PrincipalAmount,
            InvestmentAmount,
            PercentAnnualSpread,
            ParticipationNet,
            ParticipationGross,
            Participation3,
            Participation4,
            Premium,
            ReinstatementPremium,
            EnteredDate,
            EditedDate
        )
        SELECT t.ReinsuranceTreatySID,
               @PortfolioSID AS PortfolioSID,
               t.PrincipalAmount,
               t.InvestmentAmount,
               t.PercentAnnualSpread,
               t.ParticipationNet,
               t.ParticipationGross,
               t.Participation3,
               t.Participation4,
               t.Premium,
               t.ReinstatementPremium,
               GETDATE() AS EnteredDate,
               GETDATE() AS EditedDate
        FROM dbo.tReinsuranceTreaty t
            JOIN dbo.tReinsuranceProgram p
                ON p.ReinsuranceProgramSID = t.ReinsuranceProgramSID
            JOIN dbo.fCOMMON_ListToTable(@ReinsuranceProgramSIDList) l
                ON p.ReinsuranceProgramSID = l.strValue;
        --/*******************************************************************************
        --Retrun PortfolioSID in a dataset
        --*******************************************************************************/
        SELECT @PortfolioSID AS PortfolioSID;
        IF @Debug = 1
        BEGIN
            SELECT @SPName ''@SPName'',
                   ''tPortfolio Inserted '',
                   *
            FROM dbo.tPortfolio
            WHERE PortfolioSID = @PortfolioSID;
            SELECT @SPName ''@SPName'',
                   ''tPortfolio filter Inserted '',
                   *
            FROM dbo.tPortfolioFilter
            WHERE PortfolioFilterSID = @PortfolioFilterSID;
        END;
        --/*******************************************************************************
        --commit nested transaction
        --*******************************************************************************/
        COMMIT TRAN ReCreatePortfolio;
        --/*******************************************************************************
        --end 
        --*******************************************************************************/
        -- PRINT END OF PROC
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName;
        RETURN @Result;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 -- TODO check for nested transaction instead 
            ROLLBACK TRAN ReCreatePortfolio;
        -- re-raise the error to be caught in the calling process
        EXECUTE @Result = dbo.pReThrowError @SPName, @Debug;
    END CATCH;
END; -- OF PROC
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLOSS_ReGetExpAdjFactorByExposureType]'
GO
IF OBJECT_ID(N'[dbo].[pLOSS_ReGetExpAdjFactorByExposureType]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT:				dbo.pLOSS_ReGetExpAdjFactorByExposureType
DESCRIPTION:		Returns GeographySID, AREA and Subarea information on the basis of ExposureType code
ExposedToEntities:	No
ResultView:			N/A
Usage:				DECLARE	@return_value int
EXEC @return_value = [dbo].[pLOSS_ReGetExpAdjFactorByExposureType]
    @ExposureSetSID = 1,
    @YearID = 2017,
    @PerilSetCodeList = ''3,4'',
	@AggregateExposureTypeCode = 21, -- 1:AdjustmentFactorPremium,2:AdjustmentFactorTotalInsuredValue,3:AdjustmentFactorRiskCount,4:Rates,5:UserSpecifiedMarketShare,17:AdjustmentFactorPayroll; Custom = 21
    @Debug = 1
**********************************************************************************************************/
ALTER
--ALTER 
PROCEDURE [dbo].[pLOSS_ReGetExpAdjFactorByExposureType]
    @ExposureSetSID INT,
    @YearID INT,
    @PerilSetCodeList VARCHAR(200),
    @AggregateExposureTypeCode INT,
    @Debug BIT = 0
AS
    BEGIN
        SET NOCOUNT ON
        DECLARE @Result INT = 0
        DECLARE @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
        DECLARE @Stmt VARCHAR(MAX)
        BEGIN TRY
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': START OF '',
                    @SPName
            --if no exposure exists exit 
            IF EXISTS (
                          SELECT
                                1
                          FROM  dbo.tExposureSet
                          WHERE ExposureSetSID = @ExposureSetSID
                                AND StatusCode != ''A''
                      )
                RETURN 0;
            --get list of perils 
            CREATE TABLE #PerilSetCodeList
                (
                    PerilSetCode INT
                )
            INSERT INTO #PerilSetCodeList
                        SELECT DISTINCT CASE WHEN Value IN ( 3, 67 ) THEN 67
                                             ELSE Value
                                        END AS PerilSetCode
                        FROM   AIRProject.dbo.fCOMMON_ConvertListToTable(@PerilSetCodeList, '','')
            IF @Debug = 1
                SELECT
                     ''pGetAggregateExposureByCountryPerilSetCodePerf: #PerilSetCodeList'',
                     *
                FROM #PerilSetCodeList
            --Check for CustomAdjustment Factor
            IF @AggregateExposureTypeCode <> 21
                BEGIN
                    SELECT
                               tr.ReinsuranceExposureAdjustmentFactorSID,
                               tr.ExposureSetSID,
                               tr.PerilSetCode,
                               tr.YearID,
                               tr.LOBCode,
                               ta.OldAreaLevel1,
                               tr.AdjustmentFactorTotalInsuredValue,
                               tr.AdjustmentFactorRiskCount,
                               tr.AdjustmentFactorPremium,
                               tr.AdjustmentFactorPayroll
                    FROM       AIRExposureRe..tReinsuranceExposureAdjustmentFactor tr WITH (NOLOCK)
                    INNER JOIN AIRReference..tConvertCL2Country ta
                        ON tr.CountryCode = ta.CountryCode
                    INNER JOIN #PerilSetCodeList pc
                        ON CASE tr.PerilSetCode
                                WHEN 3 THEN 67
                                ELSE tr.PerilSetCode
                           END = pc.PerilSetCode
                    WHERE      tr.ExposureSetSID = @ExposureSetSID
                               AND tr.YearID = @YearID
                               AND tr.LOBCode NOT
                               BETWEEN 148 AND 167
                               AND (
                                       (
                                           @AggregateExposureTypeCode = 1
                                           AND tr.AdjustmentFactorPremium <> 1
                                           AND tr.AdjustmentFactorPremium IS NOT NULL
                                       )
                                       OR (
                                              @AggregateExposureTypeCode = 2
                                              AND tr.AdjustmentFactorTotalInsuredValue <> 1
                                              AND tr.AdjustmentFactorTotalInsuredValue IS NOT NULL
                                          )
                                       OR (
                                              @AggregateExposureTypeCode = 3
                                              AND tr.AdjustmentFactorRiskCount <> 1
                                              AND tr.AdjustmentFactorRiskCount IS NOT NULL
                                          )
                                       OR (
                                              @AggregateExposureTypeCode = 17
                                              AND tr.AdjustmentFactorPayroll <> 1
                                              AND tr.AdjustmentFactorPayroll IS NOT NULL
                                          )
                                   )
                END
            ELSE
                BEGIN
                    SELECT
                               tr.ReinsuranceExposureAdjustmentFactorSID,
                               tr.ExposureSetSID,
                               tr.PerilSetCode,
                               tr.YearID,
                               tr.LOBCode,
                               ta.OldAreaLevel1 AS CountryID,
                               tr.AdjustmentFactorTotalInsuredValue,
                               tr.AdjustmentFactorRiskCount,
                               tr.AdjustmentFactorPremium,
                               tr.AdjustmentFactorPayroll
                    FROM       AIRExposureRe..tReinsuranceExposureAdjustmentFactor tr WITH (NOLOCK)
                    INNER JOIN AIRReference..tConvertCL2Country ta
                        ON tr.CountryCode = ta.CountryCode
                    JOIN       #PerilSetCodeList pc
                        ON CASE tr.PerilSetCode
                                WHEN 3 THEN 67
                                ELSE tr.PerilSetCode
                           END = pc.PerilSetCode
                    WHERE      tr.ExposureSetSID = @ExposureSetSID
                               AND tr.YearID = @YearID
                               AND tr.AdjustmentFactorTotalInsuredValue <> 1
                               AND tr.AdjustmentFactorTotalInsuredValue IS NOT NULL
                               AND tr.LOBCode
                               BETWEEN 148 AND 167
                END
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName
            RETURN @Result
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = dbo.pReThrowError
                @SPName,
                @Debug
        END CATCH;
    END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLoss_ReGetMergedExposureRates]'
GO
IF OBJECT_ID(N'[dbo].[pLoss_ReGetMergedExposureRates]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
DATE :					11-2018
OBJECT:					dbo.pMigration_LogStatus 
DESCRIPTION:			Get Exposure Rates, if not present get default rates 
ExposedToEntities:		NO
ResultView:				None
Usage:
			
USE AIRExposureRe
DECLARE @RC int
DECLARE @BusinessUnitSID int = 2
DECLARE @ExposureSetSID int = 1
DECLARE @YearID int = 2017
DECLARE @PerilSetCodeList  VARCHAR(200) = ''16384,4''
DECLARE @ExposureTypeForRates INT = 1      -- 1 is Premium will be check only Premium >0 then load the Rates
DECLARE @Debug bit = 0
EXECUTE @RC = dbo.pLoss_ReGetMergedExposureRates 
   @BusinessUnitSID
  ,@ExposureSetSID
  ,@YearID
  ,@PerilSetCodeList
  ,@ExposureTypeForRates
  ,@Debug
ExposureTypeForRates	AggregateExposureType
1						Premium
2						Sums Insured
3						Number of Risks
5						Market Share
17						Payroll
******************************************************************************************************/
ALTER
--ALTER
PROCEDURE [dbo].[pLoss_ReGetMergedExposureRates]
    @BusinessUnitSID INT,
    @ExposureSetSID INT,
    @YearID INT,
    @PerilSetCodeList VARCHAR(200),
    @ExposureTypeForRates INT, -- 1 is Premium will be check only Premium > 0 then load the Rates, 2 = 
    @Debug BIT = 0
AS
    BEGIN
        -- DECLARE VARIABLES
        DECLARE
            @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
            @Result INT = 0
        SET NOCOUNT ON
        BEGIN TRY
            -- PRINT START OF PROC
            IF @Debug = 1
                EXEC @Result = AIRProject.dbo.pCOMMON_PrintVariable
                    '': START OF '',
                    @SPName
            --/******************************************************************************
            --convert list to table 
            --******************************************************************************/
            CREATE TABLE #PerilSetCodeList
                (
                    PerilSetCode INT
                )
            INSERT INTO #PerilSetCodeList
                        SELECT DISTINCT CASE WHEN Value IN ( 3, 67 ) THEN 67
                                             ELSE Value
                                        END AS PerilSetCode
                        FROM   AIRProject.dbo.fCOMMON_ConvertListToTable(@PerilSetCodeList, '','')
            IF @Debug = 1
                SELECT
                     ''pGetAggregateExposureByCountryPerilSetCodePerf: #PerilSetCodeList'',
                     *
                FROM #PerilSetCodeList
            --/******************************************************************************
            --get Exposure Rates
            --******************************************************************************/
            SELECT
                      ae.ExposureSetSID,
                      ae.PerilSetCode,
                      cm.IntLevel1,
                      cm.IntLevel2,
                      cm.IntLevel3,
                      ae.GeographySID,
                      ae.LOBCode,
                      COALESCE(NULLIF(ae.Rates, 0), NULLIF(ier.UserDefinedRate, 0), NULLIF(ier.Rate, 0)) AS Rate
            FROM      dbo.tAggregateExposure ae WITH (NOLOCK)
            LEFT JOIN AIRUserSetting.dbo.tReinsuranceIndustryRate ier WITH (NOLOCK)
                ON ier.GeographySID = ae.GeographySID
                   AND ier.LOBCode = ae.LOBCode
                   AND ier.PerilSetCode = ae.PerilSetCode
                   AND ier.YearID = ae.YearID
                   AND ier.BusinessUnitSID = @BusinessUnitSID
            JOIN      AIRGeography.dbo.tReinsuranceInternalCodeMapping cm WITH (NOLOCK)
                ON cm.GeographySID = ae.GeographySID
            JOIN      #PerilSetCodeList pl
                ON pl.PerilSetCode = CASE ae.PerilSetCode
                                          WHEN 3 THEN 67
                                          ELSE ae.PerilSetCode
                                     END
            WHERE     ae.ExposureSetSID = @ExposureSetSID
                      AND ae.YearID = @YearID
                      AND CASE @ExposureTypeForRates
                               WHEN 1 THEN ae.Premium
                               WHEN 2 THEN ae.TotalInsuredValue
                               WHEN 3 THEN ae.RiskCount
                               WHEN 5 THEN ae.UserSpecifiedMarketShare
                               WHEN 17 THEN ae.Payroll
                          END > 0
                      AND COALESCE(NULLIF(ae.Rates, 0), NULLIF(ier.UserDefinedRate, 0), NULLIF(ier.Rate, 0)) > 0
            -- PRINT END OF PROC
            IF @Debug = 1
                EXEC @Result = AIRProject.dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName
            RETURN @Result
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = AIRProject.dbo.pReThrowError
                @SPName,
                @Debug
        END CATCH;
    END; -- OF PROC
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLOSS_ReGetReinsuranceTreaty]'
GO
IF OBJECT_ID(N'[dbo].[pLOSS_ReGetReinsuranceTreaty]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
DATE :					02-24-2017
OBJECT:					dbo.pLoss_ReGetReinsuranceTreaty  
DESCRIPTION:			Move pLoss_ReGetReinsuranceTreaty from AIRExposureRe to AIRProject
ExposedToEntities:		YES
ResultView:				None
Usage		:			DECLARE @AnalysisSID  INT = 1
						DECLARE @Debug BIT = 1
						EXECUTE dbo.pLOSS_ReGetReinsuranceTreaty @AnalysisSID ,@Debug
******************************************************************************************************/
ALTER
--ALTER 
PROCEDURE [dbo].[pLOSS_ReGetReinsuranceTreaty]
    (
        @AnalysisSID INT,
        @Debug BIT = 0
    )
AS
    BEGIN
        SET NOCOUNT ON
        DECLARE
            @Result INT = 0,
            @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
        BEGIN TRY
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': START OF '',
                    @SPName
            EXECUTE AIRProject.dbo.pLOSS_ReGetReinsuranceTreaty
                @AnalysisSID,
                @Debug
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName
            RETURN @Result
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = dbo.pReThrowError
                @SPName,
                @Debug
        END CATCH
    END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pAGGEXP_DeleteExposureViaCriteria]'
GO
IF OBJECT_ID(N'[dbo].[pAGGEXP_DeleteExposureViaCriteria]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
Object: pAGGEXP_DeleteExposureViaCriteria
Description: Delete some or all exposure in an exposure set, based on criteria such as country, year, peril, and exposure type.
SPExposedToEntities: Yes
ResultView: None
*********************************************************************************************************
exec [dbo].[pAGGEXP_DeleteExposureViaCriteria]
@ExposureSetSid=4
,@XmlExposureFilter=''<Root>
  <CountryCodeList>
    <CountryCode>US</CountryCode>
    <CountryCode>CA</CountryCode>
    <CountryCode>CN</CountryCode>
  </CountryCodeList>
  <PerilSetList>
    <PerilSet>67</PerilSet>
    <PerilSet>8</PerilSet>
    <PerilSet>4</PerilSet>
  </PerilSetList>
  <ExposureTypeList>
    <ExposureType>2</ExposureType>
    <ExposureType>3</ExposureType>
    <ExposureType>17</ExposureType>
  </ExposureTypeList>
  <YearIDList>
    <YearID>2014</YearID>
    <YearID>2013</YearID>
  </YearIDList>
</Root>''
,@Debug=1
*/
ALTER 
  --ALTER 
PROCEDURE [dbo].[pAGGEXP_DeleteExposureViaCriteria]
    @ExposureSetSid INT
   ,@XmlExposureFilter XML
   ,@Debug BIT = 0  
AS
BEGIN
SET NOCOUNT ON
    DECLARE @Result INT = 0
    DECLARE @SPName NVARCHAR(392)=DB_NAME()+''.''+SCHEMA_NAME()+''.'' +OBJECT_NAME(@@PROCID)   
	DECLARE @TargetType VARCHAR(50)  
    DECLARE @YearIds TABLE (YearID smallint)
	DECLARE @CountryCodes TABLE (CountryCode VARCHAR(15) )
	DECLARE @PerilIds TABLE (PerilSetCode INT)
	DECLARE @AggregateExposureTypes TABLE(AggregateExposureTypeCode INT)
	DECLARE @ErrMsg NVARCHAR(2048)
    IF @Debug=1 EXEC dbo.pCOMMON_PrintVariable '': START OF '',@SPName
	IF OBJECT_ID(''tempdb..#ProgramSids'') IS NOT NULL
		DROP TABLE #ProgramSids
	CREATE TABLE #ProgramSids
	(
		[TargetSID] [int]
	)
  
    BEGIN TRY
	    INSERT INTO @CountryCodes
		SELECT 
		   b.value(''(./text())[1]'',''Varchar(50)'') as [CountryCode]
		FROM @XmlExposureFilter.nodes(''/Root/CountryCodeList/CountryCode'') as a(b) 
		IF NOT EXISTS (SELECT 1 FROM @CountryCodes)
			THROW 50000, ''Invalid XML in @XmlExposureFilter. <CountryCodeList> cannot be empty.'', 1;		
	
		INSERT INTO @PerilIds
		SELECT 
		   b.value(''(./text())[1]'',''Varchar(50)'') as [PerilSetCode]
		FROM @XmlExposureFilter.nodes(''/Root/PerilSetList/PerilSet'') as a(b) 
		IF NOT EXISTS (SELECT 1 FROM @PerilIds)
			THROW 50000, ''Invalid XML in @XmlExposureFilter. <PerilSetList> cannot be empty.'', 1;
		INSERT INTO @YearIds 
		SELECT 
		   b.value(''(./text())[1]'',''Varchar(50)'') as [YearID]
		FROM @XmlExposureFilter.nodes(''/Root/YearIDList/YearID'') as a(b) 
		IF NOT EXISTS (SELECT 1 FROM @YearIds)
			THROW 50000, ''Invalid XML in @XmlExposureFilter. <YearIDList> cannot be empty.'', 1;
		INSERT INTO  @AggregateExposureTypes
		SELECT 
		   b.value(''(./text())[1]'',''Varchar(50)'') as [AggregateExposureTypeCode]
		FROM @XmlExposureFilter.nodes(''/Root/ExposureTypeList/ExposureType'') as a(b) 
		IF NOT EXISTS (SELECT 1 FROM  @AggregateExposureTypes)
			THROW 50000, ''Invalid XML in @XmlExposureFilter. <AggregateExposureTypeList> cannot be empty.'', 1;
		UPDATE  a
		SET [Premium]=CASE WHEN  EXISTS (SELECT 1 FROM @AggregateExposureTypes WHERE AggregateExposureTypeCode=1) THEN 0.0 ELSE Premium END,
		 [TotalInsuredValue]=CASE WHEN  EXISTS (SELECT 1 FROM @AggregateExposureTypes WHERE AggregateExposureTypeCode=2) THEN 0.0 ELSE TotalInsuredValue END,
		 [RiskCount]=CASE WHEN  EXISTS (SELECT 1 FROM @AggregateExposureTypes WHERE AggregateExposureTypeCode=3) THEN 0.0 ELSE RiskCount END,
		 [Rates]=CASE WHEN  EXISTS (SELECT 1 FROM @AggregateExposureTypes WHERE AggregateExposureTypeCode=4) THEN 0.0 ELSE Rates END,
		 [UserSpecifiedMarketShare]=CASE WHEN  EXISTS (SELECT 1 FROM @AggregateExposureTypes WHERE AggregateExposureTypeCode=5) THEN 0.0 ELSE UserSpecifiedMarketShare END,
		 [Payroll]=CASE WHEN  EXISTS (SELECT 1 FROM @AggregateExposureTypes WHERE AggregateExposureTypeCode=17) THEN 0.0 ELSE Payroll END
		FROM [dbo].[tAggregateExposure] a
		JOIN @PerilIds b
		ON a.PerilSetCode =b.PerilSetCode
		JOIN @CountryCodes c
		ON a.CountryCode=c.CountryCode
		JOIN @YearIds d
		ON a.YearID=d.YearID
		WHERE a.[ExposureSetSID]=@ExposureSetSid
		INSERT INTO #ProgramSids
			SELECT
			pt.[ReinsuranceProgramSID]
			FROM AIRExposureRe..tReinsuranceProgramTargetXRef pt 
		JOIN [dbo].[tAggregateExposure] a On a.ExposureSetSID = pt.ExposureSetSID
		JOIN @PerilIds b
		ON a.PerilSetCode =b.PerilSetCode
		JOIN @CountryCodes c
		ON a.CountryCode=c.CountryCode
		JOIN @YearIds d
		ON a.YearID=d.YearID	
		WHERE a.[ExposureSetSID]=@ExposureSetSid
		AND ISNULL(TotalInsuredValue,0)+ISNULL(RiskCount,0)+ISNULL(Premium,0)+ISNULL(Payroll ,0)+ISNULL(UserSpecifiedMarketShare,0)=0;
		EXEC AIRExposureRe.dbo.pUSR_ReInvalidateProgramBySidList @Debug
		
		IF OBJECT_ID(''tempdb..#ProgramSids'') IS NOT NULL
			DROP TABLE #ProgramSids
		
			
		DELETE a
		FROM [dbo].[tAggregateExposure] a
		JOIN @PerilIds b
		ON a.PerilSetCode =b.PerilSetCode
		JOIN @CountryCodes c
		ON a.CountryCode=c.CountryCode
		JOIN @YearIds d
		ON a.YearID=d.YearID	
		WHERE a.[ExposureSetSID]=@ExposureSetSid
		AND ISNULL(TotalInsuredValue,0)+ISNULL(RiskCount,0)+ISNULL(Premium,0)+ISNULL(Payroll ,0)+ISNULL(UserSpecifiedMarketShare,0)=0;
        /*
			Delete exposure sets for custome LOBs and associated loss results
		*/
        IF EXISTS
        (
            SELECT 1
            FROM @AggregateExposureTypes
            WHERE AggregateExposureTypeCode = 21
        )
        BEGIN
            DELETE a
            FROM [dbo].[tAggregateExposure] a
                JOIN @PerilIds b
                    ON a.PerilSetCode = b.PerilSetCode
                JOIN @CountryCodes c
                    ON a.CountryCode = c.CountryCode
                JOIN @YearIds d
                    ON a.YearID = d.YearID
            WHERE a.[ExposureSetSID] = @ExposureSetSid
                  AND a.LOBCode
                  BETWEEN 148 AND 167;
          END  						
		/*
		END - Delete exposure sets for custome LOBs and associated loss results
		*/
    END TRY
    BEGIN CATCH
        EXECUTE @Result=dbo.pReThrowError @SPName, @Debug
    END CATCH;
    IF @Debug=1 EXEC dbo.pCOMMON_PrintVariable '': END OF '',@SPName
    RETURN @Result
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pPLA_CopyReinsuranceProgram_EPAdjustment]'
GO
IF OBJECT_ID(N'[dbo].[pPLA_CopyReinsuranceProgram_EPAdjustment]', 'P') IS NOT NULL
EXEC sp_executesql N'  /*****************************************************************************************************
Object: [dbo].[pPLA_ReinsuranceProgram_EPAdjustment]
Description: Returns VALUES RELATED TO  EP adjustment screen other than EP points
SPExposedToEntities: 
ResultView: 
******************************************************************************************************/
ALTER --ALTER
PROCEDURE [dbo].[pPLA_CopyReinsuranceProgram_EPAdjustment] 
@BusinessUnitSID INT,
@SourceProgramSID INT,
@TargetProgramSID INT,
@modelcode SMALLINT,
@overwrite BIT=0,
@Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT =0
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
BEGIN TRY
	
IF @overwrite=1
BEGIN
DELETE FROM AIRExposureRe.dbo.tReinsuranceProgramEPAdjustmentPoints
WHERE ReinsuranceProgramSID = @TargetProgramSID
      AND ModelCode = @modelcode;
DELETE FROM AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment
WHERE ReinsuranceProgramSID = @TargetProgramSID
      AND ModelCode = @modelcode;
END
IF NOT EXISTS (SELECT 1 FROM AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment
WHERE ReinsuranceProgramSID = @TargetProgramSID
      AND ModelCode = @modelcode )
BEGIN
INSERT INTO AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment
(
    ReinsuranceProgramSID,
    ModelCode,
    AdjustmentMethodCode,
    EPAnnualTypeCode,
    ScalingMethodCode,
    RPIntervalMin,
    RPIntervalMax,
    ModelComment
)
SELECT @TargetProgramSID,
       ModelCode,
       AdjustmentMethodCode,
       EPAnnualTypeCode,
       ScalingMethodCode,
       RPIntervalMin,
       RPIntervalMax,
       ModelComment
FROM AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment
WHERE ReinsuranceProgramSID = @SourceProgramSID
      AND ModelCode = @modelcode;
INSERT INTO AIRExposureRe.dbo.tReinsuranceProgramEPAdjustmentPoints
(
    ReinsuranceProgramSID,
    ModelCode,
    ReturnPeriod,
    AdjustmentValue
)
SELECT @TargetProgramSID,
       ModelCode,
       ReturnPeriod,
       AdjustmentValue
FROM AIRExposureRe.dbo.tReinsuranceProgramEPAdjustmentPoints
WHERE ReinsuranceProgramSID = @SourceProgramSID
      AND ModelCode = @modelcode;
	  
END
	END TRY
	BEGIN CATCH	
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
	
	RETURN @Result
END
 
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pPLA_Get_CopyReinsuranceProgram_EPAdjustment]'
GO
IF OBJECT_ID(N'[dbo].[pPLA_Get_CopyReinsuranceProgram_EPAdjustment]', 'P') IS NOT NULL
EXEC sp_executesql N'     /*****************************************************************************************************
Object: [dbo].[pPLA_Get_ReinsuranceProgram_EPAdjustment]
Description: Returns VALUES RELATED TO  EP adjustment screen other than EP points
SPExposedToEntities: 
ResultView: 
******************************************************************************************************/
ALTER --ALTER
PROCEDURE [dbo].[pPLA_Get_CopyReinsuranceProgram_EPAdjustment] 
@BusinessUnitSID INT,
@modelfilter XML,
@Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT
	DECLARE @iscustom INT
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
BEGIN TRY
	
	SELECT *
	 INTO  #modelinfo
	 FROM  (
			SELECT RANK() OVER (PARTITION BY ModelCode
								ORDER BY ModelCode,
										 IsPreviousVersionModel ASC
							   ) rank1 ,
				   ModelCode,model
				   
			FROM AIRUserSetting.dbo.tModelInfo
			WHERE StatusCode = ''A'' ) s
			WHERE rank1=1
		SELECT Tbl.Col.value(''Modules[1]'', ''varchar(20)'') AS Module,
			   Tbl.Col.value(''Country[1]'', ''varchar(3)'') AS CountryCode,
			   Tbl.Col.value(''Peril[1]'', ''int'') AS PerilSetCode,
			   Tbl.Col.value(''Value[1]'', ''varchar(20)'') AS CatalogSize,
			   Tbl.Col.value(''Key[1]'', ''varchar(30)'') AS [Key]
		--Tbl.Col.value(''YearMax[1]'', ''int'') AS YearMax ,
		--Tbl.Col.value(''ModelLOB[1]'', ''varchar(3)'') AS ModelLOB
		INTO #tModelCountryPeril
		FROM @modelfilter.nodes(''//Options/Option'')Tbl(Col);
		IF EXISTS
		(
			SELECT 1
			FROM #tModelCountryPeril
			WHERE [Key] = ''Custom Models and LOBs''
		)
			SET @iscustom = 1;
SELECT DISTINCT
                  s1.ModelCode,
				  s2.[Key],
				  s2.[CatalogSize]
            INTO #Licensedmodel
            FROM
            (
                  SELECT DISTINCT
                        ModelCode,
                        CountryCode,
                        PerilSetCode
                  FROM [AIRUserSetting].[dbo].[vwReinsuranceModelCountryPerilXref]
                  --WHERE ModelCode IN( 11, 31, 52, 54)
            ) s1
                  INNER JOIN 
                  (
                        SELECT CountryCode,
                                 PerilSetCode,
								 [Key],
								 [CatalogSize]
                        FROM #tModelCountryPeril
                        WHERE Module = ''Aggregate Loss''
                  ) s2
                        ON s1.CountryCode = s2.CountryCode
                           AND s1.PerilSetCode & s2.PerilSetCode <> 0
	
--SELECT c.CompanySID,
--       c.CompanyName,
--       p.ReinsuranceProgramSID,
--       p.ProgramID
--FROM AIRExposureRe.dbo.tCompany c
--    INNER JOIN AIRExposureRe.dbo.tReinsuranceProgram p
--        ON c.CompanySID = p.CompanySID;
SELECT 	   CAST(c.CompanySID AS INT) CompanySID,
		   c.CompanyName,
		   p.ReinsuranceProgramSID,
		   p.ProgramID,
		   CAST(m.ModelCode AS SMALLINT) ModelCode,
		   m.Model [ModelDescription]
		   INTO #PLAModels
	FROM
	(
		SELECT DISTINCT
			ModelCode
		FROM AIRUserSetting.dbo.tReinsuranceCatalog
		WHERE YearMax IN ( 10000,500000)
			  AND CatalogTypeCode = 2
			  AND ISArchived = 0
	) s
		INNER JOIN #modelinfo  m
			ON s.ModelCode = m.ModelCode
		INNER JOIN #Licensedmodel lm
			ON s.ModelCode=lm.ModelCode AND lm.CatalogSize IN (10000,500000) 
		LEFT JOIN AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment ep
			ON m.ModelCode = ep.ModelCode 
		INNER JOIN AIRExposureRe.dbo.tReinsuranceProgram p
		ON ep.ReinsuranceProgramSID=p.ReinsuranceProgramSID
			AND p.StatusCode=''A''
    INNER JOIN AIRExposureRe.dbo.tCompany c
        ON c.CompanySID = p.CompanySID
		AND c.BusinessUnitSID=@BusinessUnitSID
IF @iscustom=1 
		
		BEGIN
		INSERT INTO #PLAModels
		(	CompanySID,
		    CompanyName,
			ReinsuranceProgramSID,
			ProgramID,
			ModelCode,
			ModelDescription
		    
		)
			SELECT CAST(c1.CompanySID AS INT) CompanySID,
				   c1.CompanyName,
				   p.ReinsuranceProgramSID,
				   p.ProgramID,
				   CAST(m.ModelCode AS SMALLINT) ModelCode,
				   m.Model [ModelDescription]
			FROM 
			AIRUserSetting.dbo.tReinsuranceCatalog c INNER JOIN 
			AIRUserSetting.dbo.tModel m
			ON c.modelcode=m.ModelCode
		LEFT JOIN AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment ep
			ON m.ModelCode = ep.ModelCode 
		INNER JOIN AIRExposureRe.dbo.tReinsuranceProgram p
		ON ep.ReinsuranceProgramSID=p.ReinsuranceProgramSID
			AND p.StatusCode=''A''
        INNER JOIN AIRExposureRe.dbo.tCompany c1
        ON c1.CompanySID = p.CompanySID
		AND c.BusinessUnitSID=@BusinessUnitSID
		WHERE c.iscustom=1
				END
		SELECT 
		    CompanySID,
		    CompanyName,
			ReinsuranceProgramSID,
			ProgramID,
			ModelCode,
			ModelDescription
			FROM #PLAModels
		ORDER BY CompanyName,ProgramID,ModelCode;
	END TRY
	BEGIN CATCH	
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
	
	RETURN @Result
END
 
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pPLA_Get_ReinsuranceProgram_EPAdjustment]'
GO
IF OBJECT_ID(N'[dbo].[pPLA_Get_ReinsuranceProgram_EPAdjustment]', 'P') IS NOT NULL
EXEC sp_executesql N'  
   /*****************************************************************************************************
Object: [dbo].[pPLA_Get_ReinsuranceProgram_EPAdjustment]
Description: Returns VALUES RELATED TO  EP adjustment screen other than EP points
SPExposedToEntities: 
ResultView: 
******************************************************************************************************/
ALTER --ALTER
PROCEDURE [dbo].[pPLA_Get_ReinsuranceProgram_EPAdjustment] 
@programsid INT,
@modelfilter XML,
@debug INT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT
	DECLARE @iscustom INT
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
BEGIN TRY
	
		SELECT Tbl.Col.value(''Modules[1]'', ''varchar(20)'') AS Module,
			   Tbl.Col.value(''Country[1]'', ''varchar(3)'') AS CountryCode,
			   Tbl.Col.value(''Peril[1]'', ''int'') AS PerilSetCode,
			   Tbl.Col.value(''Value[1]'', ''varchar(20)'') AS CatalogSize,
			   Tbl.Col.value(''Key[1]'', ''varchar(30)'') AS [Key]
		--Tbl.Col.value(''YearMax[1]'', ''int'') AS YearMax ,
		--Tbl.Col.value(''ModelLOB[1]'', ''varchar(3)'') AS ModelLOB
		INTO #tModelCountryPeril
		FROM @modelfilter.nodes(''//Options/Option'')Tbl(Col);
		IF EXISTS
		(
			SELECT 1
			FROM #tModelCountryPeril
			WHERE [Key] = ''Custom Models and LOBs''
		)
			SET @iscustom = 1;
		SELECT DISTINCT
                  s1.ModelCode,
				  s2.[Key],
				  s2.[CatalogSize]
            INTO #Licensedmodel
            FROM
            (
                  SELECT DISTINCT
                        ModelCode,
                        CountryCode,
                        PerilSetCode
                  FROM [AIRUserSetting].[dbo].[vwReinsuranceModelCountryPerilXref]
                  --WHERE ModelCode IN( 11, 31, 52, 54)
            ) s1
                  INNER JOIN 
                  (
                        SELECT CountryCode,
                                 PerilSetCode,
								 [Key],
								 [CatalogSize]
                        FROM #tModelCountryPeril
                        WHERE Module = ''Aggregate Loss''
                  ) s2
                        ON s1.CountryCode = s2.CountryCode
                           AND s1.PerilSetCode & s2.PerilSetCode <> 0
	
	
	SELECT DISTINCT
		modelcode
	INTO #modelcode
	FROM AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment
	WHERE ReinsuranceProgramSID = @programsid;
	SELECT CAST(m.ModelCode AS SMALLINT) ModelCode,
		   m.Model [ModelDescription],
		   ep.AdjustmentMethodCode,
		   ep.EPAnnualTypeCode,
		   ep.ScalingMethodCode,
		   ep.RPIntervalMin,
		   ep.RPIntervalMax,
		   ep.ModelComment,
		  CAST( CASE
			   WHEN m1.ModelCode IS NOT NULL THEN
				   1
			   ELSE
				   0
		   END   AS BIT)IsModifed
		   INTO #PLAModels
	FROM
	(
		SELECT DISTINCT
			ModelCode
		FROM AIRUserSetting.dbo.tReinsuranceCatalog
		WHERE YearMax IN ( 10000)
			  AND CatalogTypeCode = 2
			  AND ISArchived = 0
	) s
		INNER JOIN 
		(SELECT DISTINCT modelcode,model FROM 
		AIRUserSetting.dbo.tModelInfo 
		WHERE  StatusCode = ''A'' ) m
			ON s.ModelCode = m.ModelCode
		INNER JOIN #Licensedmodel lm
			ON s.ModelCode=lm.ModelCode AND lm.CatalogSize IN (10000)
		LEFT JOIN AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment ep
			ON m.ModelCode = ep.ModelCode AND ep.ReinsuranceProgramSID=@programsid
		LEFT JOIN #modelcode m1
		ON s.ModelCode=m1.ModelCode
		
		IF @iscustom=1 
		
		BEGIN
		INSERT INTO #PLAModels
		(	ModelCode,
		    ModelDescription,
		    AdjustmentMethodCode,
		    EPAnnualTypeCode,
		    ScalingMethodCode,
		    RPIntervalMin,
		    RPIntervalMax,
		    ModelComment,
			IsModifed
		)
		SELECT DISTINCT
					CAST(m.ModelCode AS SMALLINT) ModelCode,
				   m2.Model [ModelDescription],
				   ep.AdjustmentMethodCode,
				   ep.EPAnnualTypeCode,
				   ep.ScalingMethodCode,
				   ep.RPIntervalMin,
				   ep.RPIntervalMax,
				   ep.ModelComment,
				   CAST( CASE
					   WHEN m1.ModelCode IS NOT NULL THEN
						   1
					   ELSE
						   0
				   END   AS BIT)IsModifed
				FROM AIRUserSetting.dbo.tReinsuranceCatalog m
				INNER JOIN AIRUserSetting.dbo.tModel m2
				ON m.ModelCode=m2.ModelCode
				LEFT JOIN AIRExposureRe.dbo.tReinsuranceProgramEPAdjustment ep
					ON m.ModelCode = ep.ModelCode AND ep.ReinsuranceProgramSID=@programsid
				LEFT JOIN #modelcode m1
				ON m.ModelCode=m1.ModelCode	
				WHERE IsCustom=1;
				END
	
	SELECT  ModelCode,
		    ModelDescription,
		    AdjustmentMethodCode,
		    EPAnnualTypeCode,
		    ScalingMethodCode,
		    RPIntervalMin,
		    RPIntervalMax,
		    ModelComment,
			IsModifed
			FROM #PLAModels
	END TRY
	BEGIN CATCH	
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
	
	RETURN @Result
END
 
 
 
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pPLA_Get_ReinsuranceProgram_EPAPoints]'
GO
IF OBJECT_ID(N'[dbo].[pPLA_Get_ReinsuranceProgram_EPAPoints]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
Object: [dbo].[pPLA_Get_ReinsuranceProgram_EPAPoints]
Description: Returns EPPoint VALUES RELATED TO  EP adjustment screen 
SPExposedToEntities: 
ResultView: 
******************************************************************************************************/
ALTER PROCEDURE [dbo].[pPLA_Get_ReinsuranceProgram_EPAPoints] 
@programsid INT,
@modelcode smallint,
@debug INT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
	BEGIN TRY
		SELECT 
			ReturnPeriod
			, AdjustmentValue
		FROM AIRExposureRe.dbo.tReinsuranceProgramEPAdjustmentPoints
		WHERE ReinsuranceProgramSID = @programsid
		AND ModelCode = @modelcode
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH
	RETURN @Result
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pPRTCopy_ReCopyPortfolio]'
GO
IF OBJECT_ID(N'[dbo].[pPRTCopy_ReCopyPortfolio]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
DATE :					08-2016
OBJECT:					dbo.pPRTCopy_ReCopyPortfolio
DESCRIPTION:			copy data from the existing portfolio along with the treaties 
ExposedToEntities:		NO
ResultView:				Yes
						rvPRTCopy_ReCopyPortfolio
usage:					DECLARE @PortfolioSID INT = 8,
								@PortfolioName varchar(255) = ''Newportflio_stc'',
								@PortfolioDescription varchar(255) = ''description sdhsdkjfhskdjhfskdjfhkj'',
								@Author varchar(255) = ''i55782'',
								@Debug BIT = 1
						EXECUTE dbo.pPRTCopy_ReCopyPortfolio @PortfolioSID,@PortfolioName, @PortfolioDescription, @Author, @Debug
select * from tportfolio where portfoliosid in (5, 8)
select * from tPortfolioFilter where portfoliosid in (
select * from dbo.tPortfolioReinsuranceTreaty
**********************************************************************************************************/
ALTER
-- ALTER 
PROCEDURE [dbo].[pPRTCopy_ReCopyPortfolio]
    @PortfolioSID INT,
    @PortfolioName VARCHAR(255),
	@PortfolioDescription VARCHAR(4000),
	@Author VARCHAR(255),
    @Debug BIT = 0
AS
BEGIN -- OF PROC
    -- DECLARE VARIABLES
    DECLARE @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
            @Result INT = 0,
            @IsDynamic BIT = 0,
            @PortfolioNextSID INT,
            @PortfolioFilterSID INT;
    SET NOCOUNT ON;
    BEGIN TRY
	IF NOT EXISTS (SELECT 1 FROM AIRExposureRe.dbo.tPortfolio WHERE PortfolioName = @PortfolioName)
        BEGIN
            SET @IsDynamic =
            (
                SELECT CASE
                           WHEN PortfolioTypeCode = ''DYN'' THEN
                               1
                           ELSE
                               0
                       END
                FROM dbo.tPortfolio
                WHERE PortfolioSID = @PortfolioSID
            );
            EXEC dbo.pGetSIDRange @TableSID = NULL,
                                  @TableName = ''tPortfolio'',
                                  @Amount = 1,
                                  @NextSID = @PortfolioNextSID OUTPUT;
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName;
            -- insert potfolio data
            INSERT INTO dbo.tPortfolio
            (
                PortfolioSID,
                PortfolioFilterSID,
                PortfolioName,
                BusinessUnitSID,
                TotalInvestmentAmount,
                ReinsuranceLayerCount,
                RiskRatio,
                StatusCode,
                Description,
                EnteredDate,
                EditedDate,
                Author,
                PortfolioTypeCode
            )
            SELECT @PortfolioNextSID,
                   PortfolioFilterSID,
                   @PortfolioName,
                   BusinessUnitSID,
                   TotalInvestmentAmount,
                   ReinsuranceLayerCount,
                   RiskRatio,
                   StatusCode,
                   @PortfolioDescription,
                   EnteredDate,
                   EditedDate,
                   @Author,
                   PortfolioTypeCode
            FROM dbo.tPortfolio
            WHERE PortfolioSID = @PortfolioSID;
            -- insert portfolio filter (if any) 
            IF @IsDynamic = 1
            BEGIN
                EXEC dbo.pGetSIDRange @TableSID = NULL,
                                      @TableName = ''tPortfolioFilter'',
                                      @Amount = 1,
                                      @NextSID = @PortfolioFilterSID OUTPUT;
                INSERT INTO dbo.tPortfolioFilter
                (
                    PortfolioFilterSID,
                    Expression,
                    SqlString,
                    EnteredDate,
                    EditedDate
                )
                SELECT @PortfolioFilterSID,
                       Expression,
                       SqlString,
                       EnteredDate,
                       EditedDate
                FROM dbo.tPortfolioFilter
                WHERE PortfolioFilterSID =
                (
                    SELECT PortfolioFilterSID
                    FROM dbo.tPortfolio
                    WHERE PortfolioSID = @PortfolioNextSID
                );
            END;
            -- insert treaty data
            INSERT INTO dbo.tPortfolioReinsuranceTreaty
            (
                ReinsuranceTreatySID,
                PortfolioSID,
                PrincipalAmount,
                InvestmentAmount,
                PercentAnnualSpread,
                ParticipationNet,
                ParticipationGross,
                Participation3,
                Participation4,
                Premium,
                ReinstatementPremium,
                EnteredDate,
                EditedDate
            )
            SELECT ReinsuranceTreatySID,
                   @PortfolioNextSID,
                   PrincipalAmount,
                   InvestmentAmount,
                   PercentAnnualSpread,
                   ParticipationNet,
                   ParticipationGross,
                   Participation3,
                   Participation4,
                   Premium,
                   ReinstatementPremium,
                   EnteredDate,
                   EditedDate
            FROM dbo.tPortfolioReinsuranceTreaty
            WHERE PortfolioSID = @PortfolioSID;
        END
		ELSE 
		BEGIN 
		SET @PortfolioNextSID = -1
		END 
		;
		IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName;
		SELECT @PortfolioNextSID;
        RETURN @PortfolioNextSID;
    END TRY
    BEGIN CATCH
        -- re-raise the error to be caught in the calling process
        EXECUTE @Result = dbo.pReThrowError @SPName, @Debug;
    END CATCH;
END; -- OF PROC
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pPRTEXPORT_GetPortfolioList]'
GO
IF OBJECT_ID(N'[dbo].[pPRTEXPORT_GetPortfolioList]', 'P') IS NOT NULL
EXEC sp_executesql N' /******************************************************************************************************
Object: dbo.pGetPortfolioEXPList 
Description:	Get a simple list of Portfolios that would be exported
SPExposedToEntities : 06-22-2017
ResultView: dbo.rvGetPortfolioEXPList
Usage:
DECLARE @BusinessUnitSID int
DECLARE @Debug bit
SET @BusinessUnitSID = 2
SET @Debug = 1
EXECUTE @RC = [dbo].[pPRTEXPORT_GetPortfolioList]
   @BusinessUnitSID = BusinessUnitSID
   , @Debug = @Debug
*******************************************************************************************************/
ALTER 
-- ALTER
PROCEDURE [dbo].[pPRTEXPORT_GetPortfolioList]
	@BusinessUnitSID int,
	@Debug BIT =0
AS
BEGIN
	SET NOCOUNT ON
	BEGIN TRY
		DECLARE @Result INT
		DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
		
		IF ISNULL(@BusinessUnitSID,0)  = 0
			EXEC @BusinessUnitSID = AIRProject.[dbo].[pCOMMON_ReGetBusinessUnitSID]
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		SELECT 
			P.PortfolioSID,
			P.PortfolioName,
			PT.PortfolioType,
			P.EnteredDate
		FROM [airexposureRe].[dbo].[tPortfolio] P
		JOIN [AIRReference].[dbo].[tPortfolioType] PT ON
			P.PortfolioTypeCode = PT.PortfolioTypeCode
		WHERE P.BusinessUnitSID = @BusinessUnitSID 
		ORDER BY P.EnteredDate DESC
		
	END TRY
	BEGIN CATCH
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pReGetContractSources]'
GO
IF OBJECT_ID(N'[dbo].[pReGetContractSources]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT:					pGetContractSources
DESCRIPTION:			Get contract and source information by CompanySID and ContractSubjectSID 
ExposedToEntities:		02/21/2017
ResultView:				NA
Usage : 
DECLARE	@return_value int
EXEC	@return_value = [dbo].[pReGetContractSources]
		@CompanySID = 1,
		@ContractSubjectSID = 1,
**********************************************************************************************************/
ALTER 
--ALTER
PROCEDURE [dbo].[pReGetContractSources] 
      @CompanySID                INT ,
	  @ContractSubjectSID        INT, 
	  @Debug BIT = 0 
AS
BEGIN
SET NOCOUNT ON
	DECLARE @Result INT
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
      SELECT   src.[ReinsuranceProgramSID] AS [ReinsuranceProgramSID],
      src.[IsAssessmentProgram] , 
      src.[CompanySID] AS [CompanySID], 
      lnk.[ParticipationTypeCode], 
      lnk.[ParticipationAmount],  
	  src.IsAssessmentProgram AS bAssessment,
      bSelected = CASE
            WHEN sub.[ReinsuranceProgramSID] IS NOT NULL THEN 1
            ELSE 0
      END
      FROM AIRExposureRe..tReinsuranceProgram [src] 
			INNER JOIN AIRExposureRe..tCompany cmp On src.[CompanySID] = cmp.[CompanySID]
            LEFT OUTER JOIN AIRExposureRe..vwReinsuranceProgramSourceInure AS lnk ON src.ReinsuranceProgramSID = lnk.[ReinsuranceProgramSourceInureSID] 
			AND lnk.[ReinsuranceProgramSubjectSID] = @ContractSubjectSID
            LEFT OUTER JOIN AIRExposureRe..tReinsuranceProgram AS sub ON 
			lnk.[ReinsuranceProgramSubjectSID] = sub.[ReinsuranceProgramSID] 
			
      WHERE 
       (src.IsAssessmentProgram = 1 OR
       (src.IsAssessmentProgram = 0 AND src.[CompanySID] = @CompanySID) )
      AND src.ReinsuranceProgramSID != @ContractSubjectSID
	SET @Result = 0
IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
	RETURN @Result
      
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pReGetReinsuranceParticipationByTreaty]'
GO
IF OBJECT_ID(N'[dbo].[pReGetReinsuranceParticipationByTreaty]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
DATE :					07-17-2017
OBJECT:					dbo.[pReGetReinsuranceParticipationByTreaty] 
DESCRIPTION:			Get ParticipationAmount by ProgramSID
ExposedToEntities:		No
ResultView:				None
Usage		:			DECLARE @ReinsuranceProgramSID INT = 1
						DECLARE @Debug BIT = 1
						EXECUTE [dbo].[pReGetReinsuranceParticipationByTreaty] @ReinsuranceProgramSID,@Debug
******************************************************************************************************/
ALTER
--ALTER 
PROCEDURE [dbo].[pReGetReinsuranceParticipationByTreaty]
(
    @ReinsuranceSourceProgramSID INT,
	@ReinsuranceSubjectProgramSID INT,
    @Debug BIT = 0
)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @Result INT = 0,
            @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
            @IsAssessmentProgram INT = 0,
            @PartCode INT = 0,
            @FinCode NVARCHAR(10)
    BEGIN TRY
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName;
        --Get the IsAssessmentProgram
        SELECT @IsAssessmentProgram = IsAssessmentProgram
        FROM [dbo].tReinsuranceProgram
        WHERE ReinsuranceProgramSID = @ReinsuranceSourceProgramSID;
        --IF FinancialPerspectiveCode = ''RIGU'' Then Go to IF
        IF @IsAssessmentProgram = 1
        BEGIN
            SELECT ReinsuranceTreatySID,
                   ParticipationAmount, 0 AS IsNetRetain
            FROM [dbo].tReinsuranceProgramSourceInure si
                INNER JOIN [dbo].tReinsuranceTreaty tr
                    ON si.ReinsuranceProgramSourceInureSID = ReinsuranceProgramSID
            WHERE si.ReinsuranceProgramSubjectSID = @ReinsuranceSubjectProgramSID
			AND si.ReinsuranceProgramSourceInureSID = @ReinsuranceSourceProgramSID
        END;
        ELSE
        BEGIN
            --Get ParticipationTypeCode
            SELECT @PartCode = ParticipationTypeCode,
                   @FinCode = FinancialPerspectiveCode
            FROM AIRExposureRe..vwReinsuranceProgramSourceInure
            WHERE ReinsuranceProgramSourceInureSID = @ReinsuranceSourceProgramSID AND ReinsuranceProgramSubjectSID=@ReinsuranceSubjectProgramSID;
            -- Get ParticipationAmount on the basis of ParticipationTypeCode
            SELECT ReinsuranceTreatySID,
                   CASE @PartCode
                       WHEN 1 THEN
                           1.0
                       WHEN 2 THEN
                           ParticipationNet
                       WHEN 3 THEN
                           ParticipationGross
                       WHEN 4 THEN
                           Participation3
                       WHEN 5 THEN
                           Participation4
                   END AS ParticipationAmount,
                   CASE @FinCode
                       WHEN ''CON'' THEN
                           0
                       ELSE
                           1
                   END AS IsNetRetain
            FROM [dbo].tReinsuranceTreaty
            WHERE ReinsuranceProgramSID = @ReinsuranceSourceProgramSID;
        END;
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName;
        RETURN @Result;
    END TRY
    BEGIN CATCH
        -- re-raise the error to be caught in the calling process
        EXECUTE @Result = dbo.pReThrowError @SPName, @Debug;
    END CATCH;
END;
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[fReUNICEDE2_GetMatrixRow]'
GO
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fReUNICEDE2_GetMatrixRow]') AND (type = 'IF' OR type = 'FN' OR type = 'TF'))
EXEC sp_executesql N' /*****************************************************************************************************
DESCRIPTION:	return 1 row of Matrix for a specific @PerilSetCode
				DECLARE @CountryTbl udtCountryCodeList
				SELECT * FROM [dbo].[fReUNICEDE2_GetMatrixRow] (7,2014,4,@CountryTbl)
*****************************************************************************************************/
ALTER 
--ALTER
FUNCTION [dbo].[fReUNICEDE2_GetMatrixRow] (
	@ExposureSetSID INT ,
	@YearID SMALLINT,
	@PerilSetCode INT,
	@CountryTbl udtCountryCodeList READONLY
)
RETURNS @Result TABLE (PerilSetCode INT, 
				 IsSI bit, 
				 IsNR bit,
				 IsPR bit,
				 IsPY bit,
				 IsMS bit)
AS
BEGIN
	DECLARE @SeparatorLength TINYINT
	DECLARE @ID INT = 1
		 
		IF NOT EXISTS (SELECT 1 FROM @CountryTbl) 
			INSERT INTO @Result
			SELECT  TOP 1
				@PerilSetCode AS PerilsetCode,
				IIF(t1.TotalInsuredValue>0,1,0)  as IsSI,
				IIF(t2.RiskCount>0,1, 0)  as isNR,
				IIF(t3.Premium>0,1, 0)   as  IsPR,
				IIF(t4.Payroll>0,1, 0)   As IsPY,
				IIF(t5.UserSpecifiedMarketShare>0,1, 0)   AS IsMS
			FROM [dbo].[tAggregateExposure] a
			OUTER APPLY (SELECT top 1 [TotalInsuredValue] 
					from [dbo].[tAggregateExposure] 
					where ExposureSetSID=@ExposureSetSID 
					AND  YearID=@YearID 
					AND IntAreaScheme=1006
					AND PerilSetCode & @PerilSetCode>0
					AND ISNULL(TotalInsuredValue,0) > 0
				) t1
			OUTER APPLY (SELECT top 1 [RiskCount] 
				from [dbo].[tAggregateExposure] 
				where ExposureSetSID=@ExposureSetSID 
				AND  YearID=@YearID 
				AND IntAreaScheme=1006
				AND PerilSetCode & @PerilSetCode>0 
				AND ISNULL(RiskCount,0) > 0
				) t2
			OUTER APPLY (SELECT top 1 [Premium] 
				from [dbo].[tAggregateExposure] 
				where ExposureSetSID=@ExposureSetSID 
				AND  YearID=@YearID 
				AND PerilSetCode & @PerilSetCode>0
				AND ISNULL(Premium,0) > 0
				) t3
			OUTER APPLY (SELECT top 1 [Payroll] 
				from [dbo].[tAggregateExposure] 
				where ExposureSetSID=@ExposureSetSID 
				AND  YearID=@YearID 
				AND IntAreaScheme=1006
				AND PerilSetCode & @PerilSetCode>0 
				AND ISNULL(Payroll,0) > 0
				) t4
			OUTER APPLY (SELECT top 1 [UserSpecifiedMarketShare] 
				from [dbo].[tAggregateExposure] 
				where ExposureSetSID=@ExposureSetSID 
				AND  YearID=@YearID 
				AND PerilSetCode & @PerilSetCode>0
				AND ISNULL(UserSpecifiedMarketShare,0) > 0
				) t5
			WHERE ExposureSetSID=@ExposureSetSID
			AND YearID=@YearID 
			AND PerilSetCode=@PerilSetCode
			AND (IntAreaScheme IN (1006,1000) OR (t5.UserSpecifiedMarketShare>0 
			   AND IntAreaScheme IN (1001,1009,1011,1012,1013,1021,1022,1024,1025,1038,1050) ))
		ELSE
			INSERT INTO @Result
			SELECT   TOP 1
				@PerilSetCode AS PerilsetSID,
				IIF(t1.TotalInsuredValue>0,1,0)  as IsSI,
				IIF(t2.RiskCount>0,1, 0)  as IsNR,
				IIF(t3.Premium>0,1, 0)   as  IsPR,
				IIF(t4.Payroll>0,1, 0)   As IsPY,
				IIF(t5.UserSpecifiedMarketShare>0,1, 0)   AS IsMS
			FROM [dbo].[tAggregateExposure] a
			OUTER APPLY (SELECT top 1 [TotalInsuredValue] 
					from [dbo].[tAggregateExposure] 
					where ExposureSetSID=@ExposureSetSID 
					AND  YearID=@YearID 
					AND IntAreaScheme=1006
					AND PerilSetCode & @PerilSetCode>0 
					AND ISNULL(TotalInsuredValue,0) > 0
				) t1
			OUTER APPLY (SELECT top 1 [RiskCount] 
				from [dbo].[tAggregateExposure] 
				where ExposureSetSID=@ExposureSetSID 
				AND  YearID=@YearID 
				AND IntAreaScheme=1006
				AND PerilSetCode & @PerilSetCode>0
				AND ISNULL(RiskCount,0) > 0
				) t2
			OUTER APPLY (SELECT top 1 [Premium] 
				from [dbo].[tAggregateExposure] 
				where ExposureSetSID=@ExposureSetSID 
				AND  YearID=@YearID 
				AND PerilSetCode & @PerilSetCode>0 
				AND ISNULL(Premium,0) > 0
				) t3
			OUTER APPLY (SELECT top 1 [Payroll] 
				from [dbo].[tAggregateExposure] 
				where ExposureSetSID=@ExposureSetSID 
				AND  YearID=@YearID 
				AND IntAreaScheme=1006
				AND PerilSetCode & @PerilSetCode>0
				AND ISNULL(Payroll,0) > 0
				) t4
			OUTER APPLY (SELECT top 1 [UserSpecifiedMarketShare] 
				from [dbo].[tAggregateExposure] 
				where ExposureSetSID=@ExposureSetSID 
				AND  YearID=@YearID 
				AND PerilSetCode & @PerilSetCode>0
				AND ISNULL(UserSpecifiedMarketShare,0) > 0
				) t5
			WHERE ExposureSetSID=@ExposureSetSID
			AND YearID=@YearID 
			AND PerilSetCode=@PerilSetCode
			AND (IntAreaScheme IN (1006,1000) OR (t5.UserSpecifiedMarketShare>0 
			   AND IntAreaScheme IN (1001,1009,1011,1012,1013,1021,1022,1024,1025,1038,1050) ))
	RETURN 
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pSyncUIAggregateExposure]'
GO
IF OBJECT_ID(N'[dbo].[pSyncUIAggregateExposure]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT:				dbo.pSyncUIAggregateExposure
DESCRIPTION:		Returns aggregate exposure on Country level filtered according to input parameters
ExposedToEntities:	Yes?
ResultView:			
Usage:				EXEC dbo.pSyncUIAggregateExposure
						@ExposureSetSID = 18, 
						@TableName = ''AIRWork.dbo.t18_Import_A2033A93A2FB487A844E260D5B1C7AAE'', 
						@Debug = 1
**********************************************************************************************************/
ALTER --ALTER 
PROCEDURE [dbo].[pSyncUIAggregateExposure]
	@ExposureSetSID INTEGER, 
	@TableName SYSNAME, 
	@Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INTEGER = 0
	DECLARE @SPName SYSNAME = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	DECLARE @SQLStmt NVARCHAR(MAX)
	DECLARE @SQLStmtParameters NVARCHAR(MAX)
	DECLARE @RowCount INTEGER;
	DECLARE @NextSID INTEGER;
	BEGIN TRY
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': @TableName value '', @TableName
		SET @SQLStmt=  ''
			ALTER TABLE '' + @TableName +'' 
				ADD CountryCode VARCHAR(15),
					CountryName VARCHAR(255),
					CRESTACode VARCHAR(15),
					CRESTAName VARCHAR(255),
					AreaCode VARCHAR(15),
					AreaName VARCHAR(255),
					SubareaCode VARCHAR(15),
					ParentGeographySID INTEGER,
					GeoLevelCode  VARCHAR(10)'';
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt =  ''
			UPDATE '' + @TableName + ''
				SET IntAreaScheme = b.AreaScheme,
					CountryCode = b.CountryCode,
					AreaCode = b.AreaCode,
					CRESTACode = b.CRESTACode,
					SubareaCode = b.SubareaCode,
					GeoLevelCode = b.GeoLevelCode,
					ParentGeographySID = b.ParentGeographySID
			FROM AIRGeography.dbo.tReinsuranceGeography b
			WHERE  '' + @TableName + ''.GeographySID = b.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt=N'' SELECT DISTINCT GeoLevelCode FROM '' + @TableName 
		EXEC SP_EXECUTESQL @SQLStmt
		IF @@ROWCOUNT>1
		   RAISERROR(''Multi GeolevelCode found in the staging table.'',16,1)
		SET @SQLStmt =  ''
			UPDATE '' + @TableName + ''
				SET CurrencyCode = b.CurrencyCode
			FROM '' + @TableName + '' a
			JOIN AIRReference.dbo.tCountryCurrencyXRef b
				ON a.CountryCode = b.CountryCode
				AND b.IsDefault = 1''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt =  ''
			UPDATE '' + @TableName + ''
				SET TotalInsuredValue = ISNULL(a.TotalInsuredValue, b.TotalInsuredValue),
					RiskCount = ISNULL(a.RiskCount, b.RiskCount),
					Premium = ISNULL(a.Premium, b.Premium),
					Payroll = ISNULL(a.Payroll, b.Payroll),
					UserSpecifiedMarketShare = ISNULL(a.UserSpecifiedMarketShare, b.UserSpecifiedMarketShare),
					Rates = ISNULL(a.Rates, b.Rates)
			FROM '' + @TableName + '' a
			JOIN dbo.tAggregateExposure  b
				ON b.ExposureSetSID = @ExposureSetSID
				AND a.PerilSetCode 	= b.PerilSetCode
				AND a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.GeographySID = b.GeographySID
				AND a.LOBCode = b.LOBCode''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @SQLStmt =  ''
			SELECT * 
			INTO '' + @TableName + ''_1
			FROM '' + @TableName + '' 
			WHERE  GeoLevelCode = ''''SUBA''''''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt =  ''
			SELECT *
			INTO '' + @TableName + ''_0 
			FROM '' + @TableName + '' 
			WHERE  GeoLevelCode IN (''''AREA'''',''''CRES'''')''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt =  ''
			SELECT * 
			INTO '' + @TableName + ''_00
			FROM '' + @TableName + ''
			WHERE  GeoLevelCode = ''''COUN''''''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Country level records count @RowCount = '', @RowCount
		SET @SQLStmt =  ''
			SELECT * 
			INTO '' + @TableName + ''_Sub
			FROM '' + @TableName + ''_1''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Subarea level records count @RowCount = '', @RowCount
		SET @SQLStmt =  ''
			INSERT INTO '' + @TableName + ''_Sub
			SELECT 
				t1.YearID,
				b.AreaScheme AS IntAreaScheme,
				t1.PerilSetCode,
				t1.LOBCode,
				t1.Premium,
				t1.Payroll,
				t1.RiskCount,
				t1.TotalInsuredValue,
				CAST(NULL AS FLOAT) AS UserSpecifiedMarketShare,
				t1.IsLossMarketShare,
				c.GeographySID,
				t1.CurrencyCode,
				t1.Rates,
				c.CountryCode,
				c.CountryName,
				c.CRESTACode,
				c.CRESTAName,
				c.AreaCode,
				c.AreaName,
				c.SubareaCode,
				COALESCE(c.GeographySID,NULL) AS ParentGeorgraphySID,
				b.GeoLevelCode
			FROM
			(
				SELECT  DISTINCT
					t.*
				FROM dbo.tAggregateExposure t
				JOIN '' + @TableName + ''_1 c
					ON	t.YearID = c.YearID 
					AND t.IntAreaScheme = c.IntAreaScheme	
					AND t.PerilSetCode = c.PerilSetCode	
					AND t.LOBCode = c.LOBCode	
					AND t.ExposureSetSID = @ExposureSetSID 
					AND t.CountryCode = c.CountryCode  
					AND (t.AreaCode = c.AreaCode 
						OR t.CRESTACode = c.CRESTACode) 
					AND t.GeoLevelCode = ''''SUBA''''
				LEFT JOIN  '' + @TableName + ''_1 ae
					ON  t.YearID = ae.YearID
					AND t.IntAreaScheme = ae.IntAreaScheme
					AND t.PerilSetCode = ae.PerilSetCode
					AND t.LOBCode = ae.LOBCode
					AND t.CountryCode = ae.CountryCode
					AND (t.AreaCode = ae.AreaCode
						OR t.CRESTACode = ae.CRESTACode)
					AND t.GeographySID = ae.GeographySID
				WHERE ae.YearID IS NULL
			) t1
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON t1.GeographySID = b.GeographySID
			JOIN AIRGeography.dbo.tReinsuranceGeography c
				ON b.ParentGeographySID = c.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @SQLStmt = ''  
			DELETE FROM dbo.tAggregateExposure
			WHERE AggregateExposureSID IN
				(
					SELECT DISTINCT a.AggregateExposureSID
					FROM dbo.tAggregateExposure a
					JOIN '' + @TableName + ''_Sub ad
						ON a.ExposureSetSID = @ExposureSetSID
						AND ad.YearID = a.YearID	
						AND ad.IntAreaScheme = a.IntAreaScheme	
						AND ad.PerilSetCode = a.PerilSetCode	
						AND ad.LOBCode = a.LOBCode	
						AND ad.GeographySID = a.GeographySID
					WHERE ISNULL(ad.TotalInsuredValue,0) + ISNULL(ad.RiskCount,0) + ISNULL(ad.Premium,0) + ISNULL(ad.Payroll,0)  
						+ ISNULL(ad.UserSpecifiedMarketShare,0) + ISNULL(ad.Rates,0) = 0
				)''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		--1100 rule
		SET @SQLStmt = ''
			DELETE FROM dbo.tAggregateExposure
			WHERE AggregateExposureSID IN
				(
					SELECT DISTINCT a.AggregateExposureSID
					FROM dbo.tAggregateExposure a
					JOIN '' + @TableName + ''_Sub ad
						ON a.ExposureSetSID = @ExposureSetSID
						AND ad.YearID = a.YearID	
						AND ad.IntAreaScheme = a.IntAreaScheme	
						AND ad.PerilSetCode = a.PerilSetCode	
						AND ad.ParentGeographySID = a.GeographySID
					LEFT JOIN '' + @TableName + ''_Sub ee
						ON a.ExposureSetSID = @ExposureSetSID
						AND ee.YearID = a.YearID	
						AND ee.IntAreaScheme = a.IntAreaScheme	
						AND ee.PerilSetCode = a.PerilSetCode	
						AND ee.LOBCode = a.LOBCode	
						AND ee.ParentGeographySID = a.GeographySID
					WHERE ee.YearID IS NULL
				)''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Area/Cresta level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			SELECT 
				t1.YearID,
				c.AreaScheme AS  IntAreaScheme,
				t1.PerilSetCode,
				t1.LOBCode,
				t1.Premium,
				t1.Payroll,
				t1.RiskCount,
				t1.TotalInsuredValue,
				CAST(0.0 AS FLOAT)  AS UserSpecifiedMarketShare,
				t1.IsLossMarketShare,
				c.GeographySID,
				t1.CurrencyCode,
				CAST(0.0 AS FLOAT)   AS Rates,
				c.CountryCode,
				c.CountryName,
				c.CRESTACode,
				c.CRESTAName,
				c.AreaCode,
				c.AreaName,
				c.SubareaCode,
				COALESCE(c.GeographySID,NULL) AS ParentGeorgraphySID,
				c.GeoLevelCode
			INTO '' + @TableName + ''_AreaCRESTA
			FROM (
				SELECT 
					YearID,
					PerilSetCode,
					LOBCode,
					SUM(a.Premium) AS Premium,
					SUM(a.Payroll) AS Payroll,
					SUM(a.RiskCount) AS RiskCount,
					SUM(a.TotalInsuredValue) AS TotalInsuredValue,
					0 AS IsLossMarketShare,
					 ParentGeographySID,
					MAX(a.CurrencyCode) AS CurrencyCode
				FROM '' + @TableName + ''_Sub a
				GROUP BY YearID,
					PerilSetCode,
					LOBCode,
					 ParentGeographySID
				) t1
			JOIN AIRGeography.dbo.tReinsuranceGeography c
				ON t1.ParentGeographySID = c.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt = ''
			INSERT INTO '' + @TableName + ''_AreaCRESTA
			SELECT a.*
			FROM '' + @TableName + ''_0 AS a
			LEFT JOIN '' + @TableName + ''_AreaCRESTA ae
				ON a.YearID = ae.YearID	
				AND a.IntAreaScheme = ae.IntAreaScheme	
				AND a.PerilSetCode = ae.PerilSetCode	
				AND a.LOBCode = ae.LOBCode 
				AND a.GeographySID = ae.GeographySID
				AND ae.YearID IS NULL''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''_0 into area level records count @RowCount = '', @RowCount
		--Update area level data from exsiting data
		SET @SQLStmt = '' 
				UPDATE A SET A.UserSpecifiedMarketShare = ae.UserSpecifiedMarketShare, A.Rates = ae.Rates 
				FROM '' + @TableName + ''_AreaCRESTA a
				JOIN AIRExposureRe.dbo.tAggregateExposure  ae
				ON  ae.ExposureSetSID = @ExposureSetSID
				AND  a.YearID = ae.YearID	
				AND a.IntAreaScheme = ae.IntAreaScheme	
				AND a.PerilSetCode = ae.PerilSetCode	
				AND a.LOBCode = ae.LOBCode 
				AND a.GeographySID = ae.GeographySID
				AND a.GeoLevelCode IN (''''AREA'''',''''CRES'''')''
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		--Update area level data if its updated
		SET @SQLStmt =  ''
			UPDATE  A SET A.UserSpecifiedMarketShare = b.UserSpecifiedMarketShare, A.Rates = b.Rates  				
			FROM '' + @TableName + ''_AreaCRESTA a			
			JOIN '' + @TableName + ''_0 b
				ON  a.PerilSetCode 	= b.PerilSetCode
				AND a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.GeographySID = b.GeographySID
				AND a.LOBCode = b.LOBCode 
				AND a.GeoLevelCode IN (''''AREA'''',''''CRES'''')''				
		
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL 	@SQLStmt
		SET @SQLStmt = ''
			INSERT INTO  '' + @TableName + ''_1 
			SELECT * 
			FROM  '' + @TableName + ''_AreaCRESTA''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Area level records into _target @RowCount = '', @RowCount
		SET @SQLStmt = ''
			INSERT INTO '' + @TableName + ''_AreaCRESTA
			SELECT	 
				t1.YearID,
				b.AreaScheme AS IntAreaScheme,
				t1.PerilSetCode,
				t1.LOBCode,
				t1.Premium,
				t1.Payroll,
				t1.RiskCount,
				t1.TotalInsuredValue,
				CAST(0.0 AS FLOAT)  AS UserSpecifiedMarketShare,
				t1.IsLossMarketShare,
				c.GeographySID,
				t1.CurrencyCode,
				CAST(0.0 AS FLOAT)  AS Rates,
				c.CountryCode,
				c.CountryName,
				c.CRESTACode,
				c.CRESTAName,
				c.AreaCode,
				c.AreaName,
				c.SubareaCode,
				COALESCE(c.GeographySID,NULL) AS ParentGeorgraphySID,
				c.GeoLevelCode
			FROM (
				SELECT 
					a.YearID,
					a.IntAreaScheme,
					a.PerilSetCode,
					a.LOBCode,
					a.CountryCode,
					SUM(a.Premium) AS Premium,
					SUM(a.Payroll) AS Payroll,
					SUM(a.RiskCount) AS RiskCount,
					SUM(ISNULL(ae.TotalInsuredValue, a.TotalInsuredValue)) AS TotalInsuredValue,
					0 AS IsLossMarketShare,
					a.GeographySID AS GeographySID,
					MAX(a.CurrencyCode) AS CurrencyCode
				FROM (
					SELECT DISTINCT t.*
					FROM dbo.tAggregateExposure t
					JOIN '' + @TableName + ''_AreaCRESTA c
						ON	t.YearID = c.YearID	
						AND t.IntAreaScheme = c.IntAreaScheme
						AND t.PerilSetCode = c.PerilSetCode
						AND t.LOBCode = c.LOBCode
						AND t.ExposureSetSID = @ExposureSetSID
						AND t.CountryCode = c.CountryCode
						AND (
							t.GeoLevelCode = ''''AREA'''' 
							OR (
								t.GeoLevelCode = ''''CRES'''' 
								AND t.CountryCode != ''''EC''''
								)
							)
					) a
				LEFT JOIN '' + @TableName + ''_AreaCRESTA ae
					ON  a.YearID = ae.YearID
					AND a.IntAreaScheme = ae.IntAreaScheme
					AND a.PerilSetCode = ae.PerilSetCode
					AND a.LOBCode = ae.LOBCode
					AND a.CountryCode = ae.CountryCode
					AND a.GeographySID=ae.GeographySID
				WHERE ae.YearID IS NULL
				GROUP BY 
					a.YearID,
					a.IntAreaScheme,
					a.PerilSetCode,
					a.LOBCode,
					a.CountryCode,
					a.geographysid
			) t1
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON t1.GeographySID = b.GeographySID
			JOIN AIRGeography.dbo.tReinsuranceGeography c
				ON b.ParentGeographySID = c.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Aggregated to area level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			SELECT 
				t1.YearID,
				1006 AS IntAreaScheme,
				t1.PerilSetCode,
				t1.LOBCode,
				t1.Premium,
				t1.Payroll,
				t1.RiskCount,
				t1.TotalInsuredValue,
				CAST(0.0 AS FLOAT)  AS UserSpecifiedMarketShare,
				t1.IsLossMarketShare,
				CASE WHEN c.countrycode= ''''EC'''' THEN 63 ELSE c.GeographySID END AS GeographySID,
				t1.CurrencyCode,
				CAST(0.0 AS FLOAT)  AS Rates,
				c.CountryCode,
				c.CountryName,
				c.CRESTACode,
				c.CRESTAName,
				c.AreaCode,
				c.AreaName,
				c.SubareaCode,
				COALESCE(c.GeographySID,NULL) AS ParentGeorgraphySID,
				''''COUN'''' AS GeoLevelCode
			INTO '' + @TableName + ''_Country
			FROM (
				SELECT 
					YearID,
					PerilSetCode,
					LOBCode,
					SUM(a.Premium) AS Premium,
					SUM(a.Payroll) AS Payroll,
					SUM(a.RiskCount) AS RiskCount,
					SUM(a.TotalInsuredValue) AS TotalInsuredValue,
					0 AS IsLossMarketShare,
					MAX(a.GeographySID ) AS GeographySID,
					MAX(a.CurrencyCode) AS CurrencyCode
				FROM  '' + @TableName + ''_AreaCRESTA a
				GROUP BY 
					YearID,
					PerilSetCode,
					LOBCode
				) t1
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON t1.GeographySID = b.GeographySID
			JOIN AIRGeography.dbo.tReinsuranceGeography c
				ON b.ParentGeographySID = c.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''_AreaCRESTA into country level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			INSERT INTO '' + @TableName + ''_Country
			SELECT a.*
			FROM '' + @TableName + ''_00 AS a
			LEFT JOIN '' + @TableName + ''_Country ae
				ON a.YearID = ae.YearID
				AND a.IntAreaScheme = ae.IntAreaScheme
				AND a.PerilSetCode = ae.PerilSetCode
				AND a.LOBCode = ae.LOBCode
				AND a.GeographySID = ae.GeographySID
				AND ae.YearID IS NULL''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''_00 to country level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			INSERT INTO  '' + @TableName + ''_1 
			SELECT * 
			FROM  '' + @TableName + ''_Country''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt = ''
			DELETE
			FROM dbo.tAggregateExposure
			WHERE AggregateExposureSID IN 
				(
					SELECT DISTINCT a.AggregateExposureSID
					FROM dbo.tAggregateExposure a
					JOIN '' + @TableName + ''_1 ad
						ON a.ExposureSetSID = @ExposureSetSID
						AND ad.YearID = a.YearID
						AND ad.IntAreaScheme = a.IntAreaScheme
						AND ad.PerilSetCode = a.PerilSetCode
						AND ad.LOBCode = a.LOBCode
						AND ad.GeographySID = a.GeographySID
					WHERE ISNULL(ad.TotalInsuredValue,0) + ISNULL(ad.RiskCount,0) + ISNULL(ad.Premium,0) + ISNULL(ad.Payroll,0)
						 + ISNULL(ad.UserSpecifiedMarketShare,0) + ISNULL(ad.Rates,0) = 0
				)''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''deleted main table @RowCount = '', @RowCount
		SET @SQLStmt = ''
			UPDATE dbo.tAggregateExposure
				SET Premium = b.Premium,
					Payroll = b.Payroll,
					RiskCount = b.RiskCount,
					TotalInsuredValue = b.TotalInsuredValue,
					UserSpecifiedMarketShare = b.UserSpecifiedMarketShare,
					Rates = b.Rates,
					IsLossMarketShare = 0,
					CurrencyCode = b.CurrencyCode
			FROM dbo.tAggregateExposure a
			JOIN '' + @TableName + ''_1 b
				ON a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.PerilSetCode = b.PerilSetCode
				AND a.LOBCode = b.LOBCode
				AND a.ExposureSetSID = @ExposureSetSID
				AND a.GeographySID = b.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''update main table @RowCount = '', @RowCount
/*
-- is this needed or it this a debug info???
		SET @SQLStmt = ''
			SELECT b.*
			FROM '' + @TableName + ''_1 b
			LEFT JOIN AIRExposureRe.dbo.tAggregateExposure a
				ON a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.PerilSetCode = b.PerilSetCode
				AND a.LOBCode = b.LOBCode
				AND a.ExposureSetSID = @ExposureSetSID
				AND a.GeographySID = b.GeographySID
				AND a.YearID IS NULL''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Final Insert @RowCoun''
--*/
-- converted previous statement to count from select *
		SET @SQLStmt = ''
			SELECT @RowCount = COUNT(1)
			FROM '' + @TableName + ''_1 b
			LEFT JOIN dbo.tAggregateExposure a
				ON a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.PerilSetCode = b.PerilSetCode
				AND a.LOBCode = b.LOBCode
				AND a.ExposureSetSID = @ExposureSetSID
				AND a.GeographySID = b.GeographySID
				AND a.YearID IS NULL''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER, @RowCount INTEGER OUTPUT''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID,
			@RowCount OUTPUT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Final Insert @RowCount = '', @RowCount
		--Then get next SID value to be used for insert command
		EXEC dbo.pGetSIDRange 
			@TableName = ''tAggregateExposure'', 
			@Amount = @RowCount,  
			@NextSID = @NextSID OUTPUT
		SET @SQLStmt = ''
			INSERT INTO dbo.tAggregateExposure
				(
					AggregateExposureSID,
					ExposureSetSID,
					PerilSetCode,
					YearID,
					LOBCode,
					CountryCode,
					AreaCode,
					SubareaCode,
					CRESTACode,
					GeographySID,
					CurrencyCode,
					IntAreaScheme,
					TotalInsuredValue,
					RiskCount,
					Premium,
					Payroll,
					UserSpecifiedMarketShare,
					Rates,
					CountryName,
					AreaName,
					SubareaName,
					CRESTAName,
					GeoLevelCode,
					IsLossMarketShare
				)
			SELECT @NextSID - 1 + ROW_NUMBER() OVER ( ORDER BY ( SELECT 0 ) ) AS AggregateExposureSID,
				@ExposureSetSID AS ExposureSetSID,
				ad.PerilSetCode,
				ad.YearID,
				ad.LOBCode,
				ad.CountryCode,
				ad.AreaCode,
				ad.SubareaCode,
				ad.CRESTACode,
				ad.GeographySID,
				ad.CurrencyCode,
				ad.IntAreaScheme,
				ad.TotalInsuredValue,
				ad.RiskCount,
				ad.Premium,
				ad.Payroll,
				ad.UserSpecifiedMarketShare,
				ad.Rates,
				b.CountryName,
				b.AreaName,
				b.SubareaName,
				b.CRESTAName,
				b.GeoLevelCode,
				0 AS IsLossMarketShare
			FROM '' + @TableName + ''_1 ad
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON ad.GeographySID = b.GeographySID
			LEFT JOIN dbo.tAggregateExposure ae
				ON 	@ExposureSetSID = ae.ExposureSetSID
				AND ad.YearID = ae.YearID
				AND ad.IntAreaScheme = ae.IntAreaScheme
				AND ad.PerilSetCode = ae.PerilSetCode
				AND ad.LOBCode = ae.LOBCode
				AND ad.GeographySID = ae.GeographySID
			WHERE 
				ae.YearID IS NULL 
				AND ISNULL(ad.TotalInsuredValue,0) + ISNULL(ad.RiskCount,0) + ISNULL(ad.Premium,0) + ISNULL(ad.Payroll,0)
					 + ISNULL(ad.UserSpecifiedMarketShare,0) + ISNULL(ad.Rates,0) > 0''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@NextSID = '', @NextSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER, @NextSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID, 
			@NextSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''update main table @RowCount = '', @RowCount
		SET @SQLStmt = ''
			DROP TABLE '' + @TableName + ''_1
			DROP TABLE '' + @TableName + ''_Sub
			DROP TABLE '' + @TableName + ''_AreaCRESTA
			DROP TABLE '' + @TableName + ''_Country
			DROP TABLE '' + @TableName + ''_0
			DROP TABLE '' + @TableName + ''_00''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
		RETURN @Result
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
END		-- Proc
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pULF_ReGetIEDTakeUpRates]'
GO
IF OBJECT_ID(N'[dbo].[pULF_ReGetIEDTakeUpRates]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT:				dbo.pULF_ReGetIEDTakeUpRates
DESCRIPTION:		Returns TakeUpRates on Country, Area ans Subarea levels filtered according to input parameters
ExposedToEntities:	Yes
ResultView:			rvULF_ReGetIEDTakeUpRates
Usage:				EXEC pULF_ReGetIEDTakeUpRates 28,234,2020,0						
**********************************************************************************************************/
ALTER
--ALTER
 PROCEDURE [dbo].[pULF_ReGetIEDTakeUpRates]
	 @ModelCode INT
	,@AppliesToAreaSID INT  =0         
	,@Year INT = 2020	
    ,@Debug BIT = 0
WITH ENCRYPTION
AS
BEGIN
SET NOCOUNT ON
	DECLARE @SQL NVARCHAR(max) = ''''
	DECLARE @Result INT = 0
	DECLARE @SPName NVARCHAR(392)=DB_NAME()+''.''+SCHEMA_NAME()+''.''+OBJECT_NAME(@@PROCID)   
	DECLARE @tablename VARCHAR(40)   
	DECLARE @PerilSetCode INT
	DECLARE @ParentGeoSid INT   
	DECLARE @AggregateExposureTypeCode INT
	
	SET @AggregateExposureTypeCode = 1	
	
    BEGIN TRY
	SET @tablename= ''[AIRIndustry].dbo.TblIndustry''+CAST(@Year AS VARCHAR(10))
	IF OBJECT_ID(''tempdb.dbo.tReinsuranceExposureToIndustryLOBMap'') IS NOT NULL
		DROP TABLE #tReinsuranceExposureToIndustryLOBMap;
	
		CREATE TABLE #tReinsuranceExposureToIndustryLOBMap (		
		[CountryID] [int] NOT NULL,
		[PerilID] [int] NOT NULL,
		[ExposureTypeID] [int] NOT NULL,
		[LOBCode] [int] NOT NULL,
		[ILFLOBIndex] [int] NOT NULL,
		[TURLOBIndex] [int] NOT NULL,
		[LOBSpecID] [int] NOT NULL,
		[Version] [int] NOT NULL
		)
		
		INSERT INTO #tReinsuranceExposureToIndustryLOBMap
		SELECT 
		DISTINCT
		IMIndex.CountryID,
		IMIndex.PerilID,
		IMIndex.ExposureTypeID,
		IMIndex.LOBCode,
		IMIndex.ILFLOBIndex,
		IMIndex.TURLOBIndex,
		IMIndex.LOBSpecID,
		IMIndex.Version
		FROM AIRReference..[tReinsuranceTakeUpRatesLOBMapping] IMIndex
		INNER JOIN AIRReference..tReinsuranceTakeUpRatesMapping TR ON TR.IEDPeril = IMIndex.PerilID AND TR.exposureType	=IMIndex.ExposureTypeID AND IMIndex.CountryID = TR.CountryID
				INNER JOIN [AIRReference].[dbo].[TblModelInfo] MI ON  MI.intCountry = TR.CountryID and  MI.intModel = TR.ModelCode		
		WHERE  TR.ModelCode = @ModelCode
		
	SELECT 
	   @PerilSetCode = MAX([PerilSetCode]) 
	FROM [AIRUserSetting].[dbo].[tReinsuranceCatalog]  WHERE [ModelCode] =@ModelCode		
	DECLARE @PerilSetCodeBitwise INT
	DECLARE @ErrMsg VARCHAR(512)
	DECLARE @IsSecure BIT = 0
    IF @Debug=1 EXEC dbo.pCOMMON_PrintVariable '': START OF '',@SPName
	
	IF (@PerilSetCode &0x43 >0)
			SET @PerilSetCodeBitwise=3
		ELSE IF (@PerilSetCode &0x208 >0)
		   SET @PerilSetCodeBitwise=12
		ELSE IF (@PerilSetCode &0x810 >0)
		   SET @PerilSetCodeBitwise=2064
		ELSE IF @PerilSetCode in (4,32,1024,16384,32768) 
           SET @PerilSetCodeBitwise=@PerilSetCode
        ELSE
              BEGIN
                  SET @ErrMsg=concat(''Invalid @PerilSetCode= '' , @PerilSetCode)
                     RAISERROR(@ErrMsg, 16,1)
              END
		IF OBJECT_ID(''tempdb.dbo.#AppliesTo'') IS NOT NULL
		DROP TABLE #AppliesTo;
		CREATE TABLE #AppliesTo (IntLevelID INT, IntLevel1 INT , IntLevel2 INT, IntLevel3 INT)
		CREATE CLUSTERED INDEX [IX_tempdb_AppliesTo] ON #AppliesTo
		(
			[intLevel1] ASC,
			[intLevel2] ASC,
			[intLevel3] ASC
		)
		IF @AppliesToAreaSID = 0
		BEGIN
			INSERT INTO #AppliesTo
			SELECT LM.IntLevelID, LM.IntLevel1, LM.IntLevel2, LM.IntLevel3 FROM  AirGeography..tReinsuranceInternalCodeMapping LM
			INNER JOIN [AIRReference].[dbo].[TblModelInfo] MI ON  MI.intCountry = LM.IntLevel1 and  MI.intModel = @ModelCode
	   END
	   ELSE
	   BEGIN
			
			;WITH t1
			  AS (
			SELECT LM.IntLevelID, LM.IntLevel1, LM.IntLevel2, LM.IntLevel3,L1.GeographySID FROM [tAppliesToAreaGeoXRef]  AppliesTo 
			INNER JOIN  AirGeography..tReinsuranceGeography L1 ON L1.GeographySID  = AppliesTo.GeographySID
			INNER JOIN   AirGeography..tReinsuranceInternalCodeMapping LM ON LM.GeographySID  = L1.GeographySID
			INNER JOIN [AIRReference].[dbo].[TblModelInfo] MI ON  MI.intCountry = LM.IntLevel1 and  MI.intModel = @ModelCode
			WHERE AppliesTo.appliestoareasid = @AppliesToAreaSID
			)		
	  
			INSERT INTO #AppliesTo
			SELECT LM.IntLevelID, LM.IntLevel1, LM.IntLevel2, LM.IntLevel3 FROM T1
			INNER JOIN   AirGeography..tReinsuranceInternalCodeMapping LM ON  LM.IntLevel1 = T1.IntLevel1 		
			WHERE T1.IntLevelID = 1 
			UNION
			SELECT LM.IntLevelID, LM.IntLevel1, LM.IntLevel2, LM.IntLevel3 FROM T1
			INNER JOIN   AirGeography..tReinsuranceInternalCodeMapping LM ON  LM.IntLevel1 = T1.IntLevel1  AND LM.IntLevel2 =  T1.IntLevel2		
			WHERE T1.IntLevelID = 2
			UNION
			SELECT LM.IntLevelID, LM.IntLevel1, LM.IntLevel2, LM.IntLevel3 FROM T1
			INNER JOIN   AirGeography..tReinsuranceInternalCodeMapping LM ON  LM.IntLevel1 = T1.IntLevel1  AND LM.IntLevel2 =  T1.IntLevel2 AND LM.IntLevel3 =  T1.IntLevel3		
			WHERE T1.IntLevelID = 3
	END
	
		DECLARE @variable float=2
					;WITH CTE_IndustryExposure
            AS (
             SELECT  	
				IntPeril,
				@PerilSetCode as PerilSetCode,
				IntType,
				IntYear,
				IntAreaLevel1,
				IntAreaLevel2,
				IntAreaLevel3,
				IntAreaLevel4,
				IntAreaScheme,
				StrCurrency,
				IntUnits,
				IntLOB,	
				SIGN(lb.dbllob1)
       * (1.0 + (lb.dbllob1 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob1 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB1,
       SIGN(lb.dbllob2)
       * (1.0 + (lb.dbllob2 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob2 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB2,
       SIGN(lb.dbllob3)
       * (1.0 + (lb.dbllob3 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob3 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB3,
       SIGN(lb.dbllob4)
       * (1.0 + (lb.dbllob4 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob4 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB4,
       SIGN(lb.dbllob5)
       * (1.0 + (lb.dbllob5 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob5 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB5,
       SIGN(lb.dbllob6)
       * (1.0 + (lb.dbllob6 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob6 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB6,
       SIGN(lb.dbllob7)
       * (1.0 + (lb.dbllob7 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob7 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB7,
       SIGN(lb.dbllob8)
       * (1.0 + (lb.dbllob8 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob8 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB8,
       SIGN(lb.dbllob9)
       * (1.0 + (lb.dbllob9 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob9 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB9,
       SIGN(lb.dbllob10)
       * (1.0 + (lb.dbllob10 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob10 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB10,
       SIGN(lb.dbllob11)
       * (1.0 + (lb.dbllob11 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob11 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB11,
       SIGN(lb.dbllob12)
       * (1.0 + (lb.dbllob12 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob12 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB12,
       SIGN(lb.dbllob13)
       * (1.0 + (lb.dbllob13 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob13 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB13,
       SIGN(lb.dbllob14)
       * (1.0 + (lb.dbllob14 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob14 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB14,
       SIGN(lb.dbllob15)
       * (1.0 + (lb.dbllob15 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob15 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB15,
       SIGN(lb.dbllob16)
       * (1.0 + (lb.dbllob16 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob16 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB16,
       SIGN(lb.dbllob17)
       * (1.0 + (lb.dbllob17 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob17 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB17,
       SIGN(lb.dbllob18)
       * (1.0 + (lb.dbllob18 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob18 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB18,
       SIGN(lb.dbllob19)
       * (1.0 + (lb.dbllob19 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob19 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB19,
       SIGN(lb.dbllob20)
       * (1.0 + (lb.dbllob20 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dbllob20 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB20,
	   SIGN(lb.dblTakeupRates1)
       * (1.0 + (lb.dblTakeupRates1 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates1 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblLOB21,
       SIGN(lb.dblTakeupRates2)
       * (1.0 + (lb.dblTakeupRates2 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates2 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates2,
       SIGN(lb.dblTakeupRates3)
       * (1.0 + (lb.dblTakeupRates3 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates3 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates3,
       SIGN(lb.dblTakeupRates4)
       * (1.0 + (lb.dblTakeupRates4 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates4 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates4,
       SIGN(lb.dblTakeupRates5)
       * (1.0 + (lb.dblTakeupRates5 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates5 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates5,
       SIGN(lb.dblTakeupRates6)
       * (1.0 + (lb.dblTakeupRates6 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates6 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates6,
       SIGN(lb.dblTakeupRates7)
       * (1.0 + (lb.dblTakeupRates7 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates7 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates7,
       SIGN(lb.dblTakeupRates8)
       * (1.0 + (lb.dblTakeupRates8 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates8 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates8,
       SIGN(lb.dblTakeupRates9)
       * (1.0 + (lb.dblTakeupRates9 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates9 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates9,
       SIGN(lb.dblTakeupRates10)
       * (1.0 + (lb.dblTakeupRates10 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates10 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates10,
       SIGN(lb.dblTakeupRates11)
       * (1.0 + (lb.dblTakeupRates11 & 0x000FFFFFFFFFFFFF) * POWER(@variable, -52))
       * POWER(@variable, (lb.dblTakeupRates11 & 0x7ff0000000000000) / 0x0010000000000000 - 1023) AS dblTakeupRates11
	   ,0 AS dblTakeupRates12,
		0 AS dblTakeupRates13,
		0 AS dblTakeupRates14,
		0 AS dblTakeupRates15,
		0 AS dblTakeupRates16,
		0 AS dblTakeupRates17,
		0 AS dblTakeupRates18,
		0 AS dblTakeupRates19,
		0 AS dblTakeupRates20 FROM (
               --Get industry data 
               SELECT
		-- SQL Prompt formatting off
		
				--CAST(NEWID() AS BINARY(16)) AS GuidExposure,
				IntPeril,
				IntType,
				IntYear,
				IntAreaLevel1,
				IntAreaLevel2,
				IntAreaLevel3,
				IntAreaLevel4,
				IntAreaScheme,
				StrCurrency,
				IntUnits,
				IntLOB,		
		-- SQL Prompt formatting off
		CAST(CAST(REVERSE(SUBSTRING(binData,9,8)) as BINARY(8))  AS BIGINT) AS dblLob1,
		CAST(CAST(REVERSE(SUBSTRING(binData,17,8)) as BINARY(8)) AS BIGINT) AS dblLob2,
	    CAST(CAST(REVERSE(SUBSTRING(binData,25,8)) as BINARY(8)) AS BIGINT) AS dblLob3,
		CAST(CAST(REVERSE(SUBSTRING(binData,33,8)) as BINARY(8)) AS BIGINT) AS dblLob4,
		CAST(CAST(REVERSE(SUBSTRING(binData,41,8)) as BINARY(8)) AS BIGINT) AS dblLob5,	
		CAST(CAST(REVERSE(SUBSTRING(binData,49,8)) as BINARY(8)) AS BIGINT) AS dblLob6,
		CAST(CAST(REVERSE(SUBSTRING(binData,57,8)) as BINARY(8)) AS BIGINT) AS dblLob7,
		CAST(CAST(REVERSE(SUBSTRING(binData,65,8)) as BINARY(8)) AS BIGINT) AS dblLob8,
		CAST(CAST(REVERSE(SUBSTRING(binData,73,8)) as BINARY(8)) AS BIGINT) AS dblLob9,
		CAST(CAST(REVERSE(SUBSTRING(binData,81,8)) as BINARY(8)) AS BIGINT) AS dblLob10,			
		CAST(CAST(REVERSE(SUBSTRING(binData,89,8)) as BINARY(8)) AS BIGINT) AS dblLob11,
		CAST(CAST(REVERSE(SUBSTRING(binData,97,8)) as BINARY(8)) AS BIGINT) AS dblLob12,
		CAST(CAST(REVERSE(SUBSTRING(binData,105,8)) as BINARY(8)) AS BIGINT)  AS dblLob13,
	    CAST(CAST(REVERSE(SUBSTRING(binData,113,8)) as BINARY(8)) AS BIGINT)  AS dblLob14,
		CAST(CAST(REVERSE(SUBSTRING(binData,121,8)) as BINARY(8)) AS BIGINT)  AS dblLob15,
		CAST(CAST(REVERSE(SUBSTRING(binData,129,8)) as BINARY(8)) AS BIGINT)  AS dblLob16,	
		CAST(CAST(REVERSE(SUBSTRING(binData,137,8)) as BINARY(8)) AS BIGINT)  AS dblLob17,
		CAST(CAST(REVERSE(SUBSTRING(binData,145,8)) as BINARY(8)) AS BIGINT)  AS dblLob18,
		CAST(CAST(REVERSE(SUBSTRING(binData,153,8)) as BINARY(8)) AS BIGINT)  AS dblLob19,
		CAST(CAST(REVERSE(SUBSTRING(binData,161,8)) as BINARY(8)) AS BIGINT)  AS dblLob20,
		CAST(CAST(REVERSE(SUBSTRING(binData,169,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates1	,
		CAST(CAST(REVERSE(SUBSTRING(binData,177,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates2	,
		CAST(CAST(REVERSE(SUBSTRING(binData,185,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates3	,
		CAST(CAST(REVERSE(SUBSTRING(binData,193,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates4	,
		CAST(CAST(REVERSE(SUBSTRING(binData,201,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates5	,
		CAST(CAST(REVERSE(SUBSTRING(binData,209,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates6	,
		CAST(CAST(REVERSE(SUBSTRING(binData,217,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates7	,
		CAST(CAST(REVERSE(SUBSTRING(binData,225,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates8	,
		CAST(CAST(REVERSE(SUBSTRING(binData,233,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates9	,
		CAST(CAST(REVERSE(SUBSTRING(binData,241,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates10	,
		CAST(CAST(REVERSE(SUBSTRING(binData,249,8)) as BINARY(8)) AS BIGINT)  AS dblTakeupRates11	
							-- SQL Prompt formatting on
        FROM      [AIRIndustry].dbo.TblIndustry2020 ev
		 JOIN [AIRReference].[dbo].[TblModelInfo] MI ON  MI.intCountry = IntAreaLevel1 and  MI.intModel = @ModelCode
		 --JOIN #AppliesTo A ON A.IntLevel1 = ev.IntAreaLevel1 AND A.IntLevel2 = ev.IntAreaLevel2 AND A.IntLevel3 = ev.IntAreaLevel3
		 JOIN AIRReference.dbo.tReinsuranceTakeUpRatesMapping TR ON TR.ModelCode =  MI.intModel AND TR.IEDPeril = ev.IntPeril and ev.inttype = TR.exposureType		
		 
		 ) lb)		
																										
					
					
								SELECT 
								@ModelCode as ModelCode
								--,t1.IntPeril
								,IEDRates.ILFPeril AS IntPeril
								--,t1.IntType
								--,t1.IntYear
								,t1.intArealevel1
								,t1.intArealevel2
								,t1.intArealevel3								
								,rxim.[LOBCode] AS LOBCode
								,rxim.[ILFLOBIndex] -1 AS LOBIndex								
								,SUM(t1.AMt) AS dblTakeUpRate
								,LOBC.[LobCatagoryDesc]
								,LOBC.[LobCatagoryCode]
								FROM
								(
										SELECT DISTINCT
										IntPeril
										,IntType
										,IntYear
										,IntLOB
										,intArealevel1
										,intArealevel2
										,intArealevel3
										,LobN
										,Amt
										FROM 
										(
											SELECT
												   IE.IntPeril
												  ,IE.IntType
												  ,IE.IntYear
												  ,IE.IntLOB
												  ,IE.intArealevel1
												  ,IE.intArealevel2
												  ,IE.intArealevel3
												  ,IE.DblLOB1
												  ,IE.DblLOB2
												  ,CASE WHEN TOT.DblLOB3 = 0 THEN 1 ELSE IE.DblLOB3 END DblLOB3
												  ,CASE WHEN TOT.DblLOB4 = 0 THEN 1 ELSE  IE.DblLOB4 END DblLOB4
												  ,CASE WHEN TOT.DblLOB5 = 0 THEN 1 ELSE  IE.DblLOB5 END DblLOB5
												  ,CASE WHEN TOT.DblLOB6 = 0 THEN 1 ELSE  IE.DblLOB6 END DblLOB6
												  ,CASE WHEN TOT.DblLOB7 = 0 THEN 1 ELSE  IE.DblLOB7 END DblLOB7
												  ,CASE WHEN TOT.DblLOB8 = 0 THEN 1 ELSE  IE.DblLOB8  END DblLOB8
												  ,CASE WHEN TOT.DblLOB9 = 0 THEN 1 ELSE  IE.DblLOB9  END DblLOB9
												  ,CASE WHEN TOT.DblLOB10 = 0 THEN 1 ELSE  IE.DblLOB10  END DblLOB10
												  ,CASE WHEN TOT.DblLOB11 = 0 THEN 1 ELSE  IE.DblLOB11  END DblLOB11
												  ,CASE WHEN TOT.DblLOB12 = 0 THEN 1 ELSE  IE.DblLOB12  END DblLOB12
												  ,CASE WHEN TOT.DblLOB13 = 0 THEN 1 ELSE  IE.DblLOB13  END DblLOB13
												  ,CASE WHEN TOT.DblLOB14 = 0 THEN 1 ELSE  IE.DblLOB14  END DblLOB14
												  ,CASE WHEN TOT.DblLOB15 = 0 THEN 1 ELSE  IE.DblLOB15  END DblLOB15
												  ,CASE WHEN TOT.DblLOB16 = 0 THEN 1 ELSE  IE.DblLOB16  END DblLOB16
												  ,CASE WHEN TOT.DblLOB17 = 0 THEN 1 ELSE  IE.DblLOB17  END DblLOB17
												  ,CASE WHEN TOT.DblLOB18 = 0 THEN 1 ELSE  IE.DblLOB18  END DblLOB18
												  ,CASE WHEN TOT.DblLOB19 = 0 THEN 1 ELSE  IE.DblLOB19  END DblLOB19
												  ,CASE WHEN TOT.DblLOB20 = 0 THEN 1 ELSE  IE.DblLOB20  END DblLOB20
												  ,CASE WHEN TOT.DblLOB21 = 0 THEN 1 ELSE  IE.DblLOB21  END DblLOB21												 
											 FROM [CTE_IndustryExposure] IE
											INNER JOIN
											(
											SELECT 						
													 intArealevel1
													 ,IntPeril			
													,SUM(DblLOB3) AS DblLOB3
													,SUM(DblLOB4) AS DblLOB4
													,SUM(DblLOB5) AS DblLOB5
													,SUM(DblLOB6) AS DblLOB6
													,SUM(DblLOB7) AS DblLOB7
													,SUM(DblLOB8) AS DblLOB8
													,SUM(DblLOB9) AS DblLOB9
													,SUM(DblLOB10) AS DblLOB10
													,SUM(DblLOB11) AS DblLOB11
													,SUM(DblLOB12) AS DblLOB12
													,SUM(DblLOB13) AS DblLOB13
													,SUM(DblLOB14) AS DblLOB14
													,SUM(DblLOB15) AS DblLOB15
													,SUM(DblLOB16) AS DblLOB16
													,SUM(DblLOB17) AS DblLOB17
													,SUM(DblLOB18) AS DblLOB18
													,SUM(DblLOB19) AS DblLOB19
													,SUM(DblLOB20) AS DblLOB20
													,SUM(DblLOB21) AS DblLOB21
												FROM  [CTE_IndustryExposure] 
												GROUP BY 	 		
													intArealevel1,IntPeril) TOT ON  TOT.intArealevel1  = IE.intArealevel1 and TOT.IntPeril = IE.IntPeril
										) p
										unPIVOT
										(  Amt FOR LobN IN
											(
												   DblLOB1
												  ,DblLOB2
												  ,DblLOB3
												  ,DblLOB4
												  ,DblLOB5
												  ,DblLOB6
												  ,DblLOB7
												  ,DblLOB8
												  ,DblLOB9
												  ,DblLOB10
												  ,DblLOB11
												  ,DblLOB12
												  ,DblLOB13
												  ,DblLOB14
												  ,DblLOB15
												  ,DblLOB16
												  ,DblLOB17
												  ,DblLOB18
												  ,DblLOB19
												  ,DblLOB20
												  ,DblLOB21
											)
										) unpvt
										WHERE Amt >= 0
									) t1
									JOIN  AIRReference.dbo.tReinsuranceTakeUpRatesMapping IEDRates 
									ON IEDRates.IEDPeril =  t1.IntPeril 
									AND IEDRates.ModelCode = @Modelcode
									AND t1.IntType = IEDRates.ExposureType
									AND t1.IntAreaLevel1= IEDRates.CountryID
									JOIN  #tReinsuranceExposureToIndustryLOBMap rxim
									ON rxim.CountryId  = IEDRates.CountryID 
									AND t1.IntPeril = rxim.PerilID 
									AND t1.IntType=rxim.ExposureTypeID AND 		rxim.ExposureTypeID = IEDRates.ExposureType							
									AND t1.LObN =concat(''DblLOB'', rxim.[TURLOBIndex] + IEDRates.TakeUpRateIndex -2)
									AND rxim.version=
									(	 SELECT MAX(version) 
										 FROM #tReinsuranceExposureToIndustryLOBMap
										 WHERE CountryId=rxim.CountryId
										 AND PerilID=rxim.PerilID
										 AND ExposureTypeID=rxim.ExposureTypeID
										 AND [LOBCode]=rxim.[LOBCode]
									 )
									 JOIN AIRReference.dbo.[tReinsuranceLOB] LOB ON LOB.LOBCode  = rxim.[LOBCode]
									 JOIN [AIRReference].[dbo].[TReinsurenceLobCategoryCode] LOBC ON LOB.[LobCatagoryCode] = LOBC.[LobCatagoryCode]		
									 JOIN #AppliesTo A ON   A.IntLevel1 = T1.IntAreaLevel1 AND A.IntLevel2 = T1.IntAreaLevel2 AND A.IntLevel3 = T1.IntAreaLevel3							 
									 GROUP BY	 --t1.IntPeril,
									 IEDRates.ILFPeril 												
												,t1.intArealevel1
												,t1.intArealevel2
												,t1.intArealevel3
												,rxim.[LOBCode] 
												,rxim.[ILFLOBIndex]
												,LOBC.[LobCatagoryDesc]
												,LOBC.[LobCatagoryCode]
		
		
    END TRY
    BEGIN CATCH
        EXECUTE @Result=dbo.pReThrowError @SPName, @Debug
    END CATCH;
    IF @Debug=1 EXEC dbo.pCOMMON_PrintVariable '': END OF '',@SPName
    RETURN @Result
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLOSS_ReGetExpAdjFactorByExposureType_NGM]'
GO
IF OBJECT_ID(N'[dbo].[pLOSS_ReGetExpAdjFactorByExposureType_NGM]', 'P') IS NOT NULL
EXEC sp_executesql N'  /**********************************************************************************************************
OBJECT:				dbo.pLOSS_ReGetExpAdjFactorByExposureType_NGM
DESCRIPTION:		Returns GeographySID, AREA and Subarea information on the basis of ExposureType code
ExposedToEntities:	No
ResultView:			N/A
Usage:				DECLARE	@return_value int
EXEC @return_value = [dbo].[pLOSS_ReGetExpAdjFactorByExposureType_NGM]
    @ExposureSetSID = 1,
    @YearID = 2017,
    @PerilSetCodeList = ''3,4'',
	@AggregateExposureTypeCode = 21, -- 1:AdjustmentFactorPremium,2:AdjustmentFactorTotalInsuredValue,3:AdjustmentFactorRiskCount,4:Rates,5:UserSpecifiedMarketShare,17:AdjustmentFactorPayroll; Custom = 21
    @Debug = 1
**********************************************************************************************************/
ALTER
--ALTER 
PROCEDURE [dbo].[pLOSS_ReGetExpAdjFactorByExposureType_NGM]
    @ExposureSetSID INT,
    @YearID INT,
    @PerilSetCodeList VARCHAR(200),
    @AggregateExposureTypeCode INT,
    @Debug BIT = 0
AS
    BEGIN
        SET NOCOUNT ON
        DECLARE @Result INT = 0
        DECLARE @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
        DECLARE @Stmt VARCHAR(MAX)
        BEGIN TRY
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': START OF '',
                    @SPName
            --if no exposure exists exit 
            IF EXISTS (
                          SELECT
                                1
                          FROM  dbo.tExposureSet
                          WHERE ExposureSetSID = @ExposureSetSID
                                AND StatusCode != ''A''
                      )
                RETURN 0;
            --get list of perils 
            CREATE TABLE #PerilSetCodeList
                (
                    PerilSetCode INT
                )
            INSERT INTO #PerilSetCodeList
                        SELECT DISTINCT CASE WHEN Value IN ( 3, 67 ) THEN 67
                                             ELSE Value
                                        END AS PerilSetCode
                        FROM   AIRProject.dbo.fCOMMON_ConvertListToTable_NGM(@PerilSetCodeList, '','')
            IF @Debug = 1
                SELECT
                     ''pGetAggregateExposureByCountryPerilSetCodePerf: #PerilSetCodeList'',
                     *
                FROM #PerilSetCodeList
            --Check for CustomAdjustment Factor
            IF @AggregateExposureTypeCode <> 21
                BEGIN
                    SELECT
                               tr.ReinsuranceExposureAdjustmentFactorSID,
                               tr.ExposureSetSID,
                               tr.PerilSetCode,
                               tr.YearID,
                               tr.LOBCode,
                               ta.OldAreaLevel1,
                               tr.AdjustmentFactorTotalInsuredValue,
                               tr.AdjustmentFactorRiskCount,
                               tr.AdjustmentFactorPremium,
                               tr.AdjustmentFactorPayroll
                    FROM       AIRExposureRe..tReinsuranceExposureAdjustmentFactor tr WITH (NOLOCK)
                    INNER JOIN AIRReference..tConvertCL2Country ta
                        ON tr.CountryCode = ta.CountryCode
                    INNER JOIN #PerilSetCodeList pc
                        ON CASE tr.PerilSetCode
                                WHEN 3 THEN 67
                                ELSE tr.PerilSetCode
                           END = pc.PerilSetCode
                    WHERE      tr.ExposureSetSID = @ExposureSetSID
                               AND tr.YearID = @YearID
                               AND tr.LOBCode NOT
                               BETWEEN 148 AND 167
                               AND (
                                       (
                                           @AggregateExposureTypeCode = 1
                                           AND tr.AdjustmentFactorPremium <> 0
                                           AND tr.AdjustmentFactorPremium IS NOT NULL
                                       )
                                       OR (
                                              @AggregateExposureTypeCode = 2
                                              AND tr.AdjustmentFactorTotalInsuredValue <> 0
                                              AND tr.AdjustmentFactorTotalInsuredValue IS NOT NULL
                                          )
                                       OR (
                                              @AggregateExposureTypeCode = 3
                                              AND tr.AdjustmentFactorRiskCount <> 0
                                              AND tr.AdjustmentFactorRiskCount IS NOT NULL
                                          )
                                       OR (
                                              @AggregateExposureTypeCode = 17
                                              AND tr.AdjustmentFactorPayroll <> 0
                                              AND tr.AdjustmentFactorPayroll IS NOT NULL
                                          )
                                   )
                END
            ELSE
                BEGIN
                    SELECT
                               tr.ReinsuranceExposureAdjustmentFactorSID,
                               tr.ExposureSetSID,
                               tr.PerilSetCode,
                               tr.YearID,
                               tr.LOBCode,
                               ta.OldAreaLevel1 AS CountryID,
                               tr.AdjustmentFactorTotalInsuredValue,
                               tr.AdjustmentFactorRiskCount,
                               tr.AdjustmentFactorPremium,
                               tr.AdjustmentFactorPayroll
                    FROM       AIRExposureRe..tReinsuranceExposureAdjustmentFactor tr WITH (NOLOCK)
                    INNER JOIN AIRReference..tConvertCL2Country ta
                        ON tr.CountryCode = ta.CountryCode
                    JOIN       #PerilSetCodeList pc
                        ON CASE tr.PerilSetCode
                                WHEN 3 THEN 67
                                ELSE tr.PerilSetCode
                           END = pc.PerilSetCode
                    WHERE      tr.ExposureSetSID = @ExposureSetSID
                               AND tr.YearID = @YearID
                               AND tr.AdjustmentFactorTotalInsuredValue <> 0
                               AND tr.AdjustmentFactorTotalInsuredValue IS NOT NULL
                               AND tr.LOBCode
                               BETWEEN 148 AND 167
                END
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName
            RETURN @Result
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = dbo.pReThrowError
                @SPName,
                @Debug
        END CATCH;
    END
 
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLoss_ReGetMergedExposureRates_NGM]'
GO
IF OBJECT_ID(N'[dbo].[pLoss_ReGetMergedExposureRates_NGM]', 'P') IS NOT NULL
EXEC sp_executesql N'  /*****************************************************************************************************
DATE :					11-2018
OBJECT:					dbo.pMigration_LogStatus 
DESCRIPTION:			Get Exposure Rates, if not present get default rates 
ExposedToEntities:		NO
ResultView:				None
Usage:
			
USE AIRExposureRe
DECLARE @RC int
DECLARE @BusinessUnitSID int = 2
DECLARE @ExposureSetSID int = 1
DECLARE @YearID int = 2017
DECLARE @PerilSetCodeList  VARCHAR(200) = ''16384,4''
DECLARE @ExposureTypeForRates INT = 1      -- 1 is Premium will be check only Premium >0 then load the Rates
DECLARE @Debug bit = 0
EXECUTE @RC = dbo.pLoss_ReGetMergedExposureRates_NGM 
   @BusinessUnitSID
  ,@ExposureSetSID
  ,@YearID
  ,@PerilSetCodeList
  ,@ExposureTypeForRates
  ,@Debug
ExposureTypeForRates	AggregateExposureType
1						Premium
2						Sums Insured
3						Number of Risks
5						Market Share
17						Payroll
******************************************************************************************************/
ALTER
--ALTER
PROCEDURE [dbo].[pLoss_ReGetMergedExposureRates_NGM]
    @BusinessUnitSID INT,
    @ExposureSetSID INT,
    @YearID INT,
    @PerilSetCodeList VARCHAR(200),
    @ExposureTypeForRates INT, -- 1 is Premium will be check only Premium > 0 then load the Rates, 2 = 
    @Debug BIT = 0
AS
    BEGIN
        -- DECLARE VARIABLES
        DECLARE
            @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
            @Result INT = 0
        SET NOCOUNT ON
        BEGIN TRY
            -- PRINT START OF PROC
            IF @Debug = 1
                EXEC @Result = AIRProject.dbo.pCOMMON_PrintVariable
                    '': START OF '',
                    @SPName
            --/******************************************************************************
            --convert list to table 
            --******************************************************************************/
            CREATE TABLE #PerilSetCodeList
                (
                    PerilSetCode INT
                )
            INSERT INTO #PerilSetCodeList
                        SELECT DISTINCT CASE WHEN Value IN ( 3, 67 ) THEN 67
                                             ELSE Value
                                        END AS PerilSetCode
                        FROM   AIRProject.dbo.fCOMMON_ConvertListToTable_NGM(@PerilSetCodeList, '','')
            IF @Debug = 1
                SELECT
                     ''pGetAggregateExposureByCountryPerilSetCodePerf: #PerilSetCodeList'',
                     *
                FROM #PerilSetCodeList
            --/******************************************************************************
            --get Exposure Rates
            --******************************************************************************/
            SELECT
                      ae.ExposureSetSID,
                      ae.PerilSetCode,
                      cm.IntLevel1,
                      cm.IntLevel2,
                      cm.IntLevel3,
                      ae.GeographySID,
                      ae.LOBCode,
                      COALESCE(NULLIF(ae.Rates, 0), NULLIF(ier.UserDefinedRate, 0), NULLIF(ier.Rate, 0)) AS Rate
            FROM      dbo.tAggregateExposure ae WITH (NOLOCK)
            LEFT JOIN AIRUserSetting.dbo.tReinsuranceIndustryRate ier WITH (NOLOCK)
                ON ier.GeographySID = ae.GeographySID
                   AND ier.LOBCode = ae.LOBCode
                   AND ier.PerilSetCode = ae.PerilSetCode
                   AND ier.YearID = ae.YearID
                   AND ier.BusinessUnitSID = @BusinessUnitSID
            JOIN      AIRGeography.dbo.tReinsuranceInternalCodeMapping cm WITH (NOLOCK)
                ON cm.GeographySID = ae.GeographySID
            JOIN      #PerilSetCodeList pl
                ON pl.PerilSetCode = CASE ae.PerilSetCode
                                          WHEN 3 THEN 67
                                          ELSE ae.PerilSetCode
                                     END
            WHERE     ae.ExposureSetSID = @ExposureSetSID
                      AND ae.YearID = @YearID
                      AND CASE @ExposureTypeForRates
                               WHEN 1 THEN ae.Premium
                               WHEN 2 THEN ae.TotalInsuredValue
                               WHEN 3 THEN ae.RiskCount
                               WHEN 5 THEN ae.UserSpecifiedMarketShare
                               WHEN 17 THEN ae.Payroll
                          END > 0
                      AND COALESCE(NULLIF(ae.Rates, 0), NULLIF(ier.UserDefinedRate, 0), NULLIF(ier.Rate, 0)) > 0
            -- PRINT END OF PROC
            IF @Debug = 1
                EXEC @Result = AIRProject.dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName
            RETURN @Result
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = AIRProject.dbo.pReThrowError
                @SPName,
                @Debug
        END CATCH;
    END; -- OF PROC
 
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pCOMP_IMPORT_SyncUIAggregateExposure]'
GO
IF OBJECT_ID(N'[dbo].[pCOMP_IMPORT_SyncUIAggregateExposure]', 'P') IS NOT NULL
EXEC sp_executesql N'  /**********************************************************************************************************
OBJECT:				dbo.pCOMP_IMPORT_SyncUIAggregateExposure
DESCRIPTION:		Rollup Data 
ExposedToEntities:	Yes?
ResultView:			
Usage:				EXEC dbo.pCOMP_IMPORT_SyncUIAggregateExposure
						@ExposureSetSID = 18, 
						@TableName = ''AIRWork.dbo.t18_Import_A2033A93A2FB487A844E260D5B1C7AAE'', 
						@Debug = 1
**********************************************************************************************************/
ALTER 
--ALTER
PROCEDURE [dbo].[pCOMP_IMPORT_SyncUIAggregateExposure]
	@ExposureSetSID INTEGER, 
	@TableName SYSNAME, 
	@Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INTEGER = 0
	DECLARE @SPName SYSNAME = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	DECLARE @SQLStmt NVARCHAR(MAX)
	DECLARE @SQLStmtParameters NVARCHAR(MAX)
	DECLARE @RowCount INTEGER;
	DECLARE @NextSID INTEGER;
	BEGIN TRY
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': @TableName value '', @TableName
		SET @SQLStmt=  ''
			ALTER TABLE '' + @TableName +'' 
				ADD CountryCode VARCHAR(15),
					CountryName VARCHAR(255),
					CRESTACode VARCHAR(15),
					CRESTAName VARCHAR(255),
					AreaCode VARCHAR(15),
					AreaName VARCHAR(255),
					SubareaCode VARCHAR(15),
					ParentGeographySID INTEGER,
					GeoLevelCode  VARCHAR(10)'';
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt =  ''
			UPDATE t
				SET IntAreaScheme = b.AreaScheme,
					CountryCode = b.CountryCode,
					AreaCode = b.AreaCode,
					Areaname=b.Areaname,
					CRESTACode = b.CRESTACode,
					SubareaCode = b.SubareaCode,
					GeoLevelCode = b.GeoLevelCode,
					ParentGeographySID = b.ParentGeographySID
			FROM '' + @TableName + '' t WITH (UPDLOCK) 
			INNER JOIN 	AIRGeography.dbo.tReinsuranceGeography b ON t.GeographySID= b.GeographySID''
			
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt=N'' SELECT DISTINCT GeoLevelCode FROM '' + @TableName 
		EXEC SP_EXECUTESQL @SQLStmt
		IF @@ROWCOUNT>1
		   RAISERROR(''Multi GeolevelCode found in the staging table.'',16,1)
		SET @SQLStmt =  ''
			UPDATE '' + @TableName + ''
				SET CurrencyCode = b.CurrencyCode
			FROM '' + @TableName + '' a
			JOIN AIRReference.dbo.tCountryCurrencyXRef b WITH (UPDLOCK)
				ON a.CountryCode = b.CountryCode
				AND b.IsDefault = 1''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt =  ''
			UPDATE '' + @TableName + '' WITH (UPDLOCK)
				SET TotalInsuredValue = ISNULL(a.TotalInsuredValue, b.TotalInsuredValue),
					RiskCount = ISNULL(a.RiskCount, b.RiskCount),
					Premium = ISNULL(a.Premium, b.Premium),
					Payroll = ISNULL(a.Payroll, b.Payroll),
					UserSpecifiedMarketShare = ISNULL(a.UserSpecifiedMarketShare, b.UserSpecifiedMarketShare),
					Rates = ISNULL(a.Rates, b.Rates)
			FROM '' + @TableName + '' a
			JOIN dbo.tAggregateExposure  b WITH (NOLOCK)
				ON b.ExposureSetSID = @ExposureSetSID
				AND a.PerilSetCode 	= b.PerilSetCode
				AND a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.GeographySID = b.GeographySID
				AND a.LOBCode = b.LOBCode''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @SQLStmt =  ''
			SELECT * 
			INTO '' + @TableName + ''_1
			FROM '' + @TableName + '' 
			WHERE  GeoLevelCode = ''''SUBA''''''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt =  ''
			SELECT *
			INTO '' + @TableName + ''_0 
			FROM '' + @TableName + '' WITH (NOLOCK)
			WHERE  GeoLevelCode IN (''''AREA'''',''''CRES'''')''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt =  ''
			SELECT * 
			INTO '' + @TableName + ''_00
			FROM '' + @TableName + '' WITH (NOLOCK)
			WHERE  GeoLevelCode = ''''COUN''''''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Country level records count @RowCount = '', @RowCount
		SET @SQLStmt =  ''
			SELECT * 
			INTO '' + @TableName + ''_Sub
			FROM '' + @TableName + ''_1  WITH (NOLOCK)''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Subarea level records count @RowCount = '', @RowCount
		SET @SQLStmt =  ''
			INSERT INTO '' + @TableName + ''_Sub
			SELECT 
				t1.YearID,
				b.AreaScheme AS IntAreaScheme,
				t1.PerilSetCode,
				t1.LOBCode,
				t1.Premium,
				t1.Payroll,
				t1.RiskCount,
				t1.TotalInsuredValue,
				CAST(NULL AS FLOAT) AS UserSpecifiedMarketShare,
				t1.IsLossMarketShare,
				c.GeographySID,
				t1.CurrencyCode,
				t1.Rates,
				c.CountryCode,
				c.CountryName,
				c.CRESTACode,
				c.CRESTAName,
				c.AreaCode,
				c.AreaName,
				c.SubareaCode,
				COALESCE(c.GeographySID,NULL) AS ParentGeorgraphySID,
				b.GeoLevelCode
			FROM
			(
				SELECT  DISTINCT
					t.*
				FROM dbo.tAggregateExposure t WITH (NOLOCK)
				JOIN '' + @TableName + ''_1 c WITH (NOLOCK)
					ON	t.YearID = c.YearID 
					AND t.IntAreaScheme = c.IntAreaScheme	
					AND t.PerilSetCode = c.PerilSetCode	
					AND t.LOBCode = c.LOBCode	
					AND t.ExposureSetSID = @ExposureSetSID 
					AND t.CountryCode = c.CountryCode  
					AND (t.AreaCode = c.AreaCode 
						OR t.CRESTACode = c.CRESTACode) 
					AND t.GeoLevelCode = ''''SUBA''''
				LEFT JOIN  '' + @TableName + ''_1 ae WITH (NOLOCK)
					ON  t.YearID = ae.YearID
					AND t.IntAreaScheme = ae.IntAreaScheme
					AND t.PerilSetCode = ae.PerilSetCode
					AND t.LOBCode = ae.LOBCode
					AND t.CountryCode = ae.CountryCode
					AND (t.AreaCode = ae.AreaCode
						OR t.CRESTACode = ae.CRESTACode)
					AND t.GeographySID = ae.GeographySID
				WHERE ae.YearID IS NULL
			) t1
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON t1.GeographySID = b.GeographySID
			JOIN AIRGeography.dbo.tReinsuranceGeography c
				ON b.ParentGeographySID = c.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @SQLStmt = ''  
			DELETE FROM dbo.tAggregateExposure  WITH (UPDLOCK)
			WHERE AggregateExposureSID IN
				(
					SELECT DISTINCT a.AggregateExposureSID
					FROM dbo.tAggregateExposure a  WITH (UPDLOCK)
					JOIN '' + @TableName + ''_Sub ad
						ON a.ExposureSetSID = @ExposureSetSID
						AND ad.YearID = a.YearID	
						AND ad.IntAreaScheme = a.IntAreaScheme	
						AND ad.PerilSetCode = a.PerilSetCode	
						AND ad.LOBCode = a.LOBCode	
						AND ad.GeographySID = a.GeographySID
					WHERE ISNULL(ad.TotalInsuredValue,0) + ISNULL(ad.RiskCount,0) + ISNULL(ad.Premium,0) + ISNULL(ad.Payroll,0)  
						+ ISNULL(ad.UserSpecifiedMarketShare,0) + ISNULL(ad.Rates,0) = 0
				)''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		--1100 rule
		SET @SQLStmt = ''
			DELETE FROM dbo.tAggregateExposure  WITH (UPDLOCK)
			WHERE AggregateExposureSID IN
				(
					SELECT DISTINCT a.AggregateExposureSID
					FROM dbo.tAggregateExposure a  WITH (UPDLOCK)
					JOIN '' + @TableName + ''_Sub ad WITH (NOLOCK)
						ON a.ExposureSetSID = @ExposureSetSID
						AND ad.YearID = a.YearID	
						AND ad.IntAreaScheme = a.IntAreaScheme	
						AND ad.PerilSetCode = a.PerilSetCode	
						AND ad.ParentGeographySID = a.GeographySID
					LEFT JOIN '' + @TableName + ''_Sub ee WITH (NOLOCK)
						ON a.ExposureSetSID = @ExposureSetSID
						AND ee.YearID = a.YearID	
						AND ee.IntAreaScheme = a.IntAreaScheme	
						AND ee.PerilSetCode = a.PerilSetCode	
						AND ee.LOBCode = a.LOBCode	
						AND ee.ParentGeographySID = a.GeographySID
					WHERE ee.YearID IS NULL
				)''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Area/Cresta level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			SELECT 
				t1.YearID,
				c.AreaScheme AS  IntAreaScheme,
				t1.PerilSetCode,
				t1.LOBCode,
				t1.Premium,
				t1.Payroll,
				t1.RiskCount,
				t1.TotalInsuredValue,
				CAST(0.0 AS FLOAT)  AS UserSpecifiedMarketShare,
				t1.IsLossMarketShare,
				c.GeographySID,
				t1.CurrencyCode,
				CAST(0.0 AS FLOAT)   AS Rates,
				c.CountryCode,
				c.CountryName,
				c.CRESTACode,
				c.CRESTAName,
				c.AreaCode,
				c.AreaName,
				c.SubareaCode,
				COALESCE(c.GeographySID,NULL) AS ParentGeorgraphySID,
				c.GeoLevelCode
			INTO '' + @TableName + ''_AreaCRESTA
			FROM (
				SELECT 
					YearID,
					PerilSetCode,
					LOBCode,
					SUM(a.Premium) AS Premium,
					SUM(a.Payroll) AS Payroll,
					SUM(a.RiskCount) AS RiskCount,
					SUM(a.TotalInsuredValue) AS TotalInsuredValue,
					0 AS IsLossMarketShare,
					MAX(a.GeographySID ) AS GeographySID,
					MAX(a.CurrencyCode) AS CurrencyCode
				FROM '' + @TableName + ''_Sub a WITH (NOLOCK)
				GROUP BY YearID,
					PerilSetCode,
					LOBCode,
					AreaName,
					CRESTAName
				) t1
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON t1.GeographySID = b.GeographySID
			JOIN AIRGeography.dbo.tReinsuranceGeography c
				ON b.ParentGeographySID = c.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt = ''
			INSERT INTO '' + @TableName + ''_AreaCRESTA
			SELECT a.*
			FROM '' + @TableName + ''_0 AS a WITH (NOLOCK)
			LEFT JOIN '' + @TableName + ''_AreaCRESTA ae
				ON a.YearID = ae.YearID	
				AND a.IntAreaScheme = ae.IntAreaScheme	
				AND a.PerilSetCode = ae.PerilSetCode	
				AND a.LOBCode = ae.LOBCode 
				AND a.GeographySID = ae.GeographySID
				AND ae.YearID IS NULL''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''_0 into area level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			INSERT INTO  '' + @TableName + ''_1 
			SELECT * 
			FROM  '' + @TableName + ''_AreaCRESTA''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Area level records into _target @RowCount = '', @RowCount
		SET @SQLStmt = ''
			INSERT INTO '' + @TableName + ''_AreaCRESTA
			SELECT	 
				t1.YearID,
				b.AreaScheme AS IntAreaScheme,
				t1.PerilSetCode,
				t1.LOBCode,
				t1.Premium,
				t1.Payroll,
				t1.RiskCount,
				t1.TotalInsuredValue,
				CAST(0.0 AS FLOAT)  AS UserSpecifiedMarketShare,
				t1.IsLossMarketShare,
				c.GeographySID,
				t1.CurrencyCode,
				CAST(0.0 AS FLOAT)  AS Rates,
				c.CountryCode,
				c.CountryName,
				c.CRESTACode,
				c.CRESTAName,
				c.AreaCode,
				c.AreaName,
				c.SubareaCode,
				COALESCE(c.GeographySID,NULL) AS ParentGeorgraphySID,
				c.GeoLevelCode
			FROM (
				SELECT 
					a.YearID,
					a.IntAreaScheme,
					a.PerilSetCode,
					a.LOBCode,
					a.CountryCode,
					SUM(a.Premium) AS Premium,
					SUM(a.Payroll) AS Payroll,
					SUM(a.RiskCount) AS RiskCount,
					SUM(ISNULL(ae.TotalInsuredValue, a.TotalInsuredValue)) AS TotalInsuredValue,
					0 AS IsLossMarketShare,
					MAX(a.GeographySID) AS GeographySID,
					MAX(a.CurrencyCode) AS CurrencyCode
				FROM (
					SELECT DISTINCT t.*
					FROM dbo.tAggregateExposure t WITH (NOLOCK)
					JOIN '' + @TableName + ''_AreaCRESTA c
						ON	t.YearID = c.YearID	
						AND t.IntAreaScheme = c.IntAreaScheme
						AND t.PerilSetCode = c.PerilSetCode
						AND t.LOBCode = c.LOBCode
						AND t.ExposureSetSID = @ExposureSetSID
						AND t.CountryCode = c.CountryCode
						AND (
							t.GeoLevelCode = ''''AREA'''' 
							OR (
								t.GeoLevelCode = ''''CRES'''' 
								AND t.CountryCode != ''''EC''''
								)
							)
					) a
				LEFT JOIN '' + @TableName + ''_AreaCRESTA ae WITH (NOLOCK)
					ON  a.YearID = ae.YearID
					AND a.IntAreaScheme = ae.IntAreaScheme
					AND a.PerilSetCode = ae.PerilSetCode
					AND a.LOBCode = ae.LOBCode
					AND a.CountryCode = ae.CountryCode
					AND a.GeographySID=ae.GeographySID
				WHERE ae.YearID IS NULL
				GROUP BY 
					a.YearID,
					a.IntAreaScheme,
					a.PerilSetCode,
					a.LOBCode,
					a.CountryCode,
					a.AreaName,
					a.CRESTAName
			) t1
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON t1.GeographySID = b.GeographySID
			JOIN AIRGeography.dbo.tReinsuranceGeography c
				ON b.ParentGeographySID = c.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Aggregated to area level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			SELECT 
				t1.YearID,
				1006 AS IntAreaScheme,
				t1.PerilSetCode,
				t1.LOBCode,
				t1.Premium,
				t1.Payroll,
				t1.RiskCount,
				t1.TotalInsuredValue,
				CAST(0.0 AS FLOAT)  AS UserSpecifiedMarketShare,
				t1.IsLossMarketShare,
				CASE WHEN c.countrycode= ''''EC'''' THEN 63 ELSE c.GeographySID END AS GeographySID,
				t1.CurrencyCode,
				CAST(0.0 AS FLOAT)  AS Rates,
				c.CountryCode,
				c.CountryName,
				c.CRESTACode,
				c.CRESTAName,
				c.AreaCode,
				c.AreaName,
				c.SubareaCode,
				COALESCE(c.GeographySID,NULL) AS ParentGeorgraphySID,
				''''COUN'''' AS GeoLevelCode
			INTO '' + @TableName + ''_Country
			FROM (
				SELECT 
					YearID,
					PerilSetCode,
					LOBCode,
					SUM(a.Premium) AS Premium,
					SUM(a.Payroll) AS Payroll,
					SUM(a.RiskCount) AS RiskCount,
					SUM(a.TotalInsuredValue) AS TotalInsuredValue,
					0 AS IsLossMarketShare,
					MAX(a.GeographySID ) AS GeographySID,
					MAX(a.CurrencyCode) AS CurrencyCode
				FROM  '' + @TableName + ''_AreaCRESTA a WITH (NOLOCK)
				GROUP BY 
					YearID,
					PerilSetCode,
					LOBCode
				) t1
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON t1.GeographySID = b.GeographySID
			JOIN AIRGeography.dbo.tReinsuranceGeography c
				ON b.ParentGeographySID = c.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''_AreaCRESTA into country level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			INSERT INTO '' + @TableName + ''_Country
			SELECT a.*
			FROM '' + @TableName + ''_00 AS a WITH (NOLOCK)
			LEFT JOIN '' + @TableName + ''_Country ae WITH (NOLOCK)
				ON a.YearID = ae.YearID
				AND a.IntAreaScheme = ae.IntAreaScheme
				AND a.PerilSetCode = ae.PerilSetCode
				AND a.LOBCode = ae.LOBCode
				AND a.GeographySID = ae.GeographySID
				AND ae.YearID IS NULL''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''_00 to country level records count @RowCount = '', @RowCount
		SET @SQLStmt = ''
			INSERT INTO  '' + @TableName + ''_1 
			SELECT * 
			FROM  '' + @TableName + ''_Country''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		SET @SQLStmt = ''
			DELETE
			FROM dbo.tAggregateExposure WITH (UPDLOCK)
			WHERE AggregateExposureSID IN 
				(
					SELECT DISTINCT a.AggregateExposureSID
					FROM dbo.tAggregateExposure a WITH (UPDLOCK)
					JOIN '' + @TableName + ''_1 ad WITH (NOLOCK)
						ON a.ExposureSetSID = @ExposureSetSID
						AND ad.YearID = a.YearID
						AND ad.IntAreaScheme = a.IntAreaScheme
						AND ad.PerilSetCode = a.PerilSetCode
						AND ad.LOBCode = a.LOBCode
						AND ad.GeographySID = a.GeographySID
					WHERE ISNULL(ad.TotalInsuredValue,0) + ISNULL(ad.RiskCount,0) + ISNULL(ad.Premium,0) + ISNULL(ad.Payroll,0)
						 + ISNULL(ad.UserSpecifiedMarketShare,0) + ISNULL(ad.Rates,0) 
						 + ISNULL(a.UserSpecifiedMarketShare,0)= 0
				)''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''deleted main table @RowCount = '', @RowCount
		SET @SQLStmt = ''
			UPDATE dbo.tAggregateExposure WITH (UPDLOCK)
				SET Premium = b.Premium,
					Payroll = b.Payroll,
					RiskCount = b.RiskCount,
					TotalInsuredValue = b.TotalInsuredValue,
					UserSpecifiedMarketShare =CASE WHEN ISNULL(a.UserSpecifiedMarketShare,0) > 0 THEN a.UserSpecifiedMarketShare ELSE b.UserSpecifiedMarketShare END,
					Rates=CASE WHEN ISNULL(a.Rates,0) > 0 THEN a.Rates ELSE b.Rates END ,
					IsLossMarketShare = 0,
					CurrencyCode = b.CurrencyCode
			FROM dbo.tAggregateExposure a WITH (UPDLOCK)
			JOIN '' + @TableName + ''_1 b
				ON a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.PerilSetCode = b.PerilSetCode
				AND a.LOBCode = b.LOBCode
				AND a.ExposureSetSID = @ExposureSetSID
				AND a.GeographySID = b.GeographySID''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''update main table @RowCount = '', @RowCount
/*
-- is this needed or it this a debug info???
		SET @SQLStmt = ''
			SELECT b.*
			FROM '' + @TableName + ''_1 b
			LEFT JOIN AIRExposureRe.dbo.tAggregateExposure a
				ON a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.PerilSetCode = b.PerilSetCode
				AND a.LOBCode = b.LOBCode
				AND a.ExposureSetSID = @ExposureSetSID
				AND a.GeographySID = b.GeographySID
				AND a.YearID IS NULL''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Final Insert @RowCoun''
--*/
-- converted previous statement to count from select *
		SET @SQLStmt = ''
			SELECT @RowCount = COUNT(1)
			FROM '' + @TableName + ''_1 b
			LEFT JOIN dbo.tAggregateExposure a WITH (NOLOCK)
				ON a.YearID = b.YearID
				AND a.IntAreaScheme = b.IntAreaScheme
				AND a.PerilSetCode = b.PerilSetCode
				AND a.LOBCode = b.LOBCode
				AND a.ExposureSetSID = @ExposureSetSID
				AND a.GeographySID = b.GeographySID
				AND a.YearID IS NULL''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER, @RowCount INTEGER OUTPUT''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID,
			@RowCount OUTPUT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''Final Insert @RowCount = '', @RowCount
		--Then get next SID value to be used for insert command
		EXEC dbo.pGetSIDRange 
			@TableName = ''tAggregateExposure'', 
			@Amount = @RowCount,  
			@NextSID = @NextSID OUTPUT
		SET @SQLStmt = ''
			INSERT INTO dbo.tAggregateExposure WITH (UPDLOCK)
				(
					AggregateExposureSID,
					ExposureSetSID,
					PerilSetCode,
					YearID,
					LOBCode,
					CountryCode,
					AreaCode,
					SubareaCode,
					CRESTACode,
					GeographySID,
					CurrencyCode,
					IntAreaScheme,
					TotalInsuredValue,
					RiskCount,
					Premium,
					Payroll,
					UserSpecifiedMarketShare,
					Rates,
					CountryName,
					AreaName,
					SubareaName,
					CRESTAName,
					GeoLevelCode,
					IsLossMarketShare
				)
			SELECT @NextSID - 1 + ROW_NUMBER() OVER ( ORDER BY ( SELECT 0 ) ) AS AggregateExposureSID,
				@ExposureSetSID AS ExposureSetSID,
				ad.PerilSetCode,
				ad.YearID,
				ad.LOBCode,
				ad.CountryCode,
				ad.AreaCode,
				ad.SubareaCode,
				ad.CRESTACode,
				ad.GeographySID,
				ad.CurrencyCode,
				ad.IntAreaScheme,
				ad.TotalInsuredValue,
				ad.RiskCount,
				ad.Premium,
				ad.Payroll,
				ad.UserSpecifiedMarketShare,
				ad.Rates,
				b.CountryName,
				b.AreaName,
				b.SubareaName,
				b.CRESTAName,
				b.GeoLevelCode,
				0 AS IsLossMarketShare
			FROM '' + @TableName + ''_1 ad WITH (NOLOCK)
			JOIN AIRGeography.dbo.tReinsuranceGeography b
				ON ad.GeographySID = b.GeographySID
			LEFT JOIN dbo.tAggregateExposure ae WITH (UPDLOCK)
				ON 	@ExposureSetSID = ae.ExposureSetSID
				AND ad.YearID = ae.YearID
				AND ad.IntAreaScheme = ae.IntAreaScheme
				AND ad.PerilSetCode = ae.PerilSetCode
				AND ad.LOBCode = ae.LOBCode
				AND ad.GeographySID = ae.GeographySID
			WHERE 
				ae.YearID IS NULL 
				AND ISNULL(ad.TotalInsuredValue,0) + ISNULL(ad.RiskCount,0) + ISNULL(ad.Premium,0) + ISNULL(ad.Payroll,0)
					 + ISNULL(ad.UserSpecifiedMarketShare,0) + ISNULL(ad.Rates,0) > 0''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@ExposureSetSID = '', @ExposureSetSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@NextSID = '', @NextSID
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		SET @SQLStmtParameters = ''@ExposureSetSID INTEGER, @NextSID INTEGER''
		EXEC SP_EXECUTESQL 
			@SQLStmt, 
			@SQLStmtParameters, 
			@ExposureSetSID, 
			@NextSID
		SET @RowCount = @@ROWCOUNT
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''update main table @RowCount = '', @RowCount
		SET @SQLStmt = ''
			DROP TABLE '' + @TableName + ''_1
			DROP TABLE '' + @TableName + ''_Sub
			DROP TABLE '' + @TableName + ''_AreaCRESTA
			DROP TABLE '' + @TableName + ''_Country
			DROP TABLE '' + @TableName + ''_0
			DROP TABLE '' + @TableName + ''_00''
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable ''@SQLStmt = '', @SQLStmt
		EXEC SP_EXECUTESQL @SQLStmt
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
		RETURN @Result
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
END		-- Proc
 
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Refreshing [dbo].[vCOMMON_GetNewID]'
GO
IF OBJECT_ID(N'[dbo].[vCOMMON_GetNewID]', 'V') IS NOT NULL
EXEC sp_refreshview N'[dbo].[vCOMMON_GetNewID]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pUNICEDE_ImportBulkInsertPreProcess]'
GO
IF OBJECT_ID(N'[dbo].[pUNICEDE_ImportBulkInsertPreProcess]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT: [dbo].[pUNICEDE_ImportBulkInsertPreProcess]
DESCRIPTION:	create a statging table in AIrWork database for a specific ExposuresetSID
ExposedToEntities: <Yes>
Return value: int
Usage : 
	DECLARE	@return_value VARCHAR(130)
	exec [dbo].[pUNICEDE_ImportBulkInsertPreProcess] 10000, @return_value OUT,1;
	SELECT	@return_value;
Notes : Name Changed
**********************************************************************************************************/
ALTER
--ALTER
PROCEDURE [dbo].[pUNICEDE_ImportBulkInsertPreProcess] 
	@ExposuresetSID INTEGER
	,@Tablename VARCHAR(127) OUTPUT 
	,@Debug Bit= FALSE
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @ShortTablename VARCHAR(127)
	DECLARE @Result INT = 0
	DECLARE @SPName SYSNAME = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	DECLARE @SQLStmt NVARCHAR(MAX)
	BEGIN TRY
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		SELECT @TableName= dbo.fUNICEDE_ImportGetTableName(@ExposuresetSID);
		SET @ShortTableName=SUBSTRING(@TableName, len(@TableName)-CHARINDEX(''.'',REVERSE(@TableName))+2, CHARINDEX(''.'',REVERSE(@TableName) ))
		SET @SQLStmt =
		''CREATE TABLE '' + @TableName + ''
		(
			YearID SMALLINT NOT NULL,
			IntAreaScheme SMALLINT NOT NULL,
			PerilSetCode INTEGER NOT NULL,
			LOBCode INTEGER NOT NULL,
			Premium FLOAT,
			Payroll FLOAT,
			RiskCount FLOAT,
			TotalInsuredValue FLOAT,
			UserSpecifiedMarketShare FLOAT,
			IsLossMarketShare BIT,
			GeographySID INT NOT NULL,
			CurrencyCode CHAR(3),
			Rates FLOAT
			
		);'';
		IF @Debug = 1 PRINT @SQLStmt
		EXEC @Result =sp_executesql @SQLStmt
		SET  @SQLStmt =N''
			USE AIRWork
			GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON ''+@ShortTablename+
			'' TO airuserrole
			USE AIRExposureRe''
		IF @Debug = 1 PRINT @SQLStmt
		EXEC @Result =sp_executesql @SQLStmt
		SET  @SQLStmt =N''CREATE INDEX IDX_''+ LOWER(SUBSTRING(@TableName, len(@TableName)-CHARINDEX(''.'',REVERSE(@TableName))+2, CHARINDEX(''.'',REVERSE(@TableName) )))+ '' 
			ON ''+@TableName+
			''(
				YearID,
				IntAreaScheme,
				PerilSetCode,
				LOBCode, 
				GeographySID
			)''
		IF @Debug = 1 PRINT @SQLStmt
		EXEC @Result =sp_executesql @SQLStmt
		--select table name as another way of return - temporary till application consumes OUTPUT variable 
		SELECT @TableName AS TableName
		
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	
	RETURN @Result 
END;
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pLOSS_ReGetReinsuranceTreaty_NGM]'
GO
IF OBJECT_ID(N'[dbo].[pLOSS_ReGetReinsuranceTreaty_NGM]', 'P') IS NOT NULL
EXEC sp_executesql N'  /*****************************************************************************************************
DATE :					02-24-2017
OBJECT:					dbo.pLoss_ReGetReinsuranceTreaty_NGM  
DESCRIPTION:			Move pLoss_ReGetReinsuranceTreaty_NGM from AIRExposureRe to AIRProject
ExposedToEntities:		YES
ResultView:				None
Usage		:			DECLARE @AnalysisSID  INT = 1
						DECLARE @Debug BIT = 1
						EXECUTE dbo.pLOSS_ReGetReinsuranceTreaty_NGM @AnalysisSID ,@Debug
******************************************************************************************************/
ALTER
--ALTER 
PROCEDURE [dbo].[pLOSS_ReGetReinsuranceTreaty_NGM]
    (
        @AnalysisSID INT,
        @Debug BIT = 0
    )
AS
    BEGIN
        SET NOCOUNT ON
        DECLARE
            @Result INT = 0,
            @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
        BEGIN TRY
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': START OF '',
                    @SPName
            EXECUTE AIRProject.dbo.pLOSS_ReGetReinsuranceTreaty_NGM
                @AnalysisSID,
                @Debug
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName
            RETURN @Result
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = dbo.pReThrowError
                @SPName,
                @Debug
        END CATCH
    END
 
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Refreshing [dbo].[vwReinsuranceProgram]'
GO
IF OBJECT_ID(N'[dbo].[vwReinsuranceProgram]', 'V') IS NOT NULL
EXEC sp_refreshview N'[dbo].[vwReinsuranceProgram]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pValidateExposure]'
GO
IF OBJECT_ID(N'[dbo].[pValidateExposure]', 'P') IS NOT NULL
EXEC sp_executesql N' /******************************************************************************************************
Object:						pValidateExposure
Description:				To validate the exposure before running loss analysis
SPExposedToEntities :		08-10-2016
ResultView:					rvValidateExposure
Usage:
							DECLARE	@return_value int
							EXEC	@return_value = [dbo].[pValidateExposure]
									@AnalysisSID = 1,
									@Debug = 1
							SELECT	''Return Value'' = @return_value
*******************************************************************************************************/
ALTER
  --ALTER 
PROCEDURE [dbo].[pValidateExposure]
    (
     @AnalysisSID INT,
     @Debug BIT = 0
    )
AS
/* Commeted out it is failing on Portfolio Analysis*/
--BEGIN
--    SET NOCOUNT ON;
--    DECLARE
--        @MaxYear INT,
--        @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
--        @Result INT= 0,
--        @CLFSetSID INT,
--        @ExposureSetSID INT,
--		@pCount INT,
--		@SQLStmt NVARCHAR(MAX)=''''
--    BEGIN TRY
	    
--        IF @Debug = 1
--            EXEC dbo.pCOMMON_PrintVariable
--                '': START OF '',
--                @SPName;
		
--        CREATE TABLE #ValidationResult
--            (
--             ValidationResult BIT,
--             ValidationMessage VARCHAR(500)
--            )
--	   SELECT @pCount= COUNT(DISTINCT rptxf.ReinsuranceProgramSID)
--	   FROM  AIRExposureRe.dbo.tReinsuranceProgramTargetXRef rptxf
--	   JOIN AIRProject.dbo.tAnalysisTargetXref atxf
--	   ON rptxf.ReinsuranceProgramSID = atxf.AnalysisTargetSID
--		 AND atxf.AnalysisTargetTypeCode=''PGM''
--	   WHERE atxf.AnalysisSID = @AnalysisSID 
	     
--	   IF @pCount=0
--			INSERT  #ValidationResult
--			SELECT
--				CAST(0 AS BIT) AS ValidationResult,
--				''Analysis/target or program/target do(es) not Exist.'' AS ValidationMessage
--	   ELSE IF @pCount<>1
--			 INSERT  #ValidationResult
--			  ---Passing Portfolio Analysis to fixed multiple program
--			 SELECT
--				CAST(1 AS BIT) AS ValidationResult,
--				''Passed'' AS ValidationMessage
--				--CAST(0 AS BIT) AS ValidationResult,
--				--''Analysis has multi program.'' AS ValidationMessage
--		ELSE
--			/******************************************************************************************************
--			Single program
--			****************************************************************************************************/
--			BEGIN 
--			/******************************************************************************************************
--			First check source, if it has source then it''s good and stop further check
--			*******************************************************************************************************/
--					IF EXISTS (SELECT 1
--							FROM AIRExposureRe.dbo.tReinsuranceProgramTargetXRef rptxf
--							JOIN AIRProject.dbo.tAnalysisTargetXref atxf
--							ON rptxf.ReinsuranceProgramSID = atxf.AnalysisTargetSID
--								AND atxf.AnalysisTargetTypeCode=''PGM'' 
--							JOIN AIRExposureRe.dbo.tReinsuranceProgram rp
--						    ON rptxf.ReinsuranceProgramSID=rp.ReinsuranceProgramSID
--								AND rp.StatusCode=''A''
--							JOIN AIRExposureRe.dbo.tReinsuranceProgramSourceInure ri
--							ON rptxf.ReinsuranceProgramSID=ri.ReinsuranceProgramSubjectSID
--							  AND ri.IsSource=1 )
--					BEGIN
--						INSERT  #ValidationResult
--						SELECT
--						CAST(1 AS BIT) AS ValidationResult,
--						''Analysis has source.'' AS ValidationMessage
--					END
--					ELSE
--					/******************************************************************************************************
--					No source found, then check CLF and ExposuresetSID
--					*******************************************************************************************************/
--					BEGIN
--						SELECT
--							@CLFSetSID = MAX(rptxf.CLFSetSID),
--							@ExposureSetSID = MAX(rptxf.ExposureSetSID)
--							-- the MAX just want to know if all NULL or not
--						FROM
--							AIRExposureRe.dbo.tReinsuranceProgramTargetXRef rptxf
--						JOIN AIRProject.dbo.tAnalysisTargetXref atxf
--							ON rptxf.ReinsuranceProgramSID = atxf.AnalysisTargetSID
--						WHERE
--							atxf.AnalysisSID = @AnalysisSID
			
			
--						IF @CLFSetSID IS NOT NULL
--							INSERT  #ValidationResult
--							EXEC   dbo.pValidateProgramTargetCLF
--							@AnalysisSID,
--							@Debug 
				
			
--						IF @ExposureSetSID IS NOT NULL AND  EXISTS (	SELECT *
--									FROM
--										#ValidationResult
--									WHERE
--										ValidationResult = 1)
--						BEGIN
--							--remove CLF check sucess message first 
--							TRUNCATE TABLE #ValidationResult
--							--validate Exposure
--							INSERT  #ValidationResult
--									EXEC dbo.pValidateProgramTargetExposure
--										@AnalysisSID,
--										@Debug
--						END
					
--				END
							 
				
--		END  --end of ELSE (Single program)
--		/******************************************************************************************************
--		Return validation result 
--		*******************************************************************************************************/
--		IF NOT EXISTS (SELECT 1 FROM #ValidationResult )
--			SELECT
--			CAST(1 AS BIT) AS ValidationResult,
--			''Success.'' AS ValidationMessage
--		ELSE
--			SELECT
--				ValidationResult,
--				ValidationMessage
--			FROM
--				#ValidationResult 
--		IF @Debug = 1
--            EXEC dbo.pCOMMON_PrintVariable
--                '': END OF '',
--                @SPName;
--        RETURN @Result;
--    END TRY
--    BEGIN CATCH	
--		-- re-raise the error to be caught in the calling process
--        EXECUTE @Result = dbo.pReThrowError
--            @SPName,
--            @Debug;
--    END CATCH;
		
--END;	
BEGIN
    SET NOCOUNT ON;
    DECLARE
        @MaxYear INT,
        @ExpSID INT,
        @SubCount INT,
        @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
        @IsSubjectProgram INT= 0,
        @Result INT= 0;
    BEGIN TRY
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable
                '': START OF '',
                @SPName;
		
        SET @SubCount = 0;
        SELECT
            CONVERT(BIT,1) AS ValidationResult,
            ''Success'' AS ValidationMessage;
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable
                '': END OF '',
                @SPName;
        RETURN @Result;
    END TRY
    BEGIN CATCH	
		-- re-raise the error to be caught in the calling process
        EXECUTE @Result = dbo.pReThrowError
            @SPName,
            @Debug;
    END CATCH;
		
END;
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pValidateProgramTargetCLF]'
GO
IF OBJECT_ID(N'[dbo].[pValidateProgramTargetCLF]', 'P') IS NOT NULL
EXEC sp_executesql N' /******************************************************************************************************
Object:						pValidateProgramTargetCLF
Description:				To validate the exposure before running loss analysis
SPExposedToEntities :		08-10-2016
ResultView:					rvValidateExposure
Usage:
							DECLARE	@return_value int
							EXEC	@return_value = [dbo].[pValidateProgramTargetCLF]
									@AnalysisSID = 1,
									@Debug = 1
							SELECT	''Return Value'' = @return_value
*******************************************************************************************************/
ALTER
   --ALTER 
PROCEDURE [dbo].[pValidateProgramTargetCLF]
    (
     @AnalysisSID BIGINT,
     @Debug BIT = 0
    )
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE
        @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
        @Result INT= 0
    BEGIN TRY
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable
                '': START OF '',
                @SPName;
/******************************************************************************************************
Check for CLF
*******************************************************************************************************/
        IF EXISTS ( SELECT
                        *
                    FROM
                        AIRProject.dbo.tAnalysisTargetXref txref
                    INNER JOIN AIRExposureRe.dbo.tReinsuranceProgramTargetXRef ptxref
                        ON txref.AnalysisTargetSID = ptxref.ReinsuranceProgramSID
						   AND txref.AnalysisTargetTypeCode=''PGM''
                    JOIN AIRExposureRe.[dbo].[tCompanyLossAssociation] cl
                        ON ptxref.CompanyLossAssociationSID = cl.CompanyLossAssociationSID
                    WHERE
                        txref.AnalysisSID = @AnalysisSID
                        AND cl.StatusCode = ''A'' )
            SELECT
                CAST(1 AS BIT) AS ValidationResult,
                ''Success CLF'' AS ValidationMessage 
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable
                '': END OF '',
                @SPName;
        RETURN @Result;
    END TRY
    BEGIN CATCH	
		-- re-raise the error to be caught in the calling process
        EXECUTE @Result = dbo.pReThrowError
            @SPName,
            @Debug;
    END CATCH;
		
END;	
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
COMMIT TRANSACTION
GO
PRINT N'Refreshing [dbo].[vwReinsuranceTreatyDetails]'
GO
--#region Not Redgate - fake AirUserSetting if needed

DECLARE @AirUserSettingExists BIT = 0
DECLARE @tUDCClassificationExists BIT = 0
DECLARE @tUserDefinedCategoryExists BIT = 0

DECLARE @sql_tUDCClassification NVARCHAR(MAX) = '
	CREATE TABLE AirUserSetting.dbo.tUDCClassification (
		UDCClassificationSID INT
		,UserDefinedCategorySID INT
		,UDCClassificationName VARCHAR(128)
	)'

DECLARE @sql_tUserDefinedCategory NVARCHAR(MAX) = '
	CREATE TABLE AirUserSetting.dbo.tUserDefinedCategory (
		UserDefinedCategorySID INT
		,SystemUserDefinedCategoryCode VARCHAR(10)
	)'

IF EXISTS(SELECT 1 FROM sys.databases WHERE Name = 'AirUserSetting') 
	SET @AirUserSettingExists = 1
ELSE
	CREATE DATABASE AirUserSetting

IF EXISTS(SELECT 1 FROM AirUserSetting.sys.tables WHERE Name = 'tUDCClassification') 
	SET @tUDCClassificationExists = 1
ELSE
	EXEC sp_sqlexec @sql_tUDCClassification

IF EXISTS(SELECT 1 FROM AirUserSetting.sys.tables WHERE Name = 'tUserDefinedCategory') 
	SET @tUserDefinedCategoryExists = 1
ELSE
	EXEC sp_sqlexec @sql_tUserDefinedCategory
--#endregion Not Redgate - fake AirUserSetting if needed

IF OBJECT_ID(N'[dbo].[vwReinsuranceTreatyDetails]', 'V') IS NOT NULL
EXEC sp_refreshview N'[dbo].[vwReinsuranceTreatyDetails]'

PRINT N'Refreshing [dbo].[vwReinsuranceTreatyDetailsDynamicPortfolio]'
IF OBJECT_ID(N'[dbo].[vwReinsuranceTreatyDetailsDynamicPortfolio]', 'V') IS NOT NULL
EXEC sp_refreshview N'[dbo].[vwReinsuranceTreatyDetailsDynamicPortfolio]'

--#region Not Redgate - remove AirUserSetting
IF @AirUserSettingExists = 0
	DROP DATABASE AirUserSetting
ELSE BEGIN
	IF @tUDCClassificationExists = 0 DROP TABLE AirUserSetting.dbo.tUDCClassification
	IF @tUserDefinedCategoryExists = 0 DROP TABLE AirUserSetting.dbo.tUserDefinedCategory
END
--#endregion Not Redgate - remove AirUserSetting
GO
BEGIN TRANSACTION
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pValidateProgramTargetExposure]'
GO
IF OBJECT_ID(N'[dbo].[pValidateProgramTargetExposure]', 'P') IS NOT NULL
EXEC sp_executesql N' /******************************************************************************************************
Object:						pValidateProgramTargetExposure
Description:				To validate the exposure before running loss analysis
SPExposedToEntities :		08-10-2016
ResultView:					rvValidateExposure
Usage:
							DECLARE	@return_value int
							EXEC	@return_value = [dbo].[pValidateProgramTargetExposure]
									@AnalysisSID = 1,
									@Debug = 1
							SELECT	''Return Value'' = @return_value
*******************************************************************************************************/
ALTER
  -- ALTER 
PROCEDURE [dbo].[pValidateProgramTargetExposure]
    (
     @AnalysisSID BIGINT,
     @Debug BIT = 0
    )
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE
        @MaxYear INT,
        @SubCount INT,
        @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
        @IsSubjectProgram INT= 0,
        @Result INT= 0;
    DECLARE @ExposureSetSID INT 
    DECLARE @ReinsuranceProgramSID INT 
    DECLARE @Geography_Validated BIT = 0
    DECLARE @ExposureTypeAndYear_Validated BIT = 0
		 
    BEGIN TRY
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable
                '': START OF '',
                @SPName;
/******************************************************************************************************
Exposure validation - exposure type and Geography and perilsetcode and SubjectAssesmentTypeCode
*******************************************************************************************************/
--get ExposureSetSID,@ReinsuranceProgramSID
        SELECT
            @ExposureSetSID = pxrf.ExposureSetSID,
            @ReinsuranceProgramSID = pxrf.ReinsuranceProgramSID
        FROM
            dbo.tReinsuranceProgramTargetXRef pxrf
        JOIN AIRProject.dbo.tAnalysisTargetXref txrf
            ON pxrf.ReinsuranceProgramSID = txrf.AnalysisTargetSID
			 AND txrf.AnalysisTargetTypeCode=''PGM''
        JOIN AIRExposureRe.dbo.tExposureSet es
            ON es.ExposureSetSID = pxrf.ExposureSetSID
				  
        WHERE
            txrf.AnalysisSID = @AnalysisSID
            AND es.StatusCode = ''A''
--Geography
        IF EXISTS ( SELECT
                        *
                    FROM
                        AIRExposureRe.dbo.tReinsuranceTreaty tr
                    INNER JOIN dbo.tAppliesToAreaGeoXRef axref
                        ON tr.AppliesToAreaSID = axref.AppliesToAreaSID
                    INNER JOIN AIRGeography.dbo.tReinsuranceGeography rg
                        ON axref.GeographySID = rg.GeographySID
                    INNER JOIN AIRExposureRe.dbo.tAggregateExposure ae
                        ON ae.CountryCode = rg.CountryCode
                           AND ae.ExposureSetSID = @ExposureSetSID )
            SET @Geography_Validated = 1
--exposure type and year
        IF @Geography_Validated = 1
            AND EXISTS ( SELECT
                            *
                         FROM
                            dbo.tReinsuranceProgramTargetXRef pxrf
                         INNER JOIN AIRExposureRe.dbo.tReinsuranceTreaty tr
                            ON tr.ReinsuranceProgramSID = pxrf.ReinsuranceProgramSID
                         INNER JOIN dbo.tAppliesToAreaGeoXRef axref
                            ON tr.AppliesToAreaSID = axref.AppliesToAreaSID
                         INNER JOIN AIRGeography.dbo.tReinsuranceGeography rg
                            ON axref.GeographySID = rg.GeographySID
                         INNER JOIN AIRExposureRe.dbo.tAggregateExposure ae
                            ON ae.CountryCode = rg.CountryCode
                         WHERE
                            pxrf.ReinsuranceProgramSID = @ReinsuranceProgramSID
                            AND ae.ExposureSetSID = @ExposureSetSID
                            AND (
                                 (
                                  pxrf.ExposureTypeCode = ''SI''
                                  AND ae.TotalInsuredValue > 0
                                 )
                                 OR (
                                     pxrf.ExposureTypeCode = ''PY''
                                     AND ae.Payroll > 0
                                    )
                                 OR (
                                     pxrf.ExposureTypeCode = ''MS''
                                     AND ae.UserSpecifiedMarketShare > 0
                                    )
                                 OR (
                                     pxrf.ExposureTypeCode = ''PR''
                                     AND ae.Premium > 0
                                    )
                                 OR (
                                     pxrf.ExposureTypeCode = ''NR''
                                     AND ae.RiskCount > 0
                                    )
                                )
                            AND (
                                 pxrf.YearSID IS NULL
                                 OR pxrf.YearSID = ae.YearID
                                ) )
            SET @ExposureTypeAndYear_Validated = 1
-- ExposureTypeAndYear not Validated but it is subject program 
        IF @ExposureTypeAndYear_Validated = 0
            IF EXISTS ( SELECT
                            IsAssessmentProgram
                        FROM
                            AIRProject.dbo.tAnalysisTargetXref txref
                        JOIN AIRExposureRe.dbo.tReinsuranceProgram pg
                        ON txref.AnalysisTargetSID = pg.ReinsuranceProgramSID
							 AND txref.AnalysisTargetTypeCode=''PGM''
                        WHERE
                            pg.StatusCode = ''A''
                            AND txref.AnalysisSID = @AnalysisSID )
                SELECT
                    CAST(1 AS BIT) AS ValidationResult,
                    ''Success'' AS ValidationMessage;
            ELSE
                SELECT
                    CAST(0 AS BIT) AS ValidationResult,
                    ''No Exposure for type and year Exists'' AS ValidationMessage;
-- ExposureTypeAndYear Validated validate perilcode too 
        IF @ExposureTypeAndYear_Validated = 1
            BEGIN 
                SELECT
                    @MaxYear = MAX(YearID)
                FROM
                    dbo.tAggregateExposure ae
                WHERE
                    ae.ExposureSetSID = @ExposureSetSID;
                IF EXISTS ( SELECT
                                   DISTINCT
                                t.[ReinsuranceTreatySID]
                            FROM
                                dbo.tReinsuranceTreaty t
                            JOIN dbo.tReinsuranceProgramTargetXRef pxrf
                                ON t.ReinsuranceProgramSID = pxrf.ReinsuranceProgramSID
                            JOIN dbo.tAggregateExposure ae
                                ON pxrf.ExposureSetSID = ae.ExposureSetSID
                                   AND ae.PerilSetCode & (CASE WHEN t.PerilSetCode IN (512, 8) THEN 8
                                                               WHEN t.PerilSetCode IN (2048, 16) THEN 2064
                                                               WHEN t.PerilSetCode IN (1, 2, 3, 64) THEN 67
                                                               ELSE t.PerilSetCode
                                                          END) > 0
                                   AND ae.ExposureSetSID = @ExposureSetSID
                                   AND ae.YearID = ISNULL(pxrf.YearSID, @MaxYear) )
                    SELECT
                        CAST(1 AS BIT) AS ValidationResult,
                        ''Success'' AS ValidationMessage
                ELSE
                    SELECT
                        CAST(0 AS BIT) AS ValidationResult,
                        ''No Exposure Exists'' AS ValidationMessage
            END 
										
        IF @Debug = 1
            EXEC dbo.pCOMMON_PrintVariable
                '': END OF '',
                @SPName;
        RETURN @Result;
    END TRY
    BEGIN CATCH	
		-- re-raise the error to be caught in the calling process
        EXECUTE @Result = dbo.pReThrowError
            @SPName,
            @Debug;
    END CATCH;
		
END;	
 '

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Refreshing [dbo].[vwReinsuranceTreatyList]'
GO
IF OBJECT_ID(N'[dbo].[vwReinsuranceTreatyList]', 'V') IS NOT NULL
EXEC sp_refreshview N'[dbo].[vwReinsuranceTreatyList]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Refreshing [dbo].[vwReinsuranceProgramSourceInure]'
GO
IF OBJECT_ID(N'[dbo].[vwReinsuranceProgramSourceInure]', 'V') IS NOT NULL
EXEC sp_refreshview N'[dbo].[vwReinsuranceProgramSourceInure]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pAGGEXP_CheckCustomLOBDataExistence]'
GO
IF OBJECT_ID(N'[dbo].[pAGGEXP_CheckCustomLOBDataExistence]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT:					pAGGEXP_CheckCustomLOBDataExistence]
DESCRIPTION:			Check whether there is any customlob exposureData for given exposuresetsid
ExposedToEntities:		01/23/2019 
ResultView:				None
Usage : 
DECLARE	@return_value int
EXEC	@return_value = [dbo].[pAGGEXP_CheckCustomLOBDataExistence]
		@ExposureSetSID = 1,
		@Debug = 1
SELECT	''Return Value'' = @return_value
Notes : 
**********************************************************************************************************/
ALTER
--ALTER 
PROCEDURE [dbo].[pAGGEXP_CheckCustomLOBDataExistence]
    (
        @ExposureSetSID INT,
        @Debug BIT = 0
    )
AS
    BEGIN
        SET NOCOUNT ON
        DECLARE @Result INT = 0
        DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
        BEGIN TRY
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': START OF '',
                    @SPName
            SELECT TOP 1 TotalInsuredValue
            FROM   AIRExposureRe.dbo.tAggregateExposure
            WHERE  LOBCode
                   BETWEEN 148 AND 167 -- 148 AND 167 are hard coeded boundary IDs for custom LOb codes 
                   AND TotalInsuredValue > 0
                   AND ExposureSetSID = @ExposureSetSID
            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName
            RETURN @Result
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = dbo.pReThrowError
                @SPName,
                @Debug
        END CATCH
    END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pAGGEXP_GetAffectedLossAnalyses]'
GO
IF OBJECT_ID(N'[dbo].[pAGGEXP_GetAffectedLossAnalyses]', 'P') IS NOT NULL
EXEC sp_executesql N' /******************************************************************************************************
Object: dbo.pAGGEXP_GetAffectedLossAnalyses 
Description:	Get the list of Affected lossAnalysis rows if a arget is modified or deleted
SPExposedToEntities : Yes
*******************************************************************************************************/
/*
 exec [dbo].[pAGGEXP_GetAffectedLossAnalyses] @TargetSid=''<Root> <TargetType>CompanyLossAssociation</TargetType>
  <Targets>
    <Target>
      <Sid>8</Sid>
    </Target>
	<Target>
	  <Sid>10</Sid>
    </Target>
  </Targets>
</Root>'', @debug=1
 exec [dbo].[pAGGEXP_GetAffectedLossAnalyses] @TargetSid=''<Root> <TargetType>Program</TargetType>
  <Targets>
    <Target>
      <Sid>18</Sid>
    </Target>
	<Target>
	  <Sid>19</Sid>
    </Target>
  </Targets>
</Root>'', @debug=1
*/
ALTER
	--ALTER 
 PROCEDURE [dbo].[pAGGEXP_GetAffectedLossAnalyses]
	@TargetSid XML ,
	/*<Root>
  <TargetType>AggExposureSet</TargetType>
  <Targets>
    <Target>
      <Sid>4</Sid>
    </Target>
  </Targets>
</Root>
*/
		@Debug BIT =0
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @TargetType VARCHAR(50)
	DECLARE @Result INT
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	DECLARE  @Sids TABLE (TargetSID int)
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
	
	DECLARE @ExposuresetSID int
	BEGIN TRY
		SELECT @TargetType=x.Filter.value(''TargetType[1]'', ''varchar(50)'') 
		FROM @TargetSid.nodes(''//Root'') AS x ( Filter )
		WHERE x.Filter.value(''TargetType[1]'', ''varchar(50)'') IS NOT NULL ;
		INSERT INTO @Sids
	    SELECT x.Filter.value(''Sid[1]'', ''INT'') AS TargetSID
		FROM @TargetSid.nodes(''//Root/Targets/Target'') AS x ( Filter )
		WHERE x.Filter.exist(''//Root/Targets/Target'') = 1
		IF NOT EXISTS (SELECT 1 FROM  @Sids )
			THROW 50000, ''Invalid XML in @TargetSid. There must be st leat 1 Target'', 1;
		IF @TargetType =''AggExposureSet''
			SELECT a.[AnalysisSID]
				  ,a.[AnalysisName]
			FROM AIRProject..tAnalysis a
			JOIN AIRPROJECT..tAnalysisTargetXref tr ON a.AnalysisSID=tr.AnalysisSID
			JOIN AIRExposureRe..tReinsuranceProgramTargetXRef b ON tr.AnalysisTargetSID=b.ReinsuranceProgramSID
			AND tr.AnalysisTargetTypeCode=''PGM''
			JOIN @Sids t ON b.ExposureSetSID=t.TargetSID
			WHERE a.AnalysisTypeCode=''AGGR_LOSS''
		ELSE IF @TargetType=''CompanyLossAssociation''
			SELECT a.[AnalysisSID]
				  ,a.[AnalysisName]
			FROM AIRProject..tAnalysis a
			JOIN AIRPROJECT..tAnalysisTargetXref tr ON a.AnalysisSID=tr.AnalysisSID
			JOIN AIRExposureRe..tReinsuranceProgramTargetXRef b ON tr.AnalysisTargetSID=b.ReinsuranceProgramSID
			AND tr.AnalysisTargetTypeCode=''PGM''
			JOIN @Sids t ON b.CompanyLossAssociationSID=t.TargetSID
			WHERE a.AnalysisTypeCode=''AGGR_LOSS''
		ELSE IF @TargetType=''Program''
			SELECT a.[AnalysisSID]
				  ,a.[AnalysisName]
			FROM AIRProject..tAnalysis a
			JOIN AIRPROJECT..tAnalysisTargetXref tr ON a.AnalysisSID=tr.AnalysisSID
			JOIN AIRExposureRe..tReinsuranceProgramTargetXRef b ON tr.AnalysisTargetSID=b.ReinsuranceProgramSID
			AND tr.AnalysisTargetTypeCode=''PGM''
			JOIN @Sids t ON b.ReinsuranceProgramSID=t.TargetSID
			WHERE a.AnalysisTypeCode=''AGGR_LOSS''
        ELSE IF  @TargetType=''Portfolio''
			SELECT	a.[AnalysisSID]
					,a.[AnalysisName]
			FROM  [AIRExposureRe].[dbo].[tPortfolio] p
			JOIN [AIRProject].[dbo].[tAnalysisTargetXref] ax on (ax.AnalysisTargetSID = p.PortfolioSID)
			     AND ax.AnalysisTargetTypeCode=''PRT''
			JOIN [AIRProject].[dbo].[tAnalysis] a on (ax.AnalysisSID = a.AnalysisSID)
			JOIN @Sids t ON p.PortfolioSID=t.TargetSID
			WHERE a.AnalysisTypeCode=''AGGR_LOSS''
		
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pAggregateExposureSumLevelsUp]'
GO
IF OBJECT_ID(N'[dbo].[pAggregateExposureSumLevelsUp]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
DATE :					04-2017
OBJECT:					dbo.pAggregateExposureSumLevelsUp 
DESCRIPTION:			Insert data for Source and Inuring
ExposedToEntities:		YES
ResultView:				None
Usage		:			DECLARE @ExposureSetSID INT = 1
						DECLARE @PerilSetCode INT = 4
						DECLARE @YearID INT = 2016
						DECLARE @LOBCode INT = 12
						DECLARE @Debug BIT = 0
						EXECUTE [dbo].pAggregateExposureSumLevelsUp 
						@ExposureSetSID,
						@PerilSetCode,
						@YearID,
						@LOBCode,
						@Debug
******************************************************************************************************/
ALTER
--ALTER
PROCEDURE [dbo].[pAggregateExposureSumLevelsUp]
    @ExposureSetSID INT,
    @PerilSetCode INT NULL,
    @YearID INT NULL,
    @LOBCode INT NULL,
    @Debug BIT = 0
AS
    BEGIN
        -- DECLARE VARIABLES
        DECLARE
            @SPName sysname = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID),
            @Result INT = 0
        DECLARE @RecordCountTotal INT = 0
        DECLARE @RecordCountUpdatedArea INT = 0
        DECLARE @RecordCountUpdatedCountry INT = 0
        SET NOCOUNT ON
        BEGIN TRY
            -- PRINT START OF PROC
            IF @Debug = 1
                EXEC @Result = AIRProject.dbo.pCOMMON_PrintVariable
                    '': START OF '',
                    @SPName
            --/******************************************************************************
            --create log table 
            --******************************************************************************/
            CREATE TABLE #UpdateLog
                (
                    UpdateLogSID INT IDENTITY(1, 1),
                    RecordSet VARCHAR(30),
                    AggregateExposureSID INT,
                    ExposureSetSID INT,
                    PerilSetCode INT,
                    YearID SMALLINT,
                    GeographySID INT,
                    CountryCode VARCHAR(15),
                    CountryName VARCHAR(255),
                    CRESTACode VARCHAR(15),
                    CRESTAName VARCHAR(255),
                    AreaCode VARCHAR(15),
                    AreaName VARCHAR(255),
                    SubareaCode VARCHAR(15),
                    SubareaName VARCHAR(255),
                    CurrencyCode CHAR(3),
                    LOBCode INT,
                    GeoLevelCode VARCHAR(10),
                    INSERTED_TotalInsuredValue VARCHAR(30),
                    DELETED_TotalInsuredValue VARCHAR(30),
                    INSERTED_RiskCount VARCHAR(30),
                    DELETED_RiskCount VARCHAR(30),
                    INSERTED_Premium VARCHAR(30),
                    DELETED_Premium VARCHAR(30),
                    INSERTED_Payroll VARCHAR(30),
                    DELETED_Payroll VARCHAR(30),
                    DateEntered DATETIME
                        DEFAULT (GETDATE())
                )
            --/******************************************************************************
            --first get all levels 
            --******************************************************************************/
            SELECT
                 ae.AggregateExposureSID,
                 ae.ExposureSetSID,
                 ae.PerilSetCode,
                 ae.YearID,
                 ae.LOBCode,
                 ae.GeographySID,
                 rg.GeoLevelCode,
                 rg.ParentGeographySID
            INTO
                 #AllGeoLevels
            FROM dbo.tAggregateExposure ae
            JOIN AIRGeography.dbo.tReinsuranceGeography rg
                ON ae.GeographySID = rg.GeographySID
                   AND (
                           @ExposureSetSID IS NULL
                           OR ae.ExposureSetSID = @ExposureSetSID
                       )
                   AND (
                           @PerilSetCode IS NULL
                           OR ae.PerilSetCode = @PerilSetCode
                       )
                   AND (
                           @YearID IS NULL
                           OR ae.YearID = @YearID
                       )
                   AND (
                           @LOBCode IS NULL
                           OR ae.LOBCode = @LOBCode
                       )
            SET @RecordCountTotal = @@ROWCOUNT
            --/******************************************************************************
            --update Level 2
            --******************************************************************************/
            --get sum of SUBA level
            SELECT
                     ae_Level3.ExposureSetSID,
                     ae_Level3.PerilSetCode,
                     ae_Level3.YearID,
                     ae_Level3.LOBCode,
                     al.ParentGeographySID,
                     SUM(ae_Level3.Premium) AS Premium,
                     SUM(ae_Level3.Payroll) AS Payroll,
                     SUM(ae_Level3.RiskCount) AS RiskCount,
                     SUM(ae_Level3.TotalInsuredValue) AS TotalInsuredValue
            INTO
                     #SummedUpLevel3
            FROM     AIRExposureRe.dbo.tAggregateExposure ae_Level3
            JOIN     #AllGeoLevels al
                ON al.GeographySID = ae_Level3.GeographySID
                   AND al.GeoLevelCode IN ( ''SUBA'' )
            WHERE    (
                         @ExposureSetSID IS NULL
                         OR ae_Level3.ExposureSetSID = @ExposureSetSID
                     )
                     AND (
                             @PerilSetCode IS NULL
                             OR ae_Level3.PerilSetCode = @PerilSetCode
                         )
                     AND (
                             @YearID IS NULL
                             OR ae_Level3.YearID = @YearID
                         )
                     AND (
                             @LOBCode IS NULL
                             OR ae_Level3.LOBCode = @LOBCode
                         )
            GROUP BY ae_Level3.ExposureSetSID,
                     ae_Level3.PerilSetCode,
                     ae_Level3.YearID,
                     ae_Level3.LOBCode,
                     al.ParentGeographySID
            --update Level 2
            UPDATE
                  ae_Level2
            SET
                  ae_Level2.Premium = ss.Premium,
                  ae_Level2.Payroll = ss.Payroll,
                  ae_Level2.RiskCount = ss.RiskCount,
                  ae_Level2.TotalInsuredValue = ss.TotalInsuredValue
            OUTPUT
                ''AREA/CRESTA update'' AS RecordSet,
                INSERTED.AggregateExposureSID,
                INSERTED.ExposureSetSID,
                INSERTED.PerilSetCode,
                INSERTED.YearID,
                INSERTED.GeographySID,
                INSERTED.CountryCode,
                INSERTED.CountryName,
                INSERTED.CRESTACode,
                INSERTED.CRESTAName,
                INSERTED.AreaCode,
                INSERTED.AreaName,
                INSERTED.SubareaCode,
                INSERTED.SubareaName,
                INSERTED.CurrencyCode,
                INSERTED.LOBCode,
                INSERTED.GeoLevelCode,
                CONVERT(VARCHAR(30), INSERTED.TotalInsuredValue) INSERTED_TotalInsuredValue,
                CONVERT(VARCHAR(30), DELETED.TotalInsuredValue) DELETED_TotalInsuredValue,
                CONVERT(VARCHAR(30), INSERTED.RiskCount) INSERTED_RiskCount,
                CONVERT(VARCHAR(30), DELETED.RiskCount) DELETED_RiskCount,
                CONVERT(VARCHAR(30), INSERTED.Premium) INSERTED_Premium,
                CONVERT(VARCHAR(30), DELETED.Premium) DELETED_Premium,
                CONVERT(VARCHAR(30), INSERTED.Payroll) INSERTED_Payroll,
                CONVERT(VARCHAR(30), DELETED.Payroll) DELETED_Payroll,
                GETDATE() AS DateEntered
            INTO #UpdateLog
            FROM  #SummedUpLevel3 ss
            JOIN  AIRExposureRe.dbo.tAggregateExposure ae_Level2
                ON ae_Level2.ExposureSetSID = ss.ExposureSetSID
                   AND ae_Level2.PerilSetCode = ss.PerilSetCode
                   AND ae_Level2.YearID = ss.YearID
                   AND ae_Level2.LOBCode = ss.LOBCode
                   AND ae_Level2.GeographySID = ss.ParentGeographySID
            WHERE ae_Level2.Premium <> ss.Premium
                  OR ae_Level2.Payroll <> ss.Payroll
                  OR ae_Level2.RiskCount <> ss.RiskCount
                  OR ae_Level2.TotalInsuredValue <> ss.TotalInsuredValue
            SET @RecordCountUpdatedArea = @@ROWCOUNT
            --/******************************************************************************
            --update Level 1
            --******************************************************************************/
            --get sum of AREA/CRESTA level
            SELECT
                     ae_Level2.ExposureSetSID,
                     ae_Level2.PerilSetCode,
                     ae_Level2.YearID,
                     ae_Level2.LOBCode,
                     al.ParentGeographySID,
                     SUM(ae_Level2.Premium) AS Premium,
                     SUM(ae_Level2.Payroll) AS Payroll,
                     SUM(ae_Level2.RiskCount) AS RiskCount,
                     SUM(ae_Level2.TotalInsuredValue) AS TotalInsuredValue
            INTO
                     #SummedUpLevel2
            FROM     AIRExposureRe.dbo.tAggregateExposure ae_Level2
            JOIN     #AllGeoLevels al
                ON al.GeographySID = ae_Level2.GeographySID
            WHERE    (
                         @ExposureSetSID IS NULL
                         OR ae_Level2.ExposureSetSID = @ExposureSetSID
                     )
                     AND (
                             @PerilSetCode IS NULL
                             OR ae_Level2.PerilSetCode = @PerilSetCode
                         )
                     AND (
                             @YearID IS NULL
                             OR ae_Level2.YearID = @YearID
                         )
                     AND (
                             @LOBCode IS NULL
                             OR ae_Level2.LOBCode = @LOBCode
                         )
                     AND al.GeoLevelCode IN ( ''AREA'', ''CRESTA'' )
            GROUP BY ae_Level2.ExposureSetSID,
                     ae_Level2.PerilSetCode,
                     ae_Level2.YearID,
                     ae_Level2.LOBCode,
                     al.ParentGeographySID
            --update Level 1
            UPDATE
                  ae_Level1
            SET
                  ae_Level1.Premium = ss.Premium,
                  ae_Level1.Payroll = ss.Payroll,
                  ae_Level1.RiskCount = ss.RiskCount,
                  ae_Level1.TotalInsuredValue = ss.TotalInsuredValue
            OUTPUT
                ''COUNTRY update'' AS RecordSet,
                INSERTED.AggregateExposureSID,
                INSERTED.ExposureSetSID,
                INSERTED.PerilSetCode,
                INSERTED.YearID,
                INSERTED.GeographySID,
                INSERTED.CountryCode,
                INSERTED.CountryName,
                INSERTED.CRESTACode,
                INSERTED.CRESTAName,
                INSERTED.AreaCode,
                INSERTED.AreaName,
                INSERTED.SubareaCode,
                INSERTED.SubareaName,
                INSERTED.CurrencyCode,
                INSERTED.LOBCode,
                INSERTED.GeoLevelCode,
                CONVERT(VARCHAR(30), INSERTED.TotalInsuredValue) INSERTED_TotalInsuredValue,
                CONVERT(VARCHAR(30), DELETED.TotalInsuredValue) DELETED_TotalInsuredValue,
                CONVERT(VARCHAR(30), INSERTED.RiskCount) INSERTED_RiskCount,
                CONVERT(VARCHAR(30), DELETED.RiskCount) DELETED_RiskCount,
                CONVERT(VARCHAR(30), INSERTED.Premium) INSERTED_Premium,
                CONVERT(VARCHAR(30), DELETED.Premium) DELETED_Premium,
                CONVERT(VARCHAR(30), INSERTED.Payroll) INSERTED_Payroll,
                CONVERT(VARCHAR(30), DELETED.Payroll) DELETED_Payroll,
                GETDATE() AS DateEntered
            INTO #UpdateLog
            FROM  #SummedUpLevel2 ss
            JOIN  AIRExposureRe.dbo.tAggregateExposure ae_Level1
                ON ae_Level1.ExposureSetSID = ss.ExposureSetSID
                   AND ae_Level1.PerilSetCode = ss.PerilSetCode
                   AND ae_Level1.YearID = ss.YearID
                   AND ae_Level1.LOBCode = ss.LOBCode
                   AND ae_Level1.GeographySID = ss.ParentGeographySID
            WHERE ae_Level1.Premium <> ss.Premium
                  OR ae_Level1.Payroll <> ss.Payroll
                  OR ae_Level1.RiskCount <> ss.RiskCount
                  OR ae_Level1.TotalInsuredValue <> ss.TotalInsuredValue
            SET @RecordCountUpdatedCountry = @@ROWCOUNT
            --/******************************************************************************
            --Return updated record data 
            --******************************************************************************/
            IF @Debug = 1
                BEGIN
                    SELECT
                        @RecordCountTotal AS RecordCountTotal,
                        @RecordCountUpdatedArea AS RecordCountUpdatedArea,
                        @RecordCountUpdatedCountry AS RecordCountUpdatedCountry,
                        CONVERT(
                                   DECIMAL(5, 0),
                                   100 * ((@RecordCountUpdatedArea + @RecordCountUpdatedCountry) / (ISNULL(NULLIF(@RecordCountTotal, 0), 1) * 1.00))
                               ) AS RatioOfRecordsUpdated
                    SELECT
                             UpdateLogSID,
                             RecordSet,
                             AggregateExposureSID,
                             ExposureSetSID,
                             PerilSetCode,
                             YearID,
                             GeographySID,
                             CountryCode,
                             CountryName,
                             CRESTACode,
                             CRESTAName,
                             AreaCode,
                             AreaName,
                             SubareaCode,
                             SubareaName,
                             CurrencyCode,
                             LOBCode,
                             GeoLevelCode,
                             CASE WHEN ISNULL(INSERTED_TotalInsuredValue, '''') <> ISNULL(DELETED_TotalInsuredValue, '''') THEN
                                      ''>>>>'' + CONVERT(VARCHAR(30), INSERTED_TotalInsuredValue)
                                  ELSE INSERTED_TotalInsuredValue
                             END AS INSERTED_TotalInsuredValue,
                             CASE WHEN ISNULL(INSERTED_TotalInsuredValue, '''') <> ISNULL(DELETED_TotalInsuredValue, '''') THEN
                                      ''>>>>'' + CONVERT(VARCHAR(30), DELETED_TotalInsuredValue)
                                  ELSE DELETED_TotalInsuredValue
                             END AS DELETED_TotalInsuredValue,
                             CASE WHEN ISNULL(INSERTED_RiskCount, '''') <> ISNULL(DELETED_RiskCount, '''') THEN ''>>>>'' + CONVERT(VARCHAR(30), INSERTED_RiskCount)
                                  ELSE INSERTED_RiskCount
                             END AS INSERTED_RiskCount,
                             CASE WHEN ISNULL(INSERTED_RiskCount, '''') <> ISNULL(DELETED_RiskCount, '''') THEN ''>>>>'' + CONVERT(VARCHAR(30), DELETED_RiskCount)
                                  ELSE DELETED_RiskCount
                             END AS DELETED_RiskCount,
                             CASE WHEN ISNULL(INSERTED_Premium, '''') <> ISNULL(DELETED_Premium, '''') THEN ''>>>>'' + CONVERT(VARCHAR(30), INSERTED_Premium)
                                  ELSE INSERTED_Premium
                             END AS INSERTED_Premium,
                             CASE WHEN ISNULL(INSERTED_Premium, '''') <> ISNULL(DELETED_Premium, '''') THEN ''>>>>'' + CONVERT(VARCHAR(30), DELETED_Premium)
                                  ELSE DELETED_Premium
                             END AS DELETED_Premium,
                             CASE WHEN ISNULL(INSERTED_Payroll, '''') <> ISNULL(DELETED_Payroll, '''') THEN ''>>>>'' + CONVERT(VARCHAR(30), INSERTED_Payroll)
                                  ELSE INSERTED_Payroll
                             END AS INSERTED_Payroll,
                             CASE WHEN ISNULL(INSERTED_Payroll, '''') <> ISNULL(DELETED_Payroll, '''') THEN ''>>>>'' + CONVERT(VARCHAR(30), DELETED_Payroll)
                                  ELSE DELETED_Payroll
                             END AS DELETED_Payroll,
                             DateEntered
                    FROM     #UpdateLog
                    ORDER BY UpdateLogSID
                END
            -- PRINT END OF PROC
            IF @Debug = 1
                EXEC @Result = AIRProject.dbo.pCOMMON_PrintVariable
                    '': END OF '',
                    @SPName
            RETURN @Result
        END TRY
        BEGIN CATCH
            -- re-raise the error to be caught in the calling process
            EXECUTE @Result = AIRProject.dbo.pReThrowError
                @SPName,
                @Debug
        END CATCH;
    END; -- OF PROC
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pCREPS_GetProgramSourceInure]'
GO
IF OBJECT_ID(N'[dbo].[pCREPS_GetProgramSourceInure]', 'P') IS NOT NULL
EXEC sp_executesql N' /******************************************************************************************************
Object: dbo.pCREPS_GetProgramSourceInure  
Description:	Get the list of Reinsurance program relationships 
SPExposedToEntities : 01-25-2017
*******************************************************************************************************/
ALTER PROCEDURE [dbo].[pCREPS_GetProgramSourceInure]
	@TargetProgramSID INT,	
	@BusinessUnitSID int = 1,
	@Debug BIT =0
AS
BEGIN
	SET NOCOUNT ON
	BEGIN TRY
		DECLARE @Result INT
		DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		;WITH RelationTree AS (
			SELECT 0 AS ReinsuranceProgramSubjectSID
				, @TargetProgramSID AS [ReinsuranceProgramSourceInureSID]
				, CAST(NULL as bit) AS IsSource 
				, 0 AS treelevel  
			UNION ALL
			SELECT 
				r.ReinsuranceProgramSubjectSID
				, r.ReinsuranceProgramSourceInureSID
				, r.IsSource 
				, treelevel + 1
			FROM RelationTree  t
			JOIN AIRExposureRe.dbo.[tReinsuranceProgramSourceInure] r ON t.[ReinsuranceProgramSourceInureSID] = r.ReinsuranceProgramSubjectSID
			JOIN AIRExposureRe.dbo.[tReinsuranceProgram] p ON r.ReinsuranceProgramSourceInureSID=p.ReinsuranceProgramSID AND p.StatusCode=''A'' 
			JOIN AIRExposureRe.dbo.[tReinsuranceProgram] q ON r.ReinsuranceProgramSubjectSID=q.ReinsuranceProgramSID AND q.StatusCode=''A'' 
		)
		SELECT SI.ReinsuranceProgramSubjectSID, SI.ReinsuranceProgramSourceInureSID, SI.FinancialPerspectiveCode, SI.ParticipationAmount, SI.IsSource 
		FROM RelationTree T
		JOIN AIRExposureRe.dbo.[tReinsuranceProgramSourceInure] SI ON 
			T.ReinsuranceProgramSubjectSID = SI.ReinsuranceProgramSubjectSID
			AND t.ReinsuranceProgramSourceInureSID = SI.ReinsuranceProgramSourceInureSID
		
		
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pCREPS_GetProgramSourceInureNoChildrenForeignAssessment]'
GO
IF OBJECT_ID(N'[dbo].[pCREPS_GetProgramSourceInureNoChildrenForeignAssessment]', 'P') IS NOT NULL
EXEC sp_executesql N' 		
/******************************************************************************************************
Object: dbo.pCREPS_GetProgramSourceInureNoChildrenForeignAssessment  
Description:	Get the list of Reinsurance program relationships from TargetProgramSID without children from foreign assessment programs
				Implement the same logic and validation from CREPS UI
SPExposedToEntities : 11-05-2019
*******************************************************************************************************/
ALTER 
-- ALTER 
PROCEDURE [dbo].[pCREPS_GetProgramSourceInureNoChildrenForeignAssessment]
	@TargetProgramSID INT,	
	@BusinessUnitSID int = 1,
	@Debug BIT =0
AS
BEGIN
	SET NOCOUNT ON
	BEGIN TRY
		DECLARE @Result INT
		DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
		IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
		;WITH RelationTree AS (
			SELECT 0 AS ReinsuranceProgramSubjectSID
				, @TargetProgramSID AS [ReinsuranceProgramSourceInureSID]
				, CAST(NULL as bit) AS IsSource 
				, 0 as CompanySIDSubject
				, (SELECT CompanySID FROM AIRExposureRe.dbo.[tReinsuranceProgram]  WHERE ReinsuranceProgramSID = @TargetProgramSID ) as CompanySIDInure
				, cast(0 as bit) as IsAssessmentProgramSubject 
				, (SELECT CAST(IsAssessmentProgram as bit) FROM AIRExposureRe.dbo.[tReinsuranceProgram]  WHERE ReinsuranceProgramSID = @TargetProgramSID ) as IsAssessmentInure
				, 0 AS treelevel  
				
			UNION ALL
			SELECT 
				r.ReinsuranceProgramSubjectSID
				, r.ReinsuranceProgramSourceInureSID
				, r.IsSource 
				, q.CompanySID as CompanySIDSubject
				, p.CompanySID as CompanySIDInure
				, q.IsAssessmentProgram  as IsAssessmentProgramSubject
				, cast(p.IsAssessmentProgram as bit) as IsAssessmentInure
				, treelevel + 1
			FROM RelationTree  t
			JOIN AIRExposureRe.dbo.[tReinsuranceProgramSourceInure] r ON t.[ReinsuranceProgramSourceInureSID] = r.ReinsuranceProgramSubjectSID
			JOIN AIRExposureRe.dbo.[tReinsuranceProgram] p ON r.ReinsuranceProgramSourceInureSID=p.ReinsuranceProgramSID 
				AND p.StatusCode=''A'' 
			JOIN AIRExposureRe.dbo.[tReinsuranceProgram] q ON r.ReinsuranceProgramSubjectSID=q.ReinsuranceProgramSID 
				AND q.StatusCode=''A'' 
				AND q.CompanySID = (SELECT CompanySID FROM AIRExposureRe.dbo.[tReinsuranceProgram]  WHERE ReinsuranceProgramSID = @TargetProgramSID )
		)
		SELECT DISTINCT SI.ReinsuranceProgramSubjectSID, SI.ReinsuranceProgramSourceInureSID, SI.FinancialPerspectiveCode, SI.ParticipationAmount, SI.IsSource
		FROM RelationTree T
		JOIN AIRExposureRe.dbo.[tReinsuranceProgramSourceInure] SI ON 
			T.ReinsuranceProgramSubjectSID = SI.ReinsuranceProgramSubjectSID
			AND t.ReinsuranceProgramSourceInureSID = SI.ReinsuranceProgramSourceInureSID
		
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug
	END CATCH;
	IF @Debug = 1 EXEC dbo.pCOMMON_PrintVariable '': END OF '', @SPName
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pCREPS_GetSourceInureByProgram]'
GO
IF OBJECT_ID(N'[dbo].[pCREPS_GetSourceInureByProgram]', 'P') IS NOT NULL
EXEC sp_executesql N' 		
/******************************************************************************************************
Object: dbo.pCREPS_GetSourceInureByProgram  
Description:	Get the records from tReinsuranceProgramSourceInure based on the company from the TargetProgramSID
SPExposedToEntities : 02-07-2017
*******************************************************************************************************/
ALTER PROCEDURE [dbo].[pCREPS_GetSourceInureByProgram]
	@TargetProgramSID int,
	@CompanySID INT = 0,	
	@BusinessUnitSID int = 1,
	@Debug BIT = FALSE
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT
		
	BEGIN TRY
		
		DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	
		IF @Debug = 1 
		 BEGIN
			EXEC dbo.pCOMMON_PrintVariable '': START OF '', @SPName
			EXEC dbo.pCOMMON_PrintVariable '': ReinsuraceProgramSID - '', @TargetProgramSID
		 END
		 
		IF @TargetProgramSID = 0 and @CompanySID = 0
			RAISERROR (''TargetProgramSID and CompanySID cannot be zero.'', 
               16, -- Severity.  
               1 -- State.  
               );   
		IF @TargetProgramSID <> 0
		BEGIN
			SELECT 
				SI.ReinsuranceProgramSubjectSID,
				SI.ReinsuranceProgramSourceInureSID,
				SI.FinancialPerspectiveCode,
				SI.ParticipationAmount,
				SI.IsSource
			FROM 
				AIRExposureRe.dbo.tReinsuranceProgramSourceInure SI WITH(NOLOCK)
			JOIN 
				AIRExposureRe.dbo.tReinsuranceProgram RP WITH(NOLOCK) 
				ON SI.ReinsuranceProgramSubjectSID = RP.ReinsuranceProgramSID
				AND RP.StatusCode=''A''
			WHERE 
				EXISTS(	SELECT 1 
						FROM AIRExposureRe.dbo.tReinsuranceProgram P WITH(NOLOCK) 
						WHERE P.reinsuranceprogramSID = @TargetProgramSID and  RP.CompanySID = P.CompanySID AND P.StatusCode=''A'')
		END
		ELSE
		BEGIN
			SELECT 
					SI.ReinsuranceProgramSubjectSID,
					SI.ReinsuranceProgramSourceInureSID,
					SI.FinancialPerspectiveCode,
					SI.ParticipationAmount,
					SI.IsSource
				FROM 
					AIRExposureRe.dbo.tReinsuranceProgramSourceInure SI WITH(NOLOCK)
				JOIN 
					AIRExposureRe.dbo.tReinsuranceProgram RP WITH(NOLOCK) 
					ON SI.ReinsuranceProgramSubjectSID = RP.ReinsuranceProgramSID
					AND RP.StatusCode=''A''
				WHERE 
					EXISTS(
							SELECT 1 
							FROM airexposurere.dbo.tReinsuranceProgram p
							WHERE p.ReinsuranceProgramSID = si.ReinsuranceProgramSubjectSID
							AND P.StatusCode=''A''
							AND p.CompanySID = @CompanySID 
						  )
		END
	END TRY
	BEGIN CATCH
		-- re-raise the error to be caught in the calling process
		EXECUTE @Result = [dbo].pReThrowError @SPName, @Debug
	END CATCH;
	IF @Debug = 1 EXEC [dbo].pCOMMON_PrintVariable '': END OF '', @SPName
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pDELETE_ReGetCLATableSize]'
GO
IF OBJECT_ID(N'[dbo].[pDELETE_ReGetCLATableSize]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
DATE :					03-2020
OBJECT:					dbo.pDELETE_ReGetCLATableSize
DESCRIPTION:			Returns CLAs Table sizes based on compatibility
ExposedToEntities:		NO
ResultView: NA
DECLARE @ModelCompatibility TINYINT = 2,
        @Debug BIT = 0;
EXEC dbo.pDELETE_ReGetCLATableSize @ModelCompatibility, @Debug				
**********************************************************************************************************/
ALTER 
-- ALTER 
PROC [dbo].[pDELETE_ReGetCLATableSize]
    @ModelCompatibility TINYINT = 0,
    @Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
    -- VARIABLES 
    DECLARE @DataSourceName sysname;
    DECLARE @SQLStmt VARCHAR(max) = '''';
    SET @DataSourceName = '''';
    -- DROP/CREATE TEMP TABLES 
    IF OBJECT_ID(''tempdb.dbo.#DBLossSet'') IS NOT NULL
        DROP TABLE #DBLossSet;
    IF OBJECT_ID(''tempdb.dbo.#DB'') IS NOT NULL
        DROP TABLE #DB;
    IF OBJECT_ID(''tempdb.dbo.#tBulkCLA_DATA'') IS NOT NULL
        DROP TABLE #tBulkCLA_DATA;
    IF OBJECT_ID(''tempdb.dbo.#tFinalCLA_DATA'') IS NOT NULL
        DROP TABLE #tFinalCLA_DATA;
	CREATE TABLE #tDintinctFinalCLA_DATA
    (
        CompanyLossSetSID INT
      , modelcode SMALLINT
      , modelversion VARCHAR(50)
      , DataSourceName VARCHAR(100)
      , table_name VARCHAR(100)
      , data_size VARCHAR(10)
    );
    /*
        Check if the tCompanyCLASizes is populated, in not, call SP to populate it
    */ 
	IF @Debug = 1 
		SELECT  * FROM dbo.tCompanyCLASizes
    /* pGet_CLASizeByCompany Call */
        EXEC AIRExposureRe.dbo.pGet_CLASizeByCompany @Debug
	/*
	 Debug 
	*/
	
	IF @DEBUG = 1 
	    SELECT DISTINCT CompanyLossSetSID
             , modelcode
             , modelversion
             , DataSourceName
             , table_name
             , CLASizeinMB 
	    FROM #tFinalCLA_DATA 
	/*
	 move data to final table 
	*/
	
	INSERT INTO #tDintinctFinalCLA_DATA
	SELECT DISTINCT CompanyLossSetSID
         , modelcode
         , modelversion
         , DataSourceName
         , table_name
         , CLASizeinMB 
	FROM dbo.tCompanyCLASizes 
	
;WITH CTESUpportedModel
    AS (SELECT m.CurrenCLFSupportedModelSID,
               m.ModelCode,
               m.ModelName,
               m.ModelVersion,
               LatestSupportCLFVersion,
               LEFT(m.LatestSupportCLFVersion, CHARINDEX(''.'', m.LatestSupportCLFVersion, 1) - 1) major1,
               SUBSTRING(
                            SUBSTRING(
                                         m.LatestSupportCLFVersion,
                                         CHARINDEX(''.'', m.LatestSupportCLFVersion) + 1,
                                         LEN(m.LatestSupportCLFVersion)
                                     ),
                            1,
                            CHARINDEX(
                                         ''.'',
                                         SUBSTRING(
                                                      m.LatestSupportCLFVersion,
                                                      CHARINDEX(''.'', m.LatestSupportCLFVersion) + 1,
                                                      LEN(m.LatestSupportCLFVersion)
                                                  )
                                     ) - 1
                        ) minor1,
               RIGHT(m.LatestSupportCLFVersion, CHARINDEX(''.'', REVERSE(m.LatestSupportCLFVersion), 1) - 1) patch1,
               IsArchive
        FROM AIRReference.dbo.tCurrenCLFSupportedModel m
        WHERE m.IsArchive = CASE
                                WHEN @ModelCompatibility = 1 THEN
                                    0
                                WHEN @ModelCompatibility = 2 THEN
                                    1
                                WHEN @ModelCompatibility IS NULL
                                     OR @ModelCompatibility = 0 THEN
                                    IsArchive
                                ELSE
                                    IsArchive
                            END),
		CLAs AS (
		SELECT tc.DataSourceName databasename,
           ts.table_name TableName,
           ts.data_size TotalSpaceMB,
           tc.CompanyLossAssociationSID,
           tc.CompanyLossSetSID,
           tc.CompanyLossSetName,
           ts.modelcode,
		   ts.ModelVersion,
		   LEFT(ts.ModelVersion, CHARINDEX(''.'', ts.ModelVersion, 1) - 1) major2,
               SUBSTRING(
                            SUBSTRING(ts.ModelVersion, CHARINDEX(''.'', ts.ModelVersion) + 1, LEN(ts.ModelVersion)),
                            1,
                            CHARINDEX(
                                         ''.'',
                                         SUBSTRING(
                                                      ts.ModelVersion,
                                                      CHARINDEX(''.'', ts.ModelVersion) + 1,
                                                      LEN(ts.ModelVersion)
                                                  )
                                     ) - 1
                        ) minor2,
               RIGHT(ts.ModelVersion, CHARINDEX(''.'', REVERSE(ts.ModelVersion), 1) - 1) patch2
    FROM #tDintinctFinalCLA_DATA ts
        INNER JOIN AIRExposureRe.dbo.tCompanyLossAssociation tc
            ON (
                   ts.datasourcename = tc.DataSourceName
                   AND ts.CompanyLossSetSID = tc.CompanyLossSetSID
               )
	WHERE tc.LossTypeCode = ''DB''		   
			   )
    -- RETRIVE FINAL DATA 
	INSERT INTO #tGetCLATableSize
    SELECT distinct ts.databasename,
           ts.TableName,
           ts.TotalSpaceMB,
           ts.CompanyLossAssociationSID,
           ts.CompanyLossSetSID,
           ts.CompanyLossSetName,
           ts.modelcode,
           ts.ModelVersion
    FROM CLAs ts
		INNER JOIN CTESUpportedModel sm 
			ON sm.ModelCode = ts.modelcode
	WHERE 
		  (CASE
               WHEN CAST(major2 AS INT)   > CAST(major1  AS INT) THEN 1
			   WHEN CAST(major2 AS INT)   < CAST(major1  AS INT) THEN 0 
               WHEN CAST(major2  AS INT) =  CAST(major1 AS INT)  THEN 
                   CASE
                       WHEN CAST(minor2 as INT) > CAST(minor1  AS INT) THEN 1
					   WHEN CAST(minor2 as INT) < CAST(minor1  AS INT) THEN 0
                       WHEN CAST(minor1  AS INT) = cast(minor2 AS INT) THEN
                           CASE
                               WHEN (CAST(patch2  AS INT) > CAST(patch1  AS INT)) THEN 1 -- ''1.1.1'' / ''1.1.1'' // ''1.1.1'' / ''1.1.1''
                               ELSE
                                 0
                           END
                       ELSE
                           0
                   END
			END
          ) = 1; 
        
END;
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pDELETE_ReGetCompanyLossData]'
GO
IF OBJECT_ID(N'[dbo].[pDELETE_ReGetCompanyLossData]', 'P') IS NOT NULL
EXEC sp_executesql N' /**********************************************************************************************************
DATE :					02-2020
OBJECT:					dbo.pDELETE_ReGetCompanyLossData
DESCRIPTION:			Returns CLF/CLA that based on the criteria lsited below
ExposedToEntities:		YES
ResultView: rvDELETE_ReGetCompanyLossData
DECLARE @CLFFolderName NVARCHAR(500) = ''\\Sdgtsaio3\airwork\UserClfFiles\'',
        @BusinessUnit SMALLINT = NULL,
        @InstalledDate DATETIME = NULL,         -- ''2016-10-19'',
        @ProgramExpirationDate DATETIME = NULL, --''2017-12-31'',
        @ModelCompatibility TINYINT = 0,
        @Debug BIT = 0;
EXECUTE dbo.pDELETE_ReGetCompanyLossData @CLFFolderName,
                                        @BusinessUnit,
                                        @InstalledDate,
                                        @ProgramExpirationDate,
                                        @ModelCompatibility,
                                        @Debug;						
**********************************************************************************************************/
ALTER
-- ALTER
PROC [dbo].[pDELETE_ReGetCompanyLossData]
   @CLFFolderName NVARCHAR(500) = NULL, 
    @BusinessUnit SMALLINT = NULL,
    @InstalledDate DATETIME = NULL,
    @ProgramExpirationDate DATETIME = NULL,
    @ModelCompatibility TINYINT = NULL,
    @Debug BIT = 0
AS
BEGIN -- OF PROC
    DECLARE @DirCmd VARCHAR(300) = ''dir '',
			@SQLStmt NVARCHAR(MAX) = '''' ,
			@SQLStmtParameters NVARCHAR(MAX) = '''',
			@Result BIT = 0
    SET @DirCmd = @DirCmd + @CLFFolderName + '' /b'';
    ---------------------------------------------------------------------------------------------
    -- Drop temp tables
    ---------------------------------------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#ListofCLFWithSizes'') IS NOT NULL
        DROP TABLE #ListofCLFWithSizes;
    IF OBJECT_ID(''tempdb..#ListofCLFsParent'') IS NOT NULL
        DROP TABLE #ListofCLFsParent;
    IF OBJECT_ID(''tempdb..#ListofCLFsChild'') IS NOT NULL
        DROP TABLE #ListofCLFsChild;
    IF OBJECT_ID(''tempdb..#ListofCLA'') IS NOT NULL
        DROP TABLE #ListofCLA;
    IF OBJECT_ID(''tempdb..#tGetCLATableSize'') IS NOT NULL
        DROP TABLE #tGetCLATableSize;
    IF OBJECT_ID(''tempdb..#FileData'') IS NOT NULL
        DROP TABLE #FileData;
	IF OBJECT_ID(''tempdb..#NonOrphanCLFsParent'') IS NOT NULL
        DROP TABLE #NonOrphanCLFsParent;
    IF OBJECT_ID(''tempdb..#NonOrphanCLFsChild'') IS NOT NULL
        DROP TABLE #NonOrphanCLFsChild;
    IF OBJECT_ID(''tempdb..#OrphanCLFsParent'') IS NOT NULL
        DROP TABLE #OrphanCLFsParent;
    IF OBJECT_ID(''tempdb..#OrphanCLFsChild'') IS NOT NULL
        DROP TABLE #OrphanCLFsChild;
    ---------------------------------------------------------------------------------------------
    -- Create temp tables
    ---------------------------------------------------------------------------------------------
		CREATE TABLE #NonOrphanCLFsParent
			(
			CompanyLossSetName VARCHAR(255)  NULL,
			CompanyLossAssociationSID INT  NULL,
			CompanyName VARCHAR(765)  NULL,
			CompanySID INT  NULL,
			ProgramID VARCHAR(100),
			ReinsuranceProgramSID INT  NULL,
			ExpirationDate DATE,
			PortfolioName VARCHAR(255)  NULL,
			ModelCode SMALLINT  NULL,
			CreatedDate DATE,
			Author VARCHAR(60),
			CatalogTypeCode INT  NULL,
			BaseName VARCHAR(255)  NULL,
			CLFTypeCode SMALLINT  NULL,
			LossFileExt VARCHAR(10)  NULL,
			LossTypeCode VARCHAR(10),
			productversion VARCHAR(30),
			ModelVersion VARCHAR(30)  NULL
			)
				CREATE TABLE #NonOrphanCLFsChild
			(
			CompanyLossSetName VARCHAR(255)  NULL,
			CompanyLossAssociationSID INT  NULL,
			CompanyName VARCHAR(765)  NULL,
			CompanySID INT  NULL,
			ProgramID VARCHAR(100),
			ReinsuranceProgramSID INT  NULL,
			ExpirationDate DATE,
			PortfolioName VARCHAR(255)  NULL,
			ModelCode SMALLINT  NULL,
			CreatedDate DATE,
			Author VARCHAR(60),
			CatalogTypeCode INT  NULL,
			BaseName VARCHAR(255)  NULL,
			CLFTypeCode SMALLINT  NULL,
			LossFileExt VARCHAR(10)  NULL,
			LossTypeCode VARCHAR(10),
			productversion VARCHAR(30),
			ModelVersion VARCHAR(30)  NULL
			)
				CREATE TABLE #OrphanCLFsParent
			(
			CompanyLossSetName VARCHAR(255)  NULL,
			CompanyLossAssociationSID INT  NULL,
			CompanyName VARCHAR(765)  NULL,
			CompanySID INT  NULL,
			ProgramID VARCHAR(100),
			ReinsuranceProgramSID INT  NULL,
			ExpirationDate DATE,
			PortfolioName VARCHAR(255)  NULL,
			ModelCode SMALLINT  NULL,
			CreatedDate DATE,
			Author VARCHAR(60),
			CatalogTypeCode INT  NULL,
			BaseName VARCHAR(255)  NULL,
			CLFTypeCode SMALLINT  NULL,
			LossFileExt VARCHAR(10)  NULL,
			LossTypeCode VARCHAR(10),
			productversion VARCHAR(30),
			ModelVersion VARCHAR(30)  NULL
			)
				CREATE TABLE #OrphanCLFsChild
			(
			CompanyLossSetName VARCHAR(255)  NULL,
			CompanyLossAssociationSID INT  NULL,
			CompanyName VARCHAR(765)  NULL,
			CompanySID INT  NULL,
			ProgramID VARCHAR(100),
			ReinsuranceProgramSID INT  NULL,
			ExpirationDate DATE,
			PortfolioName VARCHAR(255)  NULL,
			ModelCode SMALLINT  NULL,
			CreatedDate DATE,
			Author VARCHAR(60),
			CatalogTypeCode INT  NULL,
			BaseName VARCHAR(255)  NULL,
			CLFTypeCode SMALLINT  NULL,
			LossFileExt VARCHAR(10)  NULL,
			LossTypeCode VARCHAR(10),
			productversion VARCHAR(30),
			ModelVersion VARCHAR(30)  NULL
			)
    -- Create a table to hold a list of folders and file info
    CREATE TABLE #FileData (CompleteFileName VARCHAR(400), FileName VARCHAR(400), SizeInMB DECIMAL(13,2))
	-- Create a table to hold a list of table names
    CREATE TABLE #tGetCLATableSize
    (
        databasename NVARCHAR(128),
        tableName NVARCHAR(128),
        totalSpaceKB VARCHAR(25),
        CompanyLossAssociationSID INT,
        CompanyLossSetSID INT,
        CompanyLossSetName VARCHAR(255),
        modelcode SMALLINT,
        modelversion VARCHAR(50)
    );
    ---------------------------------------------------------------------------------------------
    -- Retrive CLA table sizes
    ---------------------------------------------------------------------------------------------
    --INSERT INTO #tGetCLATableSize
    EXEC AIRExposureRe.dbo.pDELETE_ReGetCLATableSize @ModelCompatibility, @Debug;
    ---------------------------------------------------------------------------------------------
    -- Retrive CLF Files from the disk + sizes
    ---------------------------------------------------------------------------------------------
	--INSERT INTO #FileData (CompleteFileName, FileName, SizeInMB)
    EXEC AIRExposureRe.dbo.pDELETE_GetListOfFileWithSize @CLFFolderName;
    ---------------------------------------------------------------------------------------------
    -- Retrive CLA data from different databasees
    ---------------------------------------------------------------------------------------------
    SET @SQLStmt = N''SELECT DISTINCT
           tca.CompanyLossSetName,
           tca.CompanyLossAssociationSID,
           tc.CompanyName,
           tc.CompanySID,
           trp.ProgramID,
           trp.ReinsuranceProgramSID,
           CAST(trp.ExpirationDate AS DATE) AS ExpirationDate,
           tp.PortfolioName,
           s.modelcode,
           CAST(tca.CreatedDate AS DATE) AS CreatedDate,
           tca.Author,
           tca.CatalogTypeCode,
           s.tableName BaseName,
           tca.CatalogTypeCode CLFTypeCode,
           ''''CLA'''' LossFileExt,
           tca.LossTypeCode,
           (SELECT Version FROM AIRExposureRe.dbo.tDBVersion) AS productversion,
           s.totalSpaceKB FileSize,
           s.modelversion
    INTO #ListofCLA
    FROM #tGetCLATableSize s
        INNER JOIN AIRExposureRe.dbo.tCompanyLossAssociation tca
            ON tca.CompanyLossAssociationSID = s.CompanyLossAssociationSID
               AND tca.CompanyLossSetSID = s.CompanyLossSetSID
        INNER JOIN AIRExposureRe..tCompany tc
            ON tc.CompanySID = tca.CompanySID
        LEFT JOIN AIRExposureRe.dbo.tReinsuranceProgram trp
            ON trp.CompanySID = tc.CompanySID
		INNER JOIN AIRExposureRe.dbo.tReinsuranceProgramTargetXRef trpx
            ON trpx.CompanyLossAssociationSID = tca.CompanyLossAssociationSID
			AND trpx.ReinsuranceProgramSID = trp.ReinsuranceProgramSID
        LEFT JOIN AIRExposureRe..tReinsuranceTreaty trt
            ON trt.ReinsuranceProgramSID = trp.ReinsuranceProgramSID
        LEFT JOIN AIRExposureRe.dbo.tPortfolioReinsuranceTreaty tprt
            ON tprt.ReinsuranceTreatySID = trt.ReinsuranceTreatySID
        LEFT JOIN AIRExposureRe..tPortfolio tp
            ON tp.PortfolioSID = tprt.PortfolioSID 
		WHERE LossTypeCode = ''''DB'''' AND tc.BusinessUnitSID = ISNULL(@BusinessUnit, tc.BusinessUnitSID)
          AND CAST(trp.ExpirationDate AS DATE) <= ISNULL(CAST(@ProgramExpirationDate AS DATE), CAST(trp.ExpirationDate AS DATE))
          AND CAST(tca.CreatedDate AS DATE) <= ISNULL(CAST(@InstalledDate AS DATE), CAST(tca.CreatedDate AS DATE)) 
		  and tca.StatusCode =''''A'''' ''
    ---------------------------------------------------------------------------------------------
    -- Retrive CLF data Parent
    ---------------------------------------------------------------------------------------------
    SET @SQLStmt = @SQLStmt + N''
 INSERT INTO #NonOrphanCLFsParent 
 SELECT DISTINCT
           tcla.CompanyLossSetName,
           tcla.CompanyLossAssociationSID,
           tc.CompanyName,
           tc.CompanySID,
           trp.ProgramID,
           trp.ReinsuranceProgramSID,
           CAST(trp.ExpirationDate AS DATE) AS ExpirationDate,
           tp.PortfolioName,
           tcc.ModelCode,
           CAST(tcla.CreatedDate AS DATE) AS CreatedDate,
           tcla.Author,
           tcla.CatalogTypeCode,
           tcc.BaseName,
           tcc.CLFTypeCode,
           tcc.LossFileExt,
           tcla.LossTypeCode,
           (SELECT Version FROM AIRExposureRe.dbo.tDBVersion) AS productversion,
           tcc.ModelVersion
    FROM AIRExposureRe.dbo.tCompanyLossAssociation tcla '' + 
	CASE WHEN @ModelCompatibility IN (1,2) THEN ''
		INNER JOIN (
            SELECT DISTINCT ModelCode,
                   CLFCatalogModelversion,
                   CompanyLossAssociationSID
            FROM dbo.fDELETE_ReGetSupportedCLF(@ModelCompatibility)
        ) fcla
            ON fcla.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID '' ELSE '''' END + ''
        INNER JOIN AIRExposureRe.dbo.tCompany tc
            ON tc.CompanySID = tcla.CompanySID
        INNER JOIN AIRExposureRe.dbo.tReinsuranceProgram trp -- do we need left join because there are CLF that are not assiated with CLAs and Programs?
            ON trp.CompanySID = tc.CompanySID
               AND trp.BusinessUnitSID = tc.BusinessUnitSID -- Pass me the BU from service?
        INNER JOIN AIRExposureRe..tReinsuranceTreaty trt
            ON trt.ReinsuranceProgramSID = trp.ReinsuranceProgramSID
        INNER JOIN AIRExposureRe.dbo.tCLFCatalog tcc
            ON tcc.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID
        INNER JOIN AIRExposureRe.dbo.tReinsuranceProgramTargetXRef trpx
            ON trpx.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID
               AND trpx.ReinsuranceProgramSID = trp.ReinsuranceProgramSID
        LEFT JOIN AIRExposureRe.dbo.tPortfolioReinsuranceTreaty tprt
            ON tprt.ReinsuranceTreatySID = trt.ReinsuranceTreatySID
        LEFT JOIN AIRExposureRe.dbo.tPortfolio tp
            ON tp.PortfolioSID = tprt.PortfolioSID 
			WHERE tcla.LossTypeCode <> ''''DB''''
			and tcla.StatusCode =''''A''''
          AND tcla.ParentCompanyLossAssociationSID IS NULL 
		  AND tc.BusinessUnitSID = ISNULL(@BusinessUnit, tc.BusinessUnitSID)
          AND CAST(trp.ExpirationDate AS DATE) <= ISNULL(CAST(@ProgramExpirationDate AS DATE), CAST(trp.ExpirationDate AS DATE))
          AND CAST(tcla.CreatedDate AS DATE) <= ISNULL(CAST(@InstalledDate AS DATE), CAST(tcla.CreatedDate AS DATE))
INSERT INTO #NonOrphanCLFsChild 
SELECT DISTINCT
    tcla.CompanyLossSetName,
    tcla.CompanyLossAssociationSID,
    tc.CompanyName,
    tc.CompanySID,
    trp.ProgramID,
    trp.ReinsuranceProgramSID,
    CAST(trp.ExpirationDate AS DATE) AS ExpirationDate,
    tp.PortfolioName,
    tcc.ModelCode,
    CAST(tcla.CreatedDate AS DATE) AS CreatedDate,
    tcla.Author,
    tcla.CatalogTypeCode,
    tcc.BaseName,
    tcc.CLFTypeCode,
    tcc.LossFileExt,
    tcla.LossTypeCode,
    (SELECT Version FROM AIRExposureRe.dbo.tDBVersion) AS productversion,
    tcc.ModelVersion 
FROM AIRExposureRe.dbo.tCompanyLossAssociation tcla '' + 
	CASE WHEN @ModelCompatibility IN (1,2) THEN '' INNER JOIN
        (   SELECT DISTINCT ModelCode,
                   CLFCatalogModelversion,
                   CompanyLossAssociationSID
            FROM dbo.fDELETE_ReGetSupportedCLF(@ModelCompatibility)
        ) fcla
            ON fcla.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID '' ELSE '''' END + ''
        INNER JOIN AIRExposureRe.dbo.tCompany tc
            ON tc.CompanySID = tcla.CompanySID
        INNER JOIN AIRExposureRe.dbo.tReinsuranceProgram trp -- do we need left join because there are CLF that are not assiated with CLAs and Programs?
            ON trp.CompanySID = tc.CompanySID
               AND trp.BusinessUnitSID = tc.BusinessUnitSID -- Pass me the BU from service?
        INNER JOIN AIRExposureRe..tReinsuranceTreaty trt
            ON trt.ReinsuranceProgramSID = trp.ReinsuranceProgramSID
        INNER JOIN AIRExposureRe.dbo.tCLFCatalog tcc
            ON tcc.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID
        INNER JOIN AIRExposureRe.dbo.tReinsuranceProgramTargetXRef trpx
            ON trpx.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID
               AND trpx.ReinsuranceProgramSID = trp.ReinsuranceProgramSID
        LEFT JOIN AIRExposureRe.dbo.tPortfolioReinsuranceTreaty tprt
            ON tprt.ReinsuranceTreatySID = trt.ReinsuranceTreatySID
        LEFT JOIN AIRExposureRe.dbo.tPortfolio tp
            ON tp.PortfolioSID = tprt.PortfolioSID 
			WHERE tcla.LossTypeCode <> ''''DB''''
			AND tcla.StatusCode =''''A''''
          AND tcla.ParentCompanyLossAssociationSID IS NOT NULL 
		  AND tc.BusinessUnitSID = ISNULL(@BusinessUnit, tc.BusinessUnitSID)
          AND CAST(trp.ExpirationDate AS DATE) <= ISNULL(CAST(@ProgramExpirationDate AS DATE), CAST(trp.ExpirationDate AS DATE))
          AND CAST(tcla.CreatedDate AS DATE) <= ISNULL(CAST(@InstalledDate AS DATE), CAST(tcla.CreatedDate AS DATE))
INSERT INTO #OrphanCLFsParent 
SELECT DISTINCT
       tcla.CompanyLossSetName
     , tcla.CompanyLossAssociationSID
     , tc.CompanyName
     , tc.CompanySID
     , NULL ProgramID
     , NULL ReinsuranceProgramSID
     , CAST('''''''' AS DATE) as ExpirationDate
     , NULL PortfolioName
     , tcc.ModelCode
     , CAST(tcla.CreatedDate as date) AS CreatedDate
     , tcla.Author
     , tcla.CatalogTypeCode
     , tcc.BaseName
     , tcc.CLFTypeCode
     , tcc.LossFileExt
     , tcla.LossTypeCode
     , (SELECT VERSION FROM AIRExposureRe.dbo.tDBVersion) AS productversion
     , tcc.ModelVersion 
FROM AIRExposureRe.dbo.tCompanyLossAssociation tcla '' + 
	CASE WHEN @ModelCompatibility IN (1,2) THEN '' INNER JOIN
        (
            SELECT DISTINCT ModelCode,
                   CLFCatalogModelversion,
                   CompanyLossAssociationSID
            FROM dbo.fDELETE_ReGetSupportedCLF(@ModelCompatibility)
        ) fcla
            ON fcla.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID '' ELSE '''' END + ''
INNER JOIN AIRExposureRe.dbo.tCompany                     tc
        ON tc.CompanySID = tcla.CompanySID
INNER JOIN AIRExposureRe.dbo.tCLFCatalog                  tcc
        ON tcc.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID
LEFT JOIN AIRExposureRe.dbo.tReinsuranceProgramTargetXRef trpx
        ON trpx.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID
WHERE trpx.ReinsuranceProgramSID IS NULL
      AND tcla.ParentCompanyLossAssociationSID IS NULL
	  AND tc.BusinessUnitSID = isnull(@BusinessUnit, tc.BusinessUnitSID)
      AND CAST(tcla.CreatedDate AS DATE) <= ISNULL(CAST(@InstalledDate AS DATE), CAST(tcla.CreatedDate AS DATE))
	INSERT INTO #OrphanCLFsChild 
	SELECT DISTINCT
		   tcla.CompanyLossSetName
		 , tcla.CompanyLossAssociationSID
		 , tc.CompanyName
		 , tc.CompanySID
		 , NULL ProgramID
		 , NULL ReinsuranceProgramSID
		 , CAST('''''''' AS DATE) AS ExpirationDate
		 , NULL PortfolioName
		 , tcc.ModelCode
		 , CAST(tcla.CreatedDate AS DATE) AS CreatedDate
		 , tcla.Author
		 , tcla.CatalogTypeCode
		 , tcc.BaseName
		 , tcc.CLFTypeCode
		 , tcc.LossFileExt
		 , tcla.LossTypeCode
		 , (SELECT Version FROM AIRExposureRe.dbo.tDBVersion) AS productversion
		 , tcc.ModelVersion
	FROM AIRExposureRe.dbo.tCompanyLossAssociation tcla '' + 
		CASE WHEN @ModelCompatibility IN (1,2) THEN '' INNER JOIN
			(
				SELECT DISTINCT ModelCode,
					   CLFCatalogModelversion,
					   CompanyLossAssociationSID
				FROM dbo.fDELETE_ReGetSupportedCLF(@ModelCompatibility)
			) fcla
				ON fcla.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID '' ELSE '''' END + ''
	 INNER JOIN AIRExposureRe.dbo.tCompany                      tc
			ON tc.CompanySID = tcla.CompanySID
	 INNER JOIN AIRExposureRe.dbo.tCLFCatalog                   tcc
			ON tcc.CompanyLossAssociationSID = tcla.CompanyLossAssociationSID
	INNER JOIN #OrphanCLFsParent ocp
			ON tcla.parentCompanyLossAssociationSID = ocp.CompanyLossAssociationSID
	WHERE tcla.ParentCompanyLossAssociationSID IS NOT NULL
	AND tc.BusinessUnitSID = ISNULL(@BusinessUnit, tc.BusinessUnitSID)
    AND CAST(tcla.CreatedDate AS DATE) <= ISNULL(CAST(@InstalledDate AS DATE), CAST(tcla.CreatedDate AS DATE))	
	''
SET @SQLStmt = @SQLStmt + N''
SELECT DISTINCT 
	   CompanyLossSetName
     , CompanyLossAssociationSID
     , CompanyName
     , CompanySID
     , ProgramID
     , ReinsuranceProgramSID
     , ExpirationDate
     , PortfolioName
     , ModelCode
     , CreatedDate
     , Author
     , CatalogTypeCode
     , BaseName
     , CLFTypeCode
     , LossFileExt
     , LossTypeCode
     , productversion
     , ModelVersion
INTO #ListofCLFsParent
FROM (
SELECT CompanyLossSetName
     , CompanyLossAssociationSID
     , CompanyName
     , CompanySID
     , ProgramID
     , ReinsuranceProgramSID
     , ExpirationDate
     , PortfolioName
     , ModelCode
     , CreatedDate
     , Author
     , CatalogTypeCode
     , BaseName
     , CLFTypeCode
     , LossFileExt
     , LossTypeCode
     , productversion
     , ModelVersion	
FROM #NonOrphanCLFsParent
UNION 
SELECT CompanyLossSetName
     , CompanyLossAssociationSID
     , CompanyName
     , CompanySID
     , ProgramID
     , ReinsuranceProgramSID
     , ExpirationDate
     , PortfolioName
     , ModelCode
     , CreatedDate
     , Author
     , CatalogTypeCode
     , BaseName
     , CLFTypeCode
     , LossFileExt
     , LossTypeCode
     , productversion
     , ModelVersion
FROM #NonOrphanCLFsChild
UNION 
SELECT CompanyLossSetName
     , CompanyLossAssociationSID
     , CompanyName
     , CompanySID
     , ProgramID
     , ReinsuranceProgramSID
     , ExpirationDate
     , PortfolioName
     , ModelCode
     , CreatedDate
     , Author
     , CatalogTypeCode
     , BaseName
     , CLFTypeCode
     , LossFileExt
     , LossTypeCode
     , productversion
     , ModelVersion
FROM #OrphanCLFsChild
UNION 
SELECT CompanyLossSetName
     , CompanyLossAssociationSID
     , CompanyName
     , CompanySID
     , ProgramID
     , ReinsuranceProgramSID
     , ExpirationDate
     , PortfolioName
     , ModelCode
     , CreatedDate
     , Author
     , CatalogTypeCode
     , BaseName
     , CLFTypeCode
     , LossFileExt
     , LossTypeCode
     , productversion
     , ModelVersion
FROM #OrphanCLFsParent
) AS allclfs ''	
---------------------------------------------------------------------------------------------
-- Retrive CLF data Childs
---------------------------------------------------------------------------------------------
	SET @SQLStmt = @SQLStmt + N'' SELECT DISTINCT
       tca.CompanyLossSetName,
       tca.CompanyLossAssociationSID,
       tpr.CompanyName,
       tpr.CompanySID,
       tpr.ProgramID,
       tpr.ReinsuranceProgramSID,
       ExpirationDate,
       tpr.PortfolioName,
       tclf.ModelCode,
       tpr.CreatedDate,
       tca.Author,
       tca.CatalogTypeCode,
       tclf.BaseName,
       tpr.CLFTypeCode,
       tclf.LossFileExt,
       tca.LossTypeCode,
       --tpr.IsDemandSurgeOn,
       productversion,
       tclf.ModelVersion
INTO #ListofCLFsChild
FROM AIRExposureRe..tCompanyLossAssociation tca '' + 
	CASE WHEN @ModelCompatibility IN (1,2) THEN '' INNER JOIN
        (
            SELECT DISTINCT ModelCode,
                   CLFCatalogModelversion,
                   CompanyLossAssociationSID
            FROM dbo.fDELETE_ReGetSupportedCLF(@ModelCompatibility)
        ) fcla
            ON fcla.CompanyLossAssociationSID = tca.CompanyLossAssociationSID '' ELSE '''' END + ''
    INNER JOIN #ListofCLFsParent tpr
        ON tpr.CompanyLossAssociationSID = tca.ParentCompanyLossAssociationSID
    INNER JOIN AIRExposureRe.dbo.tCLFCatalog tclf
        ON tclf.CompanyLossAssociationSID = tca.CompanyLossAssociationSID
 WHERE tca.LossTypeCode <> ''''DB'''' AND tca.ParentCompanyLossAssociationSID IS NOT NULL 
 and tca.StatusCode =''''A'''' '' 
---------------------------------------------------------------------------------------------
-- Union all CLF data
---------------------------------------------------------------------------------------------
SET @SQLStmt = @SQLStmt + N''
SELECT CompanyLossSetName,
		CompanyLossAssociationSID,
		CompanyName,
		ProgramID,
		ReinsuranceProgramSID,
		ExpirationDate,
		PortfolioName,
		FileSize CLFSize,
		BaseName FileName,
		CASE WHEN CatalogTypeCode = 3 THEN modelcode ELSE NULL END StochasticModelID,
		CASE WHEN CatalogTypeCode = 9 THEN modelcode ELSE NULL END HistModelID,
		CASE WHEN CatalogTypeCode = 11 THEN modelcode ELSE NULL END RDSModelID,
		modelcode IncompatibleModelID,
		CreatedDate,
		Author,
		LossFileExt
FROM #ListofCLA
UNION
SELECT ALLCLFs.CompanyLossSetName,
		ALLCLFs.CompanyLossAssociationSID,
		CompanyName,
		ALLCLFs.ProgramID,
		ALLCLFs.ReinsuranceProgramSID,
		ALLCLFs.ExpirationDate,
		ALLCLFs.PortfolioName,
		clfs.SizeInMB CLFSize,
		clfs.CompleteFileName FileName,
		CASE WHEN CatalogTypeCode = 3 THEN  ALLCLFs.modelcode ELSE NULL END StochasticModelID,
		CASE WHEN CatalogTypeCode = 9 THEN  ALLCLFs.modelcode ELSE NULL END HistModelID,
		CASE WHEN CatalogTypeCode = 11 THEN ALLCLFs.modelcode ELSE NULL END RDSModelID,
		ALLCLFs.modelcode IncompatibleModelID,
		ALLCLFs.CreatedDate,
		ALLCLFs.Author,
		ALLCLFs.LossFileExt
FROM
(
SELECT DISTINCT
           CompanyLossSetName,
           CompanyLossAssociationSID,
           CompanyName,
           ProgramID,
           ReinsuranceProgramSID,
           ExpirationDate,
           PortfolioName,
		   BaseName,
           ModelCode,
           CreatedDate,
           Author,
           LossFileExt,
		   CatalogTypeCode
    FROM #ListofCLFsParent
    UNION
    SELECT DISTINCT
           CompanyLossSetName,
           CompanyLossAssociationSID,
           CompanyName,
           ProgramID,
           ReinsuranceProgramSID,
           ExpirationDate,
           PortfolioName,
		   BaseName,
           ModelCode,
           CreatedDate,
           Author,
           LossFileExt,
		   CatalogTypeCode
    FROM #ListofCLFsChild
) AS ALLCLFs
    INNER JOIN #FileData clfs
        ON ALLCLFs.BaseName =clfs.FileName;''
		            IF @Debug = 1
                EXEC dbo.pCOMMON_PrintVariable '': @SQLStmt'', @SQLStmt;
 SET @SQLStmtParameters = ''@BusinessUnit SMALLINT, @ProgramExpirationDate DateTIME, @InstalledDate DATETIME, @ModelCompatibility tinyint'';
		  EXEC @Result = sp_executesql
						@SQLStmt,
						@SQLStmtParameters,
						@BusinessUnit,
						@ProgramExpirationDate,
						@InstalledDate,
						@ModelCompatibility;
END; -- OF PROC
 
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[pDELETE_Vacuum]'
GO
IF OBJECT_ID(N'[dbo].[pDELETE_Vacuum]', 'P') IS NOT NULL
EXEC sp_executesql N' /*****************************************************************************************************
Object: pDELETE_Vacuum 
Description: Removes records associated with deleted sets, cons, locs.
Intended to be run via SQL Agent.
SPExposedToEntities: NO
ResultView: NA
******************************************************************************************************/
ALTER --ALTER
PROCEDURE [dbo].[pDELETE_Vacuum]
	@BatchSize INT = 5000,
	@MaxRetries TINYINT = 3,
	@RetryWait VARCHAR(10) = ''00:00:05'',
	@Debug BIT = 0
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Result INT=0
	DECLARE @SPName NVARCHAR(392) = DB_NAME() + ''.'' + SCHEMA_NAME() + ''.'' + OBJECT_NAME(@@PROCID)
	DECLARE @DBName NVARCHAR(392) = DB_NAME()
	DECLARE @ErrorMessage VARCHAR(max)
	IF @Debug=1 EXEC dbo.pCOMMON_PrintVariable '': START OF '',@SPName
	BEGIN TRY 
		IF OBJECT_ID(''tempdb..#DELETE_ExposureSetSID'') IS NOT NULL DROP TABLE #DELETE_ExposureSetSID
		CREATE TABLE #DELETE_ExposureSetSID (ExposureSetSID INT NOT NULL PRIMARY KEY)
		INSERT #DELETE_ExposureSetSID
		SELECT e.ExposureSetSID
		  FROM dbo.tExposureSet e 
		 WHERE e.StatusCode = ''DEL''
 
		--IF @Debug = 1 SELECT * FROM #DELETE_ExposureSetSID
		IF OBJECT_ID(''tempdb..#DELETE_ContractSID'') IS NOT NULL DROP TABLE #DELETE_ContractSID
		CREATE TABLE #DELETE_ContractSID (ContractSID INT NOT NULL PRIMARY KEY)
		INSERT #DELETE_ContractSID
		SELECT c.ContractSID 
		  FROM #DELETE_ExposureSetSID e WITH (NOLOCK) 
		  JOIN dbo.tContract c ON e.ExposureSetSID = c.ExposureSetSID
		UNION
		SELECT c.ContractSID 
		  FROM dbo.tContract c
		 WHERE c.StatusCode = ''DEL'' 
		--IF @Debug = 1 SELECT * FROM #DELETE_ContractSID
		IF OBJECT_ID(''tempdb..#DELETE_LocationSID'') IS NOT NULL DROP TABLE #DELETE_LocationSID
		CREATE TABLE #DELETE_LocationSID (LocationSID INT NOT NULL PRIMARY KEY)
		INSERT #DELETE_LocationSID
		SELECT l.locationsid
		  FROM dbo.tLocation l
		  JOIN #DELETE_ContractSID c WITH (NOLOCK)  ON l.ContractSID = c.ContractSID
		UNION
		SELECT l.locationsid
		  FROM dbo.tLocation l
		   WHERE l.StatusCode = ''DEL''
			
		--IF @Debug = 1 SELECT * FROM #DELETE_LocationSID
		
		IF OBJECT_ID(''tempdb..#DELETE_CompanyLossAssociationSID'') IS NOT NULL DROP TABLE #DELETE_CompanyLossAssociationSID
		CREATE TABLE #DELETE_CompanyLossAssociationSID (CompanyLossAssociationSID INT NOT NULL PRIMARY KEY)
		INSERT #DELETE_CompanyLossAssociationSID
		SELECT l.CompanyLossAssociationsid
		  FROM dbo.tCompanyLossAssociation l
		   WHERE l.StatusCode = ''DEL''
		IF OBJECT_ID(''tempdb..#DELETE_ReinsuranceProgramStructureSID'') IS NOT NULL DROP TABLE #DELETE_ReinsuranceProgramStructureSID
		CREATE TABLE #DELETE_ReinsuranceProgramStructureSID (ReinsuranceProgramStructureSID INT NOT NULL PRIMARY KEY)
		INSERT #DELETE_ReinsuranceProgramStructureSID
		SELECT l.ReinsuranceProgramStructureSID
		  FROM dbo.tReinsuranceProgramStructure l
		   WHERE l.StatusCode = ''DEL''
		IF OBJECT_ID(''tempdb..#DELETE_ReinsuranceProgramSID'') IS NOT NULL DROP TABLE #DELETE_ReinsuranceProgramSID
		CREATE TABLE #DELETE_ReinsuranceProgramSID (ReinsuranceProgramSID INT NOT NULL PRIMARY KEY)
		INSERT #DELETE_ReinsuranceProgramSID
		SELECT l.ReinsuranceProgramSID
		  FROM dbo.tReinsuranceProgram l
		   WHERE l.StatusCode = ''DEL''
		
		
	END TRY 
	BEGIN CATCH 
		SET @ErrorMessage = ''Error creating temporary For delete. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumEngineLocPhysicalProperty @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumEngineLocPhysicalProperty. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumLayerConditionLocationXref @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLayerConditionLocationXref. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
    
	BEGIN TRY
		EXECUTE pDELETE_VacuumLocFeature @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLocFeature. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
	
	BEGIN TRY
		EXECUTE pDELETE_VacuumLocTerm @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLocTerm. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
    
	BEGIN TRY
		EXECUTE pDELETE_VacuumLocOffshore @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLocOffshore. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
    
	BEGIN TRY
		EXECUTE pDELETE_VacuumLocParsedAddress @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLocParsedAddress. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
    
	BEGIN TRY
		EXECUTE pDELETE_VacuumLocWC @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLocWC. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
		
	BEGIN TRY
		EXECUTE pDELETE_VacuumReinsAppliesToExp @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumReinsAppliesToExp. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumLayerCondition @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLayerCondition. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumLayer @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLayer. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
    
	BEGIN TRY	
		EXECUTE pDELETE_VacuumStepFunctionDetail @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumStepFunctionDetail. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
    
	BEGIN TRY
		EXECUTE pDELETE_VacuumStepFunction @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumStepFunction. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 0, 1) WITH NOWAIT 
	END CATCH
    
	BEGIN TRY
		EXECUTE pDELETE_VacuumLocation @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumLocation. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
    
	BEGIN TRY
		EXECUTE pDELETE_VacuumContract @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumContract. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	 
	END CATCH
    
	BEGIN TRY
		EXECUTE pDELETE_VacuumReinsuranceProgramSourceInure @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumReinsuranceProgramSourceInure. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumReinsuranceProgramStructure @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumReinsuranceProgramStructure. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumReinsuranceProgram @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumReinsuranceProgram. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumCompanyLossAssociation @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumCompanyLossAssociation. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
	
	BEGIN TRY
		EXECUTE pDELETE_VacuumExposureSet @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumExposureSet. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumPortfolio @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumPortfolio. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
	BEGIN TRY
		EXECUTE pDELETE_VacuumCompanyUDCClassification_Xref @BatchSize = @BatchSize, @MaxRetries = @MaxRetries, @RetryWait = @RetryWait, @Debug = @Debug
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error executing pDELETE_VacuumCompanyUDCClassification_Xref. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
	BEGIN TRY
		DELETE dbo.tCompany
		WHERE StatusCode=''DEL''
	END TRY 
	BEGIN CATCH
		SET @ErrorMessage = ''Error when DELETE tCompany table. Error Number '' + CAST(ERROR_NUMBER() AS VARCHAR(24)) + '': '' + ERROR_MESSAGE()
		EXECUTE @Result = dbo.pReThrowError @SPName, @Debug	
	END CATCH
 	IF EXISTS (SELECT 1 FROM #DELETE_LocationSID) AND NOT EXISTS (SELECT 1 FROM AIRProject.dbo.tShrinkQueue WHERE DataSourceName = @DBName AND ShrankDate IS NULL)
		INSERT INTO AIRProject.dbo.tShrinkQueue (DataSourceName, DataSourceTypeCode) VALUES (@DBName, ''EXP'')
 
 	IF @Debug=1 EXEC dbo.pCOMMON_PrintVariable '': END OF '',@SPName
	SET @Result = 0
	RETURN @Result   
END
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tGroupPortfolio]'
GO
IF OBJECT_ID(N'[dbo].[tGroupPortfolio]', 'U') IS NULL
CREATE TABLE [dbo].[tGroupPortfolio]
(
[GroupPortfolioSID] [int] NOT NULL,
[GroupPortfolioName] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Description] [varchar] (4000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[StatusCode] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[EnteredDate] [datetime] NOT NULL,
[EditedDate] [datetime] NULL,
[Author] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [pk_tGroupPortfolio] on [dbo].[tGroupPortfolio]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'pk_tGroupPortfolio' AND object_id = OBJECT_ID(N'[dbo].[tGroupPortfolio]'))
ALTER TABLE [dbo].[tGroupPortfolio] ADD CONSTRAINT [pk_tGroupPortfolio] PRIMARY KEY CLUSTERED  ([GroupPortfolioSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tGroupPortfolioViewXRef]'
GO
IF OBJECT_ID(N'[dbo].[tGroupPortfolioViewXRef]', 'U') IS NULL
CREATE TABLE [dbo].[tGroupPortfolioViewXRef]
(
[GroupPortfolioSID] [int] NOT NULL,
[PortfolioSID] [int] NOT NULL,
[DataServerSID] [int] NOT NULL,
[EnteredDate] [datetime] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [pk_tGroupPortfolioViewXRef] on [dbo].[tGroupPortfolioViewXRef]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'pk_tGroupPortfolioViewXRef' AND object_id = OBJECT_ID(N'[dbo].[tGroupPortfolioViewXRef]'))
ALTER TABLE [dbo].[tGroupPortfolioViewXRef] ADD CONSTRAINT [pk_tGroupPortfolioViewXRef] PRIMARY KEY CLUSTERED  ([GroupPortfolioSID], [PortfolioSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating statistics [PortfolioSID] on [dbo].[tGroupPortfolioViewXRef]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.stats WHERE name = N'PortfolioSID' AND object_id = OBJECT_ID(N'[dbo].[tGroupPortfolioViewXRef]'))
CREATE STATISTICS [PortfolioSID] ON [dbo].[tGroupPortfolioViewXRef] ([PortfolioSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[fDELETE_ReGetSupportedCLF]'
GO
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fDELETE_ReGetSupportedCLF]') AND (type = 'IF' OR type = 'FN' OR type = 'TF'))
EXEC sp_executesql N' /**********************************************************************************************************
OBJECT:				dbo.fDELETE_ReGetSupportedCLF
DESCRIPTION:		Returns list of Supported CompanyLossAssocitionSIDs
ExposedToEntities:	NA
ResultView:			NA
Usage:				SELECT * FROM dbo.fDELETE_ReGetSupportedCLF 
**********************************************************************************************************/
ALTER
-- ALTER 
FUNCTION [dbo].[fDELETE_ReGetSupportedCLF]
(
    @ModelCompatibility TINYINT
)
RETURNS @SupportedCLFCLALossAssociation TABLE
(
    ModelCode INT,
    CLFCatalogModelversion VARCHAR(30),
    CompanyLossAssociationSID INT,
    LatestSupportCLFVersion VARCHAR(30),
    isArchive BIT
)
AS
BEGIN
   -- CTEs
    ;
    WITH CTESUpportedModel
    AS (SELECT m.CurrenCLFSupportedModelSID,
               m.ModelCode,
               m.ModelName,
               m.ModelVersion,
               LatestSupportCLFVersion,
               LEFT(m.LatestSupportCLFVersion, CHARINDEX(''.'', m.LatestSupportCLFVersion, 1) - 1) PM_major1,
               SUBSTRING(
                            SUBSTRING(
                                         m.LatestSupportCLFVersion,
                                         CHARINDEX(''.'', m.LatestSupportCLFVersion) + 1,
                                         LEN(m.LatestSupportCLFVersion)
                                     ),
                            1,
                            CHARINDEX(
                                         ''.'',
                                         SUBSTRING(
                                                      m.LatestSupportCLFVersion,
                                                      CHARINDEX(''.'', m.LatestSupportCLFVersion) + 1,
                                                      LEN(m.LatestSupportCLFVersion)
                                                  )
                                     ) - 1
                        ) PM_minor1,
               RIGHT(m.LatestSupportCLFVersion, CHARINDEX(''.'', REVERSE(m.LatestSupportCLFVersion), 1) - 1) PM_patch1,
               IsArchive
        FROM AIRReference.dbo.tCurrenCLFSupportedModel m
        WHERE m.IsArchive = CASE
                                WHEN @ModelCompatibility = 1 THEN
                                    0
                                WHEN @ModelCompatibility = 2 THEN
                                    1
                                WHEN @ModelCompatibility IS NULL
                                     OR @ModelCompatibility = 0 THEN
                                    IsArchive
                                ELSE
                                    IsArchive
                            END),
         tCLFs
    AS (SELECT LEFT(tclf.ModelVersion, CHARINDEX(''.'', tclf.ModelVersion, 1) - 1) CLF_major2,
               SUBSTRING(
                            SUBSTRING(tclf.ModelVersion, CHARINDEX(''.'', tclf.ModelVersion) + 1, LEN(tclf.ModelVersion)),
                            1,
                            CHARINDEX(
                                         ''.'',
                                         SUBSTRING(
                                                      tclf.ModelVersion,
                                                      CHARINDEX(''.'', tclf.ModelVersion) + 1,
                                                      LEN(tclf.ModelVersion)
                                                  )
                                     ) - 1
                        ) CLF_minor2,
               RIGHT(tclf.ModelVersion, CHARINDEX(''.'', REVERSE(tclf.ModelVersion), 1) - 1) CLF_patch2,
               tca.CompanyLossAssociationSID,
               tclf.ModelCode AS Model_ID_OF_CLF,
               tclf.ModelVersion
        FROM AIRExposureRe.dbo.tCompanyLossAssociation tca
            INNER JOIN AIRExposureRe.dbo.tCLFCatalog tclf
                ON tclf.CompanyLossAssociationSID = tca.CompanyLossAssociationSID
        WHERE tca.StatusCode = ''A''
		AND tca.LossTypeCode <> ''DB'')
    INSERT INTO @SupportedCLFCLALossAssociation
    SELECT DISTINCT
           a.Model_ID_OF_CLF,
           a.ModelVersion tCLFCatalog_Model_version,
           a.CompanyLossAssociationSID,
           LatestSupportCLFVersion,
           b.IsArchive
    FROM tCLFs a
        INNER JOIN CTESUpportedModel b
            ON b.ModelCode = a.Model_ID_OF_CLF
    WHERE (CASE
               WHEN CAST(a.CLF_major2 AS INT)   < CAST(b.PM_major1  AS INT) THEN 1
			   WHEN CAST(a.CLF_major2 AS INT)   > CAST(b.PM_major1  AS INT) THEN 0 
               WHEN CAST(b.PM_major1  AS INT) =   CAST(a.CLF_major2 AS INT)  THEN 
                   CASE
                       WHEN CAST(a.CLF_minor2 as INT) < CAST(b.PM_minor1  AS INT) THEN 1
					   WHEN CAST(a.CLF_minor2 as INT) > CAST(b.PM_minor1  AS INT) THEN 0
                       WHEN CAST(b.PM_minor1  AS INT) = CAST(a.CLF_minor2 AS INT) THEN
                           CASE
                               WHEN (CAST(a.CLF_patch2  AS INT) < CAST(b.PM_patch1  AS INT)) THEN 1 -- ''1.1.1'' / ''1.1.1'' // ''1.1.1'' / ''1.1.1''
                               ELSE
                                 0
                           END
                       ELSE
                           0
                   END
               ELSE
                   0
           END
          ) = 1; 
    RETURN;
END;
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[rvCREPS_GetProgramSourceInureNoChildrenForeignAssessment]'
GO
IF OBJECT_ID(N'[dbo].[rvCREPS_GetProgramSourceInureNoChildrenForeignAssessment]', 'V') IS NOT NULL
EXEC sp_executesql N' ALTER VIEW [dbo].[rvCREPS_GetProgramSourceInureNoChildrenForeignAssessment]
AS
SELECT
CAST(0 AS INT) AS	ReinsuranceProgramSubjectSID ,
CAST(0 AS INT) AS	ReinsuranceProgramSourceInureSID ,
CAST('''' AS VARCHAR(16))  AS FinancialPerspectiveCode,
CAST(0.0 AS FLOAT)  AS ParticipationAmount,
CAST(0 AS BIT) AS IsSource
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[rvCREPS_GetProgramSourceInure]'
GO
IF OBJECT_ID(N'[dbo].[rvCREPS_GetProgramSourceInure]', 'V') IS NOT NULL
EXEC sp_executesql N' ALTER VIEW [dbo].[rvCREPS_GetProgramSourceInure]
AS
SELECT
CAST(0 AS INT) AS	ReinsuranceProgramSubjectSID ,
CAST(0 AS INT) AS	ReinsuranceProgramSourceInureSID ,
CAST('''' AS VARCHAR(16))  AS FinancialPerspectiveCode,
CAST(0.0 AS FLOAT)  AS ParticipationAmount,
CAST(0 AS BIT) AS IsSource
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[rvCREPS_GetSourceInureByProgram]'
GO
IF OBJECT_ID(N'[dbo].[rvCREPS_GetSourceInureByProgram]', 'V') IS NOT NULL
EXEC sp_executesql N' ALTER VIEW [dbo].[rvCREPS_GetSourceInureByProgram]
AS
SELECT
CAST(0 AS int) AS ReinsuranceProgramSubjectSID,
CAST(0 AS INT) AS ReinsuranceProgramSourceInureSID,
CAST('''' AS VARCHAR(10)) AS FinancialPerspectiveCode,
CAST(0.0 AS FLOAT) AS ParticipationAmount,
CAST(0 AS BIT) AS IsSource
 '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [ix_tExposureSet_StatusCode2] on [dbo].[tExposureSet]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tExposureSet_StatusCode2' AND object_id = OBJECT_ID(N'[dbo].[tExposureSet]'))
CREATE NONCLUSTERED INDEX [ix_tExposureSet_StatusCode2] ON [dbo].[tExposureSet] ([StatusCode])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [ix_tLayerConditionLocationXref_LocationSID2] on [dbo].[tLayerConditionLocationXref]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tLayerConditionLocationXref_LocationSID2' AND object_id = OBJECT_ID(N'[dbo].[tLayerConditionLocationXref]'))
CREATE NONCLUSTERED INDEX [ix_tLayerConditionLocationXref_LocationSID2] ON [dbo].[tLayerConditionLocationXref] ([LocationSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [ix_tLayerCondition_ParentLayerConditionSID2] on [dbo].[tLayerCondition]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tLayerCondition_ParentLayerConditionSID2' AND object_id = OBJECT_ID(N'[dbo].[tLayerCondition]'))
CREATE NONCLUSTERED INDEX [ix_tLayerCondition_ParentLayerConditionSID2] ON [dbo].[tLayerCondition] ([ParentLayerConditionSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [ix_tLayer_ContractSID2] on [dbo].[tLayer]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tLayer_ContractSID2' AND object_id = OBJECT_ID(N'[dbo].[tLayer]'))
CREATE NONCLUSTERED INDEX [ix_tLayer_ContractSID2] ON [dbo].[tLayer] ([ContractSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [ix_tLocFeature_IBHSFortifiedCode2] on [dbo].[tLocFeature]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tLocFeature_IBHSFortifiedCode2' AND object_id = OBJECT_ID(N'[dbo].[tLocFeature]'))
CREATE NONCLUSTERED INDEX [ix_tLocFeature_IBHSFortifiedCode2] ON [dbo].[tLocFeature] ([IBHSFortifiedCode])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [ix_tReinsuranceProgram_CompanySID2] on [dbo].[tReinsuranceProgram]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tReinsuranceProgram_CompanySID2' AND object_id = OBJECT_ID(N'[dbo].[tReinsuranceProgram]'))
CREATE NONCLUSTERED INDEX [ix_tReinsuranceProgram_CompanySID2] ON [dbo].[tReinsuranceProgram] ([CompanySID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [ix_tStepFunctionDetail_StepFunctionSID2] on [dbo].[tStepFunctionDetail]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tStepFunctionDetail_StepFunctionSID2' AND object_id = OBJECT_ID(N'[dbo].[tStepFunctionDetail]'))
CREATE NONCLUSTERED INDEX [ix_tStepFunctionDetail_StepFunctionSID2] ON [dbo].[tStepFunctionDetail] ([StepFunctionSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [ix_tStepFunction_ContractSID2] on [dbo].[tStepFunction]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tStepFunction_ContractSID2' AND object_id = OBJECT_ID(N'[dbo].[tStepFunction]'))
CREATE NONCLUSTERED INDEX [ix_tStepFunction_ContractSID2] ON [dbo].[tStepFunction] ([ContractSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Adding foreign keys to [dbo].[tGroupPortfolioViewXRef]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[fk_tGroupPortfolioViewXRef_tGroupPortfolio_GroupPortfolioSID]', 'F') AND parent_object_id = OBJECT_ID(N'[dbo].[tGroupPortfolioViewXRef]', 'U'))
ALTER TABLE [dbo].[tGroupPortfolioViewXRef] ADD CONSTRAINT [fk_tGroupPortfolioViewXRef_tGroupPortfolio_GroupPortfolioSID] FOREIGN KEY ([GroupPortfolioSID]) REFERENCES [dbo].[tGroupPortfolio] ([GroupPortfolioSID])
GO
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[fk_tGroupPortfolioViewXRef_tPortfolio_PortfolioSID]', 'F') AND parent_object_id = OBJECT_ID(N'[dbo].[tGroupPortfolioViewXRef]', 'U'))
ALTER TABLE [dbo].[tGroupPortfolioViewXRef] ADD CONSTRAINT [fk_tGroupPortfolioViewXRef_tPortfolio_PortfolioSID] FOREIGN KEY ([PortfolioSID]) REFERENCES [dbo].[tPortfolio] ([PortfolioSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Adding foreign keys to [dbo].[tReinsuranceProgramStructureXRef]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[fk_tReinsuranceProgramStructureXRef_tReinsuranceProgramStructure_ReinsuranceProgramStructureSID]', 'F') AND parent_object_id = OBJECT_ID(N'[dbo].[tReinsuranceProgramStructureXRef]', 'U'))
ALTER TABLE [dbo].[tReinsuranceProgramStructureXRef] ADD CONSTRAINT [fk_tReinsuranceProgramStructureXRef_tReinsuranceProgramStructure_ReinsuranceProgramStructureSID] FOREIGN KEY ([ReinsuranceProgramStructureSID]) REFERENCES [dbo].[tReinsuranceProgramStructure] ([ReinsuranceProgramStructureSID])
GO
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[fk_tReinsuranceProgramStructureXRef_tReinsuranceProgram_ReinsuranceProgramSID]', 'F') AND parent_object_id = OBJECT_ID(N'[dbo].[tReinsuranceProgramStructureXRef]', 'U'))
ALTER TABLE [dbo].[tReinsuranceProgramStructureXRef] ADD CONSTRAINT [fk_tReinsuranceProgramStructureXRef_tReinsuranceProgram_ReinsuranceProgramSID] FOREIGN KEY ([ReinsuranceProgramSID]) REFERENCES [dbo].[tReinsuranceProgram] ([ReinsuranceProgramSID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering extended properties'
GO
EXEC sp_updateextendedproperty N'NavPropWithoutRoles_21', N'Update|CLFCatalog|fk_tCLFCatalog_tCompanyLossAssociation_CompanyLossAssociationSID', 'SCHEMA', N'dbo', 'TABLE', N'tCompanyLossAssociation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
EXEC sp_updateextendedproperty N'NavPropWithRoles_30', N'Update|ParentLocation|fk_tLocation_tLocation_ParentLocationSID|Location1|Location', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
EXEC sp_updateextendedproperty N'NavPropWithRoles_31', N'Update|SiteLocations|fk_tLocation_tLocation_ParentLocationSID|Location|Location1', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating extended properties'
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_24', 'SCHEMA', N'dbo', 'TABLE', N'tCompanyLossAssociation', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_24', N'Update|ReinsuranceProgramTargetXRef|fk_tReinsuranceProgramTargetXRef_tCompanyLossAssociation_CompanyLossAssociationSID', 'SCHEMA', N'dbo', 'TABLE', N'tCompanyLossAssociation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_22', 'SCHEMA', N'dbo', 'TABLE', N'tCompany', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_22', N'Update|CompanyLossAssociation|fk_tCompanyLossAssociation_tCompany_CompanySID', 'SCHEMA', N'dbo', 'TABLE', N'tCompany', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_23', 'SCHEMA', N'dbo', 'TABLE', N'tCompany', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_23', N'Update|ExposureSets|fk_tExposureSet_tCompany_CompanySID', 'SCHEMA', N'dbo', 'TABLE', N'tCompany', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_25', 'SCHEMA', N'dbo', 'TABLE', N'tExposureSet', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_25', N'Update|ReinsuranceProgramTargetXRef|fk_tReinsuranceProgramTargetXRef_tExposureSet_ExposureSetSID', 'SCHEMA', N'dbo', 'TABLE', N'tExposureSet', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_13', 'SCHEMA', N'dbo', 'TABLE', N'tGroupPortfolio', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_13', N'Update|GroupPortfolioViewXRef|fk_tGroupPortfolioViewXRef_tGroupPortfolio_GroupPortfolioSID', 'SCHEMA', N'dbo', 'TABLE', N'tGroupPortfolio', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithRoles_32', 'SCHEMA', N'dbo', 'TABLE', N'tLayerCondition', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithRoles_32', N'Add|Locations|tLayerConditionLocationXref|LayerCondition|Location', 'SCHEMA', N'dbo', 'TABLE', N'tLayerCondition', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithRoles_33', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithRoles_33', N'Add|LayerConditions|tLayerConditionLocationXref|Location|LayerCondition', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithRoles_34', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithRoles_34', N'Add|StepFunctions|LocStepFunctionXref|Location|tStepFunction', 'SCHEMA', N'dbo', 'TABLE', N'tLocation', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_15', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolioFilter', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_15', N'Update|Portfolio|fk_tPortfolio_tPortfolioFilter_PortfolioFilterSID', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolioFilter', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_14', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolio', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_14', N'Update|GroupPortfolioViewXRef|fk_tGroupPortfolioViewXRef_tPortfolio_PortfolioSID', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolio', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_17', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolio', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_17', N'Update|PortfolioReinsuranceTreaty|fk_tPortfolioReinsuranceTreaty_tPortfolio_PortfolioSID', 'SCHEMA', N'dbo', 'TABLE', N'tPortfolio', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_28', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceEPCurveSet', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_28', N'Update|ReinsuranceEPCurve|fk_tReinsuranceEPCurve_tReinsuranceEPCurveSet_ReinsuranceEPCurveSetSID', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceEPCurveSet', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_29', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceEPCurve', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_29', N'Update|ReinsuranceEPCurveAdjustmentPoint|fk_tReinsuranceEPCurveAdjustmentPoint_tReinsuranceEPCurve_ReinsuranceEPCurveSID', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceEPCurve', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'EntityNameOverride', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgramStructureXRef', NULL, NULL))
EXEC sp_addextendedproperty N'EntityNameOverride', N'ReinsuranceProgramStructureXRef', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgramStructureXRef', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_19', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgramStructure', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_19', N'Update|tReinsuranceProgramStructureXRef|FK_tReinsuranceProgramStructureXRef_tReinsuranceProgramStructure', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgramStructure', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_18', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_18', N'Update|ReinsuranceProgramSourceInure|fk_ReinsuranceProgramSourceInure_ReinsuranceProgram', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_20', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_20', N'Update|ReinsuranceStructureProgramXRef|fk_ReinsuranceStructureProgramXRef_ReinsuranceProgram', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_26', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_26', N'Update|ReinsuranceProgramTargetXRef|fk_tReinsuranceProgramTargetXRef_tReinsuranceProgram_ReinsuranceProgramSID', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceProgram', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_16', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceTreaty', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_16', N'Update|PortfolioReinsuranceTreaty|fk_PortfolioReinsuranceTreaty_ReinsuranceTreaty', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceTreaty', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithoutRoles_27', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceTreaty', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithoutRoles_27', N'Update|ReinsuranceTreatyTerrorismOption|fk_tReinsuranceTreatyTerrorismOption_tReinsuranceTreaty_ReinsuranceTreatySID', 'SCHEMA', N'dbo', 'TABLE', N'tReinsuranceTreaty', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF NOT EXISTS (SELECT 1 FROM fn_listextendedproperty(N'NavPropWithRoles_35', 'SCHEMA', N'dbo', 'TABLE', N'tStepFunction', NULL, NULL))
EXEC sp_addextendedproperty N'NavPropWithRoles_35', N'Add|Locations|LocStepFunctionXref|tStepFunction|Location', 'SCHEMA', N'dbo', 'TABLE', N'tStepFunction', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
COMMIT TRANSACTION
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
--Redgate also uses NOEXEC, but we have to fiddle with it here so it is compatible with how we use it for validations above.
DECLARE @Success AS BIT
SET @Success = 1
SET NOEXEC OFF --this the problem, but we're okay as long as we flip it write back off.
IF (@Success = 1) PRINT 'The database update succeeded'
ELSE BEGIN
	IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
	PRINT 'The database update failed'
	SET NOEXEC ON --suppressing execution again.
END
GO

--#region Revert Schema and Code Changes
--</Redgate Generated>
--#endregion


--#region Clear Geocoding for Location with New GeoSids
-- For any new geosid set clear the sid and reset the status match level [NONE] to support better regeocoding.
-- The other geocoding field are unimportant once these are cleared.
UPDATE l
   SET GeomatchLevelCode = 'NONE'
      ,EnhancedGeomatchLevelCode = 'NONE'
      ,ValidatorMatchCode = 'NONE'
      ,AuditStatusCode = 536870912 -- STATUS_AFTER_IMPORT
      ,GeographySID = NULL
      ,GeocoderCode = NULL
      ,EditedDate = SYSDATETIME()
  FROM tLocation l  WITH (TABLOCKX)
 WHERE GeographySID > 9906202 --highest geographysid in down version
	OR GeographySID IS NULL --account for possiblity of leaving USER with NULL geosid. This could happen in 7.0, not sure of later, but harmless for 8.0.

GO
--#endregion Clear Geocoding for Location with New GeoSids

--#region Revert Location Names and Code for Existing Geographies
--For existing locations in countries in updated model domains with geographies that existing in the down version,
--reset codes and names to down version to support forward geocoding. 
--This requires the script is using the provided AIRDowngradeHelper
UPDATE l
   SET AreaCode = g.Areacode
      ,AreaName = g.AreaName
      ,CRESTACode = g.CRESTACode
      ,CRESTAName = g.CRESTAName
      ,PostalCode = g.PostalCode
      ,PostalName = g.PostalName
      ,SubareaCode = g.SubareaCode
      ,SubareaName = g.SubareaName
      ,Subarea2Code = g.Subarea2Code
      ,Subarea2Name = g.Subarea2Name
      ,EditedDate = SYSDATETIME()
 FROM AIRDowngradeHelper.dbo.tGeography_90_JP g 
 JOIN tLocation l WITH (TABLOCKX) ON l.GeographySID = g.GeographySID

GO
--#endregion Revert Location Names and Code for Existing Geographies

--#region Recalculate Audit Status

DECLARE @STATUS_AFTER_IMPORT AS NVARCHAR(50);
DECLARE @STATUS_AFTER_CHECK AS NVARCHAR(50);
DECLARE @STATUS_AFTER_PHYSPROP AS NVARCHAR(50);
DECLARE @STATUS_AFTER_INVCONA AS NVARCHAR(50);
DECLARE @STATUS_AFTER_INVCONB AS NVARCHAR(50)
DECLARE @STATUS_AFTER_INVCONAB AS NVARCHAR(50);
DECLARE @STATUS_AFTER_INVOCC AS NVARCHAR(50);
DECLARE @STATUS_AFTER_INVCONAOCC AS NVARCHAR(50);
DECLARE @STATUS_AFTER_INVCONBOCC AS NVARCHAR(50);
DECLARE @STATUS_AFTER_INVCONABOCC AS NVARCHAR(50);
DECLARE @STATUS_AFTER_INDRISK AS NVARCHAR(50);


SELECT @STATUS_AFTER_IMPORT = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_IMPORT';
SELECT @STATUS_AFTER_CHECK = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_CHECK';
SELECT @STATUS_AFTER_PHYSPROP = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_PHYSPROP';
SELECT @STATUS_AFTER_INVCONA = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_INVCONA';
SELECT @STATUS_AFTER_INVCONB = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_INVCONB';
SELECT @STATUS_AFTER_INVCONAB = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_INVCONAB';
SELECT @STATUS_AFTER_INVOCC = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_INVOCC';
SELECT @STATUS_AFTER_INVCONAOCC = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_INVCONAOCC';
SELECT @STATUS_AFTER_INVCONBOCC = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_INVCONBOCC';
SELECT @STATUS_AFTER_INVCONABOCC = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_INVCONABOCC';
SELECT @STATUS_AFTER_INDRISK = AuditStatusCode FROM AIRDowngradeHelper.dbo.tAuditStatus_60 WHERE AuditStatus = 'STATUS_AFTER_INDRISK';

DROP TABLE IF EXISTS #LocAuditStatusUpdate;

--Populate temp #LocAuditStatusUpdate which will be a list of valid and invalid CON/OCC Code
;WITH cte AS ( 
	SELECT l.LocationSID
	      ,ISNULL(conA.AIRConstructionCode, s.Code) ConA
	      ,l.AIRConstructionCodeA
	      ,ISNULL(ConB.AIRConstructionCode, s.Code) ConB 
	      ,l.AIRConstructionCodeB
	      ,occ.AIROccupancyCode Occ
	      ,l.AIROccupancyCode
	      ,s.CountryCode 
	      ,s.Code
	      ,s1.CountryCode CountryCodeB
	      ,s1.Code CodeB
	      ,socc.CountryCode CountryCodeOcc
	      ,socc.Code OccCode
	  FROM tLocation l
	  JOIN AIRDowngradeHelper.dbo.tAIRConstOccRegionCountryXref_80 c 
	        ON l.CountryCode = c.CountryCode 
	  LEFT JOIN AIRDowngradeHelper.dbo.tAIRConstOccRegionConstXref_90 conA 
	        ON conA.AIRConstOccRegionCode = c.AIRConstOccRegionCode
	       AND conA.AIRConstructionCode = l.AIRConstructionCodeA
	  LEFT JOIN AIRDowngradeHelper.dbo.tAIRConstOccRegionConstXref_90 conB 
	        ON ConB.AIRConstOccRegionCode = c.AIRConstOccRegionCode
	       AND ConB.AIRConstructionCode = l.AIRConstructionCodeB
	  LEFT JOIN AIRDowngradeHelper.dbo.tAIRConstOccRegionOccXref_90 occ 
	        ON occ.AIRConstOccRegionCode = c.AIRConstOccRegionCode
	       AND occ.AIROccupancyCode = l.AIROccupancyCode
	  LEFT JOIN AIRDowngradeHelper.dbo.tAIROccConSpecial_80 s 
	        ON l.CountryCode = s.CountryCode
	       AND s.AIRConstOccRegionCode = c.AIRConstOccRegionCode
	       AND s.code = l.AIRConstructionCodeA
	       AND s.TypeCode = 'CON'
	  LEFT JOIN AIRDowngradeHelper.dbo.tAIROccConSpecial_80 s1 
	        ON l.CountryCode = s1.CountryCode
	       AND s1.AIRConstOccRegionCode = c.AIRConstOccRegionCode
	       AND s1.code = l.AIRConstructionCodeB
	       AND s1.TypeCode = 'CON'
	  LEFT JOIN AIRDowngradeHelper.dbo.tAIROccConSpecial_80 socc 
	        ON l.CountryCode = socc.CountryCode
	       AND socc.AIRConstOccRegionCode = c.AIRConstOccRegionCode
	       AND socc.code = l.AIROccupancyCode
	       AND socc.TypeCode = 'OCC'
)
SELECT l.LocationSID 
      ,ConA = IIF(v.CountryCode IS NOT NULL AND v.AIRConstructionCodeA = v.Code, v.Code, v.ConA)
      ,ConB = IIF(v.CountryCodeb IS NOT NULL AND v.AIRConstructionCodeB = v.Codeb, v.Code, v.ConB)
      ,Occ = IIF(v.CountryCodeOcc IS NOT NULL AND v.AIROccupancyCode = v.OccCode, v.OccCode, v.Occ)
      ,Auditstatus = CAST(NULL AS INT) -- include column for AuditStatus
  INTO #LocAuditStatusUpdate
  FROM tLocation l
  LEFT JOIN cte v ON l.LocationSID = v.LocationSID
 WHERE l.AuditStatusCode > @STATUS_AFTER_PHYSPROP
   
-- populate column AuditStatus
UPDATE #LocAuditStatusUpdate
   SET Auditstatus =  
       CASE WHEN ConA IS NULL AND ConB > 0 AND Occ > 0 THEN @STATUS_AFTER_INVCONA
            WHEN ConB IS NULL AND ConA > 0 AND Occ > 0 THEN @STATUS_AFTER_INVCONB
            WHEN ConA IS NULL AND ConB IS NULL AND Occ > 0 THEN @STATUS_AFTER_INVCONAB
            WHEN Occ IS NULL AND ConA > 0 AND ConB > 0 THEN @STATUS_AFTER_INVOCC
            WHEN ConA IS NULL AND Occ IS NULL AND ConB > 0 THEN @STATUS_AFTER_INVCONAOCC
            WHEN ConB IS NULL and Occ IS NULL AND ConA > 0 THEN @STATUS_AFTER_INVCONBOCC
            WHEN ConA IS NULL and ConB IS NULL AND Occ IS NULL THEN @STATUS_AFTER_INVCONABOCC
            --with special handling above we may still have some that are valid. and thats okay
            ELSE @STATUS_AFTER_INDRISK
       END  

UPDATE l
   SET AuditStatusCode = v.Auditstatus
  FROM tLocation l
  JOIN #LocAuditStatusUpdate v ON v.LocationSid = l.LocationSID
                              AND v.Auditstatus != l.AuditStatusCode
                              AND l.AuditStatusCode != @STATUS_AFTER_IMPORT

DROP TABLE #LocAuditStatusUpdate
PRINT 'AuditStatusCode is successfully recomputed. '

GO 
--#endregion Recalculate Audit Status

--#region Handle Keys and Indexes
--#endregion Handle Keys and Indexes

--#region Handle tSidControl

--remove/add sid control records for dropped/added tables
--Nothing for 10.0 to 9.0 downgrade

--Add missing down version sid control, if any
--//Nothing for 10.0 to 9.0 downgrade

--Use copy of AirDbAdmin sproc to clean up any bad LastSids
DECLARE @DBNameQuoted NVARCHAR(392) = (SELECT QUOTENAME(DB_NAME()))
EXEC AirDownGradeHelper..pDS_ResetTableSIDs @DBNameQuoted
--#endregion

--#region Hide Packages to support reapplication after upgrade
/*
There were columns added after 7.0.0, but I don't consider the contents valuable enough to
to jump through hoops to retain them. These supported ignored and rollback. However, these packages
must still be hidden so they can be reapplied going back to 8.0. Simlarly any down version packages must be hidden as
then are wiped out by the upgrade and downgrade sequence

In future version we may just mark everything as IsRolledBack to hide them, even if the orginally where not rolled back.
We could add an explicit IsDowngraded column, but I probably would not unless and until downgrade is support within the product.
*/

UPDATE tDBHistory
  SET StartVersion = '-' + StartVersion
     ,PackageDescription = '[StartVersion negated during downgrade to avoid conflicts when upgrading.]
' + PackageDescription
WHERE HistoryType = 'PACKAGE'
  AND StartVersion IN ('9.0.0','10.0.0')

--#endregion Hide Packages to support reapplcation after upgrade

EXEC pDS_ResetExposureIndexes '9.0.0', @debug = 0
DROP PROC dbo.pDS_ResetExposureIndexes

--#region Record downgrade in tDbHistory
INSERT tDBHistory (
        HistoryType
        ,StartVersion
        ,EndVersion
        ,StartCodeVersion
        ,EndCodeVersion
        ,PackageSID
        ,PackageType
        ,PackageName
        ,PackageDescription
        ,ContentID
        ,ContentNotes
        ,DateApplied
)
SELECT 'DOWNGRADE'
        ,'10.0.0'
        ,'9.0.0'
        ,(SELECT CodeVersion FROM tDBVersion)   
        ,'1001'
        ,NULL
        ,'DOWNGRADE'
        ,'Downgrade from 10.0 to 9.0'
        ,'Exposure database downgrade'
        ,NULL
        ,NULL
        ,SYSDATETIME()
GO
--#endregion Record downgrade in tDbHistory

--#region Reset tDbVersion to Down Version
/*****************************************************************************************************
--Reset the tDbVersion to down version
*****************************************************************************************************/
BEGIN
DECLARE @SchemaVersion VARCHAR(10);
DECLARE @ReleasedDate DATETIME;
DECLARE @DataSourceTypeCode VARCHAR(10);
DECLARE @CodeVersion VARCHAR(10);
SET @SchemaVersion = '9.0.0';
SET @CodeVersion = '1001';
SET @ReleasedDate = '2021-06-03 16:36:18.000'; 
SET @DataSourceTypeCode = 'EXP';

--Reset the version 
UPDATE  tDBVersion
SET     DataSourceTypeCode = @DataSourceTypeCode ,
        [Version] = @SchemaVersion ,
		[CodeVersion] = @CodeVersion,
        ReleasedDate = @ReleasedDate ,
        DBUID = ISNULL(DBUID, NEWID());

END
SELECT * FROM tDBVersion;
GO 
--#endregion Reset tDbVersion to Down Version

--if validation set NOEXEC on, we want to politely turn if off now.
SET NOEXEC OFF;
PRINT 'Setting NOEXEC OFF'
GO
