SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 24;

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 ##
/*****************************************  This has been moved to an addon ********************************************

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD [SiteUrl] [nvarchar] (512) NULL'

exec sp_executesql N'UPDATE [dbo].[cs_RssCtrlFeeds] Set SiteUrl = '''''

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ALTER COLUMN [SiteUrl] [nvarchar] (512) NOT NULL'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrl] ADD [SettingsID] [int] NULL'

exec sp_executesql N'UPDATE [dbo].[cs_RssCtrl] Set [SettingsID] = (select min(SettingsID) from cs_SiteSettings)'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrl] ALTER COLUMN [SettingsID] [int] NOT NULL'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD [IntervalMinutes] [int] NULL'

exec sp_executesql N'UPDATE [dbo].[cs_RssCtrlFeeds] Set [IntervalMinutes] = 5'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ALTER COLUMN [IntervalMinutes] [int] NOT NULL'

*****************************************  This has been moved to an addon ********************************************/
--## 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
