SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 3;
Set @Minor = 0;
Set @Patch = 4;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_executesql N'CREATE TABLE [dbo].[cs_ThemeConfigurationData] (
		[ThemeName] [nvarchar] (255) NOT NULL ,
		[SettingsID] [int] NOT NULL ,
		[SectionID] [int] NOT NULL ,
		[PropertyNames] [ntext] NULL ,
		[PropertyValues] [ntext] NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_ThemeConfigurationData] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_ThemeConfigurationData] PRIMARY KEY  CLUSTERED 
	(
		[ThemeName],
		[SettingsID],
		[SectionID]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TRIGGER cs_Section_Delete ON cs_Sections 
	FOR DELETE 
	AS
	BEGIN
		DELETE cs_SectionPermissions WHERE SectionID IN (SELECT SectionID FROM DELETED)
		DELETE cs_Threads WHERE SectionID IN (SELECT SectionID FROM DELETED)
		DELETE cs_ThemeConfigurationData WHERE SectionID IN (SELECT SectionID FROM DELETED)
	END'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

