
/***********************************************
* Generated at 4/17/2008 1:47:44 PM
***********************************************/


/***********************************************
* Patch: cs_Schema_Patch_2.1.00
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.00'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Update Apple release databases to Johnny... Use the 01 patch as a template this
--one has special prerequisite handling

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

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

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

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

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

--All we are doing is updating the schema revision

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.01
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.01'

-- Add index date field to post table to support re-indexing posts after a
-- specified period of time

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

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_Posts] ADD [IndexDate] [smalldatetime]' 

--note the following line needs to be in sp_executesql because the referenced column does not exist when SQL initally
--evaluates the SQL patch and will cause an error IndexDate does not exist...

--note - due to the potential that this update will take a very long time so we will allow the column to be null
--and account for it in the corrisponding job
--exec sp_executesql N'UPDATE [dbo].[cs_Posts] SET [IndexDate] = [PostDate] WHERE IsIndexed = 1'


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

/***********************************************
* Patch: cs_Schema_Patch_2.1.02
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.02'

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

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_Sections ADD DefaultLanguage nvarchar(32) 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 

/***********************************************
* Patch: cs_Schema_Patch_2.1.03
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.03'

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

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 ##
	
CREATE TABLE [dbo].[cs_PageViews](
	[URL] [nvarchar](512) NOT NULL,
	[VisitCount] [int] NOT NULL,
	[DateTimeStamp] [datetime] NOT NULL
) 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 

/***********************************************
* Patch: cs_Schema_Patch_2.1.04
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.04'

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 = 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'ALTER TABLE dbo.cs_statistics_Site ADD ViewCount int NOT NULL DEFAULT 0'
exec sp_executesql N'ALTER TABLE dbo.cs_statistics_Site ADD ReplyCount int NOT NULL DEFAULT 0' 

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.05
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.05'

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

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 sql patch updates are no longer required, the API has been updated to accept nulls
--The patch takes too long on large databases
	
--update cs_Posts Set UserTime = PostDate where UserTime is null
--ALTER TABLE cs_posts ALTER COLUMN UserTime DateTime 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 

/***********************************************
* Patch: cs_Schema_Patch_2.1.06
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.06'

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 = 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 ##
	
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_MailingLists]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[csm_MailingLists] (
		[SectionID] [int] NOT NULL ,
		[EmailAddress] [nvarchar] (100) NOT NULL ,
		[IsMailingList] [bit] NOT NULL ,
		[SettingsID] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[csm_MailingLists] WITH NOCHECK ADD 
		CONSTRAINT [PK_le_MailingList] PRIMARY KEY  CLUSTERED 
		(
			[SectionID],
			[SettingsID]
		)  ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_EmailIds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[csm_EmailIds] (
		[EmailID] [bigint] NOT NULL ,
		[UserID] [int] NOT NULL ,
		[SectionID] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[csm_EmailIds] WITH NOCHECK ADD 
		CONSTRAINT [PK_csm_EmailIds] PRIMARY KEY  CLUSTERED 
		(
			[EmailID]
		)  ON [PRIMARY]'
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 

/***********************************************
* Patch: cs_Schema_Patch_2.1.07
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.07'

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

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

	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_RollerBlogPost_cs_RollerBlogFeeds]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogPost] DROP CONSTRAINT FK_cs_RollerBlogPost_cs_RollerBlogFeeds'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_RollerBlogFeeds_cs_RollerBlogUrls]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] DROP CONSTRAINT FK_cs_RollerBlogFeeds_cs_RollerBlogUrls'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogFeeds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_executesql N'drop table [dbo].[cs_RollerBlogFeeds]'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogPost]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_executesql N'drop table [dbo].[cs_RollerBlogPost]'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogUrls]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_executesql N'drop table [dbo].[cs_RollerBlogUrls]'


exec sp_executesql N'CREATE TABLE [dbo].[cs_RollerBlogFeeds] (
	[SectionID] [int] NOT NULL ,
	[SettingsID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Enabled] [bit] NOT NULL ,
	[IntervalMinutes] [int] NOT NULL ,
	[Title] [nvarchar] (256) NULL ,
	[PostFullArticle] [bit] NOT NULL ,
	[ExerptSize] [int] NOT NULL ,
	[SubscribeDate] [datetime] NOT NULL ,
	[LastUpdateDate] [datetime] NOT NULL ,
	[LastModifiedDate] [datetime] NOT NULL ,
	[ETag] [nvarchar] (256) NULL ,
	[State] [int] NOT NULL 
) ON [PRIMARY]'


exec sp_executesql N'CREATE TABLE [dbo].[cs_RollerBlogPost] (
	[SectionID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[PostID] [int] NOT NULL ,
	[PermaLink] [nvarchar] (512) NOT NULL ,
	[CommentUrl] [nvarchar] (512)  NULL ,
	[CommentCount] [int] NULL ,
	[GuidName] [nvarchar] (512) NULL ,
	[GuidIsPermaLink] [bit] NOT NULL 
) ON [PRIMARY]'

exec sp_executesql N'CREATE TABLE [dbo].[cs_RollerBlogUrls] (
	[UrlID] [int] IDENTITY (1, 1) NOT NULL ,
	[Url] [nvarchar] (512) NOT NULL 
) ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ADD 
	CONSTRAINT [DF_cs_RollerBlogFeeds_Enabled] DEFAULT (1) FOR [Enabled],
	CONSTRAINT [DF_cs_RollerBlogFeeds_IntervalMinutes] DEFAULT (5) FOR [IntervalMinutes],
	CONSTRAINT [DF_cs_RollerBlogFeeds_PostFullArticle] DEFAULT (0) FOR [PostFullArticle],
	CONSTRAINT [DF_cs_RollerBlogFeeds_ExerptSize] DEFAULT (256) FOR [ExerptSize],
	CONSTRAINT [DF_cs_RollerBlogFeeds_State] DEFAULT (0) FOR [State],
	CONSTRAINT [PK_cs_RollerBlogFeeds] PRIMARY KEY  CLUSTERED 
	(
		[SectionID],
		[UrlID]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogPost] ADD 
	CONSTRAINT [PK_cs_RollerBlogPost] PRIMARY KEY  CLUSTERED 
	(
		[SectionID],
		[UrlID],
		[PostID]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogUrls] ADD 
	CONSTRAINT [PK_cs_RollerBlogUrls] PRIMARY KEY  CLUSTERED 
	(
		[UrlID]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ADD 
	CONSTRAINT [FK_cs_RollerBlogFeeds_cs_RollerBlogUrls] FOREIGN KEY 
	(
		[UrlID]
	) REFERENCES [dbo].[cs_RollerBlogUrls] (
		[UrlID]
	),
	CONSTRAINT [FK_cs_RollerBlogFeeds_cs_Sections] FOREIGN KEY 
	(
		[SettingsID],
		[SectionID]
	) REFERENCES [dbo].[cs_Sections] (
		[SettingsID],
		[SectionID]
	)'

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogPost] ADD 
	CONSTRAINT [FK_cs_RollerBlogPost_cs_RollerBlogFeeds] FOREIGN KEY 
	(
		[SectionID],
		[UrlID]
	) REFERENCES [dbo].[cs_RollerBlogFeeds] (
		[SectionID],
		[UrlID]
	)'



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

/***********************************************
* Patch: cs_Schema_Patch_2.1.08
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.08'

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

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

alter table cs_PostMetadata alter column MetaKey nvarchar(100) not null
alter table cs_PostMetadata alter column MetaType nvarchar(100) not null
alter table cs_PostMetadata alter column MetaValue nvarchar(100) 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 

/***********************************************
* Patch: cs_Schema_Patch_2.1.09
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.09'

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 

/***********************************************
* Patch: cs_Schema_Patch_2.1.10
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.10'

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

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_RollerBlogFeeds ADD IsBlogAggregated bit NOT NULL DEFAULT 1'
exec sp_executesql N'ALTER TABLE dbo.cs_RollerBlogFeeds ADD IsBlogRollAggregated bit NOT NULL DEFAULT 1'
exec sp_executesql N'ALTER TABLE dbo.cs_RollerBlogFeeds ADD IsRollerBlogAggregated bit NOT NULL DEFAULT 1'

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.11
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.11'

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

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 cs_Posts ADD
	PostMedia int NOT NULL CONSTRAINT DF_cs_Posts_PostMedia DEFAULT 0'

-- Video
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 2, PostType = 1 WHERE PostType = 4'

-- Polls (within forums)
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 8 WHERE PostType = 2 OR (ApplicationPostType = 2 and SectionID in (select SectionID from cs_Sections where ApplicationType = 0))' 

-- Image
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 1, PostType = 1 WHERE PostType = 3'

-- Set PostMedia to Image for all Photo Gallery posts
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 1 WHERE PostMedia=0
		AND (SectionID IN (Select s.SectionID From cs_Sections s Where s.ApplicationType = 2))'

-- Reset all Forum PostTypes to Post (1)
exec sp_executesql N'UPDATE cs_Posts SET ApplicationPostType = 1 WHERE ApplicationPostType <> 1
		AND (SectionID IN (Select s.SectionID From cs_Sections s Where s.ApplicationType = 0))'

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


/***********************************************
* Patch: cs_Schema_Patch_2.1.12
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.12'

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

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

update cs_Posts Set PostName = Replace(PostName,'_',' ') where PostName is 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 


/***********************************************
* Patch: cs_Schema_Patch_2.1.13
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.13'

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

exec sp_executesql N'CREATE TABLE [dbo].[cs_UserInvitation] (
	[InvitationKey]  uniqueidentifier ROWGUIDCOL  NOT NULL ,
	[UserID] [int] NOT NULL ,
	[Email] [nvarchar] (255) NOT NULL ,
	[DateInvited] [datetime] NOT NULL 
) ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_UserInvitation] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_UserInvitation] PRIMARY KEY  CLUSTERED 
	(
		[InvitationKey]
	)  ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_UserInvitation] ADD 
	CONSTRAINT [DF_cs_UserInvitation_InvitationKey] DEFAULT (newid()) FOR [InvitationKey],
	CONSTRAINT [DF_cs_UserInvitation_DateInvited] DEFAULT (getdate()) FOR [DateInvited]'

exec sp_executesql N'ALTER TABLE dbo.cs_UserInvitation ADD
	PropertyNames ntext NULL,
	PropertyValues ntext 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 


/***********************************************
* Patch: cs_Schema_Patch_2.1.14
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.14'

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

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

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_Sections_MailingLists_Delete]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
begin
	exec sp_executesql N'CREATE TRIGGER csm_Sections_MailingLists_Delete ON cs_Sections
	FOR DELETE
	AS
	BEGIN
		DELETE FROM csm_MailingLists WHERE SectionID IN (SELECT SectionID FROM DELETED)
		DELETE FROM csm_EmailIds WHERE SectionID IN (SELECT SectionID FROM DELETED)
	END'
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 


/***********************************************
* Patch: cs_Schema_Patch_2.1.15
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.15'

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

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 ********************************************
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrl]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_RssCtrl] (
	[CtrlID] [int] NOT NULL ,
	[Title] [varchar] (256) NOT NULL ,
	[Name] [varchar] (256) NOT NULL ,
	[ExerptSize] [int] NOT NULL ,
	[PostCount] [int] NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrl] ADD 
	CONSTRAINT [DF_RssCtrl_ExerptSize] DEFAULT (125) FOR [ExerptSize],
	CONSTRAINT [DF_cs_RssCtrl_PostCount] DEFAULT (3) FOR [PostCount]'

	exec sp_executesql N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrl] ON [dbo].[cs_RssCtrl]([CtrlID]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlFeeds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_RssCtrlFeeds] (
	[CtrlID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Enabled] [bit] NOT NULL ,
	[Title] [nvarchar] (256) NOT NULL ,
	[SubscribeDate] [datetime] NOT NULL ,
	[LastUpdateDate] [datetime] NOT NULL ,
	[LastModifiedDate] [datetime] NOT NULL ,
	[ETag] [nvarchar] (256) NULL ,
	[State] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD 
	CONSTRAINT [DF_cs_RssCtrlFeeds_Enabled] DEFAULT (1) FOR [Enabled],
	CONSTRAINT [DF_cs_RssCtrlFeeds_State] DEFAULT (0) FOR [State]'

	exec sp_executesql N'CREATE  INDEX [IX_cs_RssCtrlFeeds] ON [dbo].[cs_RssCtrlFeeds]([CtrlID]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlPost]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_RssCtrlPost] (
	[PostID] [int] IDENTITY (1, 1) NOT NULL ,
	[CtrlID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Author] [nvarchar] (256) NOT NULL ,
	[Subject] [nvarchar] (256) NULL ,
	[Body] [ntext] NULL ,
	[PostDate] [datetime] NOT NULL ,
	[PermaLink] [nvarchar] (312) NOT NULL ,
	[CommentUrl] [nvarchar] (512) NULL ,
	[CommentCount] [int] NULL ,
	[GuidName] [nvarchar] (512) NULL ,
	[GuidIsPermaLink] [bit] NOT NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

	exec sp_executesql N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlPost] ON [dbo].[cs_RssCtrlPost]([PostID]) ON [PRIMARY]'

	exec sp_executesql N'CREATE  INDEX [IX_cs_RssCtrlPost_1] ON [dbo].[cs_RssCtrlPost]([CtrlID]) ON [PRIMARY]'

	-- Index is too big for SQL2000 
	--exec sp_executesql N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlPost_2] ON [dbo].[cs_RssCtrlPost]([PermaLink]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlUrls]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_RssCtrlUrls] (
	[UrlID] [int] IDENTITY (1, 1) NOT NULL ,
	[Url] [nvarchar] (512) NOT NULL 
	) ON [PRIMARY]'

	exec sp_executesql N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlUrls] ON [dbo].[cs_RssCtrlUrls]([UrlID]) ON [PRIMARY]'
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
/***********************************************
* Patch: cs_Schema_Patch_2.1.16
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.16'

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

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 @TABLE_SCHEMA NVARCHAR(50),@TABLE_NAME NVARCHAR(50),@COLUMN_NAME NVARCHAR(50),@CONSTRAINT_NAME NVARCHAR(50)

SET @TABLE_SCHEMA = 'dbo'
SET @TABLE_NAME = 'cs_RollerBlogFeeds'
SET @COLUMN_NAME = 'IsRollerBlogAggregated'

SELECT
	@CONSTRAINT_NAME = OBJECT_NAME(c1.cdefault)
FROM syscolumns AS c1 
		JOIN syscomments AS c2 
			ON c1.cdefault = c2.id 
WHERE 	OBJECT_NAME(c1.id) = @TABLE_NAME AND c1.name = @COLUMN_NAME 

/* the following does the same thing but is SQL 2005 only
select 
	@CONSTRAINT_NAME = d.name
  from sys.default_constraints as d
  join sys.objects as o
    on o.object_id = d.parent_object_id
  join sys.columns as c
    on c.object_id = o.object_id and c.column_id = d.parent_column_id
  join sys.schemas as s
    on s.schema_id = o.schema_id
WHERE s.name = @TABLE_SCHEMA and o.name = @TABLE_NAME and c.name = @COLUMN_NAME
*/

DECLARE @STRSQL NVARCHAR(4000);
if @CONSTRAINT_NAME is not null
BEGIN
    SELECT @STRSQL = N'ALTER TABLE [' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +'] DROP CONSTRAINT ['+@CONSTRAINT_NAME+']'
	exec sp_executesql @STRSQL
