IF NOT EXISTS(
  SELECT * FROM sys.tables WHERE name = 'BA_SiteTypeMetadataDefinitions')
BEGIN	
	CREATE TABLE [dbo].[BA_SiteTypeMetadataDefinitions] (
		[BA_SiteTypeId] int  NOT NULL,
		[BA_MetadataDefinitionId] int  NOT NULL,
		[SortOrder] int  NOT NULL
	);
	
	-- Creating primary key on [BA_SiteTypeId], [BA_MetadataDefinitionId] in table 'BA_SiteTypeMetadataDefinitions'
	ALTER TABLE [dbo].[BA_SiteTypeMetadataDefinitions]
	ADD CONSTRAINT [PK_BA_SiteTypeMetadataDefinitions]
		PRIMARY KEY CLUSTERED ([BA_SiteTypeId], [BA_MetadataDefinitionId] ASC);
	
	-- Creating foreign key on [BA_SiteTypeId] in table 'BA_SiteTypeMetadataDefinitions'
	ALTER TABLE [dbo].[BA_SiteTypeMetadataDefinitions]
	ADD CONSTRAINT [FK_BA_SiteTypeBA_SiteTypeMetadataDefinition]
		FOREIGN KEY ([BA_SiteTypeId])
		REFERENCES [dbo].[BA_SiteType]
			([Id])
		ON DELETE NO ACTION ON UPDATE NO ACTION;
	
	-- Creating foreign key on [BA_MetadataDefinitionId] in table 'BA_SiteTypeMetadataDefinitions'
	ALTER TABLE [dbo].[BA_SiteTypeMetadataDefinitions]
	ADD CONSTRAINT [FK_BA_MetadataDefinitionBA_SiteTypeMetadataDefinition]
		FOREIGN KEY ([BA_MetadataDefinitionId])
		REFERENCES [dbo].[BA_MetadataDefinition]
			([Id])
		ON DELETE NO ACTION ON UPDATE NO ACTION;
	
	-- Creating non-clustered index for FOREIGN KEY 'FK_BA_MetadataDefinitionBA_SiteTypeMetadataDefinition'
	CREATE INDEX [IX_FK_BA_MetadataDefinitionBA_SiteTypeMetadataDefinition]
	ON [dbo].[BA_SiteTypeMetadataDefinitions]
		([BA_MetadataDefinitionId]);	

	INSERT INTO [dbo].[BA_SiteTypeMetadataDefinitions](BA_SiteTypeId, BA_MetadataDefinitionId, SortOrder)
	SELECT BA_SiteTypeMetadataDefinition.SiteTypes_Id, BA_SiteTypeMetadataDefinition.MetadataDefinitions_Id, 0 FROM [dbo].[BA_SiteTypeMetadataDefinition]
END;
