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 = 9;

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'ALTER TABLE [dbo].[cs_UserAvatar]
Add [Length] [int] NULL,
[ContentType] [nvarchar] (64) NULL,
[Content] [image] NULL,
[DateLastUpdated] [datetime] NOT NULL CONSTRAINT [DF_cs_UserAvatar_DateLastUpdated] DEFAULT (getdate())'

exec sp_ExecuteSQL N'UPDATE [dbo].[cs_UserAvatar] SET Length = i.Length, ContentType = i.ContentType, [Content] = i.[Content], [DateLastUpdated] = i.[DateLastUpdated] 
	FROM [dbo].[cs_UserAvatar] a JOIN [dbo].[cs_Images] i on i.ImageID = a.ImageID'
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_UserAvatar_cs_Images]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserAvatar] DROP CONSTRAINT [FK_cs_UserAvatar_cs_Images]'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserAvatar] DROP COLUMN [ImageID]'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Images]') and OBJECTPROPERTY(id, N'IsTable') = 1)
exec sp_ExecuteSQL N'DROP TABLE [dbo].[cs_Images]'

--SQL 2000 cant handle altering an image col
--exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserAvatar]
--ALTER COLUMN [Content] [image] NOT NULL'

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