END
if exists (select * from dbo.sysobjects where id = object_id(N'[' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
    SELECT @STRSQL = N'ALTER TABLE [' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +'] DROP COLUMN ['+@COLUMN_NAME+']'
	exec sp_executesql @STRSQL
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

/***********************************************
* Patch: cs_Schema_Patch_2.1.17
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.17'

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

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

-- patch sql removed, but left in so versions won't cause errors

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.18
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.18'

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

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

IF  EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_RssCtrlPost]') AND name = N'IX_cs_RssCtrlPost_2')
	exec sp_executesql N'DROP INDEX [dbo].[cs_RssCtrlPost].[IX_cs_RssCtrlPost_2]'
	
*****************************************  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

/***********************************************
* Patch: cs_Schema_Patch_2.1.19
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.19'

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

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

-- Polls (within forums)
exec sp_executesql N'UPDATE cs_Posts SET PostMedia = 8 WHERE PostType = 2 OR (ApplicationPostType = 2 and SectionID in (select SectionID from cs_Sections where ApplicationType = 0))' 

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.20
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.20'

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

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

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PK_cs_PostReindexQueue]') and OBJECTPROPERTY(id, N'IsPrimaryKey') = 1)
exec sp_executesql N'ALTER TABLE [dbo].[cs_PostReindexQueue] DROP CONSTRAINT [PK_cs_PostReindexQueue]'

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

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.21
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.21'

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

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_UserProfile] ADD AllowSiteToContact bit NOT NULL CONSTRAINT DF_cs_UserProfile_AllowSiteToContact DEFAULT 0'
exec sp_executesql N'ALTER TABLE [dbo].[cs_UserProfile] ADD AllowSitePartnersToContact bit NOT NULL CONSTRAINT DF_cs_UserProfile_AllowSitePartnersToContact DEFAULT 0'

--## 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
/***********************************************
* Patch: cs_Schema_Patch_2.1.22
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.22'

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

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_RollerBlogFeeds] ADD [SiteUrl] [nvarchar] (512) NULL'

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

exec sp_executesql N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ALTER COLUMN [SiteUrl] [nvarchar] (512) 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

/***********************************************
* Patch: cs_Schema_Patch_2.1.23
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.23'

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

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'Update cs_Posts set PostConfiguration = 55 from cs_Posts join cs_RollerBlogPost on cs_Posts.PostID  = cs_RollerBlogPost.PostID where PostConfiguration & 16 <> 16'

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.24
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.24'

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.25
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.25'

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

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 cs_Posts Add  SpamScore [int] Not Null Constraint cs_Posts_DefaultSpamScore default(0)'

exec sp_executesql N'Alter Table cs_Posts Add  PostStatus [int] Not Null Constraint cs_Posts_DefaultPostStatus default(0)'

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

/***********************************************
* Patch: cs_Schema_Patch_2.1.26
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.26'

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

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'update cs_Posts set PostMedia = 2 where SectionID in (select SectionID from cs_Sections where ApplicationType = 1) and ApplicationPostType in (1, 2) and PropertyNames like ''%VideoUrl%'''

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


/***********************************************
* Patch: cs_Schema_Patch_2.1.27
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.27'

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

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


UPDATE	PP
SET		PP.AllowMask = CONVERT(bigint, PP.AllowMask) | CONVERT(bigint, 0x0000000000000100)
FROM	cs_ProductPermissions PP INNER JOIN aspnet_Roles R ON PP.RoleID = R.RoleId
WHERE	ApplicationType = 0 AND R.LoweredRoleName IN ('moderator', 'forumsadministrator', 'systemadministrator')


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


/***********************************************
* Patch: cs_Schema_Patch_2.1.28
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.28'

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

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 cs_posts_deleted_archive Add PropertyNames [ntext] NULL'
exec sp_executesql N'Alter Table cs_posts_deleted_archive Add PropertyValues [ntext] NULL'
exec sp_executesql N'Alter Table cs_posts_deleted_archive Add SpamScore [int] NULL'
exec sp_executesql N'Alter Table cs_posts_deleted_archive Add PostStatus [int] 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 


/***********************************************
* Patch: cs_Schema_Patch_2.1.29
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.29'

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

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.Tmp_cs_PageViews
	(
	URL nvarchar(440) NOT NULL,
	VisitCount int NOT NULL,
	DateTimeStamp datetime NOT NULL
	)  ON [PRIMARY]'

IF EXISTS(SELECT * FROM dbo.cs_PageViews)
	 EXECUTE sp_executesql
		N'INSERT INTO dbo.Tmp_cs_PageViews (URL, VisitCount, DateTimeStamp)
		SELECT CONVERT(nvarchar(440), URL), VisitCount, DateTimeStamp FROM dbo.cs_PageViews (HOLDLOCK TABLOCKX)'

EXECUTE sp_executesql
	N'DROP TABLE dbo.cs_PageViews'

EXECUTE sp_executesql
	N'EXECUTE sp_rename N''dbo.Tmp_cs_PageViews'', N''cs_PageViews'', ''OBJECT'''

EXECUTE sp_executesql
	N'CREATE CLUSTERED INDEX IX_cs_PageViews ON dbo.cs_PageViews
	(
	URL,
	DateTimeStamp
	) 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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.00
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.00'

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

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'DROP TABLE dbo.cs_EmailQueue'

exec sp_executesql N'CREATE TABLE [dbo].[mg_EmailQueue](
	[EmailID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_cs_EmailQueue_EmailID]  DEFAULT (newid()),
	[NextTryTime] [datetime] NOT NULL CONSTRAINT [DF_cs_EmailQueue_createdTimestamp]  DEFAULT (''1/1/1979 12:00:00''),
	[NumberOfTries] [int] NOT NULL CONSTRAINT [DF_cs_EmailQueue_NumberOfTries]  DEFAULT (0),
	[SettingsID] [int] NULL,
	[EmailXml] [ntext] NOT NULL DEFAULT ('''')
) ON [PRIMARY] TEXTIMAGE_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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.01
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.01'

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

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

Insert [cs_EventDescriptions] Values(320,'Blog File Storage Upload')
Insert [cs_EventDescriptions] Values(321,'Blog File Storage Delete')


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


/***********************************************
* Patch: cs_Schema_Patch_3.0.02
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.02'

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

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].[csm_MessageIDs](
	[MessageID] [nvarchar](100) NOT NULL,
	[SettingsID] [int] NOT NULL,
	[PostID] [int] NOT NULL
) 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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.03
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.03'

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

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

-- Patch removed due to issue with upgrading existing versions that have messages still in the email queue

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.04
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.04'

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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.05
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.05'

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

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_SectionSubscriptions](
	[SubscriptionID] [uniqueidentifier] ROWGUIDCOL  NOT NULL CONSTRAINT [DF_cs_SectionSubscriptions_SubscriptionID]  DEFAULT (newid()),
	[SectionID] [int] NOT NULL,
	[Email] [nvarchar](256),
	[SubscriptionType] [int] NOT NULL,
	[UserID] [int] NULL CONSTRAINT [DF_cs_SectionSubscriptions_UserID]  DEFAULT ((-1)),
	[SettingsID] [int] NULL CONSTRAINT [DF_cs_SectionSubscriptions_SettingsID]  DEFAULT ((-1)),
	[DateSubscribed] [datetime] NOT NULL,
	[DateUnsubscribed] [datetime] NULL,
	[SubscriptionFrequency] [int] NOT NULL CONSTRAINT [DF_cs_SectionSubscriptions_SubscriptionFrequency]  DEFAULT ((1)),
	[IsConfirmed] [bit] NOT NULL CONSTRAINT [DF_cs_SectionSubscriptions_IsConfirmed]  DEFAULT ((0)),
		 CONSTRAINT [PK_cs_SectionSubscriptions] PRIMARY KEY CLUSTERED 
		(
			[SubscriptionID] ASC
		) ON [PRIMARY]
		) 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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.06
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.06'

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

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


exec sp_executesql N'ALTER TABLE [dbo].[cs_ThemeConfigurationData_TEMP] ADD 
	CONSTRAINT [DF_cs_ThemeConfigurationData_TEMP_LastModified] DEFAULT (getdate()) FOR [LastModified],
	CONSTRAINT [PK_cs_ThemeConfigurationData_TEMP] PRIMARY KEY  CLUSTERED 
	(
		[ThemeConfigurationDataTempID],
		[ThemeName],
		[SettingsID],
		[SectionID]
	)  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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.07
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.07'

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

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

-- BEGIN cs_Users
EXECUTE sp_executesql
N'ALTER TABLE [dbo].[cs_Users] ADD
	[UserName] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Users_UserName] DEFAULT '''',
	[Email] [nvarchar] (256) NOT NULL CONSTRAINT [DF_cs_Users_Email] DEFAULT '''',
	[IsApproved] [bit] NULL, 
	[IsAnonymous] [bit] NOT NULL CONSTRAINT [DF_cs_Users_IsAnonymous] DEFAULT 0,
	[CreateDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Users_CreateDate] DEFAULT (getdate())'

EXECUTE sp_executesql
N'UPDATE	CU
SET
	CU.[UserName] = AU.[UserName],
	CU.[Email] = ISNULL(AM.[Email], ''''),
	CU.[IsApproved] = AM.[IsApproved],
	CU.[IsAnonymous] = AU.[IsAnonymous],
	CU.[CreateDate] = AM.[CreateDate]
FROM
	[dbo].[cs_Users] CU INNER JOIN [dbo].[aspnet_Users] AU ON CU.[MembershipID] = AU.[UserId]
	INNER JOIN [dbo].[aspnet_Membership] AM ON CU.[MembershipID] = AM.[UserId]'

EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [DF_cs_Users_UserName]'

EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [DF_cs_Users_Email]'

EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [DF_cs_Users_IsAnonymous]'

EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [DF_cs_Users_CreateDate]'

DECLARE	@ConstraintName nvarchar(255)
SELECT	@ConstraintName = CONSTRAINT_NAME
FROM	INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE	TABLE_NAME = 'cs_Users' AND CONSTRAINT_TYPE = 'FOREIGN KEY'

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = @ConstraintName AND TABLE_NAME = 'cs_Users' AND COLUMN_NAME = 'MembershipID')
BEGIN
	DECLARE	@sql nvarchar(4000)
	SET		@sql = 'ALTER TABLE [dbo].[cs_Users] DROP CONSTRAINT [' + @ConstraintName + ']'
	EXECUTE sp_executesql @sql
END
-- END cs_Users

EXECUTE sp_executesql N'ALTER TABLE [cs_ProductPermissions] DROP [FK_cs_ProductPermissions_RoleID]'

EXECUTE sp_executesql N'ALTER TABLE [cs_SectionPermissions] DROP [FK_cs_SectionPermissions_RoleID]'

EXECUTE sp_executesql N'ALTER TABLE [cs_RoleQuotas] DROP [FK_cs_GalleryRoleQuotas_aspnet_Roles]'

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.08
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.08'

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

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'INSERT INTO [dbo].[cs_SectionSubscriptions]
		([SectionID],[Email],[SubscriptionType],[UserID],[SettingsID],[DateSubscribed],[SubscriptionFrequency],[IsConfirmed])
	SELECT TS.[SectionID], U.[Email], MIN(TS.[SubscriptionType]) as [SubscriptionType], U.[UserID], TS.[SettingsID],
			MAX(TS.[DateCreated]) as [DateSubscribed], 1 as [SubscriptionFrequency], 1 as [IsConfirmed]
	FROM	[dbo].[cs_TrackedSections] TS
			INNER JOIN [dbo].[cs_Users] U ON TS.[UserID] = U.[UserID]
			INNER JOIN [dbo].[cs_Sections] Sec ON Sec.[SectionID] = TS.[SectionID]
			INNER JOIN [dbo].[cs_ApplicationType] A ON A.[ApplicationType] = Sec.[ApplicationType]
	WHERE TS.[SubscriptionType] = 3 AND A.[ApplicationName] = ''Weblog''
	GROUP BY U.[UserID], TS.[SectionID], U.[Email], TS.[SettingsID]
	Having count(*) = 1'

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.09
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.09'

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

EXECUTE sp_executesql
	N'EXEC dbo.sp_rename ''cs_Licenses'', ''cs_Licenses_2.x'''

EXECUTE sp_executesql
	N'EXEC dbo.sp_rename ''PK_cs_Licenses'', ''PK_cs_Licenses_2.x'''

EXECUTE sp_executesql
	N'EXEC dbo.sp_rename ''IX_cs_Licenses'', ''IX_cs_Licenses_2.x'''

EXECUTE sp_executesql
	N'CREATE TABLE [dbo].[cs_Licenses] (
		[LicenseID] [uniqueidentifier] NOT NULL ,
		[LicenseValue] [ntext] NOT NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

EXECUTE sp_executesql
	N'ALTER TABLE [dbo].[cs_Licenses] WITH NOCHECK ADD 
		CONSTRAINT [PK_cs_Licenses] PRIMARY KEY  CLUSTERED 
		(
			[LicenseID]
		)  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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.10
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.10'

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

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 patch has been removed

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.11
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.11'

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

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'ALTER TABLE [dbo].[cs_Licenses] ADD
	[InstallDate] [datetime] NOT NULL CONSTRAINT [DF_cs_Licenses_InstallDate] DEFAULT (getdate())'

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.12
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.12'

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

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

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.13
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.13'

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

DECLARE @ApplicationType INT
SELECT @ApplicationType = ApplicationType FROM cs_ApplicationType WHERE ApplicationName = 'Forum'

DECLARE @Parent CURSOR
SET @Parent = CURSOR LOCAL FAST_FORWARD FOR 
	SELECT DISTINCT ParentID FROM cs_Sections WHERE ApplicationType = @ApplicationType and ParentID > 0

OPEN @Parent
DECLARE @ParentID INT

FETCH NEXT FROM @Parent INTO @ParentID
WHILE (@@FETCH_STATUS = 0)
	BEGIN
		DECLARE @SortOrder INT
		SET @SortOrder = 0

		DECLARE @Section CURSOR
		SET @Section = CURSOR LOCAL FAST_FORWARD FOR
			SELECT SectionID FROM cs_Sections WHERE ParentID = @ParentID Order By [Name]

		Open @Section
		DECLARE @SectionID INT
		FETCH NEXT FROM @Section INTO @SectionID

		WHILE (@@FETCH_STATUS = 0)
			BEGIN
				UPDATE cs_Sections 
				SET SortOrder = @SortOrder
				WHERE SectionID = @SectionID

				SET @SortOrder = @SortOrder + 1
				FETCH NEXT FROM @Section INTO @SectionID
			END
		CLOSE @Section
		DEALLOCATE @Section
	
		FETCH NEXT FROM @Parent INTO @ParentID
	END

CLOSE @Parent
DEALLOCATE @Parent

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.14
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.14'

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

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

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE name = N'IX_cs_Users')
	EXECUTE sp_executesql N'DROP INDEX [dbo].[cs_Users].[IX_cs_Users]'

CREATE NONCLUSTERED INDEX IX_cs_Users_UserName ON dbo.cs_Users (UserName) ON [PRIMARY]
CREATE UNIQUE NONCLUSTERED INDEX IX_cs_Users_MembershipID ON dbo.cs_Users (MembershipID) 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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.15
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.15'

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

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'ALTER TABLE [cs_Censorship] ALTER COLUMN [Word]  nvarchar(256)'
EXECUTE sp_executesql N'ALTER TABLE [cs_Censorship] ALTER COLUMN [Replacement]  nvarchar(256)'

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.16
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.16'

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

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

delete from cs_Licenses where LicenseID in ('B3B02D98-A87D-4AE4-9786-4A98CA0D282E', '956bfd20-e904-4059-9a92-6afc433b9349')

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.17
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.17'

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

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 patch has been removed

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.18
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.18'

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

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


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


/***********************************************
* Patch: cs_Schema_Patch_3.0.19
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.19'

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

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

-- create tables for post year/month/day queries
if object_id(N'dbo.cs_weblog_PostByYearMonth_tbl01') IS NULL
	exec sp_executesql N'create table dbo.cs_weblog_PostByYearMonth_tbl01 (
	[SectionID] int not null
	, [Year] smallint not null
	, [Month] tinyint not null
	, [Day] tinyint not null
	, [PostCount] int not null
	, constraint PK_cs_weblog_PostByYearMonth_tbl01 primary key clustered (
		[SectionID] asc
		, [Year] desc
		, [Month] desc
		, [Day] desc
	)
	)'

if object_id(N'dbo.cs_weblog_PostByYearMonth_tbl02') IS NULL
	exec sp_executesql N'create table dbo.cs_weblog_PostByYearMonth_tbl02 (
	[SectionID] int not null
	, [Year] smallint not null
	, [Month] tinyint not null
	, [Day] tinyint not null
	, [PostCount] int not null
	, constraint PK_cs_weblog_PostByYearMonth_tbl02 primary key clustered (
		[SectionID] asc
		, [Year] desc
		, [Month] desc
		, [Day] desc
	)
	)'

-- adjust the fill factor on the index for cs_Posts_InCategories
if exists (select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
	where tc.TABLE_NAME = N'cs_Posts_InCategories' and tc.CONSTRAINT_NAME = 'PK_cs_PostsInCategories')
	exec sp_executesql N'alter table cs_Posts_InCategories drop constraint PK_cs_PostsInCategories'

exec sp_executesql N'ALTER TABLE [dbo].[cs_Posts_InCategories]
	ADD CONSTRAINT [PK_cs_PostsInCategories] PRIMARY KEY CLUSTERED (
		[CategoryID]
		, [PostID]
	) with fillfactor = 90'

-- for cs_Referral
-- drop cs_Referral PK constraint
IF EXISTS (select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = N'cs_Referrals'
	and CONSTRAINT_NAME = N'PK_cs_Referrals' and CONSTRAINT_TYPE = N'PRIMARY KEY')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Referrals] DROP CONSTRAINT [PK_cs_Referrals]'

-- add cs_Referral PK constraint with new fill factor
exec sp_executesql N'
ALTER TABLE [dbo].[cs_Referrals] ADD CONSTRAINT [PK_cs_Referrals] PRIMARY KEY  CLUSTERED 
	(
		[SettingsID],
		[SectionID],
		[PostID],
		[UrlID]
	) with fillfactor = 90 ON [PRIMARY] 
'

-- for cs_Urls
-- drop cs_Urls.UrlID foreign constraint
IF EXISTS (select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = N'cs_Referrals'
	and CONSTRAINT_NAME = N'FK_cs_Referrals_cs_Urls' and CONSTRAINT_TYPE = N'FOREIGN KEY')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Referrals] DROP CONSTRAINT [FK_cs_Referrals_cs_Urls]'

-- drop cs_Referrals PK constraint
IF EXISTS (select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = N'cs_Urls'
	and CONSTRAINT_NAME = N'PK_cs_Urls' and CONSTRAINT_TYPE = N'PRIMARY KEY')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Urls] DROP CONSTRAINT [PK_cs_Urls]'

-- add cs_Urls PK constraint with new fill factor
exec sp_executesql N'
ALTER TABLE [dbo].[cs_Urls] ADD CONSTRAINT [PK_cs_Urls] PRIMARY KEY  CLUSTERED 
	(
		[UrlID]
	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
'

-- add cs_Referrals FK constraint to cs_Urls.UrlID
exec sp_executesql N'
ALTER TABLE [dbo].[cs_Referrals] ADD CONSTRAINT [FK_cs_Referrals_cs_Urls] FOREIGN KEY 
	(
		[UrlID]
	) REFERENCES [cs_Urls] (
		[UrlID]
	)
'

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


/***********************************************
* Patch: cs_Schema_Patch_3.0.20
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.20'

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

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

-- updating UsernameRegex to updated pattern
exec('
declare
	@UsernameRegexOriginalEscaped nvarchar(128), @UsernameRegexNew nvarchar(128), @UsernameRegexNodeName nvarchar(128)
	, @id int, @ptrSettingsXML binary(16), @insert_offset int, @delete_length int

declare @t table (
	id int identity(1, 1) not null, ptrSettingsXML binary(16) not null
	, UsernameRegexStart int not null, UsernameRegexEnd int not null, UsernameRegexNodeLength int not null
	, insert_offset AS UsernameRegexStart + UsernameRegexNodeLength - 1
	, delete_length AS UsernameRegexEnd - (UsernameRegexStart + UsernameRegexNodeLength)
)

set nocount on

select
	-- actual pattern: N''[a-zA-Z]+[^\<\>]*''
	@UsernameRegexOriginalEscaped = N''[[]a-zA-Z]+[[][^]\&lt;\&gt;]*''
	, @UsernameRegexNew = N''^[a-zA-Z0-9_\- @\.]+$''
	, @UsernameRegexNodeName = N''UsernameRegex''

select
	db_name() DatabaseName, s.SettingsID, s.SettingsXML
	, case when patindex(
		N''%<'' + @UsernameRegexNodeName + N''>''
		+ @UsernameRegexOriginalEscaped
		+ N''</'' + @UsernameRegexNodeName + N''>%''
		, s.SettingsXML )<>0 then ''Updating'' else ''No Update'' end
from
	cs_SiteSettings s

insert into @t (ptrSettingsXML, UsernameRegexStart, UsernameRegexEnd, UsernameRegexNodeLength)
select
	TEXTPTR( s.SettingsXML )
	, patindex( N''%<'' + @UsernameRegexNodeName + N''>%'', s.SettingsXML )
	, patindex( N''%</'' + @UsernameRegexNodeName + N''>%'', s.SettingsXML )
	, 2 + LEN( @UsernameRegexNodeName )
from
	cs_SiteSettings s
where
	s.SettingsXML IS NOT NULL
	and patindex(
		N''%<'' + @UsernameRegexNodeName + N''>''
		+ @UsernameRegexOriginalEscaped
		+ N''</'' + @UsernameRegexNodeName + N''>%''
		, s.SettingsXML ) <> 0

while 1=1
begin
	select @id = (select min(id) from @t)
	if @id is null break
	
	select @ptrSettingsXML = t.ptrSettingsXML, @insert_offset = t.insert_offset, @delete_length = t.delete_length
	from @t t where id = @id
	
	UPDATETEXT cs_SiteSettings.SettingsXML @ptrSettingsXML @insert_offset @delete_length @UsernameRegexNew

	delete from @t where id = @id
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 


/***********************************************
* Patch: cs_Schema_Patch_3.0.21
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.0.21'

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

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

update aspnet_Roles set LoweredRoleName = LOWER(LoweredRoleName) where LoweredRoleName IN ( N'Registered Users', N'Trusted Users' )

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


/***********************************************
* Patch: cs_Schema_Patch_3.1.00
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.00'

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

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_Sections] add IsPublic BIT NULL'

exec sp_executesql N'create index IX_cs_Sections_Public on [dbo].[cs_Sections](SectionID,IsPublic)'

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


/***********************************************
* Patch: cs_Schema_Patch_3.1.01
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.01'

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

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_Users_OpenID] (
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[OpenID] [nvarchar] (440) NOT NULL ,
	[SettingsID] [int] NOT NULL ,
	[UserID] [int] NOT NULL ,
	[LastAccessed] [datetime] NOT NULL ,
	[Created] [datetime] NOT NULL ,
	[Email] [nvarchar] (128) NOT NULL ,
CONSTRAINT [PK_cs_Users_OpenID] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
) ON [PRIMARY]
) ON [PRIMARY]

CREATE UNIQUE NONCLUSTERED INDEX [IX_cs_Users_OpenID] ON [dbo].[cs_Users_OpenID] 
(
	[OpenID] ASC,
	[SettingsID] 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 


/***********************************************
* Patch: cs_Schema_Patch_3.1.02
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.02'

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

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_Sections] add HubSectionID INT NOT NULL DEFAULT -1'

exec sp_executesql N'create index IX_cs_Sections_Hub on [dbo].[cs_Sections](HubSectionID,SectionID)'

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


/***********************************************
* Patch: cs_Schema_Patch_3.1.03
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.03'

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

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

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionMembers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_SectionMembers] (
		[SectionID] [int] NOT NULL ,
		[UserID] [int] NOT NULL ,
		[MembershipType] [int] NOT NULL,
		[DateAdded] [datetime] NOT NULL CONSTRAINT [DF_cs_SectionMembers_DateAdded] DEFAULT (getdate())
	) ON [PRIMARY]'

	exec sp_executesql N'ALTER TABLE [dbo].[cs_SectionMembers] WITH NOCHECK ADD 
		CONSTRAINT [PK_cs_SectionMembers] PRIMARY KEY  CLUSTERED 
		(
			[UserID],
			[SectionID],
			[MembershipType]
		)  ON [PRIMARY]'

	--DROP TABLE cs_SectionMembers
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 


/***********************************************
* Patch: cs_Schema_Patch_3.1.04
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.04'

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 = 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'DECLARE @PropertyString		NVARCHAR(50)
DECLARE @PropertyDelimiter	NVARCHAR(50)
DECLARE @ValueDelimiter		NVARCHAR(50)

SET @PropertyString = ''%SectionOwners:S:%''
SET @PropertyDelimiter = ''%:%''
SET @ValueDelimiter = ''%;%''

SELECT LEN(@PropertyString)-2

CREATE TABLE #SectionOwners 
(
	SectionID int  NOT NULL,
	OwnerName nvarchar(256) collate database_default NOT NULL
)

CREATE TABLE #SectionOwnerProperty 
(
	SectionID int  NOT NULL,
	Owners nvarchar(4000) collate database_default NOT NULL
)

INSERT INTO #SectionOwnerProperty(SectionID, Owners)
SELECT
SectionID,
 
SUBSTRING(PropertyValues,
CONVERT(int, SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),0,PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))))+1,
CONVERT(int, SUBSTRING(SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))+1,100),0, PATINDEX(@PropertyDelimiter, SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))+1,100)))-1)
+1
) as Owners from cs_Sections WHERE PATINDEX(@PropertyString, PropertyNames) > 0 

WHILE EXISTS (SELECT SectionID FROM #SectionOwnerProperty WHERE PATINDEX(@ValueDelimiter, Owners) > 0)
BEGIN
	INSERT INTO #SectionOwners (SectionID, OwnerName) SELECT SectionID, LOWER(SUBSTRING(Owners,0,PATINDEX(@ValueDelimiter, Owners)))  FROM #SectionOwnerProperty WHERE PATINDEX(@ValueDelimiter, Owners) > 0 
	UPDATE #SectionOwnerProperty SET Owners = SUBSTRING(Owners,PATINDEX(@ValueDelimiter, Owners)+1, DATALENGTH(Owners) - PATINDEX(@ValueDelimiter, Owners))  FROM #SectionOwnerProperty WHERE PATINDEX(@ValueDelimiter, Owners) > 0 
END

INSERT INTO #SectionOwners (SectionID, OwnerName) SELECT SectionID, LOWER(Owners) FROM #SectionOwnerProperty WHERE PATINDEX(@ValueDelimiter, Owners) = 0 

DROP TABLE #SectionOwnerProperty

SELECT * FROM #SectionOwners
INSERT INTO cs_SectionMembers(SectionID, UserID, MembershipType) SELECT SO.SectionID, U.UserID, 1 FROM  #SectionOwners SO JOIN cs_Users U on U.UserName = SO.OwnerName LEFT OUTER JOIN cs_SectionMembers SM on SM.SectionID = SO.SectionID and SM.UserID = U.UserID and SM.MembershipType = 1 WHERE SM.MembershipType is null 

DROP TABLE #SectionOwners' 

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


/***********************************************
* Patch: cs_Schema_Patch_3.1.05
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.05'

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

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

if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[cs_Sections]') and Name = 'IsCommunityAggregated')
begin

exec sp_executesql N'alter table [dbo].[cs_Sections] add IsCommunityAggregated BIT NOT NULL DEFAULT -1'

exec sp_executesql N'DECLARE @PropertyString		NVARCHAR(50)
DECLARE @PropertyDelimiter	NVARCHAR(50)
DECLARE @ValueDelimiter		NVARCHAR(50)

SET @PropertyString = ''%IsCommunityAggregated:S:%''
SET @PropertyDelimiter = ''%:%''
SET @ValueDelimiter = ''%;%''

UPDATE cs_Sections set IsCommunityAggregated = CA.IsCommunityAggregatedProperty FROM cs_Sections S join (
SELECT
SectionID, 0 as IsCommunityAggregatedProperty
from cs_Sections WHERE PATINDEX(@PropertyString, PropertyNames) > 0 AND
LOWER(SUBSTRING(PropertyValues,
CONVERT(int, SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),0,PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))))+1,
CONVERT(int, SUBSTRING(SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))+1,100),0, PATINDEX(@PropertyDelimiter, SUBSTRING(SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100),PATINDEX(@PropertyDelimiter, SUBSTRING(PropertyNames, PATINDEX(@PropertyString, PropertyNames) + LEN(@PropertyString)-2, 100))+1,100)))-1)
+1
)) = ''false'' 
) CA on S.SectionID = CA.SectionID
'
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 


/***********************************************
* Patch: cs_Schema_Patch_3.1.06
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.06'

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 
/***********************************************
* Patch: cs_Schema_Patch_3.1.07
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.07'

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

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_Thread_Daily_Stats](
	[SectionID] [int] NOT NULL,
	[ThreadID] [int] NOT NULL,
	[Day] [datetime] NOT NULL,
	[ViewCount] [int] NOT NULL,
	CONSTRAINT [PK_cs_Thread_Daily_Stats] PRIMARY KEY CLUSTERED (
		[SectionID] ASC,
		[ThreadID] ASC
	) 
) ON [PRIMARY]


/****** Object:  Index [PK_cs_Thread_Daily_Stats]    Script Date: 06/27/2007 12:29:38 ******/
CREATE INDEX [IX_cs_Thread_Daily_Stats_Day] ON [dbo].[cs_Thread_Daily_Stats] 
(
	[Day] DESC
) 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 


/***********************************************
* Patch: cs_Schema_Patch_3.1.08
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.08'

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

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

-- *****************************************
--
-- MOVED TO SCHEMA PATCH 3.0.19
--
-- *****************************************

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


/***********************************************
* Patch: cs_Schema_Patch_3.1.09
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.09'

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

/* was just local database corruption
exec sp_executesql N'Update cs_Users set UserName = ''Anonymous'' where IsAnonymous = 1 and UserName = '''''
*/

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


/***********************************************
* Patch: cs_Schema_Patch_3.1.10
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.10'

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

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

if not exists (select * from cs_ApplicationType where ApplicationType = 11 )
	insert into cs_ApplicationType values ( 11, 'Hubs')

exec sp_executesql N'Update cs_Sections set HubSectionID = SectionID where HubSectionID = 0 and ApplicationType = 11'

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


/***********************************************
* Patch: cs_Schema_Patch_3.1.11
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.11'

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

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 @ConstraintName sysname

Select @ConstraintName = o.name from  sysobjects o join syscolumns c on c.cdefault = o.id where c.name = 'HubSectionID' and parent_obj = OBJECT_ID('[dbo].[cs_Sections]')

EXEC('ALTER TABLE cs_Sections DROP CONSTRAINT ' + @ConstraintName)

exec sp_executesql N'ALTER TABLE cs_Sections ADD CONSTRAINT DF_cs_Sections_HubSectionID DEFAULT 0 FOR HubSectionID'

exec sp_executesql N'Update cs_Sections set HubSectionID = 0 where HubSectionID = -1'


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


/***********************************************
* Patch: cs_Schema_Patch_3.1.12
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.12'

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

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

IF EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_Thread_Daily_Stats]') AND name = N'PK_cs_Thread_Daily_Stats')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Thread_Daily_Stats] DROP CONSTRAINT [PK_cs_Thread_Daily_Stats]'

IF EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_Thread_Daily_Stats]') AND name = N'IX_cs_Thread_Daily_Stats_Day')
	exec sp_executesql N'DROP INDEX [dbo].[cs_Thread_Daily_Stats].[IX_cs_Thread_Daily_Stats_Day]'

exec sp_executesql N'
ALTER TABLE [dbo].[cs_Thread_Daily_Stats] ADD CONSTRAINT [PK_cs_Thread_Daily_Stats] PRIMARY KEY CLUSTERED
(
	[SectionID] ASC
	, [ThreadID] ASC
	, [Day] DESC
) 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 


/***********************************************
* Patch: cs_Schema_Patch_3.1.13
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.13'

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

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DF_cs_Sections_EnableAutoDelete]'))
exec sp_executesql N'ALTER TABLE [dbo].[cs_Sections] DROP CONSTRAINT [DF_cs_Sections_EnableAutoDelete]'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DF_cs_Sections_AutoDeleteThreshold]'))
exec sp_executesql N'ALTER TABLE [dbo].[cs_Sections] DROP CONSTRAINT [DF_cs_Sections_AutoDeleteThreshold]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_Sections] DROP COLUMN [EnableAutoDelete]'
exec sp_executesql N'ALTER TABLE [dbo].[cs_Sections] DROP COLUMN [AutoDeleteThreshold]'

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.14
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.14'

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

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

-- *****************************************
--
-- MOVED TO SCHEMA PATCH 3.0.19
--
-- *****************************************

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.15
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.15'

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

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

if not exists (select * from cs_ApplicationType where ApplicationType = 11 )
	insert into cs_ApplicationType values ( 11, 'Hubs')

insert into [dbo].[cs_Groups] (SettingsID, Name, SortOrder, ApplicationType, Description)
select SettingsID, 'Hubs', 1, 11, ''
from [dbo].[cs_SiteSettings]
where SettingsID not in (select SettingsID from [dbo].[cs_Groups] where Name = 'Hubs' and ApplicationType = 11)

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.16
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.16'

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

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

-- *****************************************
--
-- OTHER PARTS OF THIS PATCH MOVED TO SCHEMA PATCH 3.0.19
--
-- *****************************************

-- for cs_Thread_Daily_Stats
-- drop cs_Thread_Daily_Stats PK constraint
IF EXISTS (select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = N'cs_Thread_Daily_Stats'
	and CONSTRAINT_NAME = N'PK_cs_Thread_Daily_Stats' and CONSTRAINT_TYPE = N'PRIMARY KEY')
	exec sp_executesql N'ALTER TABLE [dbo].[cs_Thread_Daily_Stats] DROP CONSTRAINT [PK_cs_Thread_Daily_Stats]'

-- add cs_Thread_Daily_Stats PK constraint with new fill factor
exec sp_executesql N'
ALTER TABLE [dbo].[cs_Thread_Daily_Stats] ADD CONSTRAINT [PK_cs_Thread_Daily_Stats] PRIMARY KEY CLUSTERED
(
	[SectionID] ASC
	, [ThreadID] ASC
	, [Day] DESC
) with fillfactor = 90 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 

/***********************************************
* Patch: cs_Schema_Patch_3.1.17
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.17'

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

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

update [dbo].[cs_SectionMembers]
set MembershipType = 8
where MembershipType = 4

update [dbo].[cs_SectionMembers]
set MembershipType = 4
where MembershipType = 3

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.18
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.18'

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

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

if not exists (select * from cs_ApplicationType where ApplicationType = 11 )
	insert into cs_ApplicationType values ( 11, 'Hubs')

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.19
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.19'

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

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

-- *****************************************
--
-- Clearing the patch; table cs_User_ApplicationToken no longer needed.
-- It's been renamed to cs_User_ApiKeys (with a different schema), which
-- can be found in patch 3.1.24.
--
-- *****************************************

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


/***********************************************
* Patch: cs_Schema_Patch_3.1.20
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.20'

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

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

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FriendRequests]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_FriendRequests](
	[FriendshipRequestID] [int] IDENTITY(1,1) NOT NULL,
	[RequestorUserID] [int] NOT NULL,
	[RequesteeUserID] [int] NOT NULL,
	[Message] [varchar](2000) NULL,
	[FriendshipState] [tinyint] NOT NULL,
	[CreatedDate] [datetime] NOT NULL CONSTRAINT [DF_cs_FriendRequests_CreatedDate]  DEFAULT (getdate()),
	[LastModifiedDate] [datetime] NOT NULL CONSTRAINT [DF_cs_FriendRequests_LastModifiedDate]  DEFAULT (getdate()),
PRIMARY KEY CLUSTERED 
(
	[FriendshipRequestID] ASC
)WITH FILLFACTOR = 90
)'
	
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Friends_xref]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_executesql N'CREATE TABLE [dbo].[cs_Friends_xref](
	[UserID] [int] NOT NULL,
	[FriendUserID] [int] NOT NULL)'
exec sp_executesql N'ALTER TABLE [dbo].[cs_Friends_xref]  
	WITH CHECK ADD  CONSTRAINT [FK_cs_Friends_xref_cs_Users] 
	FOREIGN KEY([UserID])
	REFERENCES [dbo].[cs_Users] ([UserID])'
exec sp_executesql N'ALTER TABLE [dbo].[cs_Friends_xref] 
	CHECK CONSTRAINT [FK_cs_Friends_xref_cs_Users]'

	
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 

/***********************************************
* Patch: cs_Schema_Patch_3.1.21
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.21'

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

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_Groups] ADD ParentGroupID int NOT NULL DEFAULT((0))'

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.22
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.22'

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

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

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder]'))
	exec sp_rename cs_Folder, cs_Folder_deprecated
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost]'))
	exec sp_rename cs_FeedPost, cs_FeedPost_deprecated
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed]'))
	exec sp_rename cs_Feed, cs_Feed_deprecated
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FolderFeed]'))
	exec sp_rename cs_FolderFeed, cs_FolderFeed_deprecated

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.23
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.23'

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

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_GroupPermissions](
	[SettingsID] [int] NOT NULL,
	[GroupID] [int] NOT NULL,
	[RoleID] [uniqueidentifier] NOT NULL,
	[AllowMask] [binary](8) NOT NULL,
	[DenyMask] [binary](8) NOT NULL
CONSTRAINT [PK_cs_GroupPermissions] PRIMARY KEY CLUSTERED 
(
	[SettingsID] ASC,
	[GroupID] ASC,
	[RoleID] ASC
)) ON [PRIMARY]'

EXECUTE sp_executesql N'
ALTER TABLE [dbo].[cs_GroupPermissions] ADD CONSTRAINT [FK_cs_GroupPermissions_SettingsID] FOREIGN KEY([SettingsID]) 
	REFERENCES [dbo].[cs_SiteSettings] ([SettingsID])'

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.24
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.24'

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

EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_ApiKeys](
	[ApiKeyID] [int] IDENTITY(1,1) NOT NULL,
	[UserID] [int] NOT NULL,
	[Value] [char](8) NOT NULL,
	[Name] [varchar](50) NOT NULL,
	[DateCreated] [datetime] NOT NULL CONSTRAINT [DF_cs_ApiKeys_DateCreated]  DEFAULT (getdate()),
	[Enabled] [bit] NOT NULL CONSTRAINT [DF_cs_ApiKeys_Enabled]  DEFAULT ((1)),
 CONSTRAINT [PK_cs_ApiKeys] PRIMARY KEY CLUSTERED 
(
	[ApiKeyID] ASC
)) ON [PRIMARY]'

EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_ApiKeys_UserID] ON [dbo].[cs_ApiKeys] ([UserID]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE UNIQUE NONCLUSTERED INDEX [IX_cs_ApiKeys_Value] ON [dbo].[cs_ApiKeys] ([Value])'

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.25
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.25'

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

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

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_ApiKeys]') and OBJECTPROPERTY(id, N'IsTable') = 1)
BEGIN
	if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys]') and OBJECTPROPERTY(id, N'IsTable') = 1)
BEGIN
	EXECUTE sp_Rename N'cs_User_ApiKeys', 'cs_ApiKeys'
	EXECUTE sp_Rename N'PK_cs_User_ApiKeys', 'PK_cs_ApiKeys'

	IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_ApiKeys]') AND name = N'IX_cs_User_ApiKeys_Value')
	BEGIN
		EXECUTE sp_executesql N'DROP INDEX [IX_cs_User_ApiKeys_Value] ON [dbo].[cs_ApiKeys]'
		IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_ApiKeys]') AND name = N'IX_cs_ApiKeys_Value')
			EXECUTE sp_executesql N'CREATE UNIQUE NONCLUSTERED INDEX [IX_cs_ApiKeys_Value] ON [dbo].[cs_ApiKeys] ([Value])'
	END
	IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_ApiKeys]') AND name = N'IX_cs_User_ApiKeys_UserID')
	BEGIN
		EXECUTE sp_executesql N'DROP INDEX [IX_cs_User_ApiKeys_UserID] ON [dbo].[cs_ApiKeys]'
		IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_ApiKeys]') AND name = N'IX_cs_ApiKeys_UserID')
			EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_ApiKeys_UserID] ON [dbo].[cs_ApiKeys] ([UserID]) WITH FILLFACTOR = 90 ON [PRIMARY]'
	END
END
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 

/***********************************************
* Patch: cs_Schema_Patch_3.1.26
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.26'

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

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

-- The table created is no longer required.  Empty schema patch.

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.27
* File Date: 4/14/2008 2:52:29 PM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.27'

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

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'
INSERT INTO cs_FriendRequests
	([RequestorUserID], [RequesteeUserID], [Message], [FriendshipState], [CreatedDate], [LastModifiedDate])
SELECT U.UserID, FU.UserID, ''A friendship request has been initiated.  Please either accept or reject this request.'' as [Message], 2 as [FriendshipState], getdate() as [CreatedDate], getdate() as [LastModifiedDate]
	FROM cs_Users U
	INNER JOIN cs_FavoriteUsers FU ON FU.OwnerID = U.UserID AND FU.UserID IN 
		(SELECT OwnerID FROM cs_FavoriteUsers FUs WHERE FUs.UserID = U.UserID)
WHERE NOT EXISTS (SELECT * FROM cs_FriendRequests FR WHERE FR.RequestorUserID = U.UserID AND FR.RequesteeUserID = FU.UserID)'

EXECUTE sp_executesql N'
DELETE FROM cs_FriendRequests WHERE FriendshipRequestID in
(SELECT FR.FriendshipRequestID FROM cs_FriendRequests FR
	INNER JOIN cs_FriendRequests FRS ON FR.[RequesteeUserID] = FRS.[RequestorUserID] AND FRS.[RequesteeUserID] = FR.[RequestorUserID] AND FR.[RequesteeUserID] < FRS.[RequesteeUserID]
 WHERE FR.FriendshipState = 2 AND FR.[RequesteeUserID] <> FR.[RequestorUserID])'

EXECUTE sp_executesql N'
INSERT INTO cs_Friends_xref (UserID, FriendUserID)
SELECT FR.RequestorUserID, FR.RequesteeUserID
	FROM cs_FriendRequests FR
	WHERE FR.FriendshipState = 2 AND NOT EXISTS (Select * FROM cs_Friends_xref F WHERE F.UserID = FR.RequestorUserID AND F.FriendUserID = FR.RequesteeUserID)'

EXECUTE sp_executesql N'
INSERT INTO cs_Friends_xref (UserID, FriendUserID)
SELECT FR.RequesteeUserID, FR.RequestorUserID
	FROM cs_FriendRequests FR
	WHERE FR.FriendshipState = 2 AND NOT EXISTS (Select * FROM cs_Friends_xref F WHERE F.FriendUserID = FR.RequestorUserID AND F.UserID = FR.RequesteeUserID)'

EXECUTE sp_executesql N'
INSERT INTO cs_FriendRequests
	([RequestorUserID], [RequesteeUserID], [Message], [FriendshipState], [CreatedDate], [LastModifiedDate])
SELECT U.UserID, FU.UserID, ''A friendship request has been initiated.  Please either accept or reject this request.'' as [Message], 1 as [FriendshipState], getdate() as [CreatedDate], getdate() as [LastModifiedDate]
	FROM cs_Users U
	INNER JOIN cs_FavoriteUsers FU ON FU.OwnerID = U.UserID AND FU.UserID NOT IN 
		(SELECT OwnerID FROM cs_FavoriteUsers FUs WHERE FUs.UserID = U.UserID)
WHERE NOT EXISTS (SELECT * FROM cs_FriendRequests FR WHERE FR.RequestorUserID = U.UserID AND FR.RequesteeUserID = FU.UserID)'


EXECUTE sp_executesql N'
INSERT INTO mg_EmailQueue (SettingsID, EmailXml) 
SELECT S.SettingsID, 
	N''<?xml version="1.0" encoding="utf-16"?><MailMessage><Revision>0</Revision><Headers /><DeliveryNotificationOptions>None</DeliveryNotificationOptions><Priority>Normal</Priority><From><MailAddress><Telligent.MailGateway.Common.Components.MailAddressXml><Revision>0</Revision><Name>''
	+ S.[SiteName]
	+ N'' - Automated Email</Name><Address>info@notset.com</Address></Telligent.MailGateway.Common.Components.MailAddressXml></MailAddress></From><To><MailAddress><Revision>0</Revision><Name /><Address>''
	+ U.Email
	+ N''</Address></MailAddress></To><Cc /><Bcc /><Sender><MailAddress><Telligent.MailGateway.Common.Components.MailAddressXml /></MailAddress></Sender><ReplyTo><MailAddress><Telligent.MailGateway.Common.Components.MailAddressXml /></MailAddress></ReplyTo><Subject>New Friend Request(s) on ''
	+ S.[SiteName]
	+ N''</Subject><SubjectEncoding /><Body>You have friendships that are awaiting confirmation at &lt;a href=''
	+ S.[SiteUrl]
	+ N''/&gt;''
	+ S.[SiteName]
	+ N''&lt;/a&gt;&lt;p&gt;Please visit the &lt;a href=''
	+ S.[SiteUrl]
	+ N''/members/''
	+ U.UserName
	+ N''/friends/default.aspx&gt;My Friends&lt;/a&gt; page of your profile to approve these requests.&lt;/p&gt;</Body><BodyEncoding>65001</BodyEncoding><BodyFormat /><IsBodyHtml>True</IsBodyHtml><Attachments><Attachment /></Attachments><AttachmentHandles /><AlternateViews></AlternateViews></MailMessage>''
FROM (
	SELECT DISTINCT UP.[SettingsID], UX.[Email], UX.UserName
	FROM cs_Users UX
	INNER JOIN cs_UserProfile UP on UX.UserID = UP.UserID AND UP.EnableEmail = 1
	WHERE EXISTS (
		SELECT 1 FROM [cs_FriendRequests] FR
		WHERE UX.UserID = FR.RequesteeUserID AND FR.FriendshipState = 1
	)
) AS U
INNER JOIN (
	select SX.SettingsID
		, coalesce( convert( nvarchar(512), substring(SX.SettingsXML, len(''SiteName'')+2+NULLIF(patindex(N''%<SiteName>%</SiteName>%'', SX.SettingsXML), 0),NULLIF(patindex(N''%</SiteName>%'', SX.SettingsXML), 0) - len(''SiteName'') - 2 - NULLIF(patindex(N''%<SiteName>%</SiteName>%'', SX.SettingsXML), 0)) ), N''NO_SITE''	) AS [SiteName]
		, coalesce( convert( nvarchar(512), substring(SX.SettingsXML, len(''SiteUrl'' )+2+NULLIF(patindex(N''%<SiteUrl>%</SiteUrl>%''  , SX.SettingsXML), 0),NULLIF(patindex(N''%</SiteUrl>%'' , SX.SettingsXML), 0) - len(''SiteUrl'' ) - 2 - NULLIF(patindex(N''%<SiteUrl>%</SiteUrl>%''  , SX.SettingsXML), 0)) ), N''NO SITE URL'') AS [SiteUrl]
	FROM cs_SiteSettings SX
	WHERE
		''true'' = convert( nvarchar(4), substring(SX.SettingsXML, len(''EnableEmail'')+2+NULLIF(patindex(N''%<EnableEmail>%</EnableEmail>%'', SX.SettingsXML), 0),NULLIF(patindex(N''%</EnableEmail>%'', SX.SettingsXML), 0) - len(''EnableEmail'') - 2 - NULLIF(patindex(N''%<EnableEmail>%</EnableEmail>%'', SX.SettingsXML), 0)) )
) S on S.SettingsID = U.SettingsID
'

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.28
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.28'

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

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

-- Create cs_Messaging_Messages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_Messages](
	[MessageId] [uniqueidentifier] NOT NULL,
	[AuthorId] [int] NOT NULL,
	[Subject] [nvarchar](100) NOT NULL,
	[Body] [nvarchar](1000) NOT NULL,
	[DateCreated] [datetime] NOT NULL CONSTRAINT [DF_cs_Messaging_Messages_DateCreated]  DEFAULT (getdate()),
 CONSTRAINT [PK_cs_Messaging_Messages] PRIMARY KEY CLUSTERED 
(
	[MessageId] ASC
)) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_Messages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_Messages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_Messages_cs_Users] FOREIGN KEY([AuthorId]) REFERENCES [dbo].[cs_Users] ([UserID])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_Messages] CHECK CONSTRAINT [FK_cs_Messaging_Messages_cs_Users]'

-- Create indexes for cs_Messaging_Messages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_Messages_AuthorId] ON [dbo].[cs_Messaging_Messages] ([AuthorId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_Conversations table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_Conversations](
	[ConversationId] [uniqueidentifier] NOT NULL,
	[DateCreated] [datetime] NOT NULL,
	[DateUpdated] [datetime] NOT NULL,
	[ParticipantCount] [int] NOT NULL,
	[MessageCount] [int] NOT NULL,
 CONSTRAINT [PK_cs_Messaging_Conversations] PRIMARY KEY CLUSTERED 
(
	[ConversationId] ASC
)) ON [PRIMARY]'

-- Create cs_Messaging_ConversationMessages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_ConversationMessages](
	[ConversationId] [uniqueidentifier] NOT NULL,
	[MessageId] [uniqueidentifier] NOT NULL
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_ConversationMessages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ConversationMessages_cs_Messaging_Conversations] FOREIGN KEY([ConversationId]) REFERENCES [dbo].[cs_Messaging_Conversations] ([ConversationId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationMessages] CHECK CONSTRAINT [FK_cs_Messaging_ConversationMessages_cs_Messaging_Conversations]'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ConversationMessages_cs_Messaging_Messages] FOREIGN KEY([MessageId]) REFERENCES [dbo].[cs_Messaging_Messages] ([MessageId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationMessages] CHECK CONSTRAINT [FK_cs_Messaging_ConversationMessages_cs_Messaging_Messages]'

-- Create indexes for cs_Messaging_ConversationMessages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ConversationMessages_ConversationId] ON [dbo].[cs_Messaging_ConversationMessages] ([ConversationId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ConversationMessages_MessageId] ON [dbo].[cs_Messaging_ConversationMessages] ([MessageId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_ConversationParticipants table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_ConversationParticipants](
	[ConversationId] [uniqueidentifier] NOT NULL,
	[ParticipantId] [int] NOT NULL,
	[Active] [bit] NOT NULL CONSTRAINT [DF_cs_Messaging_ConversationParticipants_Active]  DEFAULT ((1))
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_ConversationParticipants table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationParticipants]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ConversationParticipants_cs_Messaging_Conversations] FOREIGN KEY([ConversationId]) REFERENCES [dbo].[cs_Messaging_Conversations] ([ConversationId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationParticipants] CHECK CONSTRAINT [FK_cs_Messaging_ConversationParticipants_cs_Messaging_Conversations]'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationParticipants]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ConversationParticipants_cs_Users] FOREIGN KEY([ParticipantId]) REFERENCES [dbo].[cs_Users] ([UserID])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ConversationParticipants] CHECK CONSTRAINT [FK_cs_Messaging_ConversationParticipants_cs_Users]'

-- Create indexes for cs_Messaging_ConversationParticipants table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ConversationParticipants_ConversationId] ON [dbo].[cs_Messaging_ConversationParticipants] ([ConversationId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ConversationParticipants_ParticipantId] ON [dbo].[cs_Messaging_ConversationParticipants] ([ParticipantId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_ProfileMessages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_ProfileMessages](
	[UserId] [int] NOT NULL,
	[MessageId] [uniqueidentifier] NOT NULL
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_ProfileMessages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ProfileMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ProfileMessages_cs_Messaging_Messages] FOREIGN KEY([MessageId]) REFERENCES [dbo].[cs_Messaging_Messages] ([MessageId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ProfileMessages] CHECK CONSTRAINT [FK_cs_Messaging_ProfileMessages_cs_Messaging_Messages]'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ProfileMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ProfileMessages_cs_Users] FOREIGN KEY([UserId]) REFERENCES [dbo].[cs_Users] ([UserID])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ProfileMessages] CHECK CONSTRAINT [FK_cs_Messaging_ProfileMessages_cs_Users]'

-- Create indexes for cs_Messaging_ProfileMessages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ProfileMessages_MessageId] ON [dbo].[cs_Messaging_ProfileMessages] ([MessageId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ProfileMessages_UserId] ON [dbo].[cs_Messaging_ProfileMessages] ([UserId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_GroupMessages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_GroupMessages](
	[GroupId] [int] NOT NULL,
	[MessageId] [uniqueidentifier] NOT NULL
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_GroupMessages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_GroupMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_GroupMessages_cs_Messaging_Messages] FOREIGN KEY([MessageId]) REFERENCES [dbo].[cs_Messaging_Messages] ([MessageId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_GroupMessages] CHECK CONSTRAINT [FK_cs_Messaging_GroupMessages_cs_Messaging_Messages]'

-- Create indexes for cs_Messaging_GroupMessages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_GroupMessages_GroupId] ON [dbo].[cs_Messaging_GroupMessages] ([GroupId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_GroupMessages_MessageId] ON [dbo].[cs_Messaging_GroupMessages] ([MessageId]) WITH FILLFACTOR = 90 ON [PRIMARY]'

-- Create cs_Messaging_ActivityMessages table
EXECUTE sp_executesql N'
CREATE TABLE [dbo].[cs_Messaging_ActivityMessages](
	[MessageId] [uniqueidentifier] NOT NULL,
	[UserId] [int] NOT NULL,
	[GroupId] [int] NULL,
    [Type] [nvarchar](50) NOT NULL
) ON [PRIMARY]'

-- Create foreign keys for cs_Messaging_ActivityMessages table
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ActivityMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ActivityMessages_cs_Messaging_Messages] FOREIGN KEY([MessageId]) REFERENCES [dbo].[cs_Messaging_Messages] ([MessageId])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ActivityMessages] CHECK CONSTRAINT [FK_cs_Messaging_ActivityMessages_cs_Messaging_Messages]'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ActivityMessages]  WITH CHECK ADD  CONSTRAINT [FK_cs_Messaging_ActivityMessages_cs_Users] FOREIGN KEY([UserId]) REFERENCES [dbo].[cs_Users] ([UserID])'
EXECUTE sp_executesql N'ALTER TABLE [dbo].[cs_Messaging_ActivityMessages] CHECK CONSTRAINT [FK_cs_Messaging_ActivityMessages_cs_Users]'

-- Create indexes for cs_Messaging_ActivityMessages table
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ActivityMessages_MessageId] ON [dbo].[cs_Messaging_ActivityMessages] ([MessageId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ActivityMessages_UserId] ON [dbo].[cs_Messaging_ActivityMessages] ([UserId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ActivityMessages_GroupId] ON [dbo].[cs_Messaging_ActivityMessages] ([GroupId]) WITH FILLFACTOR = 90 ON [PRIMARY]'
EXECUTE sp_executesql N'CREATE NONCLUSTERED INDEX [IX_cs_Messaging_ActivityMessages_Type] ON [dbo].[cs_Messaging_ActivityMessages] ([Type]) WITH FILLFACTOR = 90 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 

/***********************************************
* Patch: cs_Schema_Patch_3.1.29
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.29'

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

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

if exists ( select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='cs_PostAttachments' and COLUMN_NAME='Content' )
	EXECUTE sp_executesql N'ALTER TABLE cs_PostAttachments ADD CONSTRAINT [DF_cs_PostAttachments_Content] DEFAULT 0x FOR [Content]'

if exists ( select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='cs_PostAttachments_TEMP' and COLUMN_NAME='Content' )
	EXECUTE sp_executesql N'ALTER TABLE cs_PostAttachments_TEMP ADD CONSTRAINT [DF_cs_PostAttachments_TEMP_Content] DEFAULT 0x FOR [Content]'

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.30
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.30'

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

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_AddonConfigurationData] (
		[AddonName] [nvarchar] (255) NOT NULL ,
		[SettingsID] [int] NOT NULL ,
		[AddonID] [uniqueidentifier] NOT NULL ,
		[PropertyNames] [ntext] NULL ,
		[PropertyValues] [ntext] NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

exec sp_executesql N'ALTER TABLE [dbo].[cs_AddonConfigurationData] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_AddonConfigurationData] PRIMARY KEY  CLUSTERED 
	(
		[SettingsID],
		[AddonID]
	)  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 

/***********************************************
* Patch: cs_Schema_Patch_3.1.31
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.31'

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

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

IF NOT EXISTS (
		select 1 from INFORMATION_SCHEMA.TABLES t
		where t.TABLE_SCHEMA = N'dbo' AND t.TABLE_NAME = N'cs_SpamPosts'
	)
	exec sp_executesql N'CREATE TABLE [dbo].[cs_SpamPosts]
(
	SpamPostID bigint identity(1, 1) not null,
	SourceProcedure nvarchar(128) not null,
	SectionID int not null,
	ParentID int not null,
	AllowDuplicatePosts bit,
	DuplicateIntervalInMinutes int,
	Subject nvarchar(256),
	UserID int not null,
	PostAuthor nvarchar(64),
	Body ntext,
	FormattedBody ntext,
	EmoticonID int,
	IsLocked bit,
	IsSticky bit,
	IsApproved bit,
	StickyDate datetime,
	PostType int,
	PostMedia int,
	PostDate datetime not null, /* ensuring that this is never null */
	UserHostAddress nvarchar(32),
	PropertyNames ntext,
	PropertyValues ntext,
	SettingsID int not null,
	IsTracked bit,
	--PostID int not null, /* leaving this one out on purpose */
	ThreadID int, /* this could possibly be null if a thread starter is ever marked as definite spam */
	PostConfiguration int,
	UpdateSectionStatistics bit,
	UserTime datetime not null, /* if for some reason this value comes in a NULL, I will use PostDate and then finally GETDATE() */
	ApplicationPostType int,
	PostName nvarchar(256),
	ThreadStatus int,
	Points int,
	PostDisplayName nvarchar(64),
	AutoApprove bit,

	/* from cs_weblog_Post_Create */
	TitleUrl nvarchar(256),
	PostConfig int,
	BlogPostType tinyint,
	Categories nvarchar(4000),
	SpamScore int,
	PostStatus int
)'

IF NOT EXISTS (
		select 1 from INFORMATION_SCHEMA.TABLES t
		where t.TABLE_SCHEMA = N'dbo' AND t.TABLE_NAME = N'cs_SpamPosts'
	)
	exec sp_executesql N'ALTER TABLE [dbo].[cs_SpamPosts] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_SpamPosts] PRIMARY KEY CLUSTERED
	(
		[SpamPostID]
	) ON [PRIMARY]'

IF indexproperty( object_id(N'[dbo].[cs_SpamPosts]'), N'IX_cs_SpamPosts_SettingsID_SectionID', N'IndexID') IS NULL
	exec sp_executesql N'CREATE INDEX [IX_cs_SpamPosts_SettingsID_SectionID] ON [dbo].[cs_SpamPosts]
	(
		[SettingsID]
		, [SectionID]
		, [ThreadID]
	) 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 

/***********************************************
* Patch: cs_Schema_Patch_3.1.32
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.32'

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

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('
if not exists( select * from cs_ApplicationType where ApplicationType = 13 )
	insert into cs_ApplicationType values( 13, ''MediaGallery'')

DECLARE @ApplicationID uniqueidentifier
DECLARE @SettingsID int
DECLARE @Perm_RoleID uniqueidentifier

DECLARE settingsCursor CURSOR FOR
select ss.SettingsID, aa.ApplicationId
from cs_SiteSettings ss
inner join aspnet_Applications aa on ss.ApplicationName = aa.ApplicationName

OPEN settingsCursor

FETCH NEXT FROM settingsCursor
INTO @SettingsID, @ApplicationID

WHILE @@FETCH_STATUS = 0
BEGIN
	IF NOT EXISTS (SELECT * FROM [aspnet_Roles] where [ApplicationId] = @ApplicationID and [LoweredRoleName] = ''mediagalleryadministrator'') BEGIN
		INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''MediaGalleryAdministrator'', N''mediagalleryadministrator'', N''Administration role for Media Galleries'')
	END

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Everyone''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x000000000000000B, 0x00001000000000B4 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Registered Users''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x000000000000008B, 0x0000100000000030 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Editor''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x00000000000002FF, 0x0000100000000000 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Moderator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x00001000000002CF, 0x0000000000000030 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''MediaGalleryAdministrator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x01001008000002FF, 0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''SystemAdministrator''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x41001008000002FF, 0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = ''Owners''
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 13, @Perm_RoleID, 0x01001008000002FF, 0 )

	FETCH NEXT FROM settingsCursor
	INTO @SettingsID, @ApplicationID
END

CLOSE settingsCursor
DEALLOCATE settingsCursor
')

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.33
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.33'

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

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_rename @objname='files_Downloads', @newname='cs_Posts_Downloads', @objtype='OBJECT'

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

/***********************************************
* Patch: cs_Schema_Patch_3.1.34
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_3.1.34'

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

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'INSERT INTO [dbo].[cs_ApplicationType] ([ApplicationType], [ApplicationName]) VALUES(14, ''Rest'')'
exec sp_executesql N'INSERT INTO [dbo].[cs_ApplicationType] ([ApplicationType], [ApplicationName]) VALUES(1000, ''Newsletter'')'
exec sp_executesql N'INSERT INTO [dbo].[cs_ApplicationType] ([ApplicationType], [ApplicationName]) VALUES(1001, ''Games'')'
exec sp_executesql N'INSERT INTO [dbo].[cs_ApplicationType] ([ApplicationType], [ApplicationName]) VALUES(53, ''Wiki'')'

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

/***********************************************
* Patch: cs_Schema_Patch_4.0.00
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.00'

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

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

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

/***********************************************
* Patch: cs_Schema_Patch_4.0.01
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.01'

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

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'DELETE FROM cs_TrackedSections WHERE SectionID = 0'

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

/***********************************************
* Patch: cs_Schema_Patch_4.0.02
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.02'

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 = 0;
Set @Patch = 2;

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


if object_id('cs_TEMP_FoldSpamConfiguration', 'P') IS NOT NULL
	exec ('drop procedure cs_TEMP_FoldSpamConfiguration')

/* create temp stored proc */
exec('
create procedure cs_TEMP_FoldSpamConfiguration
	@SettingsID int
	, @xml ntext = null
as

declare @ret int, @iXml int, @node nvarchar(128)

select @node = N''/SpamConfiguration/RuleSettings/RuleSetting''

EXECUTE @ret = [master].[dbo].[sp_xml_preparedocument] @iXml OUTPUT, @xml

declare @t table (
	[parentid] int not null
	, [id] int not null
	, [RuleID] uniqueidentifier not null
	, [Key] nvarchar(128) collate database_default not null
	, [Value] nvarchar(3875) collate database_default not null
	, [ValueLength] int not null
)

insert into @t
SELECT
	n.[parentid]
	, n.[id]
	, r.[RuleID]
    , n.[localname] [Key]
    , d.[text] [value]
    , datalength(d.[text]) / 2 [value_len] FROM (
	SELECT * FROM OPENXML(@iXml, @node, 2)
	with (
		[RuleID] uniqueidentifier ''RuleID/text()''
		, [id] int ''@mp:id''
	)
) AS r
inner join (
	SELECT [id], [parentid], [localname] FROM OPENXML(@iXml, @node, 2)
) as n on n.[parentid] = r.[id]
inner join (
	SELECT [parentid], [text] FROM OPENXML(@iXml, @node, 2)
) as d on d.[parentid] = n.[id]
where
	n.[localname] <> N''RuleID'' and n.[localname] <> ''Description'' and 
	n.[localname] <> ''MaxValueLength'' and n.[localname] <> ''DefaultValue''
order by
	n.[parentid], n.[id]

/* release the XML document now that we are done */
EXECUTE [master].[dbo].[sp_xml_removedocument] @iXml

declare @p table (
	[id] int identity(1, 1) not null
	, [AddonID] uniqueidentifier not null
	, [PropertyName] nvarchar(128) collate database_default null
	, [PropertyValue] nvarchar(3875) collate database_default null
)

insert into @p (AddonID, PropertyName, PropertyValue)
select RuleID [AddonID]
	, [Value] + N'':S:'' + coalesce((
		select cast(sum(tx.[ValueLength]) as nvarchar) from @t tx
		where tx.[Key] = ''Value'' and tx.[id] < t.[id] and tx.[RuleID] = t.[RuleID]
	), N''0'') + N'':'' + coalesce((select cast(sum(tx.[ValueLength]) as nvarchar) from @t tx 
		where tx.[parentid] = t.[parentid] and tx.[Key] = ''Value''), N''0'') + N'':'' [PropertyName]
	, (select tx.[Value] from @t tx where tx.[parentid] = t.[parentid] and tx.[Key] = ''Value'') [PropertyValue]
from @t t
where t.[Key] = ''Key''
order by
	t.[RuleID]

if object_id(''tempdb..#flat'') IS NOT NULL exec (''drop table #flat'')

create table #flat (
	[AddonID] uniqueidentifier not null
	, [PropertyNames] ntext collate database_default null
	, [PropertyValues] ntext collate database_default null
)

declare @id int, @AddonID uniqueidentifier
	, @PropertyName nvarchar(128), @PropertyValue nvarchar(3875)
	, @pnPTR binary(16), @pvPTR binary(16)

select @id = 1

while 1=1
begin
	select
		@AddonID = p.[AddonID], @PropertyName = p.[PropertyName], @PropertyValue = p.[PropertyValue]
	from @p p
	where p.[id] = @id
	
	if @@ROWCOUNT = 0 break
	
	if not exists (select 1 from #flat where [AddonID] = @AddonID)
		insert into #flat ([AddonID], [PropertyNames], [PropertyValues]) values (@AddonID, '''', '''')
	
	select @pnPTR = TEXTPTR(f.[PropertyNames]), @pvPTR = TEXTPTR(f.[PropertyValues])
	from #flat f
	where f.[AddonID] = @AddonID
	
	updatetext #flat.[PropertyNames]  @pnPTR null 0 @PropertyName
	updatetext #flat.[PropertyValues] @pvPTR null 0 @PropertyValue
	
	select @id = @id + 1
end

/* showing what was migrated */
select
	cast( f.AddonID as nvarchar(255) )
	, @SettingsID
	, f.AddonID, f.PropertyNames, f.PropertyValues
from
	#flat f
where
	not exists (
		select 1 from [cs_AddonConfigurationData] fx
		where fx.[SettingsID] = @SettingsID AND cast( f.AddonID as nvarchar(255) ) = fx.[AddonName]
	)

/* actually setting it */
INSERT INTO [cs_AddonConfigurationData]( [AddonName], [SettingsID], [AddonID], [PropertyNames], [PropertyValues] )
select
	cast( f.AddonID as nvarchar(255) )
	, @SettingsID
	, f.AddonID, f.PropertyNames, f.PropertyValues
from
	#flat f
where
	not exists (
		select 1 from [cs_AddonConfigurationData] fx
		where fx.[SettingsID] = @SettingsID AND cast( f.AddonID as nvarchar(255) ) = fx.[AddonName]
	)

drop table #flat
')

/* execute rehash - designed to work with sql 2k and 2k5 */
exec (N'
	set nocount on

	declare @qPosition int,
		@qValue nvarchar(4000),
		@hasErrorOccured bit

	/* declare 250 nvarchar(4000) (nearly 1MB worth of space) */
	declare @q1 nvarchar(4000), @q2 nvarchar(4000), @q3 nvarchar(4000), @q4 nvarchar(4000), @q5 nvarchar(4000), @q6 nvarchar(4000), @q7 nvarchar(4000), @q8 nvarchar(4000), @q9 nvarchar(4000), @q10 nvarchar(4000), 
		@q11 nvarchar(4000), @q12 nvarchar(4000), @q13 nvarchar(4000), @q14 nvarchar(4000), @q15 nvarchar(4000), @q16 nvarchar(4000), @q17 nvarchar(4000), @q18 nvarchar(4000), @q19 nvarchar(4000), @q20 nvarchar(4000), 
		@q21 nvarchar(4000), @q22 nvarchar(4000), @q23 nvarchar(4000), @q24 nvarchar(4000), @q25 nvarchar(4000), @q26 nvarchar(4000), @q27 nvarchar(4000), @q28 nvarchar(4000), @q29 nvarchar(4000), @q30 nvarchar(4000), 
		@q31 nvarchar(4000), @q32 nvarchar(4000), @q33 nvarchar(4000), @q34 nvarchar(4000), @q35 nvarchar(4000), @q36 nvarchar(4000), @q37 nvarchar(4000), @q38 nvarchar(4000), @q39 nvarchar(4000), @q40 nvarchar(4000), 
		@q41 nvarchar(4000), @q42 nvarchar(4000), @q43 nvarchar(4000), @q44 nvarchar(4000), @q45 nvarchar(4000), @q46 nvarchar(4000), @q47 nvarchar(4000), @q48 nvarchar(4000), @q49 nvarchar(4000), @q50 nvarchar(4000), 
		@q51 nvarchar(4000), @q52 nvarchar(4000), @q53 nvarchar(4000), @q54 nvarchar(4000), @q55 nvarchar(4000), @q56 nvarchar(4000), @q57 nvarchar(4000), @q58 nvarchar(4000), @q59 nvarchar(4000), @q60 nvarchar(4000), 
		@q61 nvarchar(4000), @q62 nvarchar(4000), @q63 nvarchar(4000), @q64 nvarchar(4000), @q65 nvarchar(4000), @q66 nvarchar(4000), @q67 nvarchar(4000), @q68 nvarchar(4000), @q69 nvarchar(4000), @q70 nvarchar(4000), 
		@q71 nvarchar(4000), @q72 nvarchar(4000), @q73 nvarchar(4000), @q74 nvarchar(4000), @q75 nvarchar(4000), @q76 nvarchar(4000), @q77 nvarchar(4000), @q78 nvarchar(4000), @q79 nvarchar(4000), @q80 nvarchar(4000), 
		@q81 nvarchar(4000), @q82 nvarchar(4000), @q83 nvarchar(4000), @q84 nvarchar(4000), @q85 nvarchar(4000), @q86 nvarchar(4000), @q87 nvarchar(4000), @q88 nvarchar(4000), @q89 nvarchar(4000), @q90 nvarchar(4000), 
		@q91 nvarchar(4000), @q92 nvarchar(4000), @q93 nvarchar(4000), @q94 nvarchar(4000), @q95 nvarchar(4000), @q96 nvarchar(4000), @q97 nvarchar(4000), @q98 nvarchar(4000), @q99 nvarchar(4000), @q100 nvarchar(4000), 
		@q101 nvarchar(4000), @q102 nvarchar(4000), @q103 nvarchar(4000), @q104 nvarchar(4000), @q105 nvarchar(4000), @q106 nvarchar(4000), @q107 nvarchar(4000), @q108 nvarchar(4000), @q109 nvarchar(4000), @q110 nvarchar(4000), 
		@q111 nvarchar(4000), @q112 nvarchar(4000), @q113 nvarchar(4000), @q114 nvarchar(4000), @q115 nvarchar(4000), @q116 nvarchar(4000), @q117 nvarchar(4000), @q118 nvarchar(4000), @q119 nvarchar(4000), @q120 nvarchar(4000), 
		@q121 nvarchar(4000), @q122 nvarchar(4000), @q123 nvarchar(4000), @q124 nvarchar(4000), @q125 nvarchar(4000), @q126 nvarchar(4000), @q127 nvarchar(4000), @q128 nvarchar(4000), @q129 nvarchar(4000), @q130 nvarchar(4000), 
		@q131 nvarchar(4000), @q132 nvarchar(4000), @q133 nvarchar(4000), @q134 nvarchar(4000), @q135 nvarchar(4000), @q136 nvarchar(4000), @q137 nvarchar(4000), @q138 nvarchar(4000), @q139 nvarchar(4000), @q140 nvarchar(4000), 
		@q141 nvarchar(4000), @q142 nvarchar(4000), @q143 nvarchar(4000), @q144 nvarchar(4000), @q145 nvarchar(4000), @q146 nvarchar(4000), @q147 nvarchar(4000), @q148 nvarchar(4000), @q149 nvarchar(4000), @q150 nvarchar(4000), 
		@q151 nvarchar(4000), @q152 nvarchar(4000), @q153 nvarchar(4000), @q154 nvarchar(4000), @q155 nvarchar(4000), @q156 nvarchar(4000), @q157 nvarchar(4000), @q158 nvarchar(4000), @q159 nvarchar(4000), @q160 nvarchar(4000), 
		@q161 nvarchar(4000), @q162 nvarchar(4000), @q163 nvarchar(4000), @q164 nvarchar(4000), @q165 nvarchar(4000), @q166 nvarchar(4000), @q167 nvarchar(4000), @q168 nvarchar(4000), @q169 nvarchar(4000), @q170 nvarchar(4000), 
		@q171 nvarchar(4000), @q172 nvarchar(4000), @q173 nvarchar(4000), @q174 nvarchar(4000), @q175 nvarchar(4000), @q176 nvarchar(4000), @q177 nvarchar(4000), @q178 nvarchar(4000), @q179 nvarchar(4000), @q180 nvarchar(4000), 
		@q181 nvarchar(4000), @q182 nvarchar(4000), @q183 nvarchar(4000), @q184 nvarchar(4000), @q185 nvarchar(4000), @q186 nvarchar(4000), @q187 nvarchar(4000), @q188 nvarchar(4000), @q189 nvarchar(4000), @q190 nvarchar(4000), 
		@q191 nvarchar(4000), @q192 nvarchar(4000), @q193 nvarchar(4000), @q194 nvarchar(4000), @q195 nvarchar(4000), @q196 nvarchar(4000), @q197 nvarchar(4000), @q198 nvarchar(4000), @q199 nvarchar(4000), @q200 nvarchar(4000), 
		@q201 nvarchar(4000), @q202 nvarchar(4000), @q203 nvarchar(4000), @q204 nvarchar(4000), @q205 nvarchar(4000), @q206 nvarchar(4000), @q207 nvarchar(4000), @q208 nvarchar(4000), @q209 nvarchar(4000), @q210 nvarchar(4000), 
		@q211 nvarchar(4000), @q212 nvarchar(4000), @q213 nvarchar(4000), @q214 nvarchar(4000), @q215 nvarchar(4000), @q216 nvarchar(4000), @q217 nvarchar(4000), @q218 nvarchar(4000), @q219 nvarchar(4000), @q220 nvarchar(4000), 
		@q221 nvarchar(4000), @q222 nvarchar(4000), @q223 nvarchar(4000), @q224 nvarchar(4000), @q225 nvarchar(4000), @q226 nvarchar(4000), @q227 nvarchar(4000), @q228 nvarchar(4000), @q229 nvarchar(4000), @q230 nvarchar(4000), 
		@q231 nvarchar(4000), @q232 nvarchar(4000), @q233 nvarchar(4000), @q234 nvarchar(4000), @q235 nvarchar(4000), @q236 nvarchar(4000), @q237 nvarchar(4000), @q238 nvarchar(4000), @q239 nvarchar(4000), @q240 nvarchar(4000), 
		@q241 nvarchar(4000), @q242 nvarchar(4000), @q243 nvarchar(4000), @q244 nvarchar(4000), @q245 nvarchar(4000), @q246 nvarchar(4000), @q247 nvarchar(4000), @q248 nvarchar(4000), @q249 nvarchar(4000), @q250 nvarchar(3999),
		@q251 nvarchar(1)

	/* initialize all vars */
	select @q1 = N'''', @q2 = N'''', @q3 = N'''', @q4 = N'''', @q5 = N'''', @q6 = N'''', @q7 = N'''', @q8 = N'''', @q9 = N'''', @q10 = N'''', 
		@q11 = N'''', @q12 = N'''', @q13 = N'''', @q14 = N'''', @q15 = N'''', @q16 = N'''', @q17 = N'''', @q18 = N'''', @q19 = N'''', @q20 = N'''', 
		@q21 = N'''', @q22 = N'''', @q23 = N'''', @q24 = N'''', @q25 = N'''', @q26 = N'''', @q27 = N'''', @q28 = N'''', @q29 = N'''', @q30 = N'''', 
		@q31 = N'''', @q32 = N'''', @q33 = N'''', @q34 = N'''', @q35 = N'''', @q36 = N'''', @q37 = N'''', @q38 = N'''', @q39 = N'''', @q40 = N'''', 
		@q41 = N'''', @q42 = N'''', @q43 = N'''', @q44 = N'''', @q45 = N'''', @q46 = N'''', @q47 = N'''', @q48 = N'''', @q49 = N'''', @q50 = N'''', 
		@q51 = N'''', @q52 = N'''', @q53 = N'''', @q54 = N'''', @q55 = N'''', @q56 = N'''', @q57 = N'''', @q58 = N'''', @q59 = N'''', @q60 = N'''', 
		@q61 = N'''', @q62 = N'''', @q63 = N'''', @q64 = N'''', @q65 = N'''', @q66 = N'''', @q67 = N'''', @q68 = N'''', @q69 = N'''', @q70 = N'''', 
		@q71 = N'''', @q72 = N'''', @q73 = N'''', @q74 = N'''', @q75 = N'''', @q76 = N'''', @q77 = N'''', @q78 = N'''', @q79 = N'''', @q80 = N'''', 
		@q81 = N'''', @q82 = N'''', @q83 = N'''', @q84 = N'''', @q85 = N'''', @q86 = N'''', @q87 = N'''', @q88 = N'''', @q89 = N'''', @q90 = N'''', 
		@q91 = N'''', @q92 = N'''', @q93 = N'''', @q94 = N'''', @q95 = N'''', @q96 = N'''', @q97 = N'''', @q98 = N'''', @q99 = N'''', @q100 = N'''', 
		@q101 = N'''', @q102 = N'''', @q103 = N'''', @q104 = N'''', @q105 = N'''', @q106 = N'''', @q107 = N'''', @q108 = N'''', @q109 = N'''', @q110 = N'''', 
		@q111 = N'''', @q112 = N'''', @q113 = N'''', @q114 = N'''', @q115 = N'''', @q116 = N'''', @q117 = N'''', @q118 = N'''', @q119 = N'''', @q120 = N'''', 
		@q121 = N'''', @q122 = N'''', @q123 = N'''', @q124 = N'''', @q125 = N'''', @q126 = N'''', @q127 = N'''', @q128 = N'''', @q129 = N'''', @q130 = N'''', 
		@q131 = N'''', @q132 = N'''', @q133 = N'''', @q134 = N'''', @q135 = N'''', @q136 = N'''', @q137 = N'''', @q138 = N'''', @q139 = N'''', @q140 = N'''', 
		@q141 = N'''', @q142 = N'''', @q143 = N'''', @q144 = N'''', @q145 = N'''', @q146 = N'''', @q147 = N'''', @q148 = N'''', @q149 = N'''', @q150 = N'''', 
		@q151 = N'''', @q152 = N'''', @q153 = N'''', @q154 = N'''', @q155 = N'''', @q156 = N'''', @q157 = N'''', @q158 = N'''', @q159 = N'''', @q160 = N'''', 
		@q161 = N'''', @q162 = N'''', @q163 = N'''', @q164 = N'''', @q165 = N'''', @q166 = N'''', @q167 = N'''', @q168 = N'''', @q169 = N'''', @q170 = N'''', 
		@q171 = N'''', @q172 = N'''', @q173 = N'''', @q174 = N'''', @q175 = N'''', @q176 = N'''', @q177 = N'''', @q178 = N'''', @q179 = N'''', @q180 = N'''', 
		@q181 = N'''', @q182 = N'''', @q183 = N'''', @q184 = N'''', @q185 = N'''', @q186 = N'''', @q187 = N'''', @q188 = N'''', @q189 = N'''', @q190 = N'''', 
		@q191 = N'''', @q192 = N'''', @q193 = N'''', @q194 = N'''', @q195 = N'''', @q196 = N'''', @q197 = N'''', @q198 = N'''', @q199 = N'''', @q200 = N'''', 
		@q201 = N'''', @q202 = N'''', @q203 = N'''', @q204 = N'''', @q205 = N'''', @q206 = N'''', @q207 = N'''', @q208 = N'''', @q209 = N'''', @q210 = N'''', 
		@q211 = N'''', @q212 = N'''', @q213 = N'''', @q214 = N'''', @q215 = N'''', @q216 = N'''', @q217 = N'''', @q218 = N'''', @q219 = N'''', @q220 = N'''', 
		@q221 = N'''', @q222 = N'''', @q223 = N'''', @q224 = N'''', @q225 = N'''', @q226 = N'''', @q227 = N'''', @q228 = N'''', @q229 = N'''', @q230 = N'''', 
		@q231 = N'''', @q232 = N'''', @q233 = N'''', @q234 = N'''', @q235 = N'''', @q236 = N'''', @q237 = N'''', @q238 = N'''', @q239 = N'''', @q240 = N'''', 
		@q241 = N'''', @q242 = N'''', @q243 = N'''', @q244 = N'''', @q245 = N'''', @q246 = N'''', @q247 = N'''', @q248 = N'''', @q249 = N'''', @q250 = N'''',
		@q251 = N'''''''' /* special ending for this process */

	select @qPosition = 1, @qValue = N'''', @hasErrorOccured = 0

	declare @SettingsID int, @sqlPTR binary(16), @sqlstring nvarchar(100), @index int
	select @index = 1
	DECLARE cSettingIDs CURSOR FOR
		SELECT acs.SettingsID from cs_ApplicationConfigurationSettings acs where acs.ApplicationType = 10

	open cSettingIDs
	fetch next from cSettingIDs into @SettingsID
	while @@fetch_status = 0
	begin
		set @q1 = N''exec cs_TEMP_FoldSpamConfiguration '' + cast(@SettingsID as nvarchar(10)) + N'', N''''''

		while @index <= 0x7ffffff
		begin
			select @qPosition = @qPosition + 1
			SELECT @qValue = (select substring(acs.Settings, @index, 2000)
				from cs_ApplicationConfigurationSettings acs where acs.SettingsID = @SettingsID AND acs.ApplicationType = 10)

			if @qValue is null OR datalength(@qValue) = 0 begin break end

			if @qPosition <= 100
			begin
				if @qPosition = 1 select @q1 = @qValue else if @qPosition = 2 select @q2 = @qValue else if @qPosition = 3 select @q3 = @qValue else if @qPosition = 4 select @q4 = @qValue else if @qPosition = 5 select @q5 = @qValue else if @qPosition = 6 select @q6 = @qValue else if @qPosition = 7 select @q7 = @qValue else if @qPosition = 8 select @q8 = @qValue else if @qPosition = 9 select @q9 = @qValue else if @qPosition = 10 select @q10 = @qValue 
				else if @qPosition = 11 select @q11 = @qValue else if @qPosition = 12 select @q12 = @qValue else if @qPosition = 13 select @q13 = @qValue else if @qPosition = 14 select @q14 = @qValue else if @qPosition = 15 select @q15 = @qValue else if @qPosition = 16 select @q16 = @qValue else if @qPosition = 17 select @q17 = @qValue else if @qPosition = 18 select @q18 = @qValue else if @qPosition = 19 select @q19 = @qValue else if @qPosition = 20 select @q20 = @qValue 
				else if @qPosition = 21 select @q21 = @qValue else if @qPosition = 22 select @q22 = @qValue else if @qPosition = 23 select @q23 = @qValue else if @qPosition = 24 select @q24 = @qValue else if @qPosition = 25 select @q25 = @qValue else if @qPosition = 26 select @q26 = @qValue else if @qPosition = 27 select @q27 = @qValue else if @qPosition = 28 select @q28 = @qValue else if @qPosition = 29 select @q29 = @qValue else if @qPosition = 30 select @q30 = @qValue 
				else if @qPosition = 31 select @q31 = @qValue else if @qPosition = 32 select @q32 = @qValue else if @qPosition = 33 select @q33 = @qValue else if @qPosition = 34 select @q34 = @qValue else if @qPosition = 35 select @q35 = @qValue else if @qPosition = 36 select @q36 = @qValue else if @qPosition = 37 select @q37 = @qValue else if @qPosition = 38 select @q38 = @qValue else if @qPosition = 39 select @q39 = @qValue else if @qPosition = 40 select @q40 = @qValue 
				else if @qPosition = 41 select @q41 = @qValue else if @qPosition = 42 select @q42 = @qValue else if @qPosition = 43 select @q43 = @qValue else if @qPosition = 44 select @q44 = @qValue else if @qPosition = 45 select @q45 = @qValue else if @qPosition = 46 select @q46 = @qValue else if @qPosition = 47 select @q47 = @qValue else if @qPosition = 48 select @q48 = @qValue else if @qPosition = 49 select @q49 = @qValue else if @qPosition = 50 select @q50 = @qValue 
				else if @qPosition = 51 select @q51 = @qValue else if @qPosition = 52 select @q52 = @qValue else if @qPosition = 53 select @q53 = @qValue else if @qPosition = 54 select @q54 = @qValue else if @qPosition = 55 select @q55 = @qValue else if @qPosition = 56 select @q56 = @qValue else if @qPosition = 57 select @q57 = @qValue else if @qPosition = 58 select @q58 = @qValue else if @qPosition = 59 select @q59 = @qValue else if @qPosition = 60 select @q60 = @qValue 
				else if @qPosition = 61 select @q61 = @qValue else if @qPosition = 62 select @q62 = @qValue else if @qPosition = 63 select @q63 = @qValue else if @qPosition = 64 select @q64 = @qValue else if @qPosition = 65 select @q65 = @qValue else if @qPosition = 66 select @q66 = @qValue else if @qPosition = 67 select @q67 = @qValue else if @qPosition = 68 select @q68 = @qValue else if @qPosition = 69 select @q69 = @qValue else if @qPosition = 70 select @q70 = @qValue 
				else if @qPosition = 71 select @q71 = @qValue else if @qPosition = 72 select @q72 = @qValue else if @qPosition = 73 select @q73 = @qValue else if @qPosition = 74 select @q74 = @qValue else if @qPosition = 75 select @q75 = @qValue else if @qPosition = 76 select @q76 = @qValue else if @qPosition = 77 select @q77 = @qValue else if @qPosition = 78 select @q78 = @qValue else if @qPosition = 79 select @q79 = @qValue else if @qPosition = 80 select @q80 = @qValue 
				else if @qPosition = 81 select @q81 = @qValue else if @qPosition = 82 select @q82 = @qValue else if @qPosition = 83 select @q83 = @qValue else if @qPosition = 84 select @q84 = @qValue else if @qPosition = 85 select @q85 = @qValue else if @qPosition = 86 select @q86 = @qValue else if @qPosition = 87 select @q87 = @qValue else if @qPosition = 88 select @q88 = @qValue else if @qPosition = 89 select @q89 = @qValue else if @qPosition = 90 select @q90 = @qValue 
				else if @qPosition = 91 select @q91 = @qValue else if @qPosition = 92 select @q92 = @qValue else if @qPosition = 93 select @q93 = @qValue else if @qPosition = 94 select @q94 = @qValue else if @qPosition = 95 select @q95 = @qValue else if @qPosition = 96 select @q96 = @qValue else if @qPosition = 97 select @q97 = @qValue else if @qPosition = 98 select @q98 = @qValue else if @qPosition = 99 select @q99 = @qValue else if @qPosition = 100 select @q100 = @qValue
			end
			else if @qPosition <= 200
			begin
				if @qPosition = 101 select @q101 = @qValue else if @qPosition = 102 select @q102 = @qValue else if @qPosition = 103 select @q103 = @qValue else if @qPosition = 104 select @q104 = @qValue else if @qPosition = 105 select @q105 = @qValue else if @qPosition = 106 select @q106 = @qValue else if @qPosition = 107 select @q107 = @qValue else if @qPosition = 108 select @q108 = @qValue else if @qPosition = 109 select @q109 = @qValue else if @qPosition = 110 select @q110 = @qValue
				else if @qPosition = 111 select @q111 = @qValue else if @qPosition = 112 select @q112 = @qValue else if @qPosition = 113 select @q113 = @qValue else if @qPosition = 114 select @q114 = @qValue else if @qPosition = 115 select @q115 = @qValue else if @qPosition = 116 select @q116 = @qValue else if @qPosition = 117 select @q117 = @qValue else if @qPosition = 118 select @q118 = @qValue else if @qPosition = 119 select @q119 = @qValue else if @qPosition = 120 select @q120 = @qValue
				else if @qPosition = 121 select @q121 = @qValue else if @qPosition = 122 select @q122 = @qValue else if @qPosition = 123 select @q123 = @qValue else if @qPosition = 124 select @q124 = @qValue else if @qPosition = 125 select @q125 = @qValue else if @qPosition = 126 select @q126 = @qValue else if @qPosition = 127 select @q127 = @qValue else if @qPosition = 128 select @q128 = @qValue else if @qPosition = 129 select @q129 = @qValue else if @qPosition = 130 select @q130 = @qValue 
				else if @qPosition = 131 select @q131 = @qValue else if @qPosition = 132 select @q132 = @qValue else if @qPosition = 133 select @q133 = @qValue else if @qPosition = 134 select @q134 = @qValue else if @qPosition = 135 select @q135 = @qValue else if @qPosition = 136 select @q136 = @qValue else if @qPosition = 137 select @q137 = @qValue else if @qPosition = 138 select @q138 = @qValue else if @qPosition = 139 select @q139 = @qValue else if @qPosition = 140 select @q140 = @qValue 
				else if @qPosition = 141 select @q141 = @qValue else if @qPosition = 142 select @q142 = @qValue else if @qPosition = 143 select @q143 = @qValue else if @qPosition = 144 select @q144 = @qValue else if @qPosition = 145 select @q145 = @qValue else if @qPosition = 146 select @q146 = @qValue else if @qPosition = 147 select @q147 = @qValue else if @qPosition = 148 select @q148 = @qValue else if @qPosition = 149 select @q149 = @qValue else if @qPosition = 150 select @q150 = @qValue 
				else if @qPosition = 151 select @q151 = @qValue else if @qPosition = 152 select @q152 = @qValue else if @qPosition = 153 select @q153 = @qValue else if @qPosition = 154 select @q154 = @qValue else if @qPosition = 155 select @q155 = @qValue else if @qPosition = 156 select @q156 = @qValue else if @qPosition = 157 select @q157 = @qValue else if @qPosition = 158 select @q158 = @qValue else if @qPosition = 159 select @q159 = @qValue else if @qPosition = 160 select @q160 = @qValue 
				else if @qPosition = 161 select @q161 = @qValue else if @qPosition = 162 select @q162 = @qValue else if @qPosition = 163 select @q163 = @qValue else if @qPosition = 164 select @q164 = @qValue else if @qPosition = 165 select @q165 = @qValue else if @qPosition = 166 select @q166 = @qValue else if @qPosition = 167 select @q167 = @qValue else if @qPosition = 168 select @q168 = @qValue else if @qPosition = 169 select @q169 = @qValue else if @qPosition = 170 select @q170 = @qValue 
				else if @qPosition = 171 select @q171 = @qValue else if @qPosition = 172 select @q172 = @qValue else if @qPosition = 173 select @q173 = @qValue else if @qPosition = 174 select @q174 = @qValue else if @qPosition = 175 select @q175 = @qValue else if @qPosition = 176 select @q176 = @qValue else if @qPosition = 177 select @q177 = @qValue else if @qPosition = 178 select @q178 = @qValue else if @qPosition = 179 select @q179 = @qValue else if @qPosition = 180 select @q180 = @qValue 
				else if @qPosition = 181 select @q181 = @qValue else if @qPosition = 182 select @q182 = @qValue else if @qPosition = 183 select @q183 = @qValue else if @qPosition = 184 select @q184 = @qValue else if @qPosition = 185 select @q185 = @qValue else if @qPosition = 186 select @q186 = @qValue else if @qPosition = 187 select @q187 = @qValue else if @qPosition = 188 select @q188 = @qValue else if @qPosition = 189 select @q189 = @qValue else if @qPosition = 190 select @q190 = @qValue 
				else if @qPosition = 191 select @q191 = @qValue else if @qPosition = 192 select @q192 = @qValue else if @qPosition = 193 select @q193 = @qValue else if @qPosition = 194 select @q194 = @qValue else if @qPosition = 195 select @q195 = @qValue else if @qPosition = 196 select @q196 = @qValue else if @qPosition = 197 select @q197 = @qValue else if @qPosition = 198 select @q198 = @qValue else if @qPosition = 199 select @q199 = @qValue else if @qPosition = 200 select @q200 = @qValue
			end else begin
				if @qPosition = 201 select @q201 = @qValue else if @qPosition = 202 select @q202 = @qValue else if @qPosition = 203 select @q203 = @qValue else if @qPosition = 204 select @q204 = @qValue else if @qPosition = 205 select @q205 = @qValue else if @qPosition = 206 select @q206 = @qValue else if @qPosition = 207 select @q207 = @qValue else if @qPosition = 208 select @q208 = @qValue else if @qPosition = 209 select @q209 = @qValue else if @qPosition = 210 select @q210 = @qValue 
				else if @qPosition = 211 select @q211 = @qValue else if @qPosition = 212 select @q212 = @qValue else if @qPosition = 213 select @q213 = @qValue else if @qPosition = 214 select @q214 = @qValue else if @qPosition = 215 select @q215 = @qValue else if @qPosition = 216 select @q216 = @qValue else if @qPosition = 217 select @q217 = @qValue else if @qPosition = 218 select @q218 = @qValue else if @qPosition = 219 select @q219 = @qValue else if @qPosition = 220 select @q220 = @qValue 
				else if @qPosition = 221 select @q221 = @qValue else if @qPosition = 222 select @q222 = @qValue else if @qPosition = 223 select @q223 = @qValue else if @qPosition = 224 select @q224 = @qValue else if @qPosition = 225 select @q225 = @qValue else if @qPosition = 226 select @q226 = @qValue else if @qPosition = 227 select @q227 = @qValue else if @qPosition = 228 select @q228 = @qValue else if @qPosition = 229 select @q229 = @qValue else if @qPosition = 230 select @q230 = @qValue 
				else if @qPosition = 231 select @q231 = @qValue else if @qPosition = 232 select @q232 = @qValue else if @qPosition = 233 select @q233 = @qValue else if @qPosition = 234 select @q234 = @qValue else if @qPosition = 235 select @q235 = @qValue else if @qPosition = 236 select @q236 = @qValue else if @qPosition = 237 select @q237 = @qValue else if @qPosition = 238 select @q238 = @qValue else if @qPosition = 239 select @q239 = @qValue else if @qPosition = 240 select @q240 = @qValue 
				else if @qPosition = 241 select @q241 = @qValue else if @qPosition = 242 select @q242 = @qValue else if @qPosition = 243 select @q243 = @qValue else if @qPosition = 244 select @q244 = @qValue else if @qPosition = 245 select @q245 = @qValue else if @qPosition = 246 select @q246 = @qValue else if @qPosition = 247 select @q247 = @qValue else if @qPosition = 248 select @q248 = @qValue else if @qPosition = 249 select @q249 = @qValue else if @qPosition = 250 select @q250 = @qValue
				
				if @qPosition > 250
				begin
					raiserror(''Internal Error : Command buffer limit of ~1MB has been reached! Resultset will not be executed.'', 16, -1)
					select @hasErrorOccured = 1
				end
			end

			if @hasErrorOccured = 1 begin break end

			select @index = @index + 2000, @qValue = null
		end

		if @hasErrorOccured = 1 begin break end

		/* concat all buffers and execute */
		exec(@q1+@q2+@q3+@q4+@q5+@q6+@q7+@q8+@q9+@q10+
			@q11+@q12+@q13+@q14+@q15+@q16+@q17+@q18+@q19+@q20+
			@q21+@q22+@q23+@q24+@q25+@q26+@q27+@q28+@q29+@q30+
			@q31+@q32+@q33+@q34+@q35+@q36+@q37+@q38+@q39+@q40+
			@q41+@q42+@q43+@q44+@q45+@q46+@q47+@q48+@q49+@q50+
			@q51+@q52+@q53+@q54+@q55+@q56+@q57+@q58+@q59+@q60+
			@q61+@q62+@q63+@q64+@q65+@q66+@q67+@q68+@q69+@q70+
			@q71+@q72+@q73+@q74+@q75+@q76+@q77+@q78+@q79+@q80+
			@q81+@q82+@q83+@q84+@q85+@q86+@q87+@q88+@q89+@q90+
			@q91+@q92+@q93+@q94+@q95+@q96+@q97+@q98+@q99+@q100+
			@q101+@q102+@q103+@q104+@q105+@q106+@q107+@q108+@q109+@q110+
			@q111+@q112+@q113+@q114+@q115+@q116+@q117+@q118+@q119+@q120+
			@q121+@q122+@q123+@q124+@q125+@q126+@q127+@q128+@q129+@q130+
			@q131+@q132+@q133+@q134+@q135+@q136+@q137+@q138+@q139+@q140+
			@q141+@q142+@q143+@q144+@q145+@q146+@q147+@q148+@q149+@q150+
			@q151+@q152+@q153+@q154+@q155+@q156+@q157+@q158+@q159+@q160+
			@q161+@q162+@q163+@q164+@q165+@q166+@q167+@q168+@q169+@q170+
			@q171+@q172+@q173+@q174+@q175+@q176+@q177+@q178+@q179+@q180+
			@q181+@q182+@q183+@q184+@q185+@q186+@q187+@q188+@q189+@q190+
			@q191+@q192+@q193+@q194+@q195+@q196+@q197+@q198+@q199+@q200+
			@q201+@q202+@q203+@q204+@q205+@q206+@q207+@q208+@q209+@q210+
			@q211+@q212+@q213+@q214+@q215+@q216+@q217+@q218+@q219+@q220+
			@q221+@q222+@q223+@q224+@q225+@q226+@q227+@q228+@q229+@q230+
			@q231+@q232+@q233+@q234+@q235+@q236+@q237+@q238+@q239+@q240+
			@q241+@q242+@q243+@q244+@q245+@q246+@q247+@q248+@q249+@q250+
			@q251)

		select @index = 1

		select @q1 = N'''', @q2 = N'''', @q3 = N'''', @q4 = N'''', @q5 = N'''', @q6 = N'''', @q7 = N'''', @q8 = N'''', @q9 = N'''', @q10 = N'''', 
			@q11 = N'''', @q12 = N'''', @q13 = N'''', @q14 = N'''', @q15 = N'''', @q16 = N'''', @q17 = N'''', @q18 = N'''', @q19 = N'''', @q20 = N'''', 
			@q21 = N'''', @q22 = N'''', @q23 = N'''', @q24 = N'''', @q25 = N'''', @q26 = N'''', @q27 = N'''', @q28 = N'''', @q29 = N'''', @q30 = N'''', 
			@q31 = N'''', @q32 = N'''', @q33 = N'''', @q34 = N'''', @q35 = N'''', @q36 = N'''', @q37 = N'''', @q38 = N'''', @q39 = N'''', @q40 = N'''', 
			@q41 = N'''', @q42 = N'''', @q43 = N'''', @q44 = N'''', @q45 = N'''', @q46 = N'''', @q47 = N'''', @q48 = N'''', @q49 = N'''', @q50 = N'''', 
			@q51 = N'''', @q52 = N'''', @q53 = N'''', @q54 = N'''', @q55 = N'''', @q56 = N'''', @q57 = N'''', @q58 = N'''', @q59 = N'''', @q60 = N'''', 
			@q61 = N'''', @q62 = N'''', @q63 = N'''', @q64 = N'''', @q65 = N'''', @q66 = N'''', @q67 = N'''', @q68 = N'''', @q69 = N'''', @q70 = N'''', 
			@q71 = N'''', @q72 = N'''', @q73 = N'''', @q74 = N'''', @q75 = N'''', @q76 = N'''', @q77 = N'''', @q78 = N'''', @q79 = N'''', @q80 = N'''', 
			@q81 = N'''', @q82 = N'''', @q83 = N'''', @q84 = N'''', @q85 = N'''', @q86 = N'''', @q87 = N'''', @q88 = N'''', @q89 = N'''', @q90 = N'''', 
			@q91 = N'''', @q92 = N'''', @q93 = N'''', @q94 = N'''', @q95 = N'''', @q96 = N'''', @q97 = N'''', @q98 = N'''', @q99 = N'''', @q100 = N'''', 
			@q101 = N'''', @q102 = N'''', @q103 = N'''', @q104 = N'''', @q105 = N'''', @q106 = N'''', @q107 = N'''', @q108 = N'''', @q109 = N'''', @q110 = N'''', 
			@q111 = N'''', @q112 = N'''', @q113 = N'''', @q114 = N'''', @q115 = N'''', @q116 = N'''', @q117 = N'''', @q118 = N'''', @q119 = N'''', @q120 = N'''', 
			@q121 = N'''', @q122 = N'''', @q123 = N'''', @q124 = N'''', @q125 = N'''', @q126 = N'''', @q127 = N'''', @q128 = N'''', @q129 = N'''', @q130 = N'''', 
			@q131 = N'''', @q132 = N'''', @q133 = N'''', @q134 = N'''', @q135 = N'''', @q136 = N'''', @q137 = N'''', @q138 = N'''', @q139 = N'''', @q140 = N'''', 
			@q141 = N'''', @q142 = N'''', @q143 = N'''', @q144 = N'''', @q145 = N'''', @q146 = N'''', @q147 = N'''', @q148 = N'''', @q149 = N'''', @q150 = N'''', 
			@q151 = N'''', @q152 = N'''', @q153 = N'''', @q154 = N'''', @q155 = N'''', @q156 = N'''', @q157 = N'''', @q158 = N'''', @q159 = N'''', @q160 = N'''', 
			@q161 = N'''', @q162 = N'''', @q163 = N'''', @q164 = N'''', @q165 = N'''', @q166 = N'''', @q167 = N'''', @q168 = N'''', @q169 = N'''', @q170 = N'''', 
			@q171 = N'''', @q172 = N'''', @q173 = N'''', @q174 = N'''', @q175 = N'''', @q176 = N'''', @q177 = N'''', @q178 = N'''', @q179 = N'''', @q180 = N'''', 
			@q181 = N'''', @q182 = N'''', @q183 = N'''', @q184 = N'''', @q185 = N'''', @q186 = N'''', @q187 = N'''', @q188 = N'''', @q189 = N'''', @q190 = N'''', 
			@q191 = N'''', @q192 = N'''', @q193 = N'''', @q194 = N'''', @q195 = N'''', @q196 = N'''', @q197 = N'''', @q198 = N'''', @q199 = N'''', @q200 = N'''', 
			@q201 = N'''', @q202 = N'''', @q203 = N'''', @q204 = N'''', @q205 = N'''', @q206 = N'''', @q207 = N'''', @q208 = N'''', @q209 = N'''', @q210 = N'''', 
			@q211 = N'''', @q212 = N'''', @q213 = N'''', @q214 = N'''', @q215 = N'''', @q216 = N'''', @q217 = N'''', @q218 = N'''', @q219 = N'''', @q220 = N'''', 
			@q221 = N'''', @q222 = N'''', @q223 = N'''', @q224 = N'''', @q225 = N'''', @q226 = N'''', @q227 = N'''', @q228 = N'''', @q229 = N'''', @q230 = N'''', 
			@q231 = N'''', @q232 = N'''', @q233 = N'''', @q234 = N'''', @q235 = N'''', @q236 = N'''', @q237 = N'''', @q238 = N'''', @q239 = N'''', @q240 = N'''', 
			@q241 = N'''', @q242 = N'''', @q243 = N'''', @q244 = N'''', @q245 = N'''', @q246 = N'''', @q247 = N'''', @q248 = N'''', @q249 = N'''', @q250 = N'''',
			@q251 = N'''''''' /* special ending for this process */

		fetch next from cSettingIDs into @SettingsID
	end
	close cSettingIDs
	deallocate cSettingIDs

	if @hasErrorOccured = 1
	begin
		print ''An error occured - too much data to execute!''
	end
')

/* remove temp stored proc */
if object_id('cs_TEMP_FoldSpamConfiguration', 'P') IS NOT NULL
	exec ('drop procedure cs_TEMP_FoldSpamConfiguration')


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

/***********************************************
* Patch: cs_Schema_Patch_4.0.03
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.03'

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 = 0;
Set @Patch = 3;

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 cs_Messaging_Messages ALTER COLUMN Body ntext 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 

/***********************************************
* Patch: cs_Schema_Patch_4.0.04
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.04'

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

if object_id('cs_TemporaryUserTokens') IS NULL
	EXECUTE sp_executesql N'
	CREATE TABLE [dbo].[cs_TemporaryUserTokens] (
		[TemporaryUserTokenID] [int] IDENTITY (1, 1) NOT NULL ,
		[UserID] [int] NOT NULL ,
		[SettingsID] [int] NOT NULL ,
		[Token] [uniqueidentifier] NOT NULL ,
		[ExpirationDate] [datetime] NOT NULL 
	) 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 


/***********************************************
* Patch: cs_Schema_Patch_4.0.05
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.05'

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 = 0;
Set @Patch = 5;

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('
	UPDATE cs_Censorship 
	SET Word = ''expression\(.*\);''
	WHERE Word = ''expression\(*.\);''

	UPDATE cs_Censorship 
	SET Word = ''expression\(.*\)''
	WHERE Word = ''expression\(*.\)''
')

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


/***********************************************
* Patch: cs_Schema_Patch_4.0.06
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.06'

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 = 0;
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 ##

exec('
	insert into cs_ThemeConfigurationData (ThemeName, SettingsID, SectionID, PropertyNames, PropertyValues)
	select ''calypso'', SettingsID, SectionID, PropertyNames, PropertyValues
	from cs_ThemeConfigurationData
	where ThemeName = ''default''
	and SectionID not in (
		select T.SectionID from cs_ThemeConfigurationData T where T.ThemeName = ''calypso''
		)
')

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


/***********************************************
* Patch: cs_Schema_Patch_4.0.07
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.07'

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

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

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_ModerationAudit]') AND [name] = N'IX_cs_ModerationAudit_UserID_ModerationAction')
	exec sp_executesql N'DROP INDEX [cs_ModerationAudit].[IX_cs_ModerationAudit_UserID_ModerationAction]'

exec sp_executesql N'create index IX_cs_ModerationAudit_UserID_ModerationAction on cs_ModerationAudit ( UserID, ModerationAction ) 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 


/***********************************************
* Patch: cs_Schema_Patch_4.0.08
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.08'

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 = 0;
Set @Patch = 8;

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

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

/***********************************************
* Patch: cs_Schema_Patch_4.0.09
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.09'

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 = 0;
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 ##

/* Manage updates to cs_Friends_xref */
IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_Friends_xref]') AND [name] = N'IX_cs_Friends_xref_Friends_xrefId')
	exec sp_executesql N'DROP INDEX [cs_Friends_xref].[IX_cs_Friends_xref_Friends_xrefId]'

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'cs_Friends_xref' AND COLUMN_NAME = N'Friends_xrefId')
	exec sp_executesql N'alter table [cs_Friends_xref] drop column [Friends_xrefId]'

/* this is a temporary identity */
exec sp_executesql N'alter table [cs_Friends_xref] add [Friends_xrefId] int identity(1, 1) not null'

exec sp_executesql N'CREATE INDEX [IX_cs_Friends_xref_Friends_xrefId] ON [cs_Friends_xref]
(
	[Friends_xrefId]
)
ON [PRIMARY]'

set nocount on
exec sp_executesql N'delete from [cs_Friends_xref]
where exists (
	select 1 from [cs_Friends_xref] b
	where
		b.[UserID] = [cs_Friends_xref].[UserID]
		and b.[FriendUserID] = [cs_Friends_xref].[FriendUserID]
	group by
		b.[UserID], b.[FriendUserID]
	having
		min(b.[Friends_xrefId]) < [cs_Friends_xref].[Friends_xrefId]
)'
set nocount off

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_Friends_xref]') AND [name] = N'IX_cs_Friends_xref_Friends_xrefId')
	exec sp_executesql N'DROP INDEX [cs_Friends_xref].[IX_cs_Friends_xref_Friends_xrefId]'

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'cs_Friends_xref' AND COLUMN_NAME = N'Friends_xrefId')
	exec sp_executesql N'alter table [cs_Friends_xref] drop column [Friends_xrefId]'

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_Friends_xref]') AND [name] = N'IXUC_cs_Friends_xref_UserID_FriendUserID')
	exec sp_executesql N'DROP INDEX [cs_Friends_xref].[IXUC_cs_Friends_xref_UserID_FriendUserID]'

exec sp_executesql N'CREATE UNIQUE CLUSTERED INDEX [IXUC_cs_Friends_xref_UserID_FriendUserID] ON [cs_Friends_xref]
(
	[UserID]
	, [FriendUserID]
) WITH FILLFACTOR = 90
ON [PRIMARY]'

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_Friends_xref]') AND [name] = N'IX_cs_Friends_xref_FriendUserID')
	exec sp_executesql N'DROP INDEX [cs_Friends_xref].[IX_cs_Friends_xref_FriendUserID]'

exec sp_executesql N'CREATE INDEX [IX_cs_Friends_xref_FriendUserID] ON [cs_Friends_xref]
(
	[FriendUserID]
) WITH FILLFACTOR = 90
ON [PRIMARY]'

exec sp_executesql N'dbcc dbreindex(''cs_Friends_xref'')'


/* Now manage updates to cs_SearchBarrel */
if exists (select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
	where tc.TABLE_NAME = N'cs_SearchBarrel' and tc.CONSTRAINT_NAME = 'IX_cs_SearchBarrel')
	exec sp_executesql N'ALTER TABLE [cs_SearchBarrel] DROP CONSTRAINT [IX_cs_SearchBarrel]'

exec sp_executesql N'ALTER TABLE [cs_SearchBarrel] ADD CONSTRAINT [IX_cs_SearchBarrel] UNIQUE NONCLUSTERED
(
	[WordHash] ASC,
	[PostID] ASC
) WITH FILLFACTOR = 90
ON [PRIMARY]'

IF EXISTS (SELECT 1 FROM dbo.sysindexes WHERE [id] = OBJECT_ID(N'[cs_SearchBarrel]') AND [name] = N'WordHash_SectionID_CLX_IDX')
	exec sp_executesql N'DROP INDEX [cs_SearchBarrel].[WordHash_SectionID_CLX_IDX]'

exec sp_executesql N'CREATE CLUSTERED INDEX [WordHash_SectionID_CLX_IDX] ON [cs_SearchBarrel] 
(
	[WordHash] ASC,
	[SectionID] ASC
) WITH FILLFACTOR = 90 ON [PRIMARY]'

exec sp_executesql N'dbcc dbreindex(''cs_SearchBarrel'')'



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


/***********************************************
* Patch: cs_Schema_Patch_4.0.10
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.10'

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 = 0;
Set @Patch = 10;

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

if object_id(N'cs_Visits', N'U') IS NOT NULL
	exec sp_executesql N'drop table [cs_Visits]'

if object_id(N'cs_VisitsDaily', N'U') IS NOT NULL
	exec sp_executesql N'drop table [cs_VisitsDaily]'

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


/***********************************************
* Patch: cs_Schema_Patch_4.0.11
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.11'

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 = 0;
Set @Patch = 11;

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('
DECLARE @ApplicationID uniqueidentifier
DECLARE @Perm_RoleID uniqueidentifier

DECLARE settingsCursor CURSOR FOR
select aa.ApplicationId
from cs_SiteSettings ss
inner join aspnet_Applications aa on ss.ApplicationName = aa.ApplicationName

OPEN settingsCursor

FETCH NEXT FROM settingsCursor
INTO @ApplicationID

WHILE @@FETCH_STATUS = 0
BEGIN
	IF NOT EXISTS (SELECT * FROM [aspnet_Roles] where [ApplicationId] = @ApplicationID and [LoweredRoleName] = ''groupadministrator'') BEGIN
		INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''GroupAdministrator'', N''groupadministrator'', N''Administration role for Groups'')
	END
	
	FETCH NEXT FROM settingsCursor
	INTO @ApplicationID
END

CLOSE settingsCursor
DEALLOCATE settingsCursor
')	

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


/***********************************************
* Patch: cs_Schema_Patch_4.0.12
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.12'

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 = 0;
Set @Patch = 12;

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('
DELETE FROM cs_PrivateMessages WHERE UserID NOT IN (SELECT U.UserID FROM cs_Users U)
')	

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


/***********************************************
* Patch: cs_Schema_Patch_4.0.13
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.13'

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 = 0;
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 ##

delete from [dbo].[cs_Licenses] where LicenseID = '01B84EF8-EA06-42D5-9634-AD716B8445FB'

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

/***********************************************
* Patch: cs_Schema_Patch_4.0.14
* File Date: 4/14/2008 6:37:23 PM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.14'

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 = 0;
Set @Patch = 14;

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


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_RollerBlogPost' and convert(varbinary(12), COLUMN_NAME) = 0x550072006C0049006400)
begin
	print N'Renaming cs_RollerBlogPost.UrlId to UrlID'
	exec sp_rename N'cs_RollerBlogPost.UrlId', N'UrlID_TEMP'
	exec sp_rename N'cs_RollerBlogPost.UrlID_TEMP', N'UrlID'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UrlRedirects' and convert(varbinary(10), COLUMN_NAME) = 0x750072006C0049004400)
begin
	print N'Renaming cs_UrlRedirects.urlID to UrlID'
	exec sp_rename N'cs_UrlRedirects.urlID', N'UrlID_TEMP'
	exec sp_rename N'cs_UrlRedirects.UrlID_TEMP', N'UrlID'
end

IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UrlRedirects' and convert(varbinary(6), COLUMN_NAME) = 0x750072006C00)
begin
	print N'Renaming cs_UrlRedirects.url to Url'
	exec sp_rename N'cs_UrlRedirects.url', N'Url_TEMP'
	exec sp_rename N'cs_UrlRedirects.Url_TEMP', N'Url'
end

IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UrlRedirects' and convert(varbinary(22), COLUMN_NAME) = 0x69006D007000720065007300730069006F006E007300)
begin
	print N'Renaming cs_UrlRedirects.impressions to Impressions'
	exec sp_rename N'cs_UrlRedirects.impressions', N'Impressions_TEMP'
	exec sp_rename N'cs_UrlRedirects.Impressions_TEMP', N'Impressions'
end

IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UrlRedirects' and convert(varbinary(22), COLUMN_NAME) = 0x6400650073006300720069007000740069006F006E00)
begin
	print N'Renaming cs_UrlRedirects.description to Description'
	exec sp_rename N'cs_UrlRedirects.description', N'Description_TEMP'
	exec sp_rename N'cs_UrlRedirects.Description_TEMP', N'Description'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_UserReadPost' and convert(varbinary(12), COLUMN_NAME) = 0x550073006500720049006400)
begin
	print N'Renaming cs_UserReadPost.UserId to UserID'
	exec sp_rename N'cs_UserReadPost.UserId', N'UserID_TEMP'
	exec sp_rename N'cs_UserReadPost.UserID_TEMP', N'UserID'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_Users_OpenID' and convert(varbinary(12), COLUMN_NAME) = 0x550073006500720049006400)
begin
	print N'Renaming cs_Users_OpenID.UserId to UserID'
	exec sp_rename N'cs_Users_OpenID.UserId', N'UserID_TEMP'
	exec sp_rename N'cs_Users_OpenID.UserID_TEMP', N'UserID'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_Thread_Daily_Stats' and convert(varbinary(18), COLUMN_NAME) = 0x530065006300740069006F006E0049006400)
begin
	print N'Renaming cs_Thread_Daily_Stats.SectionId to SectionID'
	exec sp_rename N'cs_Thread_Daily_Stats.SectionId', N'SectionID_TEMP'
	exec sp_rename N'cs_Thread_Daily_Stats.SectionID_TEMP', N'SectionID'
end

IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_Thread_Daily_Stats' and convert(varbinary(16), COLUMN_NAME) = 0x54006800720065006100640049006400)
begin
	print N'Renaming cs_Thread_Daily_Stats.ThreadId to ThreadID'
	exec sp_rename N'cs_Thread_Daily_Stats.ThreadId', N'ThreadID_TEMP'
	exec sp_rename N'cs_Thread_Daily_Stats.ThreadID_TEMP', N'ThreadID'
end


IF EXISTS (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = N'cs_AddonConfigurationData' and convert(varbinary(14), COLUMN_NAME) = 0x4100640064006F006E0049006400)
begin
	print N'Renaming cs_AddonConfigurationData.AddonId to AddonID'
	exec sp_rename N'cs_AddonConfigurationData.AddonId', N'AddonID_TEMP'
	exec sp_rename N'cs_AddonConfigurationData.AddonID_TEMP', N'AddonID'
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 

/***********************************************
* Patch: cs_Schema_Patch_4.0.15
* File Date: 4/14/2008 11:34:51 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_4.0.15'

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 = 0;
Set @Patch = 15;

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('
declare
	@NodeOriginalEscaped nvarchar(128), @NodeNew nvarchar(128), @NodeName nvarchar(128)
	, @id int, @ptrSettings binary(16), @insert_offset int, @delete_length int

declare @t table (
	id int identity(1, 1) not null, ptrSettings binary(16) not null
	, NodeStart int not null, NodeEnd int not null, NodeLength int not null
	, insert_offset AS NodeStart + NodeLength - 1
	, delete_length AS NodeEnd - (NodeStart + NodeLength)
)

set nocount on

select
	@NodeOriginalEscaped = N''default''
	, @NodeNew = N''hawaii''
	, @NodeName = N''DefaultTheme''

select
	db_name() DatabaseName, s.SettingsID, s.Settings
	, case when patindex(
		N''%<'' + @NodeName + N''>''
		+ @NodeOriginalEscaped
		+ N''</'' + @NodeName + N''>%''
		, s.Settings )<>0 then ''Updating'' else ''No Update'' end
from
	cs_ApplicationConfigurationSettings s
where
	s.ApplicationType in (1, 11)

insert into @t (ptrSettings, NodeStart, NodeEnd, NodeLength)
select
	TEXTPTR( s.Settings )
	, patindex( N''%<'' + @NodeName + N''>%'', s.Settings )
	, patindex( N''%</'' + @NodeName + N''>%'', s.Settings )
	, 2 + LEN( @NodeName )
from
	cs_ApplicationConfigurationSettings s
where
	s.Settings IS NOT NULL
	and patindex(
		N''%<'' + @NodeName + N''>''
		+ @NodeOriginalEscaped
		+ N''</'' + @NodeName + N''>%''
		, s.Settings ) <> 0
	and s.ApplicationType in (1, 11)

while 1=1
begin
	select @id = (select min(id) from @t)
	if @id is null break

	select @ptrSettings = t.ptrSettings, @insert_offset = t.insert_offset, @delete_length = t.delete_length
	from @t t where id = @id

	UPDATETEXT cs_ApplicationConfigurationSettings.Settings @ptrSettings @insert_offset @delete_length @NodeNew

	delete from @t where id = @id
end
')

exec('
declare
	@NodeOriginalEscaped nvarchar(128), @NodeNew nvarchar(128), @NodeName nvarchar(128)
	, @id int, @ptrSettingsXML binary(16), @insert_offset int, @delete_length int

declare @t table (
	id int identity(1, 1) not null, ptrSettingsXML binary(16) not null
	, NodeStart int not null, NodeEnd int not null, NodeLength int not null
	, insert_offset AS NodeStart + NodeLength - 1
	, delete_length AS NodeEnd - (NodeStart + NodeLength)
)

set nocount on

select
	@NodeOriginalEscaped = N''default''
	, @NodeNew = N''hawaii''
	, @NodeName = N''DefaultTheme''

select
	db_name() DatabaseName, s.SettingsID, s.SettingsXML
	, case when patindex(
		N''%<'' + @NodeName + N''>''
		+ @NodeOriginalEscaped
		+ N''</'' + @NodeName + N''>%''
		, s.SettingsXML )<>0 then ''Updating'' else ''No Update'' end
from
	cs_SiteSettings s

insert into @t (ptrSettingsXML, NodeStart, NodeEnd, NodeLength)
select
	TEXTPTR( s.SettingsXML )
	, patindex( N''%<'' + @NodeName + N''>%'', s.SettingsXML )
	, patindex( N''%</'' + @NodeName + N''>%'', s.SettingsXML )
	, 2 + LEN( @NodeName )
from
	cs_SiteSettings s
where
	s.SettingsXML IS NOT NULL
	and patindex(
		N''%<'' + @NodeName + N''>''
		+ @NodeOriginalEscaped
		+ N''</'' + @NodeName + N''>%''
		, s.SettingsXML ) <> 0

while 1=1
begin
	select @id = (select min(id) from @t)
	if @id is null break

	select @ptrSettingsXML = t.ptrSettingsXML, @insert_offset = t.insert_offset, @delete_length = t.delete_length
	from @t t where id = @id
	
	UPDATETEXT cs_SiteSettings.SettingsXML @ptrSettingsXML @insert_offset @delete_length @NodeNew

	delete from @t where id = @id
end
')

exec(N'
declare @myTable table (id int not null, idx int not null, Item nvarchar(500))

declare @t table(
	id int identity(1, 1) not null
	, SectionID int not null
	, PName nvarchar(1000) collate database_default not null
	, PType nchar(1) collate database_default not null
	, PStart int not null, PLength int not null
	, PValue nvarchar(1000) collate database_default not null
	, PValueLen as ( len(PValue) )
	)

declare @s table(
	id int identity(1, 1) not null
	, SectionID int not null
	, ptrPNames binary(16) not null
	, PNamesLength int not null
	, ptrPValues binary(16) not null
	)

declare @frommarker int, @tomarker int, @strlen int, @item nvarchar(500)
	, @PName nvarchar(1000), @PValue nvarchar(1000)
	, @OriginalTheme nvarchar(100), @NewTheme nvarchar(100)
	, @id int, @mtId int, @mtx int
	, @SectionID int, @ptrvalPN binary(16), @ptrvalPV binary(16)

set nocount on
set ansi_warnings off

select
	@OriginalTheme = N''default''
	, @NewTheme = N''hawaii''
	, @id = 1

insert into @s (SectionID, ptrPNames, PNamesLength, ptrPValues)
select
	s.SectionID, TEXTPTR(s.PropertyNames), DATALENGTH(s.PropertyNames), TEXTPTR(s.PropertyValues)
from
	cs_Sections s
where
	s.PropertyNames is not null and DATALENGTH(s.PropertyNames) > 0
	and s.PropertyValues is not null and DATALENGTH(s.PropertyValues) > 0
	and s.PropertyNames like ''%Theme:S:%''
	and s.PropertyValues like ''%'' + @OriginalTheme + ''%''
	and s.ApplicationType in (1, 11)

print ''Possibly changing themes on ('' + cast(@@ROWCOUNT as varchar) + '') sections from '' + @OriginalTheme + '' to '' + @NewTheme

while (1 = 1)
begin
	select @SectionID = SectionID, @ptrvalPN = ptrPNames, @ptrvalPV = ptrPValues from @s where id = @id

	if @@rowcount = 0 begin break end

	select @frommarker=1, @tomarker=1, @mtId = 1, @mtx = 1
	delete from @myTable
	while (@tomarker > 0)
	begin
		select @tomarker = CHARINDEX (N'':'', PropertyNames, @frommarker)
			, @strlen = case when @tomarker > 0 then @tomarker - @frommarker else DATALENGTH(PropertyNames) - @frommarker + 1 end
			, @item = ltrim(rtrim(SUBSTRING (PropertyNames, @frommarker, @strlen)))
		from cs_Sections where SectionID = @SectionID
		insert into @myTable values(@mtId, @mtx, @item)
		select @mtId = case when @mtx % 4 = 0 then @mtId + 1 else @mtId end, @mtx = case @mtx when 4 then 1 else @mtx + 1 end, @frommarker = @tomarker + 1
	end

	insert into @t (SectionID, PName, PType, PStart, PLength, PValue)
	select
		@SectionID
		, min(case when idx = 1 then Item end), min(case when idx = 2 then Item end)
		, convert(int, min(case when idx = 3 then Item end)), convert(int, min(case when idx = 4 then Item end))
		, N''''
	from @myTable
	where coalesce(Item, N'''') <> N''''
	group by id

	update t set t.PValue = substring(s.PropertyValues, t.PStart + 1, t.PLength)
	from @t t inner join cs_Sections s on t.SectionID = s.SectionID

	update @t set PValue = @NewTheme where PName = N''Theme'' and PValue = @OriginalTheme and SectionID = @SectionID

	if @@ROWCOUNT > 0
	begin
		print ''Editing theme on SectionID '' + cast(@SectionID as varchar)
		DECLARE sectionCursor CURSOR FOR
		select t1.PName + N'':'' + t1.PType + N'':'' + convert(nvarchar, coalesce(sum(t2.PValueLen), 0)) + N'':'' + convert(nvarchar, t1.PValueLen) + N'':'', t1.PValue
		from @t t1 left outer join @t t2 on t1.SectionID = t2.SectionID and t1.id > t2.id
		where t1.SectionID = @SectionID
		group by t1.id, t1.SectionID, t1.PName, t1.PType, t1.PValueLen, t1.PValue
		order by t1.id

		updatetext cs_Sections.PropertyNames  @ptrvalPN 0 null N''''
		updatetext cs_Sections.PropertyValues @ptrvalPV 0 null N''''

		open sectionCursor
		fetch next from sectionCursor into @PName, @PValue
		while @@fetch_status = 0
		begin
			updatetext cs_Sections.PropertyNames  @ptrvalPN null 0 @PName
			updatetext cs_Sections.PropertyValues @ptrvalPV null 0 @PValue
			fetch next from sectionCursor into @PName, @PValue
		end
		close sectionCursor
		deallocate sectionCursor
	end else begin
		print ''No change for SectionID '' + cast(@SectionID as varchar)
	end

	set @id = @id + 1
end
set ansi_warnings on
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 

/***********************************************
* View: cs_vw_EveryOne_Role
* File Date: 4/14/2008 11:35:04 AM
***********************************************/
Print 'Creating...cs_vw_EveryOne_Role'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_EveryOne_Role]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_EveryOne_Role]
GO


/***********************************************
* View: cs_vw_HasReadForum
* File Date: 4/14/2008 11:35:04 AM
***********************************************/
Print 'Creating...cs_vw_HasReadForum'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_HasReadForum]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_HasReadForum]
GO

Create View [dbo].cs_vw_HasReadForum

as
Select UserID, SectionID, MarkReadAfter, null as ThreadID, LastActivity FROM cs_SectionsRead 
Union
Select UserID, SectionID, null, ThreadID, null FROM cs_ThreadsRead


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_HasReadForum] to public
/***********************************************
* View: cs_vw_PostsWithAttachmentDetails
* File Date: 4/14/2008 11:35:04 AM
***********************************************/
Print 'Creating...cs_vw_PostsWithAttachmentDetails'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_PostsWithAttachmentDetails]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_PostsWithAttachmentDetails]
GO

