IF EXISTS(SELECT * FROM sys.tables WHERE name = 'BA_SiteRoleBA_Principal')
BEGIN	
	ALTER TABLE BA_SiteRolePrincipals REBUILD WITH (IGNORE_DUP_KEY = ON)

		INSERT INTO [dbo].[BA_SiteRolePrincipals](BA_SiteRoleId, BA_PrincipalPrincipalId, Created, CreatedBy_PrincipalId)
		SELECT [BA_SiteRoleBA_Principal_BA_Principal_Id], [Principals_PrincipalId], isnull(BA_SiteHistory.Created, getdate()), isnull(BA_SiteHistory.CreatedBy_PrincipalId, 1) Principals_PrincipalId
		FROM [dbo].[BA_SiteRoleBA_Principal]	
		INNER JOIN BA_SiteRole ON BA_SiteRole.Id = BA_SiteRoleBA_Principal.BA_SiteRoleBA_Principal_BA_Principal_Id
		INNER JOIN BA_Site ON BA_Site.Id = BA_SiteRole.Site_Id
		LEFT OUTER JOIN BA_SiteHistory ON BA_SiteHistory.Site_Id = BA_Site.Id and BA_SiteHistory.StatusSetTo = 0
		where created is null

	ALTER TABLE BA_SiteRolePrincipals REBUILD WITH (IGNORE_DUP_KEY = OFF)

	EXEC sp_rename 'BA_SiteRoleBA_Principal', 'BA_SiteRoleBA_Principal_DEPRECATED_6_15';  
	IF OBJECT_ID(N'[dbo].[FK_BA_SiteRoleBA_Principal_BA_SiteRole]', 'F') IS NOT NULL
		ALTER TABLE [dbo].BA_SiteRoleBA_Principal_DEPRECATED_6_15 DROP CONSTRAINT [FK_BA_SiteRoleBA_Principal_BA_SiteRole]
	IF OBJECT_ID(N'[dbo].[FK_BA_SiteRoleBA_Principal_BA_Principal]', 'F') IS NOT NULL
		ALTER TABLE [dbo].BA_SiteRoleBA_Principal_DEPRECATED_6_15 DROP CONSTRAINT [FK_BA_SiteRoleBA_Principal_BA_Principal]
	IF OBJECT_ID(N'[dbo].[PK_BA_SiteRoleBA_Principal]', 'PK') IS NOT NULL
		ALTER TABLE [dbo].BA_SiteRoleBA_Principal_DEPRECATED_6_15 DROP CONSTRAINT [PK_BA_SiteRoleBA_Principal]

END

IF EXISTS(SELECT * FROM sys.tables WHERE name = 'BA_SiteTypeMetadataDefinitions')
BEGIN	
	EXEC sp_rename 'BA_SiteTypeMetadataDefinitions', 'BA_SiteTypeMetadataDefinitions_DEPRECATED_6_15'; 
	IF OBJECT_ID(N'[dbo].[FK_BA_SiteTypeBA_SiteTypeMetadataDefinition]', 'F') IS NOT NULL
		ALTER TABLE [dbo].BA_SiteTypeMetadataDefinitions_DEPRECATED_6_15 DROP CONSTRAINT [FK_BA_SiteTypeBA_SiteTypeMetadataDefinition];
	IF OBJECT_ID(N'[dbo].[FK_BA_MetadataDefinitionBA_SiteTypeMetadataDefinition]', 'F') IS NOT NULL
	    ALTER TABLE [dbo].BA_SiteTypeMetadataDefinitions_DEPRECATED_6_15 DROP CONSTRAINT [FK_BA_MetadataDefinitionBA_SiteTypeMetadataDefinition];
END
