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 = 1;
Set @Patch = 6;

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 ##

declare @propertyValuesPtr binary(16),
	@index int,
	@sectionID int

set nocount on

declare section_cursor cursor for
select SectionID
from cs_Sections
where ApplicationType = 1
	and PropertyValues like '%poisonivy%'

open section_cursor

fetch next from section_cursor into @sectionID
while @@fetch_status = 0
begin

	select @propertyValuesPtr = textptr(PropertyValues), @index = PATINDEX('%poisonivy%', PropertyValues)
	from cs_Sections
	where SectionID = @sectionID
	
	set @index = @index - 1

	if @index >= 0 begin
		print 'Updating theme for blog with ID ' + convert(varchar(20), @sectionID) + ' ...'
		updatetext cs_Sections.PropertyValues @propertyValuesPtr @index 9 'elemental'
	end

	fetch next from section_cursor into @sectionID
end

close section_cursor
deallocate section_cursor

set nocount off

--## 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 