Create View [dbo].cs_vw_PostsWithAttachmentDetails
as

SELECT 
	p.[PostID], p.[ThreadID], p.[ParentID], p.[PostAuthor], p.[UserID], p.[SectionID], 
	p.[PostLevel], p.[SortOrder], p.[Subject], p.[PostDate], p.[IsApproved], p.[IsLocked], 
	p.[TotalViews], p.[Body], p.[FormattedBody], p.[IPAddress], p.[PostType], p.[PostMedia], p.[EmoticonID], 
	p.[PropertyNames] as PostPropertyNames, p.[PropertyValues] as PostPropertyValues, p.[SettingsID], p.[AggViews], p.[PostConfiguration], 
	p.[IsIndexed], p.[PostName], p.[UserTime], p.[ApplicationPostType], p.[Points], p.[RatingSum], 
	p.[TotalRatings], pa.[FileName] as AttachmentFilename, pa.[FileName], pa.[ContentType], pa.[ContentSize], pa.[Height], pa.[Width], pa.[IsRemote], pa.[FriendlyFileName], pa.Created,
	p.PostStatus, p.SpamScore

FROM cs_Posts p (nolock)
LEFT JOIN cs_PostAttachments pa (nolock) on p.PostID = pa.PostID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


--Select * FROM cs_vw_PostsWithAttachmentDetails

