SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

Set @Major = 4;
Set @Minor = 1;
Set @Patch = 13;

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

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Hub_ContactRequests](
	[Id] [int] IDENTITY (1, 1) NOT NULL,
	[HubId] [int] NOT NULL,
	[Subject] [nvarchar] (256) NULL,
	[Name] [nvarchar] (256) NULL,
	[EmailAddress] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Hub_ContactRequests_EmailAddress] DEFAULT (''''),
	[CreationDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Hub_ContactRequests_CreationDate] DEFAULT (getdate()),
	[Body] [ntext] NOT NULL CONSTRAINT [DF_cs_Hub_ContactRequests_Body] DEFAULT (''''),
	[IsModerated] [bit] NOT NULL CONSTRAINT [DFcs_Hub_ContactRequests_IsModerated] DEFAULT (0),
CONSTRAINT [PK_cs_Hub_ContactRequests] PRIMARY KEY CLUSTERED 
(
	[Id] ASC,
	[HubId] ASC
)) ON [PRIMARY]'

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