grant select on [dbo].[cs_vw_PostsWithAttachmentDetails] to public



/***********************************************
* View: cs_vw_UsersInRoles
* File Date: 4/14/2008 11:35:04 AM
***********************************************/
Print 'Creating...cs_vw_UsersInRoles'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_UsersInRoles]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_UsersInRoles]
GO


/***********************************************
* View: cs_vw_Users_FullUser
* File Date: 4/14/2008 11:35:04 AM
***********************************************/
Print 'Creating...cs_vw_Users_FullUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_Users_FullUser]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_Users_FullUser]
GO

Create View [dbo].cs_vw_Users_FullUser
as

SELECT
	U.AppUserToken,
	U.Email,
	U.ForceLogin,
	U.IsAnonymous,
	U.LastAction,
	U.LastActivity,
	U.MembershipID,
	U.UserAccountStatus,
	U.UserID,
	U.UserName,
	U.CreateDate,
	UP.AllowSitePartnersToContact,
	UP.AllowSiteToContact,
	UP.EnableAvatar,
	UP.EnableDisplayInMemberList,
	UP.EnableDisplayUnreadThreadsOnly,
	UP.EnableEmail,
	UP.EnableHtmlEmail,
	UP.EnableOnlineStatus,
	UP.EnablePrivateMessages,
	UP.EnableThreadTracking,
	UP.FavoritesShared,
	UP.IsAvatarApproved,
	UP.IsIgnored,
	UP.ModerationLevel,
	UP.Points as UserPoints,
	UP.PostRank,
	UP.PostSortOrder,
	UP.PropertyNames as UserPropertyNames,
	UP.PropertyValues as UserPropertyValues,
	UP.PublicToken,
	UP.SettingsID,
	UP.TimeZone,
	UP.TotalPosts
FROM
	cs_Users U (nolock)
	INNER JOIN cs_UserProfile UP (nolock) ON U.UserID = UP.UserID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_Users_FullUser] to public

/***********************************************
* View: cs_vw_weblog_PostByYearMonth
* File Date: 4/14/2008 11:35:04 AM
***********************************************/
Print 'Creating...cs_vw_weblog_PostByYearMonth'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_weblog_PostByYearMonth]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_weblog_PostByYearMonth]
GO
create view dbo.cs_vw_weblog_PostByYearMonth
as
	select * from cs_weblog_PostByYearMonth_tbl01
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_weblog_PostByYearMonth] to public
go

-- now to attempt to populate the table initially
if object_id('dbo.cs_system_GenerateWeblogYearMonthDayList') IS NOT NULL
	exec dbo.cs_system_GenerateWeblogYearMonthDayList

go

/***********************************************
* Sproc: csm_EmailIDs_FindUserEmailID
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...csm_EmailIDs_FindUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_FindUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_FindUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_FindUserEmailID
	@EmailID bigint
AS

select E.UserID, E.SectionID, S.SettingsID
 from csm_EmailIDs E
 left join cs_Sections S on (S.SectionID = E.SectionID)
 where EmailID = @EmailID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_FindUserEmailID] to public
go
/***********************************************
* Sproc: csm_EmailIDs_GetUserEmailID
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...csm_EmailIDs_GetUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_GetUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_GetUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_GetUserEmailID
	@UserID int,
	@SectionID int,
	@SettingsID int
AS

select EmailID from csm_EmailIDs where UserID = @UserID and SectionID = @SectionID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_GetUserEmailID] to public
go
/***********************************************
* Sproc: csm_EmailIDs_UpdateUserEmailID
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...csm_EmailIDs_UpdateUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_UpdateUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_UpdateUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_UpdateUserEmailID
	@EmailID bigint,
	@UserID int,
	@SectionID int,
	@SettingsID int
AS

delete from csm_EmailIDs where UserID = @UserID and SectionID = @SectionID

insert into csm_EmailIDs (EmailID, UserID, SectionID) values (@EmailID, @UserID, @SectionID)
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_UpdateUserEmailID] to public
go
/***********************************************
* Sproc: csm_MailingLists_CreateUpdate
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...csm_MailingLists_CreateUpdate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MailingLists_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MailingLists_CreateUpdate]
GO

CREATE PROCEDURE [dbo].csm_MailingLists_CreateUpdate
(
	@SectionID		int,
	@EmailAddress		nvarchar(100),
	@IsMailingList		bit,
	@SettingsID		int
)
AS

if exists(select [SectionID] from csm_MailingLists where SectionID = @SectionID and SettingsID = @SettingsID)
begin
	update csm_MailingLists set EmailAddress = @EmailAddress, IsMailingList = @IsMailingList where SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	insert into csm_MailingLists (SectionID, EmailAddress, IsMailingList, SettingsID) values (@SectionID, @EmailAddress, @IsMailingList, @SettingsID)
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MailingLists_CreateUpdate] to public
go
/***********************************************
* Sproc: csm_MailingLists_Get
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...csm_MailingLists_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MailingLists_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MailingLists_Get]
GO

CREATE PROCEDURE [dbo].csm_MailingLists_Get
(
	@SettingsID		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

-- Return all the sections that are mailing lists
SELECT
	F.SectionID, F.SettingsID, F.IsActive, F.ParentID, F.GroupID, F.Name, F.NewsgroupName, F.Description, F.DateCreated, F.Url, F.IsModerated,
	F.DaysToView, F.SortOrder, F.TotalPosts, F.TotalThreads, F.DisplayMask, F.EnablePostStatistics, F.EnableAnonymousPosting,
	F.MostRecentPostID, F.MostRecentThreadID, F.MostRecentThreadReplies, F.MostRecentPostSubject, F.MostRecentPostAuthor,
	F.MostRecentPostAuthorID, F.MostRecentPostDate, F.PostsToModerate, F.ForumType, F.IsSearchable, F.ApplicationType, F.ApplicationKey, F.Path,
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues,
	M.EmailAddress, M.IsMailingList
FROM
	csm_MailingLists M
LEFT OUTER JOIN
	cs_Sections F ON F.SettingsID = M.SettingsID AND F.SectionID = M.SectionID
WHERE
	M.SettingsID = @SettingsID

exec csm_MailingList_Permissions_Get @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MailingLists_Get] to public
go
/***********************************************
* Sproc: csm_MailingList_Permissions_Get
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...csm_MailingList_Permissions_Get'

-- exec cs_Section_Permissions_Get 1000, 0
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from sysobjects where id = object_id(N'[dbo].[csm_MailingList_Permissions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[csm_MailingList_Permissions_Get]
GO

create procedure [dbo].[csm_MailingList_Permissions_Get]
(
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1,
		EmailAddress = null,
		ApplicationKey = null,
		P.RoleID, 
		P.ApplicationType,
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))
	FROM
		cs_ProductPermissions P
	WHERE 
		P.SettingsID = @SettingsID

	UNION

	-- Return section permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 0), 
		P.SectionID, 
		M.EmailAddress,
		F.ApplicationKey,
		P.RoleID, 
		F.ApplicationType,
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))  
	FROM 
		cs_SectionPermissions P
	INNER JOIN
		csm_MailingLists M on P.SettingsID = M.SettingsID and P.SectionID = M.SectionID
	INNER JOIN
		cs_Sections F on P.SettingsID = F.SettingsID and P.SectionID = F.SectionID
	WHERE
		F.SettingsID = @SettingsID AND
		M.IsMailingList = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[csm_MailingList_Permissions_Get] to public
go
/***********************************************
* Sproc: csm_MessageID_Add
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...csm_MessageID_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MessageID_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MessageID_Add]
GO

CREATE PROCEDURE [dbo].csm_MessageID_Add
(
	@MessageID		nvarchar(100),
	@SettingsID		int,
	@PostID			int
)
AS

insert into csm_MessageIDs (MessageID, SettingsID, PostID) values (@MessageID, @SettingsID, @PostID)
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MessageID_Add] to public
go
/***********************************************
* Sproc: csm_MessageID_Check
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...csm_MessageID_Check'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MessageID_Check]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MessageID_Check]
GO

CREATE PROCEDURE [dbo].csm_MessageID_Check
(
	@MessageID		nvarchar(100),
	@SettingsID		int
)
AS

declare @Check int
set @Check = (select 1 from csm_MessageIDs where MessageID = @MessageID and SettingsID = @SettingsID)
select isnull(@Check, 0) as 'Check'
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MessageID_Check] to public
go
/***********************************************
* Sproc: csm_Post_FindPostParent
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...csm_Post_FindPostParent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_Post_FindPostParent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_Post_FindPostParent]
GO

CREATE PROCEDURE [dbo].csm_Post_FindPostParent
(
	@PostID int=-1,
	@Subject nvarchar(256)=null,
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

if @PostID <> -1
begin
	if exists(SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.PostID = @PostID)
		select @PostID as PostID
	else	select -1 as PostID
end
else
begin
	if exists(SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.Subject = @Subject)
		SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.Subject = @Subject
	else
		select -1 as PostID
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_Post_FindPostParent] to public
go
/***********************************************
* Sproc: cs_ApiKeys_Create
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_ApiKeys_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApiKeys_Create]
GO

CREATE PROCEDURE [dbo].[cs_ApiKeys_Create]
(
    @userId int,
    @value char(8),
    @name varchar(50)
)
AS

INSERT INTO cs_ApiKeys (UserID, [Value], [Name]) VALUES (@userId, @value, @name)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ApiKeys_Create to public
go

/***********************************************
* Sproc: cs_ApiKeys_Delete
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_ApiKeys_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApiKeys_Delete]
GO

CREATE PROCEDURE [dbo].[cs_ApiKeys_Delete]
(
	@apiKeyId int
)
AS

DELETE FROM cs_ApiKeys WHERE ApiKeyID = @apiKeyId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ApiKeys_Delete to public
go
/***********************************************
* Sproc: cs_ApiKeys_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_ApiKeys_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApiKeys_Get]
GO

CREATE PROCEDURE [dbo].[cs_ApiKeys_Get]
(
  @userId int
)
AS

SELECT * FROM cs_ApiKeys where UserID = @userId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ApiKeys_Get to public
go
/***********************************************
* Sproc: cs_ApiKeys_Update
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_ApiKeys_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApiKeys_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApiKeys_Update]
GO

CREATE PROCEDURE [dbo].[cs_ApiKeys_Update]
(
    @apiKeyId int,
    @name varchar(50),
    @enabled bit
)
AS

UPDATE cs_ApiKeys SET
    [Name] = @name,
    [Enabled] = @enabled
WHERE ApiKeyID = @apiKeyId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ApiKeys_Update to public
go

/***********************************************
* Sproc: cs_ApplicationConfigurationSettings_CreateUpdate
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_ApplicationConfigurationSettings_CreateUpdate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApplicationConfigurationSettings_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApplicationConfigurationSettings_CreateUpdate]
GO



CREATE  PROCEDURE [dbo].cs_ApplicationConfigurationSettings_CreateUpdate --11, 36, 0, 1, 0
(
	@SettingsID int,
	@ApplicationType smallint,
	@Settings NText = null
)

as

if exists(Select SettingsID FROM cs_ApplicationConfigurationSettings where SettingsID = @SettingsID and ApplicationType = @ApplicationType)
Begin
	Update cs_ApplicationConfigurationSettings
	Set Settings = @Settings
	where SettingsID = @SettingsID and ApplicationType = @ApplicationType
End
Else
Begin
	Insert cs_ApplicationConfigurationSettings (SettingsID, ApplicationType, Settings) 
	Values(@SettingsID, @ApplicationType, @Settings) 
End


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ApplicationConfigurationSettings_CreateUpdate] to public
go
/***********************************************
* Sproc: cs_ApplicationConfigurationSettings_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_ApplicationConfigurationSettings_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApplicationConfigurationSettings_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApplicationConfigurationSettings_Get]
GO



CREATE  PROCEDURE [dbo].cs_ApplicationConfigurationSettings_Get --11, 36, 0, 1, 0
(
	@SettingsID int,
	@ApplicationType smallint
)
as
Select Settings FROM cs_ApplicationConfigurationSettings where SettingsID = @SettingsID and ApplicationType = @ApplicationType



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ApplicationConfigurationSettings_Get] to public
go
/***********************************************
* Sproc: cs_Audit_Post
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Audit_Post'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Audit_Post]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Audit_Post]
GO


CREATE proc [dbo].cs_Audit_Post
(
	@PostID		int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- Get the Post
	exec cs_forums_Post @PostID, null, 0, @SettingsID

	SELECT
		B.Description,
		U.UserName,
		A.*
	FROM
		cs_ModerationAudit A,
		cs_ModerationAction B,
		cs_vw_Users_FullUser U
	WHERE
		A.ModerationAction = B.ModerationAction AND
		A.SettingsID = B.SettingsID AND
		U.UserID = A.ModeratorID AND
		A.PostID = @PostID AND
		A.SettingsID = @SettingsID
	ORDER BY
		ModeratedOn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_Audit_Post to public
GO
/***********************************************
* Sproc: cs_BannedAddresses_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_BannedAddresses_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedAddresses_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedAddresses_Get]
GO

CREATE Procedure [dbo].[cs_BannedAddresses_Get]
	@SettingsID	int
AS

	SELECT
		SettingsID
		, NetworkAddress
		, BannedDate
	FROM cs_BannedAddresses 
	WHERE SettingsID = @SettingsID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedAddresses_Get]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedAddress_CreateUpdateDelete
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_BannedAddress_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedAddress_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedAddress_CreateUpdateDelete]
GO

CREATE Procedure [dbo].[cs_BannedAddress_CreateUpdateDelete]
	  @SettingsID		INT
	, @NetworkAddress	NVARCHAR(50) 
	, @BannedDate		DATETIME
	, @ActionType		INT
AS
	DECLARE @ID INT
	DECLARE @ERROR INT
	DECLARE @ROWCOUNT INT
	
	-- CREATE
	IF @ActionType = 0 
	BEGIN
		IF EXISTS( SELECT * FROM cs_BannedAddresses where SettingsID = @SettingsID and NetworkAddress = @NetworkAddress )
			exec cs_BannedAddress_CreateUpdateDelete @SettingsID, @NetworkAddress, @BannedDate, 1 
		else
		BEGIN
		
			INSERT INTO cs_BannedAddresses VALUES( @SettingsID, @NetworkAddress, @BannedDate )

			SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR( 'An error occurred while trying to create a new cs_BannedAddress record.', 16, 1 )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0
			END
		END
	END
	ELSE IF( @ActionType = 1 )
	BEGIN
		-- UPDATE
		IF NOT EXISTS( SELECT * FROM cs_BannedAddresses WHERE SettingsID = @SettingsID and NetworkAddress = @NetworkAddress )
			exec cs_BannedAddress_CreateUpdateDelete @SettingsID, @NetworkAddress, @BannedDate, 0 
		ELSE
		BEGIN
			UPDATE cs_BannedAddresses SET
				SettingsID = @SettingsID,
				NetworkAddress = @NetworkAddress,
				BannedDate = @BannedDate
			WHERE
					SettingsID = @SettingsID 
				AND NetworkAddress = @NetworkAddress
				
			SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR('Could not update the cs_BannedAddress record for SettingsID %d and NetworkAddress of %d', 16, 1, @SettingsID, @NetworkAddress )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0				
			END
		END
	END
	ELSE IF( @ActionType = 2 )
	BEGIN
		-- DELETE
		DELETE cs_BannedAddresses
		WHERE SettingsID = @SettingsID
			AND NetworkAddress = @NetworkAddress
			
		SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
		IF( @ROWCOUNT = 1 )
			RETURN 0
		ELSE
			RETURN 1
		
	END
	ELSE
	BEGIN
		RAISERROR( 'The ActionType value should be between 0 and 2. The value of %d was not within this range', 16, 1, @ActionType )
		RETURN 1
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedAddress_CreateUpdateDelete]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedNetworks_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_BannedNetworks_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedNetworks_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedNetworks_Get]
GO

CREATE Procedure [dbo].[cs_BannedNetworks_Get]
	@SettingsID int
AS
	SELECT	SettingsID
		, BannedNetworkID
		, StartingAddress
		, EndingAddress
		, BannedDate
	FROM cs_BannedNetworks 
	WHERE SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_BannedNetworks_Get]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedNetwork_CreateUpdateDelete
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_BannedNetwork_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedNetwork_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedNetwork_CreateUpdateDelete]
GO


CREATE Procedure [dbo].[cs_BannedNetwork_CreateUpdateDelete]
	@BannedNetworkID	INT = 0 OUTPUT,
	@SettingsID			INT,
	@StartingAddress	NVARCHAR(50)=  null,
	@EndingAddress		NVARCHAR(50) = null,
	@BannedDate			DATETIME,
	@ActionType			INT
AS
	DECLARE @ID INT
	DECLARE @ERROR INT
	DECLARE @ROWCOUNT INT
	
	-- CREATE
	IF @ActionType = 0 
	BEGIN
		IF EXISTS( SELECT * FROM cs_BannedNetworks where SettingsID = @SettingsID and BannedNetworkID = @BannedNetworkID )
			exec cs_BannedNetwork_CreateUpdateDelete @BannedNetworkID OUTPUT, @SettingsID, @StartingAddress, @EndingAddress, @BannedDate, 1 
		ELSE
		BEGIN
		
			INSERT INTO cs_BannedNetworks (
				SettingsID,
				StartingAddress,
				EndingAddress,
				BannedDate
			) VALUES( 
				@SettingsID,
				@StartingAddress,
				@EndingAddress,
				@BannedDate
			)

			SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR( 'An error occurred while trying to create a new cs_BannedNetwork record.', 16, 1 )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				SET @BannedNetworkID = @ID
				RETURN 0
			END
		END
	END
	ELSE IF( @ActionType = 1 )
	BEGIN
		-- UPDATE
		IF NOT EXISTS( SELECT * FROM cs_BannedNetworks WHERE SettingsID = @SettingsID and BannedNetworkID = @BannedNetworkID )
			exec cs_BannedNetwork_CreateUpdateDelete @BannedNetworkID OUTPUT, @SettingsID, @StartingAddress, @EndingAddress, @BannedDate, 0 
		ELSE
		BEGIN
			UPDATE cs_BannedNetworks SET
				SettingsID		= @SettingsID,
				StartingAddress	= @StartingAddress,
				EndingAddress	= @EndingAddress,
				BannedDate		= @BannedDate
			WHERE
					SettingsID		= @SettingsID 
				AND BannedNetworkID = @BannedNetworkID
				
			SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR('Could not update the cs_BannedNetworks record for SettingsID %d and BannedNetworkID of %d', 16, 1, @SettingsID, @BannedNetworkID )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0				
			END
		END
	END
	ELSE IF( @ActionType = 2 )
	BEGIN
		-- DELETE
		DELETE cs_BannedNetworks
		WHERE SettingsID		= @SettingsID
			AND BannedNetworkID = @BannedNetworkID
			
		SELECT @ERROR = @@ERROR, @ID = SCOPE_IDENTITY(), @ROWCOUNT = @@ROWCOUNT
		IF( @ROWCOUNT = 1 )
			RETURN 0
		ELSE
			RETURN 1
		
	END
	ELSE
	BEGIN
		RAISERROR( 'The ActionType value should be between 0 and 2. The value of %d was not within this range', 16, 1, @ActionType )
		RETURN 1
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedNetwork_CreateUpdateDelete]  TO [public]
GO

/***********************************************
* Sproc: cs_BlogActivityNightlyJob
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_BlogActivityNightlyJob'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityNightlyJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityNightlyJob]
GO

CREATE    PROCEDURE [dbo].cs_BlogActivityNightlyJob

AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	declare @RunDate datetime
	declare @JobRunDate datetime
	set @JobRunDate = getdate()
	set @RunDate = dateadd(d, -1, convert(datetime, (convert(varchar(10), @JobRunDate, 101))))
	 
        insert into [cs_BlogActivityReport] 
	select t.SectionID, t.ThreadID, @RunDate as CoverageDate
	 ,TotalViews  = (select t1.TotalViews from dbo.cs_Threads t1 left outer join cs_BlogActivityReport yesterdays on t.ThreadID = yesterdays.ThreadID and yesterdays.CoverageDate = dateadd(d, -1, @RunDate) where t1.ThreadID = t.ThreadID and t1.SectionID = t.SectionID)
	 ,DayViews = (select coalesce((t1.TotalViews - yesterdays.TotalViews), t1.TotalViews) from dbo.cs_Threads t1 left outer join cs_BlogActivityReport yesterdays on t.ThreadID = yesterdays.ThreadID and yesterdays.CoverageDate = dateadd(d, -1, @RunDate) where t1.ThreadID = t.ThreadID and t1.SectionID = t.SectionID)
	 ,DayComments  = (select count(*) from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID <> p1.ParentID and p1.ApplicationPostType = 4 and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	 ,DayTrackBacks = (select count(*) from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID <> p1.ParentID and p1.ApplicationPostType = 8 and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
         ,IsPost   = (select case when p1.ApplicationPostType = 1 then 1 else 0 end from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)
	 ,IsArticle  = (select case when p1.ApplicationPostType = 2 then 1 else 0 end from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)
	 ,JobExecutionTimeStamp = @JobRunDate
         ,DayPosts = (select count(*) from dbo.cs_Posts p1 where p1.ApplicationPostType = 1 and p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	 ,DayArticles = (select count(*) from dbo.cs_Posts p1 where p1.ApplicationPostType = 2 and p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	from dbo.cs_Threads t 
	-- Some existing CS databases have orphaned thread records that should have been deleted, so check to make sure at least one top-level post exists for the thread
	where exists(select PostID from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)

END






GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_BlogActivityNightlyJob to public
go

/***********************************************
* Sproc: cs_BlogActivityReportAggregate_Get
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_BlogActivityReportAggregate_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityReportAggregate_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityReportAggregate_Get]
GO
/***********************************************
* Sproc: cs_BlogActivityReportRecords_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_BlogActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityReportRecords_Get]
GO
/***********************************************
* Sproc: cs_Censorships_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Censorships_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Censorships_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Censorships_Get]
GO


CREATE proc [dbo].cs_Censorships_Get
(
	@Word	nvarchar(256) = '',
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Censorship
	WHERE
		SettingsID = @SettingsID and (Word = @Word or (@Word = '' AND 1=1))


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Censorships_Get to public
go

/***********************************************
* Sproc: cs_Censorship_CreateUpdateDelete
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Censorship_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Censorship_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Censorship_CreateUpdateDelete]
GO


CREATE proc [dbo].cs_Censorship_CreateUpdateDelete
(
	  @Word			nvarchar(256)
	, @DeleteWord 	bit = 0
	, @Replacement	nvarchar(256)
	, @SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

if( @DeleteWord > 0 )
BEGIN
	DELETE FROM
		cs_Censorship
	WHERE
		Word = @Word and SettingsID = @SettingsID
	RETURN
END
ELSE
BEGIN
	UPDATE cs_Censorship SET
		Replacement	= @Replacement
	WHERE
		Word	= @Word and SettingsID = @SettingsID

	IF( @@rowcount = 0 )
	BEGIN
	INSERT INTO cs_Censorship (
		Word, Replacement, SettingsID
	) VALUES (
		@Word, @Replacement, @SettingsID
	)
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_Censorship_CreateUpdateDelete to public
GO
/***********************************************
* Sproc: cs_ConfigurableAddonData_CreateUpdate
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_ConfigurableAddonData_CreateUpdate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ConfigurableAddonData_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ConfigurableAddonData_CreateUpdate]
GO

CREATE PROCEDURE dbo.cs_ConfigurableAddonData_CreateUpdate
	@AddonID uniqueidentifier,
	@SettingsID int,
	@AddonName varchar(255) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null
AS

if exists(select AddonID from cs_AddonConfigurationData where AddonID = @AddonID and SettingsID = @SettingsID)
	begin
		update cs_AddonConfigurationData
		set 	AddonName = @AddonName,
			PropertyNames = @PropertyNames,
			PropertyValues = @PropertyValues
		where AddonID = @AddonID and SettingsID = @SettingsID
	end else begin
		insert into cs_AddonConfigurationData (AddonID, AddonName, SettingsID, PropertyNames, PropertyValues) 
		values (@AddonID, @AddonName, @SettingsID, @PropertyNames, @PropertyValues)
	end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_ConfigurableAddonData_CreateUpdate]  TO [public]
GO


/***********************************************
* Sproc: cs_ConfigurableAddonData_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_ConfigurableAddonData_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ConfigurableAddonData_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ConfigurableAddonData_Get]
GO

CREATE PROCEDURE dbo.cs_ConfigurableAddonData_Get
	@AddonID uniqueidentifier,
	@SettingsID int
AS
	select *
	from cs_AddonConfigurationData
	where AddonID = @AddonID and SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_ConfigurableAddonData_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Content_CreateUpdateDelete
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Content_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_CreateUpdateDelete]
GO

CREATE PROCEDURE [dbo].cs_Content_CreateUpdateDelete
(
	@ContentID	int out,
	@Action 	int,
	@Name		nvarchar(256),
	@Title		nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@Hidden		bit,
	@UpdateDate 	bit,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
	-- first check that content name is not already in use
	IF EXISTS
	(
		SELECT  
			NULL
		FROM 
			cs_Content
		WHERE
			Name = @Name and SettingsID = @SettingsID
	)
	BEGIN
		RAISERROR ( 'Content name in use', 16, 1)
		RETURN
	END				

	DECLARE @SortOrder int

	SELECT @SortOrder = coalesce(MAX(SortOrder) + 1, 1) FROM cs_Content where SettingsID = @SettingsID

	-- Create a new content
	INSERT INTO 
		cs_Content 
		(
			Name,
			Title,
			Body,
			FormattedBody,
			Hidden,
			SortOrder,
			SettingsID
		)
	VALUES 
		(
			@Name,
			@Title,
			@Body,
			@FormattedBody,
			@Hidden,
			@SortOrder,
			@SettingsID
		)
	
	SET @ContentID = SCOPE_IDENTITY()
END


-- UPDATE
ELSE IF @Action = 1
BEGIN

	IF EXISTS
	(
		SELECT  
			NULL
		FROM 
			cs_Content c
		WHERE
			c.Name = @Name
			AND c.ContentID <> @ContentID and c.SettingsID = @SettingsID
	)
	BEGIN
		RAISERROR ( 'Content name in use', 16, 1)
		RETURN
	END				

	IF EXISTS(SELECT NULL FROM cs_Content WHERE ContentID = @ContentID)
	BEGIN
		UPDATE
			cs_Content
		SET
			Name = @Name,
			Title = @Title,
			Body = @Body,
			FormattedBody = @FormattedBody
		WHERE
			ContentID = @ContentID and SettingsID = @SettingsID

		IF @UpdateDate = 1 
			EXEC cs_Content_UpdateDate @ContentID
	END

END

-- DELETE
ELSE IF @Action = 2
BEGIN
	DELETE cs_Content WHERE ContentID = @ContentID and SettingsID = @SettingsID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_CreateUpdateDelete to public
go
/***********************************************
* Sproc: cs_Content_GetIDFromName
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Content_GetIDFromName'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_GetIDFromName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_GetIDFromName]
GO
/***********************************************
* Sproc: cs_Content_GetList
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Content_GetList'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_GetList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_GetList]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[cs_Content_GetList]
(
	@SettingsID int
)
AS
	SELECT  
		*
	FROM 
		cs_Content c
	WHERE 
		c.Hidden = 0 and c.SettingsID = @SettingsID
	ORDER BY 
		c.LastModified DESC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Content_GetList] to public
go

/***********************************************
* Sproc: cs_Content_Load
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Content_Load'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_Load]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_Load]
GO

CREATE PROCEDURE [dbo].[cs_Content_Load]
(
	@ContentID int,
	@SettingsID int,
	@Name nvarchar(256) = null
)
AS
IF(@ContentID > 0)
BEGIN
	SELECT 
		[SettingsID], [ContentID], [Name], [Title], [Body], [FormattedBody], [LastModified], [SortOrder], [Hidden]
	FROM 
		[dbo].[cs_Content]
	WHERE
		ContentID = @ContentID and SettingsID = @SettingsID
END
ELSE
BEGIN
	SELECT 
		[SettingsID], [ContentID], [Name], [Title], [Body], [FormattedBody], [LastModified], [SortOrder], [Hidden]
	FROM 
		[dbo].[cs_Content]
	WHERE
		[Name] = @Name and SettingsID = @SettingsID

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_Load to public
go



/***********************************************
* Sproc: cs_Content_UpdateDate
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Content_UpdateDate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_UpdateDate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_UpdateDate]
GO

CREATE PROCEDURE [dbo].[cs_Content_UpdateDate]
(
	@ContentID int
)
AS
	UPDATE
		cs_Content
	SET
		LastModified = getdate()
	WHERE
		ContentID = @ContentID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_UpdateDate to public
go
/***********************************************
* Sproc: cs_DisallowedNames_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_DisallowedNames_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_DisallowedNames_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_DisallowedNames_Get]
GO


CREATE PROCEDURE [dbo].cs_DisallowedNames_Get
(
	@SettingsID int
)
AS 
SET Transaction Isolation Level Read UNCOMMITTED

	SELECT 
		DisallowedName 
	FROM 
		cs_DisallowedNames
	WHERE
		SettingsID = @SettingsID 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_DisallowedNames_Get to public
go
/***********************************************
* Sproc: cs_DisallowedName_CreateUpdateDelete
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_DisallowedName_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_DisallowedName_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_DisallowedName_CreateUpdateDelete]
GO


CREATE PROCEDURE [dbo].cs_DisallowedName_CreateUpdateDelete
(
	@Name		nvarchar(64),
	@Replacement 	nvarchar(64),
	@DeleteName	bit = 0,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

if( @DeleteName > 0 )
BEGIN
	DELETE FROM
		cs_DisallowedNames
	WHERE
		DisallowedName = @Name and SettingsID = @SettingsID
END
ELSE 
BEGIN
		UPDATE cs_DisallowedNames SET
			DisallowedName = @Replacement
		WHERE
			DisallowedName = @Name and SettingsID = @SettingsID

	if( @@rowcount = 0 )
	BEGIN
		INSERT INTO cs_DisallowedNames (
			DisallowedName, SettingsID
		) VALUES (
			@Name, @SettingsID
		)
		
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_DisallowedName_CreateUpdateDelete to public
go
/***********************************************
* Sproc: cs_Emails_SubscribedSection
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Emails_SubscribedSection'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_SubscribedSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_SubscribedSection]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[cs_Emails_SubscribedSection]
(
	@PostID    int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID INT
DECLARE @UserID INT
DECLARE @PostLevel INT
DECLARE @ThreadID INT

-- First get the post info
SELECT 
	@SectionID = SectionID, 
	@UserID = UserID,
	@PostLevel = PostLevel,
	@ThreadID = ThreadID
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Check if its a new thread or not
IF (@PostLevel = 1 AND @SectionID <> 0)
	BEGIN
		SELECT
			SubscriptionID, SectionID, Email, SubscriptionType, UserID, 
			SettingsID, DateSubscribed, SubscriptionFrequency, 1 as EnableHtmlEmail
		FROM 
			cs_SectionSubscriptions
		WHERE
			SectionID = @SectionID AND 
			SettingsID = @SettingsID AND
			DateUnsubscribed IS NULL AND
			IsConfirmed = 1 AND
			SubscriptionType & 3 <> 0
	END
ELSE IF (@SectionID <> 0)
	BEGIN
	-- this is a reply to an existing post (2)

		SELECT
			SubscriptionID, SectionID, Email, SubscriptionType, UserID, 
			SettingsID, DateSubscribed, SubscriptionFrequency, 1 as EnableHtmlEmail
		FROM 
			cs_SectionSubscriptions
		WHERE
			SectionID = @SectionID AND 
			SettingsID = @SettingsID AND
			DateUnsubscribed IS NULL AND
			IsConfirmed = 1 AND
			SubscriptionType & 3 = 3
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Emails_SubscribedSection] to public
go

/***********************************************
* Sproc: cs_Emails_TrackingSection
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Emails_TrackingSection'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingForum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingForum]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingSection]
GO


CREATE PROCEDURE [dbo].cs_Emails_TrackingSection
(
	@PostID    INT,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID INT
DECLARE @HubSectionID INT
DECLARE @UserID INT
DECLARE @PostLevel INT
DECLARE @ThreadID INT

-- First get the post info
SELECT 
	@SectionID = SectionID, 
	@UserID = UserID,
	@PostLevel = PostLevel,
	@ThreadID = ThreadID
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Get the hub SectionID
SELECT
  @HubSectionID = HubSectionID
FROM
  cs_Sections (nolock)
WHERE
  SectionID = @SectionID and SettingsID = @SettingsID

-- Check if its a new thread or not
IF (@PostLevel = 1)
BEGIN
	-- this is a new thread (1 & 2)
	
	IF (@SectionID <> 0) 
	BEGIN

		SELECT
			U.UserID,
			U.Email, 
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM 
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.UserID = F.UserID
		WHERE
			(F.SectionID = @SectionID or F.SectionID = @HubSectionID) AND
      F.SettingsID = @SettingsID and U.SettingsID = @SettingsID and
			U.EnableThreadTracking = 1 and
			U.EnableEmail = 1 and
			U.UserAccountStatus = 1 and
			F.SubscriptionType & 3 <> 0
	END
END
ELSE BEGIN
	-- this is a reply to an existing post (2)

	IF (@SectionID <> 0)
	BEGIN

		SELECT
			U.UserID,
			U.Email, 
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM 
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.UserID = F.UserID
		WHERE
			(F.SectionID = @SectionID or F.SectionID = @HubSectionID) AND
			U.SettingsID = @SettingsID and F.SettingsID = @SettingsID and 
			U.EnableThreadTracking = 1 and
			U.EnableEmail = 1 and
			U.UserAccountStatus = 1 and
			F.SubscriptionType & 3 = 3
	END
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Emails_TrackingSection to public
go
/***********************************************
* Sproc: cs_Emails_TrackingThread
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Emails_TrackingThread'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingThread]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingThread]
GO



CREATE PROCEDURE [dbo].cs_Emails_TrackingThread
(
	@PostID INT,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID INT
DECLARE @UserID INT
DECLARE @PostLevel INT
DECLARE @ThreadID INT

-- First get the post info
SELECT 
	@SectionID = SectionID, 
	@UserID = UserID,
	@PostLevel = PostLevel,
	@ThreadID = ThreadID
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

IF (@SectionID <> 0)
BEGIN

	SELECT
		U.UserID,
		U.Email, 
		U.EnableHtmlEmail,
		U.[PublicToken],
		U.[UserName]
	FROM 
		cs_TrackedThreads T
		JOIN cs_vw_Users_FullUser U (nolock) ON U.UserID = T.UserID			
	WHERE
		T.ThreadID = @ThreadID and T.SettingsID = @SettingsID and U.SettingsID = @SettingsID and
		U.EnableEmail = 1 and
		U.UserAccountStatus = 1 and
		U.EnableThreadTracking = 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Emails_TrackingThread to public
go
/***********************************************
* Sproc: cs_es_sprocs
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_es_sprocs'


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_es_Search_QueueManager]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_es_Search_QueueManager]
GO


Create Proc [dbo].cs_es_Search_QueueManager
(
	@PostID int,
	@SettingsID int,
	@Add bit
)

as

if @Add = 1
Begin

	Insert cs_es_Search_RemoveQueue (PostID, SettingsID) Values (@PostID, @SettingsID)

End
ELSE
BEGIN
	DELETE FROM cs_es_Search_RemoveQueue where PostID = @PostID and SettingsID = @SettingsID
END


SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_es_Search_QueueManager to public
go



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_es_Search_Queue_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_es_Search_Queue_Get]
GO


Create Proc [dbo].cs_es_Search_Queue_Get
(
	@SettingsID int
)

as

Select PostID FROM cs_es_Search_RemoveQueue where SettingsID = @SettingsID



SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_es_Search_Queue_Get to public
go
/***********************************************
* Sproc: cs_EventLog_Add
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_EventLog_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_Add]
GO

CREATE PROCEDURE [dbo].cs_EventLog_Add
(
	@EventType int,
	@Message ntext,
	@Category nvarchar(256),
	@MachineName nvarchar(256) = null,
	@EventID int,
	@SettingsID int
) AS

INSERT INTO [cs_EventLog]([Message], [Category], [SettingsID], [EventID], [EventType], [MachineName])
VALUES(  @Message, @Category, @SettingsID, @EventID, @EventType, @MachineName)


SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_Add to public
go
/***********************************************
* Sproc: cs_EventLog_Clear
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_EventLog_Clear'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_Clear]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_Clear]
GO

CREATE PROCEDURE [dbo].cs_EventLog_Clear
(
	@Date datetime
) AS

Delete FROM cs_EventLog where  EventDate <= @Date

SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_Clear to public
go
/***********************************************
* Sproc: cs_EventLog_GetEntries
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_EventLog_GetEntries'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_GetEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_GetEntries]
GO

CREATE PROCEDURE [dbo].cs_EventLog_GetEntries
(
	@SettingsID int = -1
)
AS
	SELECT TOP 1000
				EL.EventLogID,
				EL.Message,
				EL.Category,
				EL.SettingsID,
				EL.EventID,
				EL.EventType,
				EL.EventDate,
				EL.MachineName
	FROM		cs_EventLog EL
	WHERE		EL.SettingsID = @SettingsID
		OR		EL.SettingsID = -1
	ORDER BY	EL.EventLogID DESC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_GetEntries to public
go
/***********************************************
* Sproc: cs_EventLog_GetEntry
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_EventLog_GetEntry'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_GetEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_GetEntry]
GO

CREATE PROCEDURE [dbo].cs_EventLog_GetEntry
(
	@EntryID int
)
AS
	SELECT		EL.EventLogID,
				EL.Message,
				EL.Category,
				EL.SettingsID,
				EL.EventID,
				EL.EventType,
				EL.EventDate,
				EL.MachineName
	FROM		cs_EventLog EL
	WHERE		EL.EventLogID = @EntryID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_GetEntry to public
go
/***********************************************
* Sproc: cs_Exceptions_Get
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Exceptions_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Exceptions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Exceptions_Get]
GO




CREATE  procedure [dbo].cs_Exceptions_Get
(
	@SettingsID int,
	@ExceptionType int = 0,
	@MinFrequency int = 10,
	@SortOrder int = 1,
	@IncludeUnknown bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF @SortOrder = 1
	SELECT TOP 100
		E.*
	FROM
		cs_Exceptions E
	WHERE
		E.SettingsID = @SettingsID AND
		((@ExceptionType > 0 and E.Category = @ExceptionType ) or @ExceptionType <= 0 ) AND
		E.Frequency >= @MinFrequency
		AND (@IncludeUnknown = 1 OR (@IncludeUnknown = 0 AND E.Category <> 999))
	ORDER BY
		E.DateLastOccurred DESC, E.Frequency DESC
ELSE
	SELECT TOP 100
		E.*
	FROM
		cs_Exceptions E
	WHERE
		E.SettingsID = @SettingsID AND
		((@ExceptionType > 0 and E.Category = @ExceptionType ) or @ExceptionType <= 0 ) AND
		E.Frequency >= @MinFrequency
		AND (@IncludeUnknown = 1 OR (@IncludeUnknown = 0 AND E.Category <> 999))
	ORDER BY
		E.Frequency DESC, E.DateLastOccurred DESC
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Exceptions_Get to public
go
/***********************************************
* Sproc: cs_Exceptions_Log
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Exceptions_Log'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Exceptions_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Exceptions_Log]
GO




CREATE procedure [dbo].cs_Exceptions_Log
(
	@SettingsID int,
	@ExceptionHash varchar(128),
	@Category int,
	@Exception nvarchar(2000),
	@ExceptionMessage nvarchar(500),
	@UserAgent nvarchar(64),
	@IPAddress varchar(15),
	@HttpReferrer nvarchar (256),
	@HttpVerb nvarchar(24),
	@PathAndQuery nvarchar(512)
)
AS
BEGIN

SET Transaction Isolation Level Read UNCOMMITTED

IF EXISTS (SELECT ExceptionID FROM cs_Exceptions WHERE ExceptionHash = @ExceptionHash and SettingsID = @SettingsID)

	UPDATE
		cs_Exceptions
	SET
		DateLastOccurred = GetDate(),
		Frequency = Frequency + 1
	WHERE
		ExceptionHash = @ExceptionHash and SettingsID = @SettingsID
ELSE
	INSERT INTO 
		cs_Exceptions
	(
		ExceptionHash,
		SettingsID,
		Category,
		Exception,
		ExceptionMessage,
		UserAgent,
		IPAddress,
		HttpReferrer,
		HttpVerb,
		PathAndQuery,
		DateCreated,
		DateLastOccurred,
		Frequency
	)
	VALUES
	(
		@ExceptionHash,
		@SettingsID,
		@Category,
		@Exception,
		@ExceptionMessage,
		@UserAgent,
		@IPAddress,
		@HttpReferrer,
		@HttpVerb,
		@PathAndQuery,
		GetDate(),
		GetDate(),
		1
	)

END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Exceptions_Log to public
go
/***********************************************
* Sproc: cs_Favorites_Get
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Favorites_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_Get]
GO

CREATE procedure dbo.cs_Favorites_Get
(
	@FavoriteType	int,
	@UserID			int,
	@SettingsID		int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.OwnerID = @UserID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers F
		WHERE
			F.OwnerID = @UserID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.OwnerID = @UserID AND
			F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_Get] to public

/***********************************************
* Sproc: cs_Favorites_GetPosts
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Favorites_GetPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetPosts]
GO

CREATE procedure dbo.cs_Favorites_GetPosts
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

SELECT
	FP.ApplicationType,
	U.*,
	jP.TotalRatings AS PostTotalRatings,
	jP.RatingSum AS PostRatingSum,
	jP.PostID, 
	jP.ThreadID, 
	jP.ParentID, 
	jP.PostAuthor, 
	jP.UserID, 
	jP.SectionID, 
	jP.PostLevel, 
	jP.SortOrder, 
	jP.Subject, 
	jP.PostDate, 
	jP.IsApproved,
	jP.IsLocked as IsLocked,
	jP.IsIndexed, 
	jP.TotalViews as PostTotalViews,  --Conflicts with the Threads table which has precidence
	jP.Body, 
	jP.FormattedBody, 
	jP.IPAddress, 
	jP.PostType, 
	jP.PostMedia, 
	jP.EmoticonID, 
	jP.SettingsID, 
	jP.AggViews,
	jP.PostPropertyNames, 
	jP.PostPropertyValues,
	jP.PostConfiguration,
	jP.Points AS PostPoints,
	jP.PostStatus,
	jP.SpamScore,
	
	jP.AttachmentFilename,jP.ContentType, jP.IsRemote, jP.FriendlyFileName, jP.ContentSize, jP.[FileName],jP.Created, jP.Height, jP.Width,
	jP.PostName, 
	jP.ApplicationPostType, 
	jP.UserTime, 
	HasRead = 1,
	EditNotes = null, --(SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),

	jT.PostAuthor as UserName,
	jT.TotalReplies as Replies, -- (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1)

        jT.UserID as ThreadUserID,
        jT.PostAuthor as ThreadPostAuthor,
        jT.PostDate as ThreadPostDate,
        jT.ThreadDate,
        jT.LastViewedDate,
        jT.StickyDate,
        jT.TotalViews as TotalViews,
        jT.TotalReplies,
        jT.MostRecentPostAuthorID,
        jT.MostRecentPostAuthor,
        jT.MostRecentPostID,
        jT.IsLocked as ThreadIsLocked,
        jT.IsSticky,
        jT.IsApproved as ThreadIsApproved,
        jT.RatingSum,
        jT.TotalRatings,
        jT.ThreadEmoticonID,
        jT.ThreadStatus,
        jT.SettingsID
FROM
	cs_FavoritePosts FP
	JOIN cs_vw_PostsWithAttachmentDetails jP ON FP.PostID = jP.PostID
	JOIN cs_vw_Users_FullUser U ON jP.UserID = U.UserID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
WHERE
	FP.OwnerID = @UserID
	AND jP.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID AND U.SettingsID = @SettingsID
ORDER BY
	jP.Subject

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetPosts] to public

/***********************************************
* Sproc: cs_Favorites_GetSections
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Favorites_GetSections'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetSections]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetSections]
GO

CREATE procedure dbo.cs_Favorites_GetSections
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		F.SectionID,
		F.ApplicationType
	FROM
		cs_FavoriteSections F
	WHERE
		F.OwnerID = @UserID AND
		F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetSections] to public

/***********************************************
* Sproc: cs_Favorites_GetUsers
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Favorites_GetUsers'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetUsers]
GO

CREATE procedure dbo.cs_Favorites_GetUsers
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		U.*
	FROM
		cs_FavoriteUsers F,
		cs_vw_Users_FullUser U
	WHERE
		F.UserID = U.UserID AND
		F.OwnerID = @UserID AND
		F.SettingsID = @SettingsID AND
		U.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetUsers] to public

/***********************************************
* Sproc: cs_Favorites_GetUsersWatching
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Favorites_GetUsersWatching'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetUsersWatching]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetUsersWatching]
GO

CREATE procedure dbo.cs_Favorites_GetUsersWatching
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		U.*
	FROM
		cs_FavoriteUsers F,
		cs_vw_Users_FullUser U
	WHERE
		F.OwnerID = U.UserID AND
		F.UserID = @UserID AND
		F.SettingsID = @SettingsID AND
		U.SettingsID = @SettingsID AND
		(U.FavoritesShared & 2) = 2		-- sharing users

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetUsersWatching] to public

/***********************************************
* Sproc: cs_Favorite_Add
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Favorite_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Add]
GO

CREATE PROCEDURE dbo.cs_Favorite_Add
(
	@SettingsID			int,
	@UserID				int,
	@ItemID				int,
	@FavoriteType		int,
	@ApplicationType	int,
	@FavoriteID			int OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	IF @FavoriteType = 1		-- Section
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoriteSections F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	SectionID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoriteSections
				(OwnerID, SettingsID, SectionID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

	ELSE IF @FavoriteType = 2	-- User
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoriteUsers F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	UserID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoriteUsers
				(OwnerID, SettingsID, UserID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

	ELSE IF @FavoriteType = 4	-- Post
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoritePosts F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	PostID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoritePosts
				(OwnerID, SettingsID, PostID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Add] to public

/***********************************************
* Sproc: cs_Favorite_Delete
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Favorite_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Delete]
GO

CREATE PROCEDURE dbo.cs_Favorite_Delete
(
	@FavoriteType	int,
	@FavoriteID		int
)
AS
	IF @FavoriteType = 1		-- Section

		DELETE
		FROM	cs_FavoriteSections
		WHERE	FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 2	-- User

		DELETE
		FROM	cs_FavoriteUsers
		WHERE	FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 4	-- Post

		DELETE
		FROM	cs_FavoritePosts
		WHERE	FavoriteID = @FavoriteID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Delete] to public

/***********************************************
* Sproc: cs_Favorite_Get
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Favorite_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Get]
GO

CREATE procedure dbo.cs_Favorite_Get
(
	@FavoriteType	int,
	@FavoriteID		int
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED


	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers F
		WHERE
			F.FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.FavoriteID = @FavoriteID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Get] to public

/***********************************************
* Sproc: cs_Favorite_GetByUserItem
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Favorite_GetByUserItem'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_GetByUserItem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_GetByUserItem]
GO

CREATE procedure dbo.cs_Favorite_GetByUserItem
(
	@SettingsID		int,
	@FavoriteType	int,
	@UserID			int,
	@ItemID			int
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED


	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.OwnerID = @UserID AND
			F.SectionID = @ItemID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers F
		WHERE
			F.OwnerID = @UserID AND
			F.UserID = @ItemID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.OwnerID = @UserID AND
			F.PostID = @ItemID AND
			F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_GetByUserItem] to public

/***********************************************
* Sproc: cs_FeedPost_GetPost
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_FeedPost_GetPost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_GetPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_GetPost]
GO

/***********************************************
* Sproc: cs_FeedPost_GetPostFullDetails
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_FeedPost_GetPostFullDetails'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_GetPostFullDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_GetPostFullDetails]
GO

/***********************************************
* Sproc: cs_FeedPost_UpdatePosts
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_FeedPost_UpdatePosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_UpdatePosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_UpdatePosts]
GO
/***********************************************
* Sproc: cs_Feed_AddFeed
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Feed_AddFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_AddFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_AddFeed]
GO

/***********************************************
* Sproc: cs_Feed_GetAll
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Feed_GetAll'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetAll]
GO

/***********************************************
* Sproc: cs_Feed_GetAll_ModifiedSince
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Feed_GetAll_ModifiedSince'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetAll_ModifiedSince]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].[cs_Feed_GetAll_ModifiedSince]
GO
/***********************************************
* Sproc: cs_Feed_GetFeed
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Feed_GetFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetFeed]
GO

/***********************************************
* Sproc: cs_Feed_GetFeedPosts
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Feed_GetFeedPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetFeedPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetFeedPosts]
GO

/***********************************************
* Sproc: cs_Feed_GetProperties
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Feed_GetProperties'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetProperties]
GO

/***********************************************
* Sproc: cs_Feed_GetUsers
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Feed_GetUsers'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetUsers]
GO


/***********************************************
* Sproc: cs_Feed_MoveFeed
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Feed_MoveFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_MoveFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_MoveFeed]
GO

/***********************************************
* Sproc: cs_Feed_Update
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Feed_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_Update]
GO
/***********************************************
* Sproc: cs_Feed_UpdateFeedStatus
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Feed_UpdateFeedStatus'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_UpdateFeedStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_UpdateFeedStatus]
GO
/***********************************************
* Sproc: cs_Folder_AddFolder
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Folder_AddFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_AddFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_AddFolder]
GO


/***********************************************
* Sproc: cs_Folder_DeleteFolder
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Folder_DeleteFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_DeleteFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_DeleteFolder]
GO

/***********************************************
* Sproc: cs_Folder_GetFeeds
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Folder_GetFeeds'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetFeeds]
GO

/***********************************************
* Sproc: cs_Folder_GetFolders
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Folder_GetFolders'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetFolders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetFolders]
GO

/***********************************************
* Sproc: cs_Folder_GetSummary
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_Folder_GetSummary'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetSummary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetSummary]
GO

/***********************************************
* Sproc: cs_Folder_MoveFolder
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Folder_MoveFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_MoveFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_MoveFolder]
GO

/***********************************************
* Sproc: cs_Folder_RenameFolder
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_Folder_RenameFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_RenameFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_RenameFolder]
GO

/***********************************************
* Sproc: cs_ForumPostActivityReportRecords_Get
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_ForumPostActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ForumPostActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ForumPostActivityReportRecords_Get]
GO
/***********************************************
* Sproc: cs_forums_GetForumMessages
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_forums_GetForumMessages'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumMessages]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumMessages]
GO


CREATE procedure [dbo].cs_forums_GetForumMessages
(
	@MessageID int = 0,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF @MessageID = 0
	SELECT 
		*
	FROM
		cs_Messages where SettingsID = @SettingsID
ELSE
	SELECT 
		*
	FROM
		cs_Messages
	WHERE
		MessageID = @MessageID and SettingsID = @SettingsID






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumMessages to public
go
/***********************************************
* Sproc: cs_forums_GetForumModerators
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_forums_GetForumModerators'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumModerators]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumModerators]
GO

CREATE  PROCEDURE [dbo].cs_forums_GetForumModerators
(
	@SectionID	int,
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- get a list of forum moderators
	SELECT 
		UserName, EmailNotification, DateCreated
	FROM 
		Moderators (nolock)
	WHERE 
		(SectionID = @SectionID OR SectionID = 0) and SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumModerators to public
go
/***********************************************
* Sproc: cs_forums_GetForumsModeratedByUser
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_forums_GetForumsModeratedByUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumsModeratedByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumsModeratedByUser]
GO






create procedure [dbo].cs_forums_GetForumsModeratedByUser
(
	@UserName	nvarchar(50),
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- determine if this user can moderate ALL forums
	IF EXISTS(SELECT NULL FROM Moderators (nolock) WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID)
		SELECT SectionID, ForumName = 'All Forums', EmailNotification, DateCreated FROM Moderators (nolock)
		WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID
	ELSE
		-- get all of the forums moderated by this particular user
		SELECT
			M.SectionID,
			EmailNotification,
			ForumName = F.Name,
			M.DateCreated
		FROM Moderators M (nolock)
			INNER JOIN Forums F (nolock) ON
				F.SectionID = M.SectionID
		WHERE Username = @UserName and M.SettingsID = @SettingsID  and F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumsModeratedByUser to public
go
/***********************************************
* Sproc: cs_forums_GetForumsNotModeratedByUser
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_forums_GetForumsNotModeratedByUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumsNotModeratedByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumsNotModeratedByUser]
GO

CREATE  PROCEDURE [dbo].cs_forums_GetForumsNotModeratedByUser
(
	@UserName	nvarchar(50),
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- determine if this user can moderate ALL forums
	IF NOT EXISTS(SELECT NULL FROM Moderators (nolock) WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID)
		-- get all of the forums NOT moderated by this particular user
		SELECT SectionID =  0, ForumName =  'All Forums'
		UNION
		SELECT
			SectionID,
			ForumName = F.Name
		FROM Forums F (nolock) 
		WHERE SettingsID = @SettingsID and  SectionID NOT IN (SELECT SectionID FROM Moderators (nolock) WHERE Username = @UserName and SettingsID = @SettingsID)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_forums_GetForumsNotModeratedByUser] to public
go
/***********************************************
* Sproc: cs_forums_GetUnmoderatedPostStatus
* File Date: 4/14/2008 11:35:02 AM
***********************************************/
Print 'Creating...cs_forums_GetUnmoderatedPostStatus'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetUnmoderatedPostStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetUnmoderatedPostStatus]
GO

CREATE PROCEDURE [dbo].cs_forums_GetUnmoderatedPostStatus
(
  @SectionID int = null,
  @UserName varchar,
  @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
IF(@SectionID = 0)
     SET @SectionID  = null

IF(@SectionID IS Null)
BEGIN
     SELECT OldestPostAgeInMinutes = DateDiff(mi, IsNull(MIN(PostDate),GetDate()),GetDate()),TotalPostsInModerationQueue = Count(PostID)
     FROM cs_Posts P 
     WHERE P.IsApproved = 0 
     AND P.SettingsID = @SettingsID
END
ELSE
BEGIN
     SELECT OldestPostAgeInMinutes = DateDiff(mi, IsNull(MIN(PostDate),GetDate()),GetDate()),TotalPostsInModerationQueue = Count(PostID)
     FROM cs_Posts P 
     WHERE P.IsApproved = 0 
     AND P.SettingsID = @SettingsID
     AND P.SectionID = @SectionID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_forums_GetUnmoderatedPostStatus] to public
go
/***********************************************
* Sproc: cs_forums_Moderate_PostSet
* File Date: 4/14/2008 11:35:01 AM
***********************************************/
Print 'Creating...cs_forums_Moderate_PostSet'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Moderate_PostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Moderate_PostSet]
GO
CREATE PROCEDURE dbo.cs_forums_Moderate_PostSet
(
	@SectionID		int,
	@PageIndex 		int,
	@PageSize 		int,
	@SortBy 		int,
	@SortOrder 		bit,
	@UserID 		int,
	@ReturnRecordCount 	bit,
	@SettingsID		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
