if db_name() in('master','model','msdn','tempdb')
begin
	print 'Don''t add these to ' + db_name()
	return
end
/****** Object:  Table [dbo].[DeleteLog]    Script Date: 03/29/2011 17:26:23 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteLog]') AND type in (N'U'))
DROP TABLE [dbo].[DeleteLog]
GO
	
CREATE TABLE [dbo].[DeleteLog](
	[DeleteID] [int] IDENTITY(1,1) NOT NULL,
	[SPID] [int] NOT NULL CONSTRAINT [DF_DeleteLog_SPID]  DEFAULT (@@spid),
	[UserID] [nvarchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[DTS] [datetime] NOT NULL CONSTRAINT [DF_DeleteLog_DTS]  DEFAULT (getdate()),
 CONSTRAINT [PK_DeleteLog] PRIMARY KEY CLUSTERED 
(
	[DeleteID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

-- Display the status of Table creation
IF (@@Error = 0) PRINT 'Table Creation: DeleteLog Succeeded'
ELSE PRINT 'Table Creation: DeleteLog Error on Creation'
GO

/****** Object:  StoredProcedure [addAnnotation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addAnnotation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addAnnotation];
GO
	
CREATE PROCEDURE [dbo].[addAnnotation]

(
	@ItemID int,
	@TypeID int,
	@RtfText nvarchar(MAX)=null,
	@SearchText nvarchar(MAX)=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newAnnotationID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Annotations]
	(
		[ItemID],
		[TypeID],
		[RtfText],
		[SearchText],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ItemID,
		@TypeID,
		@RtfText,
		@SearchText,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newAnnotationID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Annotations] WHERE [AnnotationID]=@newAnnotationID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addAnnotation Succeeded'
ELSE PRINT 'Procedure Creation: addAnnotation Error on Creation'
GO

/****** Object:  StoredProcedure [addAnnotationType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addAnnotationType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addAnnotationType];
GO
	
CREATE PROCEDURE [dbo].[addAnnotationType]

(
	@Name nvarchar(100),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newTypeID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [AnnotationTypes]
	(
		[Name],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@Name,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newTypeID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [AnnotationTypes] WHERE [TypeID]=@newTypeID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addAnnotationType Succeeded'
ELSE PRINT 'Procedure Creation: addAnnotationType Error on Creation'
GO

/****** Object:  StoredProcedure [addAssignment] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addAssignment]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addAssignment];
GO
	
CREATE PROCEDURE [dbo].[addAssignment]

(
	@GID int,
	@RID int,
	@FolderID int,
	@StartDate datetime,
	@EndDate datetime=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@newAID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Assignments]
	(
		[GID],
		[RID],
		[FolderID],
		[StartDate],
		[EndDate],
		[DTS],
		[UsrID]
	)
	VALUES
	(
		@GID,
		@RID,
		@FolderID,
		@StartDate,
		@EndDate,
		@DTS,
		@UsrID
	)
	SELECT @newAID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Assignments] WHERE [AID]=@newAID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addAssignment Succeeded'
ELSE PRINT 'Procedure Creation: addAssignment Error on Creation'
GO

/****** Object:  StoredProcedure [addAssociation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addAssociation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addAssociation];
GO
	
CREATE PROCEDURE [dbo].[addAssociation]

(
	@VersionID int,
	@ROFstID int,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newAssociationID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Associations]
	(
		[VersionID],
		[ROFstID],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@VersionID,
		@ROFstID,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newAssociationID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Associations] WHERE [AssociationID]=@newAssociationID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addAssociation Succeeded'
ELSE PRINT 'Procedure Creation: addAssociation Error on Creation'
GO

/****** Object:  StoredProcedure [addConnection] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addConnection]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addConnection];
GO
	
CREATE PROCEDURE [dbo].[addConnection]

(
	@Name nvarchar(100)=null,
	@Title nvarchar(510)=null,
	@ConnectionString nvarchar(510)=null,
	@ServerType int,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@newDBID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Connections]
	(
		[Name],
		[Title],
		[ConnectionString],
		[ServerType],
		[Config],
		[DTS],
		[UsrID]
	)
	VALUES
	(
		@Name,
		@Title,
		@ConnectionString,
		@ServerType,
		@Config,
		@DTS,
		@UsrID
	)
	SELECT @newDBID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Connections] WHERE [DBID]=@newDBID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addConnection Succeeded'
ELSE PRINT 'Procedure Creation: addConnection Error on Creation'
GO

/****** Object:  StoredProcedure [addContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addContent];
GO
	
CREATE PROCEDURE [dbo].[addContent]

(
	@Number nvarchar(256)=null,
	@Text nvarchar(MAX)=null,
	@Type int=null,
	@FormatID int=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newContentID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Contents]
	(
		[Number],
		[Text],
		[Type],
		[FormatID],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@Number,
		@Text,
		@Type,
		@FormatID,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newContentID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Contents] WHERE [ContentID]=@newContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addContent Succeeded'
ELSE PRINT 'Procedure Creation: addContent Error on Creation'
GO

/****** Object:  StoredProcedure [addDetail] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addDetail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addDetail];
GO
	
CREATE PROCEDURE [dbo].[addDetail]

(
	@ContentID int,
	@ItemType int,
	@Text nvarchar(MAX),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newDetailID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Details]
	(
		[ContentID],
		[ItemType],
		[Text],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ContentID,
		@ItemType,
		@Text,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newDetailID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Details] WHERE [DetailID]=@newDetailID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addDetail Succeeded'
ELSE PRINT 'Procedure Creation: addDetail Error on Creation'
GO

/****** Object:  StoredProcedure [addDocument] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addDocument]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addDocument];
GO
	
CREATE PROCEDURE [dbo].[addDocument]

(
	@LibTitle nvarchar(1024)=null,
	@DocContent varbinary(MAX)=null,
	@DocAscii nvarchar(MAX)=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@FileExtension nvarchar(10),
	@newDocID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Documents]
	(
		[LibTitle],
		[DocContent],
		[DocAscii],
		[Config],
		[DTS],
		[UserID],
		[FileExtension]
	)
	VALUES
	(
		@LibTitle,
		@DocContent,
		@DocAscii,
		@Config,
		@DTS,
		@UserID,
		@FileExtension
	)
	SELECT @newDocID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Documents] WHERE [DocID]=@newDocID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addDocument Succeeded'
ELSE PRINT 'Procedure Creation: addDocument Error on Creation'
GO

/****** Object:  StoredProcedure [addDocVersion] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addDocVersion]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addDocVersion];
GO
	
CREATE PROCEDURE [dbo].[addDocVersion]

(
	@FolderID int,
	@VersionType int,
	@Name nvarchar(100),
	@Title nvarchar(510)=null,
	@ItemID int=null,
	@FormatID int=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newVersionID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [DocVersions]
	(
		[FolderID],
		[VersionType],
		[Name],
		[Title],
		[ItemID],
		[FormatID],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@FolderID,
		@VersionType,
		@Name,
		@Title,
		@ItemID,
		@FormatID,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newVersionID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [DocVersions] WHERE [VersionID]=@newVersionID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addDocVersion Succeeded'
ELSE PRINT 'Procedure Creation: addDocVersion Error on Creation'
GO

/****** Object:  StoredProcedure [addDROUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addDROUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addDROUsage];
GO
	
CREATE PROCEDURE [dbo].[addDROUsage]

(
	@DocID int,
	@ROID nvarchar(16),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@RODbID int,
	@newDROUsageID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [DROUsages]
	(
		[DocID],
		[ROID],
		[Config],
		[DTS],
		[UserID],
		[RODbID]
	)
	VALUES
	(
		@DocID,
		@ROID,
		@Config,
		@DTS,
		@UserID,
		@RODbID
	)
	SELECT @newDROUsageID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [DROUsages] WHERE [DROUsageID]=@newDROUsageID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addDROUsage Succeeded'
ELSE PRINT 'Procedure Creation: addDROUsage Error on Creation'
GO

/****** Object:  StoredProcedure [addEntry] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addEntry]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addEntry];
GO
	
CREATE PROCEDURE [dbo].[addEntry]

(
	@ContentID int,
	@DocID int,
	@DTS datetime,
	@UserID nvarchar(100),
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Entries]
	(
		[ContentID],
		[DocID],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ContentID,
		@DocID,
		@DTS,
		@UserID
	)

	SELECT 		@newLastChanged=[LastChanged]
		FROM [Entries] WHERE [ContentID]=@ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addEntry Succeeded'
ELSE PRINT 'Procedure Creation: addEntry Error on Creation'
GO

/****** Object:  StoredProcedure [addFigure] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addFigure]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addFigure];
GO
	
CREATE PROCEDURE [dbo].[addFigure]

(
	@ROFstID int,
	@ImageID int,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newFigureID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Figures]
	(
		[ROFstID],
		[ImageID],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ROFstID,
		@ImageID,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newFigureID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Figures] WHERE [FigureID]=@newFigureID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addFigure Succeeded'
ELSE PRINT 'Procedure Creation: addFigure Error on Creation'
GO

/****** Object:  StoredProcedure [addFolder] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addFolder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addFolder];
GO
	
CREATE PROCEDURE [dbo].[addFolder]

(
	@ParentID int,
	@DBID int,
	@Name nvarchar(100),
	@Title nvarchar(510)=null,
	@ShortName nvarchar(20),
	@FormatID int=null,
	@ManualOrder float=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@newFolderID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Folders]
	(
		[ParentID],
		[DBID],
		[Name],
		[Title],
		[ShortName],
		[FormatID],
		[ManualOrder],
		[Config],
		[DTS],
		[UsrID]
	)
	VALUES
	(
		@ParentID,
		@DBID,
		@Name,
		@Title,
		@ShortName,
		@FormatID,
		@ManualOrder,
		@Config,
		@DTS,
		@UsrID
	)
	SELECT @newFolderID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Folders] WHERE [FolderID]=@newFolderID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addFolder Succeeded'
ELSE PRINT 'Procedure Creation: addFolder Error on Creation'
GO

/****** Object:  StoredProcedure [addFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addFormat]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addFormat];
GO
	
CREATE PROCEDURE [dbo].[addFormat]

(
	@ParentID int,
	@Name nvarchar(20),
	@Description nvarchar(250)=null,
	@Data xml,
	@GenMac xml=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newFormatID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Formats]
	(
		[ParentID],
		[Name],
		[Description],
		[Data],
		[GenMac],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ParentID,
		@Name,
		@Description,
		@Data,
		@GenMac,
		@DTS,
		@UserID
	)
	SELECT @newFormatID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Formats] WHERE [FormatID]=@newFormatID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addFormat Succeeded'
ELSE PRINT 'Procedure Creation: addFormat Error on Creation'
GO

/****** Object:  StoredProcedure [addGrid] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addGrid]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addGrid];
GO
	
CREATE PROCEDURE [dbo].[addGrid]

(
	@ContentID int,
	@Data xml,
	@Config xml=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Grids]
	(
		[ContentID],
		[Data],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ContentID,
		@Data,
		@Config,
		@DTS,
		@UserID
	)

	SELECT 		@newLastChanged=[LastChanged]
		FROM [Grids] WHERE [ContentID]=@ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addGrid Succeeded'
ELSE PRINT 'Procedure Creation: addGrid Error on Creation'
GO

/****** Object:  StoredProcedure [addGroup] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addGroup]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addGroup];
GO
	
CREATE PROCEDURE [dbo].[addGroup]

(
	@GroupName nvarchar(50),
	@GroupType int=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@newGID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Groups]
	(
		[GroupName],
		[GroupType],
		[Config],
		[DTS],
		[UsrID]
	)
	VALUES
	(
		@GroupName,
		@GroupType,
		@Config,
		@DTS,
		@UsrID
	)
	SELECT @newGID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Groups] WHERE [GID]=@newGID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addGroup Succeeded'
ELSE PRINT 'Procedure Creation: addGroup Error on Creation'
GO

/****** Object:  StoredProcedure [addImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addImage];
GO
	
CREATE PROCEDURE [dbo].[addImage]

(
	@ContentID int,
	@ImageType int,
	@FileName nvarchar(255),
	@Data varbinary(MAX),
	@Config xml=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Images]
	(
		[ContentID],
		[ImageType],
		[FileName],
		[Data],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ContentID,
		@ImageType,
		@FileName,
		@Data,
		@Config,
		@DTS,
		@UserID
	)

	SELECT 		@newLastChanged=[LastChanged]
		FROM [Images] WHERE [ContentID]=@ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addImage Succeeded'
ELSE PRINT 'Procedure Creation: addImage Error on Creation'
GO

/****** Object:  StoredProcedure [addItem] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addItem]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addItem];
GO
	
CREATE PROCEDURE [dbo].[addItem]

(
	@PreviousID int=null,
	@ContentID int,
	@DTS datetime,
	@UserID nvarchar(100),
	@newItemID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Items]
	(
		[PreviousID],
		[ContentID],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@PreviousID,
		@ContentID,
		@DTS,
		@UserID
	)
	SELECT @newItemID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Items] WHERE [ItemID]=@newItemID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addItem Succeeded'
ELSE PRINT 'Procedure Creation: addItem Error on Creation'
GO

/****** Object:  StoredProcedure [addItemChild] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addItemChild]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addItemChild];
GO
	
--http://www.code-magazine.com/articleprint.aspx?quickid=0305111&page=4&printmode=true
--http://aleemkhan.wordpress.com/2006/07/21/t-sql-error-handling-pattern-for-nested-transactions-and-stored-procedures/
CREATE PROCEDURE [dbo].[addItemChild]
(
	@ItemID int=null,	@Number nvarchar(30)=null,	@Text nvarchar(MAX)=null,	@FormatID int=null,	@Config nvarchar(MAX)=null,
	@FromType int=null,	@Type int=null,	@DTS datetime,	@UserID nvarchar(100),	@newItemID int output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DECLARE @ChildID int,	@ContentID int,	@ParentContentID int,	@LastChanged timestamp
	,	@newLastChanged timestamp, @Error int, @Rowcount int, @ChildDeleted int
  SELECT @ChildID = pp.[ItemID],@ParentContentID = ii.ContentID, @LastChanged = pp.LastChanged
		FROM [ITEMS] ii
		LEFT JOIN [PARTS] pp on pp.ContentID=ii.ContentID and pp.FromType=@FromType
		WHERE ii.[ItemID]=@ItemID
  IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[tblParts]') AND OBJECTPROPERTY(id,N'IsTable') = 1)
  BEGIN
	  SELECT @ChildDeleted = pp.[ItemID],@ParentContentID = ii.ContentID, @LastChanged = pp.LastChanged
			FROM [ITEMS] ii
			LEFT JOIN [tblPARTS] pp on pp.ContentID=ii.ContentID and pp.FromType=@FromType
			WHERE ii.[ItemID]=@ItemID and pp.DeleteStatus > 0
	END
	EXECUTE AddContent @Number, @Text, @Type, @FormatID, @Config, @DTS, @UserID, @ContentID output, @newLastChanged output
	EXECUTE AddItem null, @ContentID,	@DTS,	@UserID ,	@newItemID output,	@newLastChanged output
	IF @ChildID is null -- No existing child - Add Parts record
	BEGIN
		IF @ChildDeleted is not null
		BEGIN
--			INSERT INTO [PartAudits] ([ContentID],[FromType],[ItemID],[DTS],[UserID],[DeleteStatus])
--			SELECT [ContentID],[FromType],[ItemID],[DTS],[UserID],[DeleteStatus]  FROM [tblParts]
--			WHERE ItemID = @ChildDeleted
			DELETE FROM [tblParts] WHERE ItemID = @ChildDeleted
		END
		EXECUTE AddPart 	@ParentContentID, @FromType, @newItemID, @DTS, @UserID, @newLastChanged output
	END
	ELSE -- Update existing Parts record
		BEGIN
			EXECUTE UpdatePart @ParentContentID, @FromType, @newItemID, @DTS, @UserID, @LastChanged, @newLastChanged output
			UPDATE [Items] SET [PreviousID]=@newItemID WHERE [ItemID]=@ChildID
			-- Update content records for the transitions
			Update CC
				Set Text = DBO.vefn_FixTransitionText(Text,TT.TransitionID,TT.TranType,TT.ToID,TT.RangeID,@ItemID,@newItemID)
			From CONTENTS CC
				JOIN Transitions TT ON TT.FromID = CC.ContentID
				WHERE TT.ToID = @ChildID OR TT.RangeID = @ChildID
			-- Update transitions that pointed to @ItemID to point to @newItemID
			Update TRANSITIONS
				Set ToID = CASE ToID WHEN @ChildID THEN @newItemID ELSE ToID END,
					RangeID = CASE RangeID WHEN @ChildID THEN @newItemID ELSE RangeID END
					WHERE ToID = @ChildID OR RangeID = @ChildID
			-- Add 'Verification Required' AnnotationType
			DECLARE @typeID int
			SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
			IF(@typeID IS NULL)
			BEGIN
				INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
				SELECT @typeID = SCOPE_IDENTITY()
			END
			-- Add "Verification Required" Annotation for each Transition that points to @newItemID or @NextID
			-- I don't expect to see any transitions that point to @ChildID.  They should have changed in
			-- the update above to point to @newItemID.  This is here for consistency with the other insert
			-- stored procedures
			INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
				SELECT ItemID, @typeID,'Verify Transition Destination',@UserID
				FROM Items where CONTENTID in (SELECT FromID FROM TRANSITIONS
				where ToID IN(@ChildID,@newItemID) OR RangeID IN(@ChildID,@newItemID))
			-- Transition Text gets updated in ItemInsertExt.cs
		END
	IF( @@TRANCOUNT > 0 ) COMMIT
  PRINT 'Child Added ' + ltrim(str(@newItemID))
	EXECUTE GetItem @newItemID
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addItemChild Succeeded'
ELSE PRINT 'Procedure Creation: addItemChild Error on Creation'
GO

/****** Object:  StoredProcedure [addItemSiblingAfter] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addItemSiblingAfter]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addItemSiblingAfter];
GO
	
CREATE PROCEDURE [dbo].[addItemSiblingAfter]
(
	@ItemID int=null,	@Number nvarchar(30)=null,	@Text nvarchar(MAX)=null,	@FormatID int=null,	@Config nvarchar(MAX)=null,
	@Type int=null, @DTS datetime,	@UserID nvarchar(100),	@newItemID int output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DECLARE @NextID int, @ContentID int,	@newLastChanged timestamp, @NewType int
	SELECT @NewType=ISNULL(@Type,[Type])
		FROM [ITEMS] II JOIN [CONTENTS] CC ON II.[ContentID]=CC.[ContentID]
		WHERE [ItemID]=@ItemID
	SELECT @NextID = [ItemID]
		FROM [ITEMS]
		WHERE [PreviousID]=@ItemID
	EXECUTE AddContent @Number, @Text, @NewType, @FormatID, @Config, @DTS, @UserID, @ContentID output, @newLastChanged output
	EXECUTE AddItem @ItemID, @ContentID,	@DTS,	@UserID ,	@newItemID output,	@newLastChanged output
  UPDATE [ITEMS] SET [PreviousID]=@newItemID, [DTS]=@DTS, [UserID]=@UserID where [ItemID]=@NextID -- Should be UpdateItem
  -- Get a list of Transitions which need to change children of @ItemID that point to @NextID
	DECLARE @NextStepTransitions TABLE
	(
		[TransitionID] int PRIMARY KEY,
		[FromID] [int],
		[ToID] [int],
		[RangeID] [int],
		[TranType] [int],
		[Config] [nvarchar](max)
	)
	Insert into @NextStepTransitions select * from vefn_NextStepTransitions(@NextID,@ItemID)
	IF (SELECT COUNT(*) from @NextStepTransitions) > 0 -- Next Step Transitions
	BEGIN
		-- Update all transitions in the list to point to @newItemID
		Update TT
			Set TT.ToID = CASE TT.ToID WHEN @NextID THEN @newItemID ELSE TT.ToID END,
				TT.RangeID = CASE TT.RangeID WHEN @NextID THEN @newItemID ELSE TT.RangeID END
		From TRANSITIONS TT
			JOIN @NextStepTransitions NS ON NS.TransitionID = TT.TransitionID
		-- Update content records for the transitions
		Update CC
			Set Text = DBO.vefn_FixTransitionText(Text,NS.TransitionID,NS.TranType,NS.ToID,NS.RangeID,@NextID,@newItemID)
		From CONTENTS CC
			JOIN @NextStepTransitions NS ON NS.FromID = CC.ContentID
	END
  -- Add 'Verification Required' AnnotationType
	DECLARE @typeID int
	SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
	IF(@typeID IS NULL)
	BEGIN
		INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
		SELECT @typeID = SCOPE_IDENTITY()
	END
  -- Add "Verification Required" Annotation for each Transition that points to @newItemID or @NextID
	INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT ItemID, @typeID,'Verify Next Step Transition Destination',@UserID
		FROM Items where CONTENTID in (SELECT FromID FROM TRANSITIONS
		where ToID IN(@newItemID) OR RangeID IN(@newItemID))
	INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT ItemID, @typeID,'Verify Transition Destination',@UserID
		FROM Items where CONTENTID in (SELECT FromID FROM TRANSITIONS
		where ToID IN(@NextID) OR RangeID IN(@NextID))
  -- Transition Text gets updated in ItemInsertExt.cs
	IF( @@TRANCOUNT > 0 ) COMMIT
	EXECUTE GetItem @newItemID
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addItemSiblingAfter Succeeded'
ELSE PRINT 'Procedure Creation: addItemSiblingAfter Error on Creation'
GO

/****** Object:  StoredProcedure [addItemSiblingBefore] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addItemSiblingBefore]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addItemSiblingBefore];
GO
	
CREATE PROCEDURE [dbo].[addItemSiblingBefore]
(
	@ItemID int=null,	@Number nvarchar(30)=null,	@Text nvarchar(MAX)=null,	@FormatID int=null,	@Config nvarchar(MAX)=null,
	@Type int=null, @DTS datetime,	@UserID nvarchar(100), @newItemID int output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DECLARE @PreviousID int, @ContentID int,	@newLastChanged timestamp, @NewType int
  SELECT @PreviousID = [PreviousID], @NewType=ISNULL(@Type,[Type])
		FROM [ITEMS] II
		JOIN [CONTENTS] CC ON CC.[ContentID]=II.[CONTENTID]
		WHERE [ItemID]=@ItemID
	EXECUTE AddContent @Number, @Text, @NewType, @FormatID, @Config, @DTS, @UserID, @ContentID output, @newLastChanged output
	EXECUTE AddItem @PreviousID, @ContentID,	@DTS,	@UserID ,	@newItemID output,	@newLastChanged output
  UPDATE [ITEMS] SET [PreviousID]=@newItemID where [ItemID]=@ItemID -- Should be UpdateItem
  UPDATE [PARTS] SET [ItemID]=@newItemID where [ItemID]=@ItemID -- Should be UpdatePart
  IF @PreviousID is null -- The step is replacing the first step
  BEGIN
		-- Update content records for the transitions
		Update CC
			Set Text = DBO.vefn_FixTransitionText(Text,TT.TransitionID,TT.TranType,TT.ToID,TT.RangeID,@ItemID,@newItemID)
		From CONTENTS CC
			JOIN Transitions TT ON TT.FromID = CC.ContentID
			WHERE TT.ToID = @ItemID OR TT.RangeID = @ItemID
		-- Update transitions that pointed to @ItemID to point to @newItemID
		Update TRANSITIONS
			Set ToID = CASE ToID WHEN @ItemID THEN @newItemID ELSE ToID END,
				RangeID = CASE RangeID WHEN @ItemID THEN @newItemID ELSE RangeID END
				WHERE ToID = @ItemID OR RangeID = @ItemID
  END
  ELSE -- Check for Transitions that point to the Next Step
  BEGIN
		-- Get a list of Transitions which need to change children of @ItemID that point to @NextID
		DECLARE @NextStepTransitions TABLE
		(
			[TransitionID] int PRIMARY KEY,
			[FromID] [int],
			[ToID] [int],
			[RangeID] [int],
			[TranType] [int],
			[Config] [nvarchar](max)
		)
		Insert into @NextStepTransitions select * from vefn_NextStepTransitions(@ItemID,@PreviousID)
		IF (SELECT COUNT(*) from @NextStepTransitions) > 0 -- Next Step Transitions
		BEGIN
			-- Update all transitions in the list to point to @newItemID
			Update TT
				Set TT.ToID = CASE TT.ToID WHEN @ItemID THEN @newItemID ELSE TT.ToID END,
					TT.RangeID = CASE TT.RangeID WHEN @ItemID THEN @newItemID ELSE TT.RangeID END
			From TRANSITIONS TT
				JOIN @NextStepTransitions NS ON NS.TransitionID = TT.TransitionID
			-- Update content records for the transitions
			Update CC
				Set Text = DBO.vefn_FixTransitionText(Text,NS.TransitionID,NS.TranType,NS.ToID,NS.RangeID,@ItemID,@newItemID)
			From CONTENTS CC
				JOIN @NextStepTransitions NS ON NS.FromID = CC.ContentID
		END
	END
  -- Add 'Verification Required' AnnotationType
	DECLARE @typeID int
	SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
	IF(@typeID IS NULL)
	BEGIN
		INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
		SELECT @typeID = SCOPE_IDENTITY()
	END
  -- Add "Verification Required" Annotation for each Transition that points to @newItemID or @NextID
	INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT ItemID, @typeID,'Verify Transition Destination',@UserID
		FROM Items where CONTENTID in (SELECT FromID FROM TRANSITIONS
		where ToID IN(@ItemID,@newItemID) OR RangeID IN(@ItemID,@newItemID))
  -- Transition Text gets updated in ItemInsertExt.cs
	IF( @@TRANCOUNT > 0 ) COMMIT
  PRINT 'Sibling Added Before ' + ltrim(str(@newItemID))
	EXECUTE GetItem @newItemID
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addItemSiblingBefore Succeeded'
ELSE PRINT 'Procedure Creation: addItemSiblingBefore Error on Creation'
GO

/****** Object:  StoredProcedure [addMembership] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addMembership]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addMembership];
GO
	
CREATE PROCEDURE [dbo].[addMembership]

(
	@UID int,
	@GID int,
	@StartDate datetime,
	@EndDate datetime=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@newUGID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Memberships]
	(
		[UID],
		[GID],
		[StartDate],
		[EndDate],
		[Config],
		[DTS],
		[UsrID]
	)
	VALUES
	(
		@UID,
		@GID,
		@StartDate,
		@EndDate,
		@Config,
		@DTS,
		@UsrID
	)
	SELECT @newUGID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Memberships] WHERE [UGID]=@newUGID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addMembership Succeeded'
ELSE PRINT 'Procedure Creation: addMembership Error on Creation'
GO

/****** Object:  StoredProcedure [addPart] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addPart]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addPart];
GO
	
CREATE PROCEDURE [dbo].[addPart]

(
	@ContentID int,
	@FromType int,
	@ItemID int,
	@DTS datetime,
	@UserID nvarchar(100),
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Parts]
	(
		[ContentID],
		[FromType],
		[ItemID],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ContentID,
		@FromType,
		@ItemID,
		@DTS,
		@UserID
	)

	SELECT 		@newLastChanged=[LastChanged]
		FROM [Parts] WHERE [ContentID]=@ContentID AND [FromType]=@FromType
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addPart Succeeded'
ELSE PRINT 'Procedure Creation: addPart Error on Creation'
GO

/****** Object:  StoredProcedure [addPdf] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addPdf]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addPdf];
GO
	
CREATE PROCEDURE [dbo].[addPdf]

(
	@DocID int,
	@DebugStatus int,
	@TopRow int,
	@PageLength int,
	@LeftMargin int,
	@PageWidth int,
	@PageCount float,
	@DocPdf varbinary(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Pdfs]
	(
		[DocID],
		[DebugStatus],
		[TopRow],
		[PageLength],
		[LeftMargin],
		[PageWidth],
		[PageCount],
		[DocPdf],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@DocID,
		@DebugStatus,
		@TopRow,
		@PageLength,
		@LeftMargin,
		@PageWidth,
		@PageCount,
		@DocPdf,
		@DTS,
		@UserID
	)

	SELECT 		@newLastChanged=[LastChanged]
		FROM [Pdfs] WHERE [DocID]=@DocID AND [DebugStatus]=@DebugStatus AND [TopRow]=@TopRow AND [PageLength]=@PageLength AND [LeftMargin]=@LeftMargin AND [PageWidth]=@PageWidth
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addPdf Succeeded'
ELSE PRINT 'Procedure Creation: addPdf Error on Creation'
GO

/****** Object:  StoredProcedure [addPermission] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addPermission]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addPermission];
GO
	
CREATE PROCEDURE [dbo].[addPermission]

(
	@RID int,
	@PermLevel int,
	@VersionType int,
	@PermValue int,
	@PermAD int,
	@StartDate datetime,
	@EndDate datetime=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@newPID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Permissions]
	(
		[RID],
		[PermLevel],
		[VersionType],
		[PermValue],
		[PermAD],
		[StartDate],
		[EndDate],
		[Config],
		[DTS],
		[UsrID]
	)
	VALUES
	(
		@RID,
		@PermLevel,
		@VersionType,
		@PermValue,
		@PermAD,
		@StartDate,
		@EndDate,
		@Config,
		@DTS,
		@UsrID
	)
	SELECT @newPID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Permissions] WHERE [PID]=@newPID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addPermission Succeeded'
ELSE PRINT 'Procedure Creation: addPermission Error on Creation'
GO

/****** Object:  StoredProcedure [addRODb] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addRODb]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addRODb];
GO
	
CREATE PROCEDURE [dbo].[addRODb]

(
	@ROName nvarchar(255),
	@FolderPath nvarchar(255),
	@DBConnectionString nvarchar(MAX),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newRODbID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [RODbs]
	(
		[ROName],
		[FolderPath],
		[DBConnectionString],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@ROName,
		@FolderPath,
		@DBConnectionString,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newRODbID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [RODbs] WHERE [RODbID]=@newRODbID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addRODb Succeeded'
ELSE PRINT 'Procedure Creation: addRODb Error on Creation'
GO

/****** Object:  StoredProcedure [addROFst] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addROFst]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addROFst];
GO
	
CREATE PROCEDURE [dbo].[addROFst]

(
	@RODbID int,
	@ROLookup varbinary(MAX),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newROFstID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [ROFsts]
	(
		[RODbID],
		[ROLookup],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@RODbID,
		@ROLookup,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newROFstID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [ROFsts] WHERE [ROFstID]=@newROFstID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addROFst Succeeded'
ELSE PRINT 'Procedure Creation: addROFst Error on Creation'
GO

/****** Object:  StoredProcedure [addROImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addROImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addROImage];
GO
	
CREATE PROCEDURE [dbo].[addROImage]

(
	@RODbID int,
	@FileName nvarchar(255),
	@Content varbinary(MAX),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newImageID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [ROImages]
	(
		[RODbID],
		[FileName],
		[Content],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@RODbID,
		@FileName,
		@Content,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newImageID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [ROImages] WHERE [ImageID]=@newImageID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addROImage Succeeded'
ELSE PRINT 'Procedure Creation: addROImage Error on Creation'
GO

/****** Object:  StoredProcedure [addRole] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addRole];
GO
	
CREATE PROCEDURE [dbo].[addRole]

(
	@Name nvarchar(50),
	@Title nvarchar(250),
	@DTS datetime,
	@UsrID nvarchar(100),
	@newRID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Roles]
	(
		[Name],
		[Title],
		[DTS],
		[UsrID]
	)
	VALUES
	(
		@Name,
		@Title,
		@DTS,
		@UsrID
	)
	SELECT @newRID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Roles] WHERE [RID]=@newRID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addRole Succeeded'
ELSE PRINT 'Procedure Creation: addRole Error on Creation'
GO

/****** Object:  StoredProcedure [addRoUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addRoUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addRoUsage];
GO
	
CREATE PROCEDURE [dbo].[addRoUsage]

(
	@ContentID int,
	@ROID nvarchar(16),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@RODbID int,
	@newROUsageID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [RoUsages]
	(
		[ContentID],
		[ROID],
		[Config],
		[DTS],
		[UserID],
		[RODbID]
	)
	VALUES
	(
		@ContentID,
		@ROID,
		@Config,
		@DTS,
		@UserID,
		@RODbID
	)
	SELECT @newROUsageID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [RoUsages] WHERE [ROUsageID]=@newROUsageID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addRoUsage Succeeded'
ELSE PRINT 'Procedure Creation: addRoUsage Error on Creation'
GO

/****** Object:  StoredProcedure [addTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addTransition];
GO
	
CREATE PROCEDURE [dbo].[addTransition]

(
	@FromID int,
	@ToID int,
	@RangeID int,
	@IsRange int,
	@TranType int,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@newTransitionID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Transitions]
	(
		[FromID],
		[ToID],
		[RangeID],
		[IsRange],
		[TranType],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@FromID,
		@ToID,
		@RangeID,
		@IsRange,
		@TranType,
		@Config,
		@DTS,
		@UserID
	)
	SELECT @newTransitionID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Transitions] WHERE [TransitionID]=@newTransitionID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addTransition Succeeded'
ELSE PRINT 'Procedure Creation: addTransition Error on Creation'
GO

/****** Object:  StoredProcedure [addUser] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addUser];
GO
	
CREATE PROCEDURE [dbo].[addUser]

(
	@UserID nvarchar(100),
	@FirstName nvarchar(50)=null,
	@MiddleName nvarchar(50)=null,
	@LastName nvarchar(50)=null,
	@Suffix nvarchar(10)=null,
	@CourtesyTitle nvarchar(10)=null,
	@PhoneNumber nvarchar(30)=null,
	@CFGName nvarchar(8)=null,
	@UserLogin nvarchar(10)=null,
	@UserName nvarchar(32)=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@newUID int output,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [Users]
	(
		[UserID],
		[FirstName],
		[MiddleName],
		[LastName],
		[Suffix],
		[CourtesyTitle],
		[PhoneNumber],
		[CFGName],
		[UserLogin],
		[UserName],
		[Config],
		[DTS],
		[UsrID]
	)
	VALUES
	(
		@UserID,
		@FirstName,
		@MiddleName,
		@LastName,
		@Suffix,
		@CourtesyTitle,
		@PhoneNumber,
		@CFGName,
		@UserLogin,
		@UserName,
		@Config,
		@DTS,
		@UsrID
	)
	SELECT @newUID= SCOPE_IDENTITY()
	SELECT 		@newLastChanged=[LastChanged]
		FROM [Users] WHERE [UID]=@newUID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addUser Succeeded'
ELSE PRINT 'Procedure Creation: addUser Error on Creation'
GO

/****** Object:  StoredProcedure [addZContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addZContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addZContent];
GO
	
CREATE PROCEDURE [dbo].[addZContent]

(
	@ContentID int,
	@OldStepSequence nvarchar(32),
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [ZContents]
	(
		[ContentID],
		[OldStepSequence]
	)
	VALUES
	(
		@ContentID,
		@OldStepSequence
	)

	SELECT 		@newLastChanged=[LastChanged]
		FROM [ZContents] WHERE [ContentID]=@ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addZContent Succeeded'
ELSE PRINT 'Procedure Creation: addZContent Error on Creation'
GO

/****** Object:  StoredProcedure [addZTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[addZTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [addZTransition];
GO
	
CREATE PROCEDURE [dbo].[addZTransition]

(
	@TransitionID int,
	@Oldto nvarchar(32),
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	INSERT INTO [ZTransitions]
	(
		[TransitionID],
		[oldto]
	)
	VALUES
	(
		@TransitionID,
		@Oldto
	)

	SELECT 		@newLastChanged=[LastChanged]
		FROM [ZTransitions] WHERE [TransitionID]=@TransitionID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: addZTransition Succeeded'
ELSE PRINT 'Procedure Creation: addZTransition Error on Creation'
GO

/****** Object:  StoredProcedure [CopyItemAndChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[CopyItemAndChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [CopyItemAndChildren];
GO
	
CREATE PROCEDURE [dbo].[CopyItemAndChildren]
(
	@StartItemID INT,
	@DestFormatID INT,
	@UserID NVARCHAR(100),
	@NewStartItemID int output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block

--+-----------------------------------------------------------------+
--¦ BEGIN TRANSACTION to make these changes temporary               ¦
--+-----------------------------------------------------------------+
	BEGIN TRANSACTION

DECLARE @Children AS TABLE
(
	ItemID INT PRIMARY KEY,
	NewItemID INT,
	ContentID INT,
	NewContentID INT,
	FormatID INT,
	NewFormatID INT
)
DECLARE @NewDocuments AS TABLE
(
	DocID INT PRIMARY KEY,
	NewDocID INT
)
-- Locals
DECLARE @DTS DATETIME -- DTS of all New Items
SET @DTS = GETDATE() -- Get the current Date and Time
-- Get a list of all of the Items to be copied based upon StartItemID and EndItemID
-- If the StartItemID = EndItemID then it is a single item and it's children
INSERT INTO @Children SELECT ItemID,ItemID,ContentID,ContentID,FormatID,FormatID FROM vefn_ChildItemsRange(@StartItemID,@StartItemID,null)
-- <<< Copy Contents >>>
-- Create new content rows to match the existing rows.  Set the type to the Current ContentID temporarily
-- so that the new content rows can be associated with the existing content rows.
INSERT INTO Contents
  ([Number],[Text],[Type],[FormatID],[Config],[DTS],[UserID])
	select [Number],[Text],[ContentID],[FormatID],[Config],@DTS,@UserID
 from Contents where ContentID in(Select ContentID from @Children)
-- Update the @Children with the NewConentIDs
UPDATE NN set NN.NewContentID = CC.ContentID
From Contents CC
Join @Children NN on NN.ContentID = CC.Type AND CC.DTS = @DTS and CC.UserID = @UserID
-- Reset the Type column in the Contents table with the Type column from the original Records.
UPDATE CC set CC.Type = CC2.Type
From Contents CC
Join @Children NN on NN.NewContentID = CC.ContentID
Join Contents CC2 on NN.ContentID = CC2.ContentID
-- Contents are done
	-- SELECT * From Contents where DTS = @DTS and UserID = @UserID
-- <<< Copy Grids >>>
INSERT INTO [Grids]([ContentID],[Data],[Config],[DTS],[UserID])
	SELECT NN.[NewContentID],[Data],[Config],@DTS,@UserID
		FROM [Grids] GG Join @Children NN on GG.ContentID = NN.ContentID
-- <<< Copy Images >>>
INSERT INTO [Images]([ContentID],[ImageType],[FileName],[Data],[Config],[DTS],[UserID])
	SELECT NN.[NewContentID],[ImageType],[FileName],[Data],[Config],@DTS,@UserID
		FROM [Images] II Join @Children NN on II.ContentID = NN.ContentID
-- Create new item rows based upon the current item rows and the @Children table, with the NewContentIDs
INSERT INTO [Items] ([PreviousID],[ContentID],[DTS],[UserID])
     SELECT II.[PreviousID], -- Leave the PreviousID as is for now
			NN.NewContentID, @DTS, @UserID
			from @Children NN
			join Items II on II.ContentID = NN.ContentID
-- Update the @Children with the NewItemIDs
UPDATE NN set NN.NewItemID = II.ItemID
From Items II
Join @Children NN on NN.NewContentID = II.ContentID AND II.DTS = @DTS and II.UserID = @UserID
DECLARE @NewItemID int
SELECT @NewItemID = NewItemID
	FROM @Children
	WHERE ItemID = @StartItemID
UPDATE NN SET NN.[NewFormatID] = CC.[FormatID]
	FROM @Children NN
	Join vefn_ChildItemsRange(@NewItemID,@NewItemID,@DestFormatID) CC
	ON NN.NewItemID = CC.ItemID
-- The @Children table is now complete
	--SELECT * From @Children
-- Update the PreviousID in the new Item rows, to the new ItemIDs based upon the old ItemIDs
Update II Set II.[PreviousID] = NN.NewItemID
from Items II
Join @Children NN on NN.ItemID = II.PreviousID AND II.DTS = @DTS and II.UserID = @UserID
-- Get the new ItemIDs based upon the old ItemIDs
SELECT @NewStartItemID = NewItemID from @Children where ItemID = @StartItemID
--SELECT @NewEndItemID = NewItemID from @Children where ItemID = @EndItemID
-- Set the PreviousID for the starting Item to null temporarily.
-- This will be adjusted based upon where the step is inserted.
Update Items Set PreviousID = null where ItemID = @NewStartItemID
-- Items are done
	--SELECT * From Items where DTS = @DTS and UserID = @UserID
-- <<< Copy Parts >>>
INSERT INTO [Parts] ([ContentID],[FromType],[ItemID],[DTS],[UserID])
Select NNF.NewContentID,[FromType],NNT.NewItemID, @DTS, @UserID from Parts PP
JOIN @Children NNF on PP.ContentID = NNF.ContentID
JOIN @Children NNT on PP.ItemID = NNT.ItemID
-- Parts are done
	-- SELECT * From Parts where DTS = @DTS and UserID = @UserID
-- <<< Copy Annotations >>>
INSERT INTO [Annotations] ([ItemID],[TypeID],[RtfText],[SearchText],[Config],[DTS],[UserID])
     Select NewItemID, TypeID, RtfText, SearchText, Config, @DTS, @UserID
			from Annotations AA Join @Children NN on AA.ItemID = NN.ItemID
-- Annotations are done
	-- SELECT * From Annotations where DTS = @DTS and UserID = @UserID
-- <<< Copy Documents and Entries>>>
-- logic to create Entries for Library Documents
INSERT INTO [Entries] ([ContentID],[DocID],[DTS],[UserID])
	SELECT NN.[NewContentID],EE.[DocID],@DTS,@UserID
  FROM [Entries] EE JOIN @Children NN on NN.ContentID = EE.ContentID
	JOIN [Documents] DD on EE.[DocID] = DD.[DocID] and Isnull(LibTitle,'') <> ''
-- Logic to create new documents for any documents used that do not have libtitles
INSERT INTO [Documents] ([LibTitle],[DocContent],[DocAscii],[Config],[DTS],[UserID],[FileExtension])
  OUTPUT CAST(INSERTED.[LibTitle] as INT),INSERTED.[DocID] INTO @NewDocuments
	SELECT str(DD.[DocID]),[DocContent],[DocAscii],[Config],@DTS,@UserID,[FileExtension]
  FROM [Entries] EE JOIN @Children NN on NN.ContentID = EE.ContentID
	JOIN [Documents] DD on EE.[DocID] = DD.[DocID] and Isnull(LibTitle,'') = ''
UPDATE DD SET LibTitle = ''
	FROM Documents DD JOIN @NewDocuments ND on DD.[DocID] = ND.[NewDocID]
	where DTS = @DTS and UserID = @UserID
-- Documents are Done
	-- SELECT * From Documents where DTS = @DTS and UserID = @UserID
-- Logic to create entries for these newly created documents
INSERT INTO [Entries] ([ContentID],[DocID],[DTS],[UserID])
	SELECT NN.[NewContentID],ND.[NewDocID],@DTS,@UserID
  FROM [Entries] EE JOIN @Children NN on NN.ContentID = EE.ContentID
	JOIN @NewDocuments ND on EE.[DocID] = ND.[DocID]
-- Logic to Create DROUsages for these newly created documents
INSERT INTO [VEPROMS].[dbo].[DROUsages] ([DocID],[ROID],[Config],[DTS],[UserID],[RODbID])
 	SELECT ND.[NewDocID],[ROID],[Config],@DTS,@UserID,[RODbID]
  FROM [DROUsages] RR
	JOIN @NewDocuments ND on RR.[DocID] = ND.[DocID]

-- Entries are done
	-- SELECT * From Entries EE JOIN Documents DD on ee.DocID = DD.DocID where EE.DTS = @DTS and EE.UserID = @UserID
-- <<< Copy RoUsages >>>
INSERT INTO [VEPROMS].[dbo].[RoUsages] ([ContentID],[ROID],[Config],[DTS],[UserID],[RODbID])
	SELECT NN.[NewContentID],CAST([ROUsageID] as nvarchar(16)),[Config],@DTS,@UserID,[RODbID]
		FROM [RoUsages] RR Join @Children NN on RR.ContentID = NN.ContentID
-- Update content records for newly copied records to use correct RO usage ids in the RO tags
DECLARE @RowsAffected int
SET @RowsAffected=1
WHILE @RowsAffected > 0
BEGIN
	UPDATE CC SET [TEXT] = C2.NewText
	FROM CONTENTS CC
	JOIN (SELECT C1.ContentID, .dbo.vefn_FixROText(C1.Text, CAST([ROID] as int), [ROUsageID]) NewText
	FROM CONTENTS C1
	JOIN @Children NN on C1.ContentID = NN.NewContentID
	JOIN RoUsages RO on NN.NewContentID = RO.ContentID) C2 ON CC.ContentID = C2.ContentID
	WHERE [TEXT] <> C2.NewText
	SET @RowsAffected = @@RowCount
END
-- Update grid records for newly copied records to use correct RO usage ids in the RO tags
SET @RowsAffected=1
WHILE @RowsAffected > 0
BEGIN
	UPDATE GG SET [Data] = G2.NewData
	FROM GRIDS GG
	JOIN (SELECT G1.ContentID, .dbo.vefn_FixROData(G1.Data, CAST([ROID] as int), [ROUsageID]) NewData
	FROM GRIDS G1
	JOIN @Children NN on G1.ContentID = NN.NewContentID
	JOIN RoUsages RO on NN.NewContentID = RO.ContentID) G2 ON GG.ContentID = G2.ContentID
	WHERE Cast([Data] as varchar(max)) <> cast(G2.NewData as varchar(max))
	SET @RowsAffected = @@RowCount
END
UPDATE RON SET [ROID] = ROO.[ROID]
	FROM RoUsages RON
	JOIN @Children NN on RON.ContentID = NN.NewContentID
	JOIN RoUsages ROO on CAST(RON.ROID as int) = ROO.RoUsageID

-- RoUsages are done
	-- SELECT * From RoUsages where DTS = @DTS and UserID = @UserID

-- <<< Copy Transtions >>>
-- Note that the inserted record has the 'TranType' field set to old transitionid.  This is done
-- so that the next step can replace the old transitionid with the new transitionid in the
-- content record's transition tokens.  The TranType gets reset after the content records are
-- updated.
-- Also note that the 'toid/rangeid' may need converted to newly copied ids or may not.  If it's
-- not a range, then it always is converted to new, if there is a new.  If it's a range, both
-- the toid & the rangeid must be new in order for the conversion to be correct.  You cannot
-- have part of the range pointing to the new and part of the range pointing to the original
-- locations.

INSERT INTO .[dbo].[Transitions] ([FromID],[ToID],[RangeID],[IsRange],[TranType],[Config],[DTS],[UserID])
	SELECT NNF.[NewContentID],
		-- if both toid & range are null, use the original toid & rangeid
		CASE WHEN NNT.[NewItemID] is null or NNR.[NewItemID] is null THEN [ToID] ELSE NNT.[NewItemID] END,
		CASE WHEN NNT.[NewItemID] is null or NNR.[NewItemID] is null THEN [RangeID] ELSE NNR.[NewItemID] END,
		[IsRange],[TransitionID],[Config],@DTS,@UserID
	FROM .[dbo].[Transitions] TT
	JOIN @Children NNF on TT.[FromID] = NNF.[ContentID]
	LEFT JOIN @Children NNT on TT.[ToID] = NNT.[ItemID]
	LEFT JOIN @Children NNR on TT.[RangeID] = NNR.[ItemID]
-- -- Update content records for newly copied records to use correct TransitionIDs in the Transition tags
SET @RowsAffected=1
WHILE @RowsAffected > 0
BEGIN
UPDATE CC SET [TEXT] = C2.NewText
	FROM CONTENTS CC
	JOIN (SELECT C1.ContentID, .dbo.vefn_FixTransitionTextForCopy(C1.Text, TRO.TransitionID, TRO.TranType,  TRO.[ToID], TRO.[RangeID],TR.[TransitionID], TR.[ToID], TR.[RangeID], .dbo.vefn_GetNewTranType(NN.FormatID, NN.NewFormatID, TRO.TranType)) NewText
	FROM CONTENTS C1
	JOIN @Children NN on C1.ContentID = NN.NewContentID
	JOIN Transitions TR on NN.NewContentID = TR.FromID
	JOIN Transitions TRO on TR.TranType = TRO.TransitionID) C2 ON CC.ContentID = C2.ContentID
	WHERE [TEXT] <> C2.NewText
	SET @RowsAffected = @@RowCount
END
-- -- Update grid records for newly copied records to use correct TransitionIDs in the Transition tags
SET @RowsAffected=1
WHILE @RowsAffected > 0
BEGIN
UPDATE GG SET [DATA] = G2.NewData
	FROM GRIDS GG
	JOIN (SELECT G1.ContentID, .dbo.vefn_FixTransitionDataForCopy(G1.Data, TRO.TransitionID, TRO.TranType,  TRO.[ToID], TRO.[RangeID],TR.[TransitionID], TR.[ToID], TR.[RangeID], .dbo.vefn_GetNewTranType(NN.FormatID, NN.NewFormatID, TRO.TranType)) NewData
	FROM GRIDS G1
	JOIN @Children NN on G1.ContentID = NN.NewContentID
	JOIN Transitions TR on NN.NewContentID = TR.FromID
	JOIN Transitions TRO on TR.TranType = TRO.TransitionID) G2 ON GG.ContentID = G2.ContentID
	WHERE Cast([DATA] as varchar(max)) <> CAST(G2.NewData as varchar(max))
	SET @RowsAffected = @@RowCount
END
-- Add 'Verification Required' AnnotationType
	DECLARE @typeID int
	SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
	IF(@typeID IS NULL)
	BEGIN
		INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
		SELECT @typeID = SCOPE_IDENTITY()
	END
	-- Add "Verification Required" Annotation for each Transition whose transition format changes
INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT NN.NewItemID, @typeID,'Verify Transition Format',@UserID
			FROM Transitions TR
			JOIN @Children NN on TR.FromID = NN.NewContentID
			JOIN Transitions TRO on TR.TranType = TRO.TransitionID
			WHERE .dbo.vefn_CompareTranFormat(NN.FormatID, NN.NewFormatID, TRO.TranType) <> 0
UPDATE TR SET TR.[TranType] = .dbo.vefn_GetNewTranType(NN.FormatID, NN.NewFormatID, TRO.TranType)
	FROM Transitions TR
	JOIN @Children NN on TR.FromID = NN.NewContentID
	JOIN Transitions TRO on TR.TranType = TRO.TransitionID
-- Transitions are done
	-- SELECT * From Transitions where DTS = @DTS and UserID = @UserID

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH

--USE MASTER
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: CopyItemAndChildren Succeeded'
ELSE PRINT 'Procedure Creation: CopyItemAndChildren Error on Creation'
GO

/****** Object:  StoredProcedure [deleteAllPdfs] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteAllPdfs]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteAllPdfs];
GO
	
CREATE PROCEDURE [dbo].[deleteAllPdfs]

(
	@DocID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Pdfs]
		WHERE [DocID] = @DocID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteAllPdfs Succeeded'
ELSE PRINT 'Procedure Creation: deleteAllPdfs Error on Creation'
GO

/****** Object:  StoredProcedure [deleteAnnotation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteAnnotation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteAnnotation];
GO
	
CREATE PROCEDURE [dbo].[deleteAnnotation]

(
	@AnnotationID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Annotations]
		WHERE [AnnotationID] = @AnnotationID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteAnnotation Succeeded'
ELSE PRINT 'Procedure Creation: deleteAnnotation Error on Creation'
GO

/****** Object:  StoredProcedure [deleteAnnotationType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteAnnotationType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteAnnotationType];
GO
	
CREATE PROCEDURE [dbo].[deleteAnnotationType]

(
	@TypeID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Annotations]
		WHERE [TypeID]=@TypeID
	DELETE [AnnotationTypes]
		WHERE [TypeID] = @TypeID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteAnnotationType Succeeded'
ELSE PRINT 'Procedure Creation: deleteAnnotationType Error on Creation'
GO

/****** Object:  StoredProcedure [deleteAssignment] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteAssignment]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteAssignment];
GO
	
CREATE PROCEDURE [dbo].[deleteAssignment]

(
	@AID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Assignments]
		WHERE [AID] = @AID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteAssignment Succeeded'
ELSE PRINT 'Procedure Creation: deleteAssignment Error on Creation'
GO

/****** Object:  StoredProcedure [deleteAssociation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteAssociation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteAssociation];
GO
	
CREATE PROCEDURE [dbo].[deleteAssociation]

(
	@AssociationID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Associations]
		WHERE [AssociationID] = @AssociationID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteAssociation Succeeded'
ELSE PRINT 'Procedure Creation: deleteAssociation Error on Creation'
GO

/****** Object:  StoredProcedure [deleteConnection] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteConnection]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteConnection];
GO
	
CREATE PROCEDURE [dbo].[deleteConnection]

(
	@DBID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Folders]
		WHERE [DBID]=@DBID
	DELETE [Connections]
		WHERE [DBID] = @DBID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteConnection Succeeded'
ELSE PRINT 'Procedure Creation: deleteConnection Error on Creation'
GO

/****** Object:  StoredProcedure [deleteContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteContent];
GO
	
CREATE PROCEDURE [dbo].[deleteContent]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Details]
		WHERE [ContentID]=@ContentID
	DELETE [Entries]
		WHERE [ContentID]=@ContentID
	DELETE [Grids]
		WHERE [ContentID]=@ContentID
	DELETE [Images]
		WHERE [ContentID]=@ContentID
	DELETE [Items]
		WHERE [ContentID]=@ContentID
	DELETE [Parts]
		WHERE [ContentID]=@ContentID
	DELETE [RoUsages]
		WHERE [ContentID]=@ContentID
	DELETE [Transitions]
		WHERE [FromID]=@ContentID
	DELETE [ZContents]
		WHERE [ContentID]=@ContentID
	DELETE [Contents]
		WHERE [ContentID] = @ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteContent Succeeded'
ELSE PRINT 'Procedure Creation: deleteContent Error on Creation'
GO

/****** Object:  StoredProcedure [deleteDetail] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteDetail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteDetail];
GO
	
CREATE PROCEDURE [dbo].[deleteDetail]

(
	@DetailID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Details]
		WHERE [DetailID] = @DetailID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteDetail Succeeded'
ELSE PRINT 'Procedure Creation: deleteDetail Error on Creation'
GO

/****** Object:  StoredProcedure [deleteDocument] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteDocument]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteDocument];
GO
	
CREATE PROCEDURE [dbo].[deleteDocument]

(
	@DocID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [DROUsages]
		WHERE [DocID]=@DocID
	DELETE [Entries]
		WHERE [DocID]=@DocID
	DELETE [Pdfs]
		WHERE [DocID]=@DocID
	DELETE [Documents]
		WHERE [DocID] = @DocID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteDocument Succeeded'
ELSE PRINT 'Procedure Creation: deleteDocument Error on Creation'
GO

/****** Object:  StoredProcedure [deleteDocVersion] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteDocVersion]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteDocVersion];
GO
	
CREATE PROCEDURE [dbo].[deleteDocVersion]

(
	@VersionID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Associations]
		WHERE [VersionID]=@VersionID
	DELETE [DocVersions]
		WHERE [VersionID] = @VersionID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteDocVersion Succeeded'
ELSE PRINT 'Procedure Creation: deleteDocVersion Error on Creation'
GO

/****** Object:  StoredProcedure [deleteDROUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteDROUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteDROUsage];
GO
	
CREATE PROCEDURE [dbo].[deleteDROUsage]

(
	@DROUsageID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [DROUsages]
		WHERE [DROUsageID] = @DROUsageID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteDROUsage Succeeded'
ELSE PRINT 'Procedure Creation: deleteDROUsage Error on Creation'
GO

/****** Object:  StoredProcedure [deleteEntry] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteEntry]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteEntry];
GO
	
CREATE PROCEDURE [dbo].[deleteEntry]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Entries]
		WHERE [ContentID] = @ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteEntry Succeeded'
ELSE PRINT 'Procedure Creation: deleteEntry Error on Creation'
GO

/****** Object:  StoredProcedure [deleteFigure] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteFigure]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteFigure];
GO
	
CREATE PROCEDURE [dbo].[deleteFigure]

(
	@FigureID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Figures]
		WHERE [FigureID] = @FigureID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteFigure Succeeded'
ELSE PRINT 'Procedure Creation: deleteFigure Error on Creation'
GO

/****** Object:  StoredProcedure [deleteFolder] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteFolder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteFolder];
GO
	
CREATE PROCEDURE [dbo].[deleteFolder]

(
	@FolderID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Assignments]
		WHERE [FolderID]=@FolderID
	DELETE [DocVersions]
		WHERE [FolderID]=@FolderID
	DELETE [Folders]
		WHERE [FolderID] = @FolderID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteFolder Succeeded'
ELSE PRINT 'Procedure Creation: deleteFolder Error on Creation'
GO

/****** Object:  StoredProcedure [deleteFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteFormat]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteFormat];
GO
	
CREATE PROCEDURE [dbo].[deleteFormat]

(
	@FormatID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Contents]
		WHERE [FormatID]=@FormatID
	DELETE [DocVersions]
		WHERE [FormatID]=@FormatID
	DELETE [Folders]
		WHERE [FormatID]=@FormatID
	DELETE [Formats]
		WHERE [FormatID] = @FormatID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteFormat Succeeded'
ELSE PRINT 'Procedure Creation: deleteFormat Error on Creation'
GO

/****** Object:  StoredProcedure [deleteGrid] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteGrid]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteGrid];
GO
	
CREATE PROCEDURE [dbo].[deleteGrid]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Grids]
		WHERE [ContentID] = @ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteGrid Succeeded'
ELSE PRINT 'Procedure Creation: deleteGrid Error on Creation'
GO

/****** Object:  StoredProcedure [deleteGroup] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteGroup]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteGroup];
GO
	
CREATE PROCEDURE [dbo].[deleteGroup]

(
	@GID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Assignments]
		WHERE [GID]=@GID
	DELETE [Memberships]
		WHERE [GID]=@GID
	DELETE [Groups]
		WHERE [GID] = @GID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteGroup Succeeded'
ELSE PRINT 'Procedure Creation: deleteGroup Error on Creation'
GO

/****** Object:  StoredProcedure [deleteImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteImage];
GO
	
CREATE PROCEDURE [dbo].[deleteImage]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Images]
		WHERE [ContentID] = @ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteImage Succeeded'
ELSE PRINT 'Procedure Creation: deleteImage Error on Creation'
GO

/****** Object:  StoredProcedure [deleteItem] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteItem]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteItem];
GO
	
CREATE PROCEDURE [dbo].[deleteItem]

(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Annotations]
		WHERE [ItemID]=@ItemID
	DELETE [DocVersions]
		WHERE [ItemID]=@ItemID
	DELETE [Parts]
		WHERE [ItemID]=@ItemID
	DELETE [Transitions]
		WHERE [RangeID]=@ItemID
	DELETE [Transitions]
		WHERE [ToID]=@ItemID
	DELETE [Items]
		WHERE [ItemID] = @ItemID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteItem Succeeded'
ELSE PRINT 'Procedure Creation: deleteItem Error on Creation'
GO

/****** Object:  StoredProcedure [DeleteItemAndChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DeleteItemAndChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [DeleteItemAndChildren];
GO
	
CREATE PROCEDURE [dbo].[DeleteItemAndChildren]
(
	@ItemID int,
	@UserID AS VARCHAR(100)
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
		declare @DeleteID int
		DECLARE @ContentID AS INT
		DECLARE @NextItemID AS INT
		DECLARE @PreviousItemID AS INT
		DECLARE @ExternalChildCount AS INT
		DECLARE @ExternalCount AS INT
		DECLARE @Path AS VARCHAR(MAX)
		DECLARE @Children AS TABLE
		(
			ItemID INT PRIMARY KEY,
			ContentID INT
		)
		DECLARE @ExternalTrans TABLE
		(
			[FromItemID] int,
			[TransitionID] [int] NOT NULL,
			[FromID] [int] NOT NULL,
			[ToID] [int] NOT NULL,
			[RangeID] [int] NOT NULL,
			[Config] [nvarchar](max) NULL
		)
		SET NOCOUNT ON
		SELECT @ContentID = ContentID, @PreviousItemID = PreviousID FROM Items WHERE ItemID = @ItemID
		SELECT @NextItemID = ItemID FROM Items WHERE PreviousID = @ItemID
		SELECT @ExternalCount = count(*) FROM vefn_FindExternalTransitions(@ItemID)
		SELECT @ExternalChildCount = count(*) FROM vefn_FindExternalChildTransitions(@ItemID)
		SET @Path = [dbo].[ve_GetShortPath](@ItemID)

		IF @ExternalCount > 0  AND @NextItemID is null
		BEGIN
			RAISERROR ('###Cannot Delete Item###Step %d has External Transitions and has no next step - (%s)',16,1,@ItemID,@Path)
			RETURN
		END

		IF @ExternalChildCount > 0
		BEGIN
			RAISERROR ('###Cannot Delete Item###Step %d has External Transitions to it''s children - (%s)',16,1,@ItemID,@Path)
			RETURN
		END
		--deletelog
		INSERT INTO DeleteLog (UserID) values (@UserID)
		Select @DeleteID = SCOPE_IDENTITY()
		--end deletelog
		-- Get list of Children
		INSERT INTO @Children SELECT * FROM vefn_ChildItems(@ItemID)
		-- UPDATE PreviousID in Items WHERE ItemID = @NextItemID
		UPDATE Items SET PreviousID = @PreviousItemID WHERE ItemID=@NextItemID
		-- UPDATE DocVersion
		UPDATE DocVersions SET ItemID=@NextItemID where ItemID = @ItemID
		-- UPDATE Parts
		IF @NextItemID is not NULL -- Remove Part Record
			BEGIN
				UPDATE PARTS SET ItemID = @NextItemID where ItemID=@ItemID
			END
		ELSE
			BEGIN
				DELETE FROM Parts WHERE ItemID=@ItemID
			END
		-- Get external transitions that point to the specified Item
		-- These will need to be adjusted to point to the next Item.
		INSERT INTO @ExternalTrans SELECT * FROM vefn_FindExternalTransitions(@ItemID);
		DECLARE @typeID int -- AnnotationType
		SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
		IF(@typeID IS NULL)
		BEGIN
			INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
			SELECT @typeID = SCOPE_IDENTITY()
		END
		-- Add 'Verification Required' annotions for transtions that point to different step
		INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])	
		SELECT ItemID, @typeID,'Verify Transition Destination',@UserID
			FROM Items where ItemID in (SELECT FromItemID FROM @ExternalTrans)
		-- Update content records for the transitions
		Update CC
			Set Text = DBO.vefn_FixTransitionText(Text,TT.TransitionID,TT.TranType,TT.ToID,TT.RangeID,@ItemID,@NextItemID)
		From CONTENTS CC
			JOIN Transitions TT ON TT.FromID = CC.ContentID
			WHERE TransitionID in(Select TransitionID from @ExternalTrans)
		-- Update transitions that point to @ItemID to Point to @NextItemID
		UPDATE TRANSITIONS
			SET ToID = case when ToID = @ItemID then @NextItemID else ToID END,
			RangeID = case when RangeID = @ItemID then @NextItemID else RangeID END
			WHERE TransitionID in(Select TransitionID from @ExternalTrans)
		-- Delete Annotations for @ItemID and children
		DELETE from Annotations where ItemID in(Select ItemID from @Children)
		-- Delete Details associated with @ContentID and children
		DELETE from Details where ContentID in(Select ContentID from @Children)
		-- Delete Grids associated with @ContentID and children
		DELETE from Grids where ContentID in(Select ContentID from @Children)
		-- Delete Images associated with @ContentID and children
		DELETE from Images where ContentID in(Select ContentID from @Children)
		-- Delete Entries associated with @ContentID and children
		DELETE from Entries where ContentID in(Select ContentID from @Children)
		-- Delete ROUsages associated with @ContentID and children
		DELETE from RoUsages where ContentID in(Select ContentID from @Children)
		-- Delete ZTransitions records associated with @ContentID and children
		DELETE FROM ZTransitions where TransitionID
			in(SELECT TransitionID from Transitions where FromID in(SELECT ContentID FROM @Children) or FromID = @ContentID)
		-- Delete Transitions associated with @ContentID and children
		DELETE FROM Transitions where FromID in(SELECT ContentID FROM @Children) or FromID = @ContentID
		-- Delete Parts associated with @ContentID and children
		DELETE from Parts where ContentID in(Select ContentID from @Children)
		-- Delete ZContents associated with @ContentID and children
		DELETE from ZContents where ContentID in(Select ContentID from @Children)
		-- Disconnect Items from Each Other
		DELETE from Items where ItemID in(Select ItemID from @Children) and PreviousID Is Not Null
		-- Disconnect Items to be deleted from each other
		Update Items set PreviousID = null where ItemID in (Select ItemID from @Children) and PreviousID Is Not Null
		-- Delete Item Records
		DELETE from Items where ItemID in(Select ItemID from @Children)
		-- DELETE Contents
		DELETE from Contents where ContentID in(Select ContentID from @Children)
		--purge deletelog
		DELETE from DeleteLog where DeleteID = @DeleteID
		--end purge deletelog
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: DeleteItemAndChildren Succeeded'
ELSE PRINT 'Procedure Creation: DeleteItemAndChildren Error on Creation'
GO

/****** Object:  StoredProcedure [DeleteItemAndChildrenTest] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DeleteItemAndChildrenTest]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [DeleteItemAndChildrenTest];
GO
	
CREATE PROCEDURE [dbo].[DeleteItemAndChildrenTest]
(
	@ItemID int,
	@UserID AS VARCHAR(100)
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
		DECLARE @ContentID AS INT
		DECLARE @NextItemID AS INT
		DECLARE @PreviousItemID AS INT
		DECLARE @ExternalChildCount AS INT
		DECLARE @ExternalCount AS INT
		DECLARE @Path AS VARCHAR(MAX)
		DECLARE @Children AS TABLE
		(
			ItemID INT PRIMARY KEY,
			ContentID INT
		)
		DECLARE @ExternalTrans TABLE
		(
			[FromItemID] int,
			[TransitionID] [int] NOT NULL,
			[FromID] [int] NOT NULL,
			[ToID] [int] NOT NULL,
			[RangeID] [int] NOT NULL,
			[Config] [nvarchar](max) NULL
		)
		SET NOCOUNT ON
		SELECT @ContentID = ContentID, @PreviousItemID = PreviousID FROM Items WHERE ItemID = @ItemID
		SELECT @NextItemID = ItemID FROM Items WHERE PreviousID = @ItemID
		SELECT @ExternalCount = count(*) FROM vefn_FindExternalTransitions(@ItemID)
		SELECT @ExternalChildCount = count(*) FROM vefn_FindExternalChildTransitions(@ItemID)
		SET @Path = [dbo].[ve_GetShortPath](@ItemID)

		IF @ExternalCount > 0  AND @NextItemID is null
		BEGIN
			PRINT '--->Cannot delete step ' + @Path + '.' + char(13) + '<===> It has External Transitions and has no next step'
			SELECT dbo.ve_GetShortPath(FromItemID) FromPath,
				dbo.ve_GetShortPath(ToID) ToPath FROM vefn_FindExternalTransitions(@ItemID)
				WHERE NOT EXISTS (SELECT * FROM Items WHERE PreviousID = @ItemID)
			RETURN
		END

		IF @ExternalChildCount > 0
		BEGIN
			PRINT '---> Cannot delete step ' + @Path + '.' + char(13) + '<===> It has External Transitions to it''s children'
			SELECT dbo.ve_GetShortPath(FromItemID) FromPath,
				dbo.ve_GetShortPath(ToID) ToPath FROM vefn_FindExternalChildTransitions(@ItemID)
			RETURN
		END

		PRINT '@Path               = ''' + @Path + ''''
		PRINT '@ItemID             = ' + cast(@ItemID as varchar(10))
		PRINT '@ContentID          = ' + isnull(cast(@ContentID as varchar(10)),'{NULL}')
		PRINT '@NextItemID         = ' + isnull(cast(@NextItemID as varchar(10)),'{NULL}')
		PRINT '@PreviousItemID     = ' + isnull(cast(@PreviousItemID as varchar(10)),'{NULL}')
		PRINT '@ExternalCount      = ' + isnull(cast(@ExternalCount as varchar(10)),'{NULL}')
		PRINT '@ExternalChildCount = ' + isnull(cast(@ExternalChildCount as varchar(10)),'{NULL}')

		PRINT '---' + char(13) +'Preparing to delete step ' + @Path+ char(13) + '---'
		-- Get list of Children
		INSERT INTO @Children SELECT * FROM vefn_ChildItems(@ItemID)
		PRINT 'Children'
		SELECT ItemID, [dbo].[ve_GetShortPath](ItemID) ItemPath, ContentID,[dbo].[ve_GetShortPathFromContentID](ContentID) ContentPath FROM @Children

		-- UPDATE PreviousID in Items WHERE ItemID = @NextItemID
		PRINT 'UPDATE Items Next'
		SELECT ItemID, [dbo].[ve_GetShortPath](@NextItemID) PathOfNextItem,[dbo].[ve_GetShortPath](PreviousID) PathOfDeletedItem, [dbo].[ve_GetShortPath](@PreviousItemID) NewPreviousPath
		 FROM Items WHERE ItemID=@NextItemID
		-- UPDATE DocVersion
		PRINT 'UPDATE DocVersions ItemID'
		SELECT [dbo].[ve_GetShortPath](ItemID) MyPath, [dbo].[ve_GetShortPath](@NextItemID) NewPath
		 FROM DocVersions WHERE ItemID=@ItemID
		SELECT VersionID, [dbo].[ve_GetShortPath](@NextItemID) NewPath
		 FROM DocVersions WHERE ItemID=@ItemID
		-- UPDATE Parts
		IF @NextItemID is not NULL -- Remove Part Record
			BEGIN
				PRINT 'UPDATE Parts'
				SELECT ItemID,@NextItemID,[dbo].[ve_GetShortPath](ItemID) ItemPath, [dbo].[ve_GetShortPath](@NextItemID) NewItemPath
					FROM Parts WHERE ItemID=@ItemID
			END
		ELSE
			BEGIN
				PRINT 'DELETE Parts'
				SELECT ContentID,FromType,[dbo].[ve_GetShortPath](ItemID) ItemPath FROM Parts WHERE ItemID=@ItemID
			END
		-- Get external transitions that point to the specified Item
		-- These will need to be adjusted to point to the next Item.
		INSERT INTO @ExternalTrans SELECT * FROM vefn_FindExternalTransitions(@ItemID);
		DECLARE @typeID int -- AnnotationType
		SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
		IF(@typeID IS NULL)
		BEGIN
			PRINT 'ADD Verification Required'
			INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
			SELECT @typeID = SCOPE_IDENTITY()
		END
		-- Get list of External Transitions

		PRINT 'UPDATE Transitions - ADD Annotations'
		SELECT [dbo].[ve_GetShortPathFromContentID](FromID)FromPath
		,[dbo].[ve_GetShortPath](ToID) ToPath
		,case when ToID = @ItemID then [dbo].[ve_GetShortPath](@NextItemID) else [dbo].[ve_GetShortPath](ToID) END NewToPath
		,[dbo].[ve_GetShortPath](RangeID) RangePath
		,case when RangeID = @ItemID then [dbo].[ve_GetShortPath](@NextItemID) else [dbo].[ve_GetShortPath](RangeID) END NewRangePath
		 FROM Transitions
		WHERE TransitionID IN(Select TransitionID from @ExternalTrans)
		-- Delete Annotations for @ItemID and children
		PRINT  'DELETE Annotations'
		SELECT AnnotationID, [dbo].[ve_GetShortPath](ItemID) ItemPath from Annotations where ItemID in(Select ItemID from @Children)
		-- Delete Details associated with @ContentID and children
		PRINT 'DELETE Details'
		SELECT [dbo].[ve_GetShortPathFromContentID](ContentID) ContentPath from Details where ContentID in(Select ContentID from @Children)
		-- Delete Entries associated with @ContentID and children
		PRINT 'DELETE Entries'
		SELECT ContentID, [dbo].[ve_GetShortPathFromContentID](ContentID) ContentPath from Entries where ContentID in(Select ContentID from @Children)
		-- Delete ROUsages associated with @ContentID and children
		PRINT 'DELETE ROUsages'
		SELECT ROUsageID, [dbo].[ve_GetShortPathFromContentID](ContentID) ContentPath from RoUsages where ContentID in(Select ContentID from @Children)
		-- Delete Transitions associated with @ContentID and children
		PRINT 'DELETE Transitions'
		SELECT TransitionID, [dbo].[ve_GetShortPathFromContentID](FromID)FromPath ,[dbo].[ve_GetShortPath](ToID) ToPath
		,[dbo].[ve_GetShortPath](RangeID) RangePath FROM Transitions where FromID in(SELECT ContentID FROM @Children) or FromID = @ContentID
		-- Delete Parts associated with @ContentID and children
		PRINT 'DELETE Parts'
		SELECT ContentID, FromType,[dbo].[ve_GetShortPathFromContentID](ContentID) ContentPath from Parts where ContentID in(Select ContentID from @Children)
		-- Delete ZContents associated with @ContentID and children
		PRINT 'DELETE XContents'
		SELECT ContentID,[dbo].[ve_GetShortPathFromContentID](ContentID) ContentPath from ZContents where ContentID in(Select ContentID from @Children)
		-- Disconnect Items from Each Other
		PRINT 'DISCONNECT Items from each other'
		SELECT ItemID, [dbo].[ve_GetShortPath](ItemID) ItemPath, [dbo].[ve_GetShortPath](PreviousID) PreviousPath from Items where ItemID in(Select ItemID from @Children) and PreviousID Is Not Null
		-- Delete Item Records
		PRINT 'DELETE Items'
		SELECT ItemID, [dbo].[ve_GetShortPath](ItemID) ItemPath from Items where ItemID in(Select ItemID from @Children)
		-- DELETE Contents
		PRINT 'DELETE Contents'
		SELECT ContentID, [dbo].[ve_GetShortPathFromContentID](ContentID) ContentPath from Contents where ContentID in(Select ContentID from @Children)
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: DeleteItemAndChildrenTest Succeeded'
ELSE PRINT 'Procedure Creation: DeleteItemAndChildrenTest Error on Creation'
GO

/****** Object:  StoredProcedure [deleteMembership] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteMembership]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteMembership];
GO
	
CREATE PROCEDURE [dbo].[deleteMembership]

(
	@UGID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Memberships]
		WHERE [UGID] = @UGID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteMembership Succeeded'
ELSE PRINT 'Procedure Creation: deleteMembership Error on Creation'
GO

/****** Object:  StoredProcedure [deletePart] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deletePart]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deletePart];
GO
	
CREATE PROCEDURE [dbo].[deletePart]

(
	@ContentID int,
	@FromType int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Parts]
		WHERE [ContentID] = @ContentID AND [FromType] = @FromType
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deletePart Succeeded'
ELSE PRINT 'Procedure Creation: deletePart Error on Creation'
GO

/****** Object:  StoredProcedure [deletePdf] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deletePdf]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deletePdf];
GO
	
CREATE PROCEDURE [dbo].[deletePdf]

(
	@DocID int,
	@DebugStatus int,
	@TopRow int,
	@PageLength int,
	@LeftMargin int,
	@PageWidth int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Pdfs]
		WHERE [DocID] = @DocID AND [DebugStatus] = @DebugStatus AND [TopRow] = @TopRow AND [PageLength] = @PageLength AND [LeftMargin] = @LeftMargin AND [PageWidth] = @PageWidth
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deletePdf Succeeded'
ELSE PRINT 'Procedure Creation: deletePdf Error on Creation'
GO

/****** Object:  StoredProcedure [deletePermission] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deletePermission]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deletePermission];
GO
	
CREATE PROCEDURE [dbo].[deletePermission]

(
	@PID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Permissions]
		WHERE [PID] = @PID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deletePermission Succeeded'
ELSE PRINT 'Procedure Creation: deletePermission Error on Creation'
GO

/****** Object:  StoredProcedure [deleteRODb] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteRODb]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteRODb];
GO
	
CREATE PROCEDURE [dbo].[deleteRODb]

(
	@RODbID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [DROUsages]
		WHERE [RODbID]=@RODbID
	DELETE [ROFsts]
		WHERE [RODbID]=@RODbID
	DELETE [ROImages]
		WHERE [RODbID]=@RODbID
	DELETE [RoUsages]
		WHERE [RODbID]=@RODbID
	DELETE [RODbs]
		WHERE [RODbID] = @RODbID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteRODb Succeeded'
ELSE PRINT 'Procedure Creation: deleteRODb Error on Creation'
GO

/****** Object:  StoredProcedure [deleteROFst] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteROFst]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteROFst];
GO
	
CREATE PROCEDURE [dbo].[deleteROFst]

(
	@ROFstID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Associations]
		WHERE [ROFstID]=@ROFstID
	DELETE [Figures]
		WHERE [ROFstID]=@ROFstID
	DELETE [ROFsts]
		WHERE [ROFstID] = @ROFstID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteROFst Succeeded'
ELSE PRINT 'Procedure Creation: deleteROFst Error on Creation'
GO

/****** Object:  StoredProcedure [deleteROImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteROImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteROImage];
GO
	
CREATE PROCEDURE [dbo].[deleteROImage]

(
	@ImageID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Figures]
		WHERE [ImageID]=@ImageID
	DELETE [ROImages]
		WHERE [ImageID] = @ImageID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteROImage Succeeded'
ELSE PRINT 'Procedure Creation: deleteROImage Error on Creation'
GO

/****** Object:  StoredProcedure [deleteRole] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteRole];
GO
	
CREATE PROCEDURE [dbo].[deleteRole]

(
	@RID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Assignments]
		WHERE [RID]=@RID
	DELETE [Permissions]
		WHERE [RID]=@RID
	DELETE [Roles]
		WHERE [RID] = @RID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteRole Succeeded'
ELSE PRINT 'Procedure Creation: deleteRole Error on Creation'
GO

/****** Object:  StoredProcedure [deleteRoUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteRoUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteRoUsage];
GO
	
CREATE PROCEDURE [dbo].[deleteRoUsage]

(
	@ROUsageID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [RoUsages]
		WHERE [ROUsageID] = @ROUsageID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteRoUsage Succeeded'
ELSE PRINT 'Procedure Creation: deleteRoUsage Error on Creation'
GO

/****** Object:  StoredProcedure [deleteTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteTransition];
GO
	
CREATE PROCEDURE [dbo].[deleteTransition]

(
	@TransitionID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [ZTransitions]
		WHERE [TransitionID]=@TransitionID
	DELETE [Transitions]
		WHERE [TransitionID] = @TransitionID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteTransition Succeeded'
ELSE PRINT 'Procedure Creation: deleteTransition Error on Creation'
GO

/****** Object:  StoredProcedure [deleteUser] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteUser];
GO
	
CREATE PROCEDURE [dbo].[deleteUser]

(
	@UID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [Memberships]
		WHERE [UID]=@UID
	DELETE [Users]
		WHERE [UID] = @UID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteUser Succeeded'
ELSE PRINT 'Procedure Creation: deleteUser Error on Creation'
GO

/****** Object:  StoredProcedure [deleteZContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteZContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteZContent];
GO
	
CREATE PROCEDURE [dbo].[deleteZContent]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [ZContents]
		WHERE [ContentID] = @ContentID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteZContent Succeeded'
ELSE PRINT 'Procedure Creation: deleteZContent Error on Creation'
GO

/****** Object:  StoredProcedure [deleteZTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteZTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [deleteZTransition];
GO
	
CREATE PROCEDURE [dbo].[deleteZTransition]

(
	@TransitionID int
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	DELETE [ZTransitions]
		WHERE [TransitionID] = @TransitionID
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: deleteZTransition Succeeded'
ELSE PRINT 'Procedure Creation: deleteZTransition Error on Creation'
GO

/****** Object:  StoredProcedure [existsAnnotation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsAnnotation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsAnnotation];
GO
	
CREATE PROCEDURE [dbo].[existsAnnotation]

(
	@AnnotationID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Annotations] WHERE [AnnotationID]=@AnnotationID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsAnnotation Succeeded'
ELSE PRINT 'Procedure Creation: existsAnnotation Error on Creation'
GO

/****** Object:  StoredProcedure [existsAnnotationType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsAnnotationType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsAnnotationType];
GO
	
CREATE PROCEDURE [dbo].[existsAnnotationType]

(
	@TypeID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [AnnotationTypes] WHERE [TypeID]=@TypeID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsAnnotationType Succeeded'
ELSE PRINT 'Procedure Creation: existsAnnotationType Error on Creation'
GO

/****** Object:  StoredProcedure [existsAssignment] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsAssignment]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsAssignment];
GO
	
CREATE PROCEDURE [dbo].[existsAssignment]

(
	@AID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Assignments] WHERE [AID]=@AID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsAssignment Succeeded'
ELSE PRINT 'Procedure Creation: existsAssignment Error on Creation'
GO

/****** Object:  StoredProcedure [existsAssociation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsAssociation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsAssociation];
GO
	
CREATE PROCEDURE [dbo].[existsAssociation]

(
	@AssociationID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Associations] WHERE [AssociationID]=@AssociationID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsAssociation Succeeded'
ELSE PRINT 'Procedure Creation: existsAssociation Error on Creation'
GO

/****** Object:  StoredProcedure [existsConnection] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsConnection]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsConnection];
GO
	
CREATE PROCEDURE [dbo].[existsConnection]

(
	@DBID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Connections] WHERE [DBID]=@DBID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsConnection Succeeded'
ELSE PRINT 'Procedure Creation: existsConnection Error on Creation'
GO

/****** Object:  StoredProcedure [existsContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsContent];
GO
	
CREATE PROCEDURE [dbo].[existsContent]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Contents] WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsContent Succeeded'
ELSE PRINT 'Procedure Creation: existsContent Error on Creation'
GO

/****** Object:  StoredProcedure [existsDetail] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsDetail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsDetail];
GO
	
CREATE PROCEDURE [dbo].[existsDetail]

(
	@DetailID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Details] WHERE [DetailID]=@DetailID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsDetail Succeeded'
ELSE PRINT 'Procedure Creation: existsDetail Error on Creation'
GO

/****** Object:  StoredProcedure [existsDocument] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsDocument]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsDocument];
GO
	
CREATE PROCEDURE [dbo].[existsDocument]

(
	@DocID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Documents] WHERE [DocID]=@DocID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsDocument Succeeded'
ELSE PRINT 'Procedure Creation: existsDocument Error on Creation'
GO

/****** Object:  StoredProcedure [existsDocVersion] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsDocVersion]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsDocVersion];
GO
	
CREATE PROCEDURE [dbo].[existsDocVersion]

(
	@VersionID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [DocVersions] WHERE [VersionID]=@VersionID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsDocVersion Succeeded'
ELSE PRINT 'Procedure Creation: existsDocVersion Error on Creation'
GO

/****** Object:  StoredProcedure [existsDROUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsDROUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsDROUsage];
GO
	
CREATE PROCEDURE [dbo].[existsDROUsage]

(
	@DROUsageID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [DROUsages] WHERE [DROUsageID]=@DROUsageID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsDROUsage Succeeded'
ELSE PRINT 'Procedure Creation: existsDROUsage Error on Creation'
GO

/****** Object:  StoredProcedure [existsEntry] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsEntry]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsEntry];
GO
	
CREATE PROCEDURE [dbo].[existsEntry]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Entries] WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsEntry Succeeded'
ELSE PRINT 'Procedure Creation: existsEntry Error on Creation'
GO

/****** Object:  StoredProcedure [existsFigure] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsFigure]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsFigure];
GO
	
CREATE PROCEDURE [dbo].[existsFigure]

(
	@FigureID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Figures] WHERE [FigureID]=@FigureID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsFigure Succeeded'
ELSE PRINT 'Procedure Creation: existsFigure Error on Creation'
GO

/****** Object:  StoredProcedure [existsFolder] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsFolder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsFolder];
GO
	
CREATE PROCEDURE [dbo].[existsFolder]

(
	@FolderID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Folders] WHERE [FolderID]=@FolderID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsFolder Succeeded'
ELSE PRINT 'Procedure Creation: existsFolder Error on Creation'
GO

/****** Object:  StoredProcedure [existsFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsFormat]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsFormat];
GO
	
CREATE PROCEDURE [dbo].[existsFormat]

(
	@FormatID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Formats] WHERE [FormatID]=@FormatID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsFormat Succeeded'
ELSE PRINT 'Procedure Creation: existsFormat Error on Creation'
GO

/****** Object:  StoredProcedure [existsGrid] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsGrid]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsGrid];
GO
	
CREATE PROCEDURE [dbo].[existsGrid]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Grids] WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsGrid Succeeded'
ELSE PRINT 'Procedure Creation: existsGrid Error on Creation'
GO

/****** Object:  StoredProcedure [existsGroup] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsGroup]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsGroup];
GO
	
CREATE PROCEDURE [dbo].[existsGroup]

(
	@GID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Groups] WHERE [GID]=@GID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsGroup Succeeded'
ELSE PRINT 'Procedure Creation: existsGroup Error on Creation'
GO

/****** Object:  StoredProcedure [existsImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsImage];
GO
	
CREATE PROCEDURE [dbo].[existsImage]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Images] WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsImage Succeeded'
ELSE PRINT 'Procedure Creation: existsImage Error on Creation'
GO

/****** Object:  StoredProcedure [existsItem] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsItem]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsItem];
GO
	
CREATE PROCEDURE [dbo].[existsItem]

(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Items] WHERE [ItemID]=@ItemID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsItem Succeeded'
ELSE PRINT 'Procedure Creation: existsItem Error on Creation'
GO

/****** Object:  StoredProcedure [existsMembership] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsMembership]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsMembership];
GO
	
CREATE PROCEDURE [dbo].[existsMembership]

(
	@UGID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Memberships] WHERE [UGID]=@UGID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsMembership Succeeded'
ELSE PRINT 'Procedure Creation: existsMembership Error on Creation'
GO

/****** Object:  StoredProcedure [existsPart] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsPart]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsPart];
GO
	
CREATE PROCEDURE [dbo].[existsPart]

(
	@ContentID int,
	@FromType int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Parts] WHERE [ContentID]=@ContentID AND [FromType]=@FromType
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsPart Succeeded'
ELSE PRINT 'Procedure Creation: existsPart Error on Creation'
GO

/****** Object:  StoredProcedure [existsPdf] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsPdf]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsPdf];
GO
	
CREATE PROCEDURE [dbo].[existsPdf]

(
	@DocID int,
	@DebugStatus int,
	@TopRow int,
	@PageLength int,
	@LeftMargin int,
	@PageWidth int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Pdfs] WHERE [DocID]=@DocID AND [DebugStatus]=@DebugStatus AND [TopRow]=@TopRow AND [PageLength]=@PageLength AND [LeftMargin]=@LeftMargin AND [PageWidth]=@PageWidth
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsPdf Succeeded'
ELSE PRINT 'Procedure Creation: existsPdf Error on Creation'
GO

/****** Object:  StoredProcedure [existsPermission] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsPermission]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsPermission];
GO
	
CREATE PROCEDURE [dbo].[existsPermission]

(
	@PID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Permissions] WHERE [PID]=@PID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsPermission Succeeded'
ELSE PRINT 'Procedure Creation: existsPermission Error on Creation'
GO

/****** Object:  StoredProcedure [existsRODb] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsRODb]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsRODb];
GO
	
CREATE PROCEDURE [dbo].[existsRODb]

(
	@RODbID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [RODbs] WHERE [RODbID]=@RODbID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsRODb Succeeded'
ELSE PRINT 'Procedure Creation: existsRODb Error on Creation'
GO

/****** Object:  StoredProcedure [existsROFst] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsROFst]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsROFst];
GO
	
CREATE PROCEDURE [dbo].[existsROFst]

(
	@ROFstID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [ROFsts] WHERE [ROFstID]=@ROFstID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsROFst Succeeded'
ELSE PRINT 'Procedure Creation: existsROFst Error on Creation'
GO

/****** Object:  StoredProcedure [existsROImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsROImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsROImage];
GO
	
CREATE PROCEDURE [dbo].[existsROImage]

(
	@ImageID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [ROImages] WHERE [ImageID]=@ImageID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsROImage Succeeded'
ELSE PRINT 'Procedure Creation: existsROImage Error on Creation'
GO

/****** Object:  StoredProcedure [existsRole] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsRole];
GO
	
CREATE PROCEDURE [dbo].[existsRole]

(
	@RID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Roles] WHERE [RID]=@RID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsRole Succeeded'
ELSE PRINT 'Procedure Creation: existsRole Error on Creation'
GO

/****** Object:  StoredProcedure [existsRoUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsRoUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsRoUsage];
GO
	
CREATE PROCEDURE [dbo].[existsRoUsage]

(
	@ROUsageID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [RoUsages] WHERE [ROUsageID]=@ROUsageID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsRoUsage Succeeded'
ELSE PRINT 'Procedure Creation: existsRoUsage Error on Creation'
GO

/****** Object:  StoredProcedure [existsTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsTransition];
GO
	
CREATE PROCEDURE [dbo].[existsTransition]

(
	@TransitionID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Transitions] WHERE [TransitionID]=@TransitionID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsTransition Succeeded'
ELSE PRINT 'Procedure Creation: existsTransition Error on Creation'
GO

/****** Object:  StoredProcedure [existsUser] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsUser];
GO
	
CREATE PROCEDURE [dbo].[existsUser]

(
	@UID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [Users] WHERE [UID]=@UID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsUser Succeeded'
ELSE PRINT 'Procedure Creation: existsUser Error on Creation'
GO

/****** Object:  StoredProcedure [existsZContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsZContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsZContent];
GO
	
CREATE PROCEDURE [dbo].[existsZContent]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [ZContents] WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsZContent Succeeded'
ELSE PRINT 'Procedure Creation: existsZContent Error on Creation'
GO

/****** Object:  StoredProcedure [existsZTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[existsZTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [existsZTransition];
GO
	
CREATE PROCEDURE [dbo].[existsZTransition]

(
	@TransitionID int
)
WITH EXECUTE AS OWNER
AS
	SELECT COUNT(*)
	FROM [ZTransitions] WHERE [TransitionID]=@TransitionID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: existsZTransition Succeeded'
ELSE PRINT 'Procedure Creation: existsZTransition Error on Creation'
GO

/****** Object:  StoredProcedure [getAffectedDRoUsages] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAffectedDRoUsages]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAffectedDRoUsages];
GO
	
/*
getAffectedDROUsages 1, '00010000019c0000', 'KBR Test', 'Changed', 'KBR'
*/
CREATE PROCEDURE [dbo].[getAffectedDRoUsages]
(
	@RODbID int,
	@ROID nvarchar(16),
	@RODesc nvarchar(MAX),
	@Command nvarchar(10),
	@UserID nvarchar(100)
)
WITH EXECUTE AS OWNER
AS
	BEGIN
		DECLARE @typeID int
		SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
		-- Add "Verification Required" Annotation for each ROUsage
		INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT ItemID, @typeID,'Referenced Object (' + @RODesc + ') ' + @Command,@UserID
		FROM Items where CONTENTID in (SELECT ContentID
		FROM DROUsages DR
		JOIN Entries EE on EE.DocID = DR.DocID
		where RODbID = @RODbID AND SUBSTRING(ROID,1,12) = SUBSTRING(@ROID,1,12))
	END
	SELECT
		[DROUsages].[DROUsageID],
		[DROUsages].[DocID],
		[DROUsages].[ROID],
		[DROUsages].[Config],
		[DROUsages].[DTS],
		[DROUsages].[UserID],
		[DROUsages].[LastChanged],
		[DROUsages].[RODbID],
		[Documents].[LibTitle] [Document_LibTitle],
		[Documents].[DocContent] [Document_DocContent],
		[Documents].[DocAscii] [Document_DocAscii],
		[Documents].[Config] [Document_Config],
		[Documents].[DTS] [Document_DTS],
		[Documents].[UserID] [Document_UserID],
		[Documents].[FileExtension] [Document_FileExtension]
	FROM [DRoUsages]
		JOIN [Documents]  ON
			[Documents].[DocID]=[DROUsages].[DocID]
	WHERE
		[DRoUsages].[RODbID]=@RODbID AND [DRoUsages].[ROID]=@ROID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAffectedDRoUsages Succeeded'
ELSE PRINT 'Procedure Creation: getAffectedDRoUsages Error on Creation'
GO

/****** Object:  StoredProcedure [getAffectedRoUsages] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAffectedRoUsages]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAffectedRoUsages];
GO
	
/*
getAffectedROUsages 1, '00010000019c0000', 'KBR Test', 'Changed', 'KBR'
*/
CREATE PROCEDURE [dbo].[getAffectedRoUsages]

(
	@RODbID int,
	@ROID nvarchar(16),
	@RODesc nvarchar(MAX),
	@Command nvarchar(10),
	@UserID nvarchar(100)
)
WITH EXECUTE AS OWNER
AS
	BEGIN
		DECLARE @typeID int
		SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
		-- Add "Verification Required" Annotation for each ROUsage
		INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT ItemID, @typeID,'Referenced Object (' + @RODesc + ') ' + @Command,@UserID
		FROM Items where CONTENTID in (SELECT ContentID FROM ROUSAGES
		where RODbID = @RODbID AND SUBSTRING(ROID,1,12) = SUBSTRING(@ROID,1,12))
	END
	SELECT
		[RoUsages].[ROUsageID],
		[RoUsages].[ContentID],
		[RoUsages].[ROID],
		[RoUsages].[Config],
		[RoUsages].[DTS],
		[RoUsages].[UserID],
		[RoUsages].[LastChanged],
		[RoUsages].[RODbID],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [RoUsages]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[RoUsages].[ContentID]
	WHERE
		[RoUsages].[RODbID]=@RODbID AND [RoUsages].[ROID]=@ROID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAffectedRoUsages Succeeded'
ELSE PRINT 'Procedure Creation: getAffectedRoUsages Error on Creation'
GO

/****** Object:  StoredProcedure [getAffectedTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAffectedTransitions]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAffectedTransitions];
GO
	
/*
exec getAffectedTransitions 2102
*/
	
CREATE PROCEDURE [dbo].[getAffectedTransitions]
(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		TT.[TransitionID],
		[FromID],
		[ToID],
		[RangeID],
		[IsRange],
		[TranType],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=TT.[TransitionID]) [ZTransitionCount]
	FROM [Transitions] TT join vefn_FindAffectedTransitions(@ItemID) TTZ on TTZ.TransitionID = TT.TransitionID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAffectedTransitions Succeeded'
ELSE PRINT 'Procedure Creation: getAffectedTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [getAnnotation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAnnotation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAnnotation];
GO
	
CREATE PROCEDURE [dbo].[getAnnotation]

(
	@AnnotationID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AnnotationID],
		[ItemID],
		[TypeID],
		[RtfText],
		[SearchText],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Annotations]
	WHERE [AnnotationID]=@AnnotationID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAnnotation Succeeded'
ELSE PRINT 'Procedure Creation: getAnnotation Error on Creation'
GO

/****** Object:  StoredProcedure [getAnnotations] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAnnotations]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAnnotations];
GO
	
CREATE PROCEDURE [dbo].[getAnnotations]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AnnotationID],
		[ItemID],
		[TypeID],
		[RtfText],
		[SearchText],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Annotations]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAnnotations Succeeded'
ELSE PRINT 'Procedure Creation: getAnnotations Error on Creation'
GO

/****** Object:  StoredProcedure [getAnnotationsByItemID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAnnotationsByItemID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAnnotationsByItemID];
GO
	
CREATE PROCEDURE [dbo].[getAnnotationsByItemID]

(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Annotations].[AnnotationID],
		[Annotations].[ItemID],
		[Annotations].[TypeID],
		[Annotations].[RtfText],
		[Annotations].[SearchText],
		[Annotations].[Config],
		[Annotations].[DTS],
		[Annotations].[UserID],
		[Annotations].[LastChanged],
		[AnnotationTypes].[Name] [AnnotationType_Name],
		[AnnotationTypes].[Config] [AnnotationType_Config],
		[AnnotationTypes].[DTS] [AnnotationType_DTS],
		[AnnotationTypes].[UserID] [AnnotationType_UserID]
	FROM [Annotations]
		JOIN [AnnotationTypes]  ON
			[AnnotationTypes].[TypeID]=[Annotations].[TypeID]
	WHERE
		[Annotations].[ItemID]=@ItemID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAnnotationsByItemID Succeeded'
ELSE PRINT 'Procedure Creation: getAnnotationsByItemID Error on Creation'
GO

/****** Object:  StoredProcedure [getAnnotationsByTypeID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAnnotationsByTypeID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAnnotationsByTypeID];
GO
	
CREATE PROCEDURE [dbo].[getAnnotationsByTypeID]

(
	@TypeID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Annotations].[AnnotationID],
		[Annotations].[ItemID],
		[Annotations].[TypeID],
		[Annotations].[RtfText],
		[Annotations].[SearchText],
		[Annotations].[Config],
		[Annotations].[DTS],
		[Annotations].[UserID],
		[Annotations].[LastChanged],
		[Items].[PreviousID] [Item_PreviousID],
		[Items].[ContentID] [Item_ContentID],
		[Items].[DTS] [Item_DTS],
		[Items].[UserID] [Item_UserID]
	FROM [Annotations]
		JOIN [Items]  ON
			[Items].[ItemID]=[Annotations].[ItemID]
	WHERE
		[Annotations].[TypeID]=@TypeID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAnnotationsByTypeID Succeeded'
ELSE PRINT 'Procedure Creation: getAnnotationsByTypeID Error on Creation'
GO

/****** Object:  StoredProcedure [getAnnotationType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAnnotationType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAnnotationType];
GO
	
CREATE PROCEDURE [dbo].[getAnnotationType]

(
	@TypeID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[TypeID],
		[Name],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[TypeID]=[AnnotationTypes].[TypeID]) [AnnotationCount]
	FROM [AnnotationTypes]
	WHERE [TypeID]=@TypeID

	SELECT
		[Annotations].[AnnotationID],
		[Annotations].[ItemID],
		[Annotations].[TypeID],
		[Annotations].[RtfText],
		[Annotations].[SearchText],
		[Annotations].[Config],
		[Annotations].[DTS],
		[Annotations].[UserID],
		[Annotations].[LastChanged],
		[Items].[PreviousID] [Item_PreviousID],
		[Items].[ContentID] [Item_ContentID],
		[Items].[DTS] [Item_DTS],
		[Items].[UserID] [Item_UserID]
	FROM [Annotations]
		JOIN [Items]  ON
			[Items].[ItemID]=[Annotations].[ItemID]
	WHERE
		[Annotations].[TypeID]=@TypeID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAnnotationType Succeeded'
ELSE PRINT 'Procedure Creation: getAnnotationType Error on Creation'
GO

/****** Object:  StoredProcedure [getAnnotationTypeByName] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAnnotationTypeByName]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAnnotationTypeByName];
GO
	
CREATE PROCEDURE [dbo].[getAnnotationTypeByName]
(
	@Name nvarchar(100)
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[TypeID],
		[Name],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[TypeID]=[AnnotationTypes].[TypeID]) [AnnotationCount]
	FROM [AnnotationTypes]
	WHERE [Name]=@Name
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAnnotationTypeByName Succeeded'
ELSE PRINT 'Procedure Creation: getAnnotationTypeByName Error on Creation'
GO

/****** Object:  StoredProcedure [getAnnotationTypes] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAnnotationTypes]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAnnotationTypes];
GO
	
CREATE PROCEDURE [dbo].[getAnnotationTypes]

WITH EXECUTE AS OWNER
AS
	SELECT
		[TypeID],
		[Name],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[TypeID]=[AnnotationTypes].[TypeID]) [AnnotationCount]
	FROM [AnnotationTypes]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAnnotationTypes Succeeded'
ELSE PRINT 'Procedure Creation: getAnnotationTypes Error on Creation'
GO

/****** Object:  StoredProcedure [getAssignment] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssignment]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssignment];
GO
	
CREATE PROCEDURE [dbo].[getAssignment]

(
	@AID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AID],
		[GID],
		[RID],
		[FolderID],
		[StartDate],
		[EndDate],
		[DTS],
		[UsrID],
		[LastChanged]
	FROM [Assignments]
	WHERE [AID]=@AID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssignment Succeeded'
ELSE PRINT 'Procedure Creation: getAssignment Error on Creation'
GO

/****** Object:  StoredProcedure [getAssignments] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssignments]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssignments];
GO
	
CREATE PROCEDURE [dbo].[getAssignments]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AID],
		[GID],
		[RID],
		[FolderID],
		[StartDate],
		[EndDate],
		[DTS],
		[UsrID],
		[LastChanged]
	FROM [Assignments]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssignments Succeeded'
ELSE PRINT 'Procedure Creation: getAssignments Error on Creation'
GO

/****** Object:  StoredProcedure [getAssignmentsByFolderID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssignmentsByFolderID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssignmentsByFolderID];
GO
	
CREATE PROCEDURE [dbo].[getAssignmentsByFolderID]

(
	@FolderID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Assignments].[AID],
		[Assignments].[GID],
		[Assignments].[RID],
		[Assignments].[FolderID],
		[Assignments].[StartDate],
		[Assignments].[EndDate],
		[Assignments].[DTS],
		[Assignments].[UsrID],
		[Assignments].[LastChanged],
		[Groups].[GroupName] [Group_GroupName],
		[Groups].[GroupType] [Group_GroupType],
		[Groups].[Config] [Group_Config],
		[Groups].[DTS] [Group_DTS],
		[Groups].[UsrID] [Group_UsrID],
		[Roles].[Name] [Role_Name],
		[Roles].[Title] [Role_Title],
		[Roles].[DTS] [Role_DTS],
		[Roles].[UsrID] [Role_UsrID]
	FROM [Assignments]
		JOIN [Groups]  ON
			[Groups].[GID]=[Assignments].[GID]
		JOIN [Roles]  ON
			[Roles].[RID]=[Assignments].[RID]
	WHERE
		[Assignments].[FolderID]=@FolderID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssignmentsByFolderID Succeeded'
ELSE PRINT 'Procedure Creation: getAssignmentsByFolderID Error on Creation'
GO

/****** Object:  StoredProcedure [getAssignmentsByGID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssignmentsByGID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssignmentsByGID];
GO
	
CREATE PROCEDURE [dbo].[getAssignmentsByGID]

(
	@GID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Assignments].[AID],
		[Assignments].[GID],
		[Assignments].[RID],
		[Assignments].[FolderID],
		[Assignments].[StartDate],
		[Assignments].[EndDate],
		[Assignments].[DTS],
		[Assignments].[UsrID],
		[Assignments].[LastChanged],
		[Folders].[ParentID] [Folder_ParentID],
		[Folders].[DBID] [Folder_DBID],
		[Folders].[Name] [Folder_Name],
		[Folders].[Title] [Folder_Title],
		[Folders].[ShortName] [Folder_ShortName],
		[Folders].[FormatID] [Folder_FormatID],
		[Folders].[ManualOrder] [Folder_ManualOrder],
		[Folders].[Config] [Folder_Config],
		[Folders].[DTS] [Folder_DTS],
		[Folders].[UsrID] [Folder_UsrID],
		[Roles].[Name] [Role_Name],
		[Roles].[Title] [Role_Title],
		[Roles].[DTS] [Role_DTS],
		[Roles].[UsrID] [Role_UsrID]
	FROM [Assignments]
		JOIN [Folders]  ON
			[Folders].[FolderID]=[Assignments].[FolderID]
		JOIN [Roles]  ON
			[Roles].[RID]=[Assignments].[RID]
	WHERE
		[Assignments].[GID]=@GID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssignmentsByGID Succeeded'
ELSE PRINT 'Procedure Creation: getAssignmentsByGID Error on Creation'
GO

/****** Object:  StoredProcedure [getAssignmentsByRID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssignmentsByRID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssignmentsByRID];
GO
	
CREATE PROCEDURE [dbo].[getAssignmentsByRID]

(
	@RID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Assignments].[AID],
		[Assignments].[GID],
		[Assignments].[RID],
		[Assignments].[FolderID],
		[Assignments].[StartDate],
		[Assignments].[EndDate],
		[Assignments].[DTS],
		[Assignments].[UsrID],
		[Assignments].[LastChanged],
		[Folders].[ParentID] [Folder_ParentID],
		[Folders].[DBID] [Folder_DBID],
		[Folders].[Name] [Folder_Name],
		[Folders].[Title] [Folder_Title],
		[Folders].[ShortName] [Folder_ShortName],
		[Folders].[FormatID] [Folder_FormatID],
		[Folders].[ManualOrder] [Folder_ManualOrder],
		[Folders].[Config] [Folder_Config],
		[Folders].[DTS] [Folder_DTS],
		[Folders].[UsrID] [Folder_UsrID],
		[Groups].[GroupName] [Group_GroupName],
		[Groups].[GroupType] [Group_GroupType],
		[Groups].[Config] [Group_Config],
		[Groups].[DTS] [Group_DTS],
		[Groups].[UsrID] [Group_UsrID]
	FROM [Assignments]
		JOIN [Folders]  ON
			[Folders].[FolderID]=[Assignments].[FolderID]
		JOIN [Groups]  ON
			[Groups].[GID]=[Assignments].[GID]
	WHERE
		[Assignments].[RID]=@RID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssignmentsByRID Succeeded'
ELSE PRINT 'Procedure Creation: getAssignmentsByRID Error on Creation'
GO

/****** Object:  StoredProcedure [getAssociation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssociation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssociation];
GO
	
CREATE PROCEDURE [dbo].[getAssociation]

(
	@AssociationID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AssociationID],
		[VersionID],
		[ROFstID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Associations]
	WHERE [AssociationID]=@AssociationID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssociation Succeeded'
ELSE PRINT 'Procedure Creation: getAssociation Error on Creation'
GO

/****** Object:  StoredProcedure [getAssociationByVersionID_ROFstID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssociationByVersionID_ROFstID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssociationByVersionID_ROFstID];
GO
	
CREATE PROCEDURE [dbo].[getAssociationByVersionID_ROFstID]
(
	@VersionID int,
	@ROFstID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AssociationID],
		[VersionID],
		[ROFstID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Associations]
	WHERE [VersionID]=@VersionID AND [ROFstID]=@ROFstID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssociationByVersionID_ROFstID Succeeded'
ELSE PRINT 'Procedure Creation: getAssociationByVersionID_ROFstID Error on Creation'
GO

/****** Object:  StoredProcedure [getAssociations] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssociations]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssociations];
GO
	
CREATE PROCEDURE [dbo].[getAssociations]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AssociationID],
		[VersionID],
		[ROFstID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Associations]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssociations Succeeded'
ELSE PRINT 'Procedure Creation: getAssociations Error on Creation'
GO

/****** Object:  StoredProcedure [getAssociationsByROFstID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssociationsByROFstID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssociationsByROFstID];
GO
	
CREATE PROCEDURE [dbo].[getAssociationsByROFstID]

(
	@ROFstID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Associations].[AssociationID],
		[Associations].[VersionID],
		[Associations].[ROFstID],
		[Associations].[Config],
		[Associations].[DTS],
		[Associations].[UserID],
		[Associations].[LastChanged],
		[DocVersions].[FolderID] [DocVersion_FolderID],
		[DocVersions].[VersionType] [DocVersion_VersionType],
		[DocVersions].[Name] [DocVersion_Name],
		[DocVersions].[Title] [DocVersion_Title],
		[DocVersions].[ItemID] [DocVersion_ItemID],
		[DocVersions].[FormatID] [DocVersion_FormatID],
		[DocVersions].[Config] [DocVersion_Config],
		[DocVersions].[DTS] [DocVersion_DTS],
		[DocVersions].[UserID] [DocVersion_UserID]
	FROM [Associations]
		JOIN [DocVersions]  ON
			[DocVersions].[VersionID]=[Associations].[VersionID]
	WHERE
		[Associations].[ROFstID]=@ROFstID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssociationsByROFstID Succeeded'
ELSE PRINT 'Procedure Creation: getAssociationsByROFstID Error on Creation'
GO

/****** Object:  StoredProcedure [getAssociationsByVersionID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getAssociationsByVersionID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getAssociationsByVersionID];
GO
	
CREATE PROCEDURE [dbo].[getAssociationsByVersionID]

(
	@VersionID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Associations].[AssociationID],
		[Associations].[VersionID],
		[Associations].[ROFstID],
		[Associations].[Config],
		[Associations].[DTS],
		[Associations].[UserID],
		[Associations].[LastChanged],
		[ROFsts].[RODbID] [ROFst_RODbID],
		[ROFsts].[ROLookup] [ROFst_ROLookup],
		[ROFsts].[Config] [ROFst_Config],
		[ROFsts].[DTS] [ROFst_DTS],
		[ROFsts].[UserID] [ROFst_UserID]
	FROM [Associations]
		JOIN [ROFsts]  ON
			[ROFsts].[ROFstID]=[Associations].[ROFstID]
	WHERE
		[Associations].[VersionID]=@VersionID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getAssociationsByVersionID Succeeded'
ELSE PRINT 'Procedure Creation: getAssociationsByVersionID Error on Creation'
GO

/****** Object:  StoredProcedure [getChildFolders] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getChildFolders]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getChildFolders];
GO
	
CREATE PROCEDURE [dbo].[getChildFolders]

(
	@ParentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FolderID],
		[ParentID],
		[DBID],
		[Name],
		[Title],
		[ShortName],
		[FormatID],
		[ManualOrder],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[FolderID]=[Folders].[FolderID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FolderID]=[Folders].[FolderID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] [Children] WHERE [Children].[ParentID]=[Folders].[FolderID]) [ChildCount]
	FROM [Folders] WHERE [ParentID]=@ParentID AND [FolderID]<>@ParentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getChildFolders Succeeded'
ELSE PRINT 'Procedure Creation: getChildFolders Error on Creation'
GO

/****** Object:  StoredProcedure [getChildFormats] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getChildFormats]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getChildFormats];
GO
	
CREATE PROCEDURE [dbo].[getChildFormats]

(
	@ParentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FormatID],
		[ParentID],
		[Name],
		[Description],
		[Data],
		[GenMac],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Contents] WHERE [Contents].[FormatID]=[Formats].[FormatID]) [ContentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FormatID]=[Formats].[FormatID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] WHERE [Folders].[FormatID]=[Formats].[FormatID]) [FolderCount],
		(SELECT COUNT(*) FROM [Formats] [Children] WHERE [Children].[ParentID]=[Formats].[FormatID]) [ChildCount]
	FROM [Formats] WHERE [ParentID]=@ParentID AND [FormatID]<>@ParentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getChildFormats Succeeded'
ELSE PRINT 'Procedure Creation: getChildFormats Error on Creation'
GO

/****** Object:  StoredProcedure [getConnection] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getConnection]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getConnection];
GO
	
CREATE PROCEDURE [dbo].[getConnection]

(
	@DBID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[DBID],
		[Name],
		[Title],
		[ConnectionString],
		[ServerType],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Folders] WHERE [Folders].[DBID]=[Connections].[DBID]) [FolderCount]
	FROM [Connections]
	WHERE [DBID]=@DBID

	SELECT
		[Folders].[FolderID],
		[Folders].[ParentID],
		[Folders].[DBID],
		[Folders].[Name],
		[Folders].[Title],
		[Folders].[ShortName],
		[Folders].[FormatID],
		[Folders].[ManualOrder],
		[Folders].[Config],
		[Folders].[DTS],
		[Folders].[UsrID],
		[Folders].[LastChanged]
	FROM [Folders]
	WHERE
		[Folders].[DBID]=@DBID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getConnection Succeeded'
ELSE PRINT 'Procedure Creation: getConnection Error on Creation'
GO

/****** Object:  StoredProcedure [getConnectionByName] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getConnectionByName]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getConnectionByName];
GO
	
CREATE PROCEDURE [dbo].[getConnectionByName]
(
	@Name nvarchar(100)
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[DBID],
		[Name],
		[Title],
		[ConnectionString],
		[ServerType],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Folders] WHERE [Folders].[DBID]=[Connections].[DBID]) [FolderCount]
	FROM [Connections]
	WHERE [Name]=@Name
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getConnectionByName Succeeded'
ELSE PRINT 'Procedure Creation: getConnectionByName Error on Creation'
GO

/****** Object:  StoredProcedure [getConnections] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getConnections]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getConnections];
GO
	
CREATE PROCEDURE [dbo].[getConnections]

WITH EXECUTE AS OWNER
AS
	SELECT
		[DBID],
		[Name],
		[Title],
		[ConnectionString],
		[ServerType],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Folders] WHERE [Folders].[DBID]=[Connections].[DBID]) [FolderCount]
	FROM [Connections]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getConnections Succeeded'
ELSE PRINT 'Procedure Creation: getConnections Error on Creation'
GO

/****** Object:  StoredProcedure [getContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getContent];
GO
	
CREATE PROCEDURE [dbo].[getContent]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[Number],
		[Text],
		[Type],
		[FormatID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[Contents].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[Contents].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[Contents].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[Contents].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[Contents].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[Contents].[ContentID]) [PartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[Contents].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[Contents].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[Contents].[ContentID]) [ZContentCount]
	FROM [Contents]
	WHERE [ContentID]=@ContentID

	SELECT
		[Details].[DetailID],
		[Details].[ContentID],
		[Details].[ItemType],
		[Details].[Text],
		[Details].[Config],
		[Details].[DTS],
		[Details].[UserID],
		[Details].[LastChanged]
	FROM [Details]
	WHERE
		[Details].[ContentID]=@ContentID


	SELECT
		[Entries].[ContentID],
		[Entries].[DocID],
		[Entries].[DTS],
		[Entries].[UserID],
		[Entries].[LastChanged],
		[Documents].[LibTitle] [Document_LibTitle],
		[Documents].[DocContent] [Document_DocContent],
		[Documents].[DocAscii] [Document_DocAscii],
		[Documents].[Config] [Document_Config],
		[Documents].[DTS] [Document_DTS],
		[Documents].[UserID] [Document_UserID],
		[Documents].[FileExtension] [Document_FileExtension]
	FROM [Entries]
		JOIN [Documents]  ON
			[Documents].[DocID]=[Entries].[DocID]
	WHERE
		[Entries].[ContentID]=@ContentID


	SELECT
		[Grids].[ContentID],
		[Grids].[Data],
		[Grids].[Config],
		[Grids].[DTS],
		[Grids].[UserID],
		[Grids].[LastChanged]
	FROM [Grids]
	WHERE
		[Grids].[ContentID]=@ContentID


	SELECT
		[Images].[ContentID],
		[Images].[ImageType],
		[Images].[FileName],
		[Images].[Data],
		[Images].[Config],
		[Images].[DTS],
		[Images].[UserID],
		[Images].[LastChanged]
	FROM [Images]
	WHERE
		[Images].[ContentID]=@ContentID


	SELECT
		[Items].[ItemID],
		[Items].[PreviousID],
		[Items].[ContentID],
		[Items].[DTS],
		[Items].[UserID],
		[Items].[LastChanged]
	FROM [Items]
	WHERE
		[Items].[ContentID]=@ContentID


	SELECT
		[Parts].[ContentID],
		[Parts].[FromType],
		[Parts].[ItemID],
		[Parts].[DTS],
		[Parts].[UserID],
		[Parts].[LastChanged],
		[Items].[PreviousID] [Item_PreviousID],
		[Items].[ContentID] [Item_ContentID],
		[Items].[DTS] [Item_DTS],
		[Items].[UserID] [Item_UserID]
	FROM [Parts]
		JOIN [Items]  ON
			[Items].[ItemID]=[Parts].[ItemID]
	WHERE
		[Parts].[ContentID]=@ContentID


	SELECT
		[RoUsages].[ROUsageID],
		[RoUsages].[ContentID],
		[RoUsages].[ROID],
		[RoUsages].[Config],
		[RoUsages].[DTS],
		[RoUsages].[UserID],
		[RoUsages].[LastChanged],
		[RoUsages].[RODbID],
		[RODbs].[ROName] [RODb_ROName],
		[RODbs].[FolderPath] [RODb_FolderPath],
		[RODbs].[DBConnectionString] [RODb_DBConnectionString],
		[RODbs].[Config] [RODb_Config],
		[RODbs].[DTS] [RODb_DTS],
		[RODbs].[UserID] [RODb_UserID]
	FROM [RoUsages]
		JOIN [RODbs]  ON
			[RODbs].[RODbID]=[RoUsages].[RODbID]
	WHERE
		[RoUsages].[ContentID]=@ContentID


	SELECT
		[Transitions].[TransitionID],
		[Transitions].[FromID],
		[Transitions].[ToID],
		[Transitions].[RangeID],
		[Transitions].[IsRange],
		[Transitions].[TranType],
		[Transitions].[Config],
		[Transitions].[DTS],
		[Transitions].[UserID],
		[Transitions].[LastChanged],
		[Items_RangeID].[PreviousID] [Item_RangeID_PreviousID],
		[Items_RangeID].[ContentID] [Item_RangeID_ContentID],
		[Items_RangeID].[DTS] [Item_RangeID_DTS],
		[Items_RangeID].[UserID] [Item_RangeID_UserID],
		[Items_ToID].[PreviousID] [Item_ToID_PreviousID],
		[Items_ToID].[ContentID] [Item_ToID_ContentID],
		[Items_ToID].[DTS] [Item_ToID_DTS],
		[Items_ToID].[UserID] [Item_ToID_UserID]
	FROM [Transitions]
		JOIN [Items] [Items_RangeID] ON
			[Items_RangeID].[ItemID]=[Transitions].[RangeID]
		JOIN [Items] [Items_ToID] ON
			[Items_ToID].[ItemID]=[Transitions].[ToID]
	WHERE
		[Transitions].[FromID]=@ContentID


	SELECT
		[ZContents].[ContentID],
		[ZContents].[OldStepSequence],
		[ZContents].[LastChanged]
	FROM [ZContents]
	WHERE
		[ZContents].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getContent Succeeded'
ELSE PRINT 'Procedure Creation: getContent Error on Creation'
GO

/****** Object:  StoredProcedure [getContentAudit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getContentAudit]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getContentAudit];
GO
	
CREATE PROCEDURE [dbo].[getContentAudit]

(
	@AuditID bigint
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[Number],
		[Text],
		[Type],
		[FormatID],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ContentAudits]
	WHERE [AuditID]=@AuditID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getContentAudit Succeeded'
ELSE PRINT 'Procedure Creation: getContentAudit Error on Creation'
GO

/****** Object:  StoredProcedure [getContentAudits] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getContentAudits]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getContentAudits];
GO
	
CREATE PROCEDURE [dbo].[getContentAudits]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[Number],
		[Text],
		[Type],
		[FormatID],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ContentAudits]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getContentAudits Succeeded'
ELSE PRINT 'Procedure Creation: getContentAudits Error on Creation'
GO

/****** Object:  StoredProcedure [getContentAuditsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getContentAuditsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getContentAuditsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getContentAuditsByContentID]
(
	@ContentID int
)

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[Number],
		[Text],
		[Type],
		[FormatID],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ContentAudits]
	WHERE ContentID = @ContentID
	ORDER BY AuditID DESC
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getContentAuditsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getContentAuditsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getContents] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getContents]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getContents];
GO
	
CREATE PROCEDURE [dbo].[getContents]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[Number],
		[Text],
		[Type],
		[FormatID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[Contents].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[Contents].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[Contents].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[Contents].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[Contents].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[Contents].[ContentID]) [PartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[Contents].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[Contents].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[Contents].[ContentID]) [ZContentCount]
	FROM [Contents]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getContents Succeeded'
ELSE PRINT 'Procedure Creation: getContents Error on Creation'
GO

/****** Object:  StoredProcedure [getContentsByFormatID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getContentsByFormatID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getContentsByFormatID];
GO
	
CREATE PROCEDURE [dbo].[getContentsByFormatID]

(
	@FormatID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Contents].[ContentID],
		[Contents].[Number],
		[Contents].[Text],
		[Contents].[Type],
		[Contents].[FormatID],
		[Contents].[Config],
		[Contents].[DTS],
		[Contents].[UserID],
		[Contents].[LastChanged],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[Contents].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[Contents].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[Contents].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[Contents].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[Contents].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[Contents].[ContentID]) [PartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[Contents].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[Contents].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[Contents].[ContentID]) [ZContentCount]
	FROM [Contents]
	WHERE
		[Contents].[FormatID]=@FormatID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getContentsByFormatID Succeeded'
ELSE PRINT 'Procedure Creation: getContentsByFormatID Error on Creation'
GO

/****** Object:  StoredProcedure [getDetail] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDetail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDetail];
GO
	
CREATE PROCEDURE [dbo].[getDetail]

(
	@DetailID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[DetailID],
		[ContentID],
		[ItemType],
		[Text],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Details]
	WHERE [DetailID]=@DetailID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDetail Succeeded'
ELSE PRINT 'Procedure Creation: getDetail Error on Creation'
GO

/****** Object:  StoredProcedure [getDetails] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDetails]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDetails];
GO
	
CREATE PROCEDURE [dbo].[getDetails]

WITH EXECUTE AS OWNER
AS
	SELECT
		[DetailID],
		[ContentID],
		[ItemType],
		[Text],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Details]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDetails Succeeded'
ELSE PRINT 'Procedure Creation: getDetails Error on Creation'
GO

/****** Object:  StoredProcedure [getDetailsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDetailsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDetailsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getDetailsByContentID]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Details].[DetailID],
		[Details].[ContentID],
		[Details].[ItemType],
		[Details].[Text],
		[Details].[Config],
		[Details].[DTS],
		[Details].[UserID],
		[Details].[LastChanged]
	FROM [Details]
	WHERE
		[Details].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDetailsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getDetailsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getDocument] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocument]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocument];
GO
	
CREATE PROCEDURE [dbo].[getDocument]

(
	@DocID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[DocID],
		[LibTitle],
		[DocContent],
		[DocAscii],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		[FileExtension],
		(SELECT COUNT(*) FROM [DROUsages] WHERE [DROUsages].[DocID]=[Documents].[DocID]) [DROUsageCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[DocID]=[Documents].[DocID]) [EntryCount],
		(SELECT COUNT(*) FROM [Pdfs] WHERE [Pdfs].[DocID]=[Documents].[DocID]) [PdfCount]
	FROM [Documents]
	WHERE [DocID]=@DocID

	SELECT
		[DROUsages].[DROUsageID],
		[DROUsages].[DocID],
		[DROUsages].[ROID],
		[DROUsages].[Config],
		[DROUsages].[DTS],
		[DROUsages].[UserID],
		[DROUsages].[LastChanged],
		[DROUsages].[RODbID],
		[RODbs].[ROName] [RODb_ROName],
		[RODbs].[FolderPath] [RODb_FolderPath],
		[RODbs].[DBConnectionString] [RODb_DBConnectionString],
		[RODbs].[Config] [RODb_Config],
		[RODbs].[DTS] [RODb_DTS],
		[RODbs].[UserID] [RODb_UserID]
	FROM [DROUsages]
		JOIN [RODbs]  ON
			[RODbs].[RODbID]=[DROUsages].[RODbID]
	WHERE
		[DROUsages].[DocID]=@DocID


	SELECT
		[Entries].[ContentID],
		[Entries].[DocID],
		[Entries].[DTS],
		[Entries].[UserID],
		[Entries].[LastChanged],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [Entries]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[Entries].[ContentID]
	WHERE
		[Entries].[DocID]=@DocID


	SELECT
		[Pdfs].[DocID],
		[Pdfs].[DebugStatus],
		[Pdfs].[TopRow],
		[Pdfs].[PageLength],
		[Pdfs].[LeftMargin],
		[Pdfs].[PageWidth],
		[Pdfs].[PageCount],
		[Pdfs].[DocPdf],
		[Pdfs].[DTS],
		[Pdfs].[UserID],
		[Pdfs].[LastChanged]
	FROM [Pdfs]
	WHERE
		[Pdfs].[DocID]=@DocID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocument Succeeded'
ELSE PRINT 'Procedure Creation: getDocument Error on Creation'
GO

/****** Object:  StoredProcedure [getDocumentAudit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocumentAudit]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocumentAudit];
GO
	
CREATE PROCEDURE [dbo].[getDocumentAudit]

(
	@AuditID bigint
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[DocID],
		[LibTitle],
		[DocContent],
		[DocAscii],
		[Config],
		[DTS],
		[UserID],
		[FileExtension],
		[DeleteStatus]
	FROM [DocumentAudits]
	WHERE [AuditID]=@AuditID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocumentAudit Succeeded'
ELSE PRINT 'Procedure Creation: getDocumentAudit Error on Creation'
GO

/****** Object:  StoredProcedure [getDocumentAudits] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocumentAudits]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocumentAudits];
GO
	
CREATE PROCEDURE [dbo].[getDocumentAudits]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[DocID],
		[LibTitle],
		[DocContent],
		[DocAscii],
		[Config],
		[DTS],
		[UserID],
		[FileExtension],
		[DeleteStatus]
	FROM [DocumentAudits]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocumentAudits Succeeded'
ELSE PRINT 'Procedure Creation: getDocumentAudits Error on Creation'
GO

/****** Object:  StoredProcedure [getDocumentAuditsByDocID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocumentAuditsByDocID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocumentAuditsByDocID];
GO
	
CREATE PROCEDURE [dbo].[getDocumentAuditsByDocID]
(
	@DocID int
)

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[DocID],
		[LibTitle],
		[DocContent],
		[DocAscii],
		[Config],
		[DTS],
		[UserID],
		[FileExtension],
		[DeleteStatus]
	FROM [DocumentAudits]
	WHERE DocID = @DocID
	ORDER BY AuditID DESC
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocumentAuditsByDocID Succeeded'
ELSE PRINT 'Procedure Creation: getDocumentAuditsByDocID Error on Creation'
GO

/****** Object:  StoredProcedure [getDocuments] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocuments]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocuments];
GO
	
CREATE PROCEDURE [dbo].[getDocuments]

WITH EXECUTE AS OWNER
AS
	SELECT
		[DocID],
		[LibTitle],
		[DocContent],
		[DocAscii],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		[FileExtension],
		(SELECT COUNT(*) FROM [DROUsages] WHERE [DROUsages].[DocID]=[Documents].[DocID]) [DROUsageCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[DocID]=[Documents].[DocID]) [EntryCount],
		(SELECT COUNT(*) FROM [Pdfs] WHERE [Pdfs].[DocID]=[Documents].[DocID]) [PdfCount]
	FROM [Documents]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocuments Succeeded'
ELSE PRINT 'Procedure Creation: getDocuments Error on Creation'
GO

/****** Object:  StoredProcedure [getDocVersion] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocVersion]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocVersion];
GO
	
CREATE PROCEDURE [dbo].[getDocVersion]

(
	@VersionID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[VersionID],
		[FolderID],
		[VersionType],
		[Name],
		[Title],
		[ItemID],
		[FormatID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[VersionID]=[DocVersions].[VersionID]) [AssociationCount]
	FROM [DocVersions]
	WHERE [VersionID]=@VersionID

	SELECT
		[Associations].[AssociationID],
		[Associations].[VersionID],
		[Associations].[ROFstID],
		[Associations].[Config],
		[Associations].[DTS],
		[Associations].[UserID],
		[Associations].[LastChanged],
		[ROFsts].[RODbID] [ROFst_RODbID],
		[ROFsts].[ROLookup] [ROFst_ROLookup],
		[ROFsts].[Config] [ROFst_Config],
		[ROFsts].[DTS] [ROFst_DTS],
		[ROFsts].[UserID] [ROFst_UserID]
	FROM [Associations]
		JOIN [ROFsts]  ON
			[ROFsts].[ROFstID]=[Associations].[ROFstID]
	WHERE
		[Associations].[VersionID]=@VersionID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocVersion Succeeded'
ELSE PRINT 'Procedure Creation: getDocVersion Error on Creation'
GO

/****** Object:  StoredProcedure [getDocVersions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocVersions]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocVersions];
GO
	
CREATE PROCEDURE [dbo].[getDocVersions]

WITH EXECUTE AS OWNER
AS
	SELECT
		[VersionID],
		[FolderID],
		[VersionType],
		[Name],
		[Title],
		[ItemID],
		[FormatID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[VersionID]=[DocVersions].[VersionID]) [AssociationCount]
	FROM [DocVersions]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocVersions Succeeded'
ELSE PRINT 'Procedure Creation: getDocVersions Error on Creation'
GO

/****** Object:  StoredProcedure [getDocVersionsByFolderID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocVersionsByFolderID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocVersionsByFolderID];
GO
	
CREATE PROCEDURE [dbo].[getDocVersionsByFolderID]

(
	@FolderID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[DocVersions].[VersionID],
		[DocVersions].[FolderID],
		[DocVersions].[VersionType],
		[DocVersions].[Name],
		[DocVersions].[Title],
		[DocVersions].[ItemID],
		[DocVersions].[FormatID],
		[DocVersions].[Config],
		[DocVersions].[DTS],
		[DocVersions].[UserID],
		[DocVersions].[LastChanged],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[VersionID]=[DocVersions].[VersionID]) [AssociationCount]
	FROM [DocVersions]
	WHERE
		[DocVersions].[FolderID]=@FolderID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocVersionsByFolderID Succeeded'
ELSE PRINT 'Procedure Creation: getDocVersionsByFolderID Error on Creation'
GO

/****** Object:  StoredProcedure [getDocVersionsByFormatID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocVersionsByFormatID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocVersionsByFormatID];
GO
	
CREATE PROCEDURE [dbo].[getDocVersionsByFormatID]

(
	@FormatID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[DocVersions].[VersionID],
		[DocVersions].[FolderID],
		[DocVersions].[VersionType],
		[DocVersions].[Name],
		[DocVersions].[Title],
		[DocVersions].[ItemID],
		[DocVersions].[FormatID],
		[DocVersions].[Config],
		[DocVersions].[DTS],
		[DocVersions].[UserID],
		[DocVersions].[LastChanged],
		[Folders].[ParentID] [Folder_ParentID],
		[Folders].[DBID] [Folder_DBID],
		[Folders].[Name] [Folder_Name],
		[Folders].[Title] [Folder_Title],
		[Folders].[ShortName] [Folder_ShortName],
		[Folders].[FormatID] [Folder_FormatID],
		[Folders].[ManualOrder] [Folder_ManualOrder],
		[Folders].[Config] [Folder_Config],
		[Folders].[DTS] [Folder_DTS],
		[Folders].[UsrID] [Folder_UsrID],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[VersionID]=[DocVersions].[VersionID]) [AssociationCount]
	FROM [DocVersions]
		JOIN [Folders]  ON
			[Folders].[FolderID]=[DocVersions].[FolderID]
	WHERE
		[DocVersions].[FormatID]=@FormatID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocVersionsByFormatID Succeeded'
ELSE PRINT 'Procedure Creation: getDocVersionsByFormatID Error on Creation'
GO

/****** Object:  StoredProcedure [getDocVersionsByItemID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocVersionsByItemID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDocVersionsByItemID];
GO
	
CREATE PROCEDURE [dbo].[getDocVersionsByItemID]

(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[DocVersions].[VersionID],
		[DocVersions].[FolderID],
		[DocVersions].[VersionType],
		[DocVersions].[Name],
		[DocVersions].[Title],
		[DocVersions].[ItemID],
		[DocVersions].[FormatID],
		[DocVersions].[Config],
		[DocVersions].[DTS],
		[DocVersions].[UserID],
		[DocVersions].[LastChanged],
		[Folders].[ParentID] [Folder_ParentID],
		[Folders].[DBID] [Folder_DBID],
		[Folders].[Name] [Folder_Name],
		[Folders].[Title] [Folder_Title],
		[Folders].[ShortName] [Folder_ShortName],
		[Folders].[FormatID] [Folder_FormatID],
		[Folders].[ManualOrder] [Folder_ManualOrder],
		[Folders].[Config] [Folder_Config],
		[Folders].[DTS] [Folder_DTS],
		[Folders].[UsrID] [Folder_UsrID],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[VersionID]=[DocVersions].[VersionID]) [AssociationCount]
	FROM [DocVersions]
		JOIN [Folders]  ON
			[Folders].[FolderID]=[DocVersions].[FolderID]
	WHERE
		[DocVersions].[ItemID]=@ItemID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocVersionsByItemID Succeeded'
ELSE PRINT 'Procedure Creation: getDocVersionsByItemID Error on Creation'
GO

/****** Object:  StoredProcedure [getDROUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDROUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDROUsage];
GO
	
CREATE PROCEDURE [dbo].[getDROUsage]

(
	@DROUsageID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[DROUsageID],
		[DocID],
		[ROID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		[RODbID]
	FROM [DROUsages]
	WHERE [DROUsageID]=@DROUsageID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDROUsage Succeeded'
ELSE PRINT 'Procedure Creation: getDROUsage Error on Creation'
GO

/****** Object:  StoredProcedure [getDROUsages] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDROUsages]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDROUsages];
GO
	
CREATE PROCEDURE [dbo].[getDROUsages]

WITH EXECUTE AS OWNER
AS
	SELECT
		[DROUsageID],
		[DocID],
		[ROID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		[RODbID]
	FROM [DROUsages]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDROUsages Succeeded'
ELSE PRINT 'Procedure Creation: getDROUsages Error on Creation'
GO

/****** Object:  StoredProcedure [getDROUsagesByDocID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDROUsagesByDocID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDROUsagesByDocID];
GO
	
CREATE PROCEDURE [dbo].[getDROUsagesByDocID]

(
	@DocID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[DROUsages].[DROUsageID],
		[DROUsages].[DocID],
		[DROUsages].[ROID],
		[DROUsages].[Config],
		[DROUsages].[DTS],
		[DROUsages].[UserID],
		[DROUsages].[LastChanged],
		[DROUsages].[RODbID],
		[RODbs].[ROName] [RODb_ROName],
		[RODbs].[FolderPath] [RODb_FolderPath],
		[RODbs].[DBConnectionString] [RODb_DBConnectionString],
		[RODbs].[Config] [RODb_Config],
		[RODbs].[DTS] [RODb_DTS],
		[RODbs].[UserID] [RODb_UserID]
	FROM [DROUsages]
		JOIN [RODbs]  ON
			[RODbs].[RODbID]=[DROUsages].[RODbID]
	WHERE
		[DROUsages].[DocID]=@DocID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDROUsagesByDocID Succeeded'
ELSE PRINT 'Procedure Creation: getDROUsagesByDocID Error on Creation'
GO

/****** Object:  StoredProcedure [getDROUsagesByRODbID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDROUsagesByRODbID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getDROUsagesByRODbID];
GO
	
CREATE PROCEDURE [dbo].[getDROUsagesByRODbID]

(
	@RODbID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[DROUsages].[DROUsageID],
		[DROUsages].[DocID],
		[DROUsages].[ROID],
		[DROUsages].[Config],
		[DROUsages].[DTS],
		[DROUsages].[UserID],
		[DROUsages].[LastChanged],
		[DROUsages].[RODbID],
		[Documents].[LibTitle] [Document_LibTitle],
		[Documents].[DocContent] [Document_DocContent],
		[Documents].[DocAscii] [Document_DocAscii],
		[Documents].[Config] [Document_Config],
		[Documents].[DTS] [Document_DTS],
		[Documents].[UserID] [Document_UserID],
		[Documents].[FileExtension] [Document_FileExtension]
	FROM [DROUsages]
		JOIN [Documents]  ON
			[Documents].[DocID]=[DROUsages].[DocID]
	WHERE
		[DROUsages].[RODbID]=@RODbID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDROUsagesByRODbID Succeeded'
ELSE PRINT 'Procedure Creation: getDROUsagesByRODbID Error on Creation'
GO

/****** Object:  StoredProcedure [getEntries] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getEntries]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getEntries];
GO
	
CREATE PROCEDURE [dbo].[getEntries]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[DocID],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Entries]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getEntries Succeeded'
ELSE PRINT 'Procedure Creation: getEntries Error on Creation'
GO

/****** Object:  StoredProcedure [getEntriesByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getEntriesByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getEntriesByContentID];
GO
	
CREATE PROCEDURE [dbo].[getEntriesByContentID]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Entries].[ContentID],
		[Entries].[DocID],
		[Entries].[DTS],
		[Entries].[UserID],
		[Entries].[LastChanged],
		[Documents].[LibTitle] [Document_LibTitle],
		[Documents].[DocContent] [Document_DocContent],
		[Documents].[DocAscii] [Document_DocAscii],
		[Documents].[Config] [Document_Config],
		[Documents].[DTS] [Document_DTS],
		[Documents].[UserID] [Document_UserID],
		[Documents].[FileExtension] [Document_FileExtension]
	FROM [Entries]
		JOIN [Documents]  ON
			[Documents].[DocID]=[Entries].[DocID]
	WHERE
		[Entries].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getEntriesByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getEntriesByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getEntriesByDocID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getEntriesByDocID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getEntriesByDocID];
GO
	
CREATE PROCEDURE [dbo].[getEntriesByDocID]

(
	@DocID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Entries].[ContentID],
		[Entries].[DocID],
		[Entries].[DTS],
		[Entries].[UserID],
		[Entries].[LastChanged],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [Entries]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[Entries].[ContentID]
	WHERE
		[Entries].[DocID]=@DocID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getEntriesByDocID Succeeded'
ELSE PRINT 'Procedure Creation: getEntriesByDocID Error on Creation'
GO

/****** Object:  StoredProcedure [getEntry] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getEntry]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getEntry];
GO
	
CREATE PROCEDURE [dbo].[getEntry]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[DocID],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Entries]
	WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getEntry Succeeded'
ELSE PRINT 'Procedure Creation: getEntry Error on Creation'
GO

/****** Object:  StoredProcedure [getEntryAudit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getEntryAudit]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getEntryAudit];
GO
	
CREATE PROCEDURE [dbo].[getEntryAudit]

(
	@AuditID bigint
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[DocID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [EntryAudits]
	WHERE [AuditID]=@AuditID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getEntryAudit Succeeded'
ELSE PRINT 'Procedure Creation: getEntryAudit Error on Creation'
GO

/****** Object:  StoredProcedure [getEntryAudits] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getEntryAudits]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getEntryAudits];
GO
	
CREATE PROCEDURE [dbo].[getEntryAudits]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[DocID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [EntryAudits]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getEntryAudits Succeeded'
ELSE PRINT 'Procedure Creation: getEntryAudits Error on Creation'
GO

/****** Object:  StoredProcedure [getEntryAuditsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getEntryAuditsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getEntryAuditsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getEntryAuditsByContentID]
(
	@ContentID int
)

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[DocID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [EntryAudits]
	WHERE ContentID = @ContentID
	ORDER BY AuditID DESC
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getEntryAuditsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getEntryAuditsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getExternalTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getExternalTransitions]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getExternalTransitions];
GO
	
/*
exec getExternalTransitions 4984
*/
	
CREATE PROCEDURE [dbo].[getExternalTransitions]
(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		TT.[TransitionID],
		TT.[FromID],
		TT.[ToID],
		TT.[RangeID],
		TT.[TranType],
		TT.[Config],
		TT.[DTS],
		TT.[UserID],
		TT.[LastChanged],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=TT.[TransitionID]) [ZTransitionCount]
		from transitions tt
		join items ii on tt.FromID = ii.ContentID
		where TT.ToID = @ItemID AND TT.FromID not in(select ContentID from vefn_childItems(@ItemID))
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getExternalTransitions Succeeded'
ELSE PRINT 'Procedure Creation: getExternalTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [getExternalTransitionsToChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getExternalTransitionsToChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getExternalTransitionsToChildren];
GO
	
/*
exec getExternalTransitionsToChildren 9392
*/
	
CREATE PROCEDURE [dbo].[getExternalTransitionsToChildren]
(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		TT.[TransitionID],
		TT.[FromID],
		TT.[ToID],
		TT.[RangeID],
		TT.[IsRange],
		TT.[TranType],
		TT.[Config],
		TT.[DTS],
		TT.[UserID],
		TT.[LastChanged],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=TT.[TransitionID]) [ZTransitionCount]
		FROM vefn_childItems(@ItemID) II
		JOIN Transitions TT on TT.ToID = II.ItemID AND TT.ToID <> @ItemID
		where TT.FromID not in(select ContentID from vefn_childItems(@ItemID))
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getExternalTransitionsToChildren Succeeded'
ELSE PRINT 'Procedure Creation: getExternalTransitionsToChildren Error on Creation'
GO

/****** Object:  StoredProcedure [getFigure] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFigure]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFigure];
GO
	
CREATE PROCEDURE [dbo].[getFigure]

(
	@FigureID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FigureID],
		[ROFstID],
		[ImageID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Figures]
	WHERE [FigureID]=@FigureID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFigure Succeeded'
ELSE PRINT 'Procedure Creation: getFigure Error on Creation'
GO

/****** Object:  StoredProcedure [getFigureByROFstID_ImageID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFigureByROFstID_ImageID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFigureByROFstID_ImageID];
GO
	
CREATE PROCEDURE [dbo].[getFigureByROFstID_ImageID]
(
	@ROFstID int,
	@ImageID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FigureID],
		[ROFstID],
		[ImageID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Figures]
	WHERE [ROFstID]=@ROFstID AND [ImageID]=@ImageID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFigureByROFstID_ImageID Succeeded'
ELSE PRINT 'Procedure Creation: getFigureByROFstID_ImageID Error on Creation'
GO

/****** Object:  StoredProcedure [getFigures] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFigures]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFigures];
GO
	
CREATE PROCEDURE [dbo].[getFigures]

WITH EXECUTE AS OWNER
AS
	SELECT
		[FigureID],
		[ROFstID],
		[ImageID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Figures]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFigures Succeeded'
ELSE PRINT 'Procedure Creation: getFigures Error on Creation'
GO

/****** Object:  StoredProcedure [getFiguresByImageID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFiguresByImageID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFiguresByImageID];
GO
	
CREATE PROCEDURE [dbo].[getFiguresByImageID]

(
	@ImageID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Figures].[FigureID],
		[Figures].[ROFstID],
		[Figures].[ImageID],
		[Figures].[Config],
		[Figures].[DTS],
		[Figures].[UserID],
		[Figures].[LastChanged],
		[ROFsts].[RODbID] [ROFst_RODbID],
		[ROFsts].[ROLookup] [ROFst_ROLookup],
		[ROFsts].[Config] [ROFst_Config],
		[ROFsts].[DTS] [ROFst_DTS],
		[ROFsts].[UserID] [ROFst_UserID]
	FROM [Figures]
		JOIN [ROFsts]  ON
			[ROFsts].[ROFstID]=[Figures].[ROFstID]
	WHERE
		[Figures].[ImageID]=@ImageID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFiguresByImageID Succeeded'
ELSE PRINT 'Procedure Creation: getFiguresByImageID Error on Creation'
GO

/****** Object:  StoredProcedure [getFiguresByROFstID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFiguresByROFstID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFiguresByROFstID];
GO
	
CREATE PROCEDURE [dbo].[getFiguresByROFstID]

(
	@ROFstID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Figures].[FigureID],
		[Figures].[ROFstID],
		[Figures].[ImageID],
		[Figures].[Config],
		[Figures].[DTS],
		[Figures].[UserID],
		[Figures].[LastChanged],
		[ROImages].[RODbID] [ROImage_RODbID],
		[ROImages].[FileName] [ROImage_FileName],
		[ROImages].[Content] [ROImage_Content],
		[ROImages].[Config] [ROImage_Config],
		[ROImages].[DTS] [ROImage_DTS],
		[ROImages].[UserID] [ROImage_UserID]
	FROM [Figures]
		JOIN [ROImages]  ON
			[ROImages].[ImageID]=[Figures].[ImageID]
	WHERE
		[Figures].[ROFstID]=@ROFstID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFiguresByROFstID Succeeded'
ELSE PRINT 'Procedure Creation: getFiguresByROFstID Error on Creation'
GO

/****** Object:  StoredProcedure [getFolder] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFolder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFolder];
GO
	
CREATE PROCEDURE [dbo].[getFolder]

(
	@FolderID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FolderID],
		[ParentID],
		[DBID],
		[Name],
		[Title],
		[ShortName],
		[FormatID],
		[ManualOrder],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[FolderID]=[Folders].[FolderID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FolderID]=[Folders].[FolderID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] [Children] WHERE [Children].[ParentID]=[Folders].[FolderID]) [ChildCount]
	FROM [Folders]
	WHERE [FolderID]=@FolderID

	SELECT
		[Assignments].[AID],
		[Assignments].[GID],
		[Assignments].[RID],
		[Assignments].[FolderID],
		[Assignments].[StartDate],
		[Assignments].[EndDate],
		[Assignments].[DTS],
		[Assignments].[UsrID],
		[Assignments].[LastChanged],
		[Groups].[GroupName] [Group_GroupName],
		[Groups].[GroupType] [Group_GroupType],
		[Groups].[Config] [Group_Config],
		[Groups].[DTS] [Group_DTS],
		[Groups].[UsrID] [Group_UsrID],
		[Roles].[Name] [Role_Name],
		[Roles].[Title] [Role_Title],
		[Roles].[DTS] [Role_DTS],
		[Roles].[UsrID] [Role_UsrID]
	FROM [Assignments]
		JOIN [Groups]  ON
			[Groups].[GID]=[Assignments].[GID]
		JOIN [Roles]  ON
			[Roles].[RID]=[Assignments].[RID]
	WHERE
		[Assignments].[FolderID]=@FolderID


	SELECT
		[DocVersions].[VersionID],
		[DocVersions].[FolderID],
		[DocVersions].[VersionType],
		[DocVersions].[Name],
		[DocVersions].[Title],
		[DocVersions].[ItemID],
		[DocVersions].[FormatID],
		[DocVersions].[Config],
		[DocVersions].[DTS],
		[DocVersions].[UserID],
		[DocVersions].[LastChanged]
	FROM [DocVersions]
	WHERE
		[DocVersions].[FolderID]=@FolderID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFolder Succeeded'
ELSE PRINT 'Procedure Creation: getFolder Error on Creation'
GO

/****** Object:  StoredProcedure [getFolderByParentID_Name] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFolderByParentID_Name]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFolderByParentID_Name];
GO
	
CREATE PROCEDURE [dbo].[getFolderByParentID_Name]
(
	@ParentID int,
	@Name nvarchar(100)
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FolderID],
		[ParentID],
		[DBID],
		[Name],
		[Title],
		[ShortName],
		[FormatID],
		[ManualOrder],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[FolderID]=[Folders].[FolderID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FolderID]=[Folders].[FolderID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] [Children] WHERE [Children].[ParentID]=[Folders].[FolderID]) [ChildCount]
	FROM [Folders]
	WHERE [ParentID]=@ParentID AND [Name]=@Name
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFolderByParentID_Name Succeeded'
ELSE PRINT 'Procedure Creation: getFolderByParentID_Name Error on Creation'
GO

/****** Object:  StoredProcedure [getFolders] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFolders]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFolders];
GO
	
CREATE PROCEDURE [dbo].[getFolders]

WITH EXECUTE AS OWNER
AS
	SELECT
		[FolderID],
		[ParentID],
		[DBID],
		[Name],
		[Title],
		[ShortName],
		[FormatID],
		[ManualOrder],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[FolderID]=[Folders].[FolderID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FolderID]=[Folders].[FolderID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] [Children] WHERE [Children].[ParentID]=[Folders].[FolderID]) [ChildCount]
	FROM [Folders]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFolders Succeeded'
ELSE PRINT 'Procedure Creation: getFolders Error on Creation'
GO

/****** Object:  StoredProcedure [getFoldersByDBID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFoldersByDBID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFoldersByDBID];
GO
	
CREATE PROCEDURE [dbo].[getFoldersByDBID]

(
	@DBID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Folders].[FolderID],
		[Folders].[ParentID],
		[Folders].[DBID],
		[Folders].[Name],
		[Folders].[Title],
		[Folders].[ShortName],
		[Folders].[FormatID],
		[Folders].[ManualOrder],
		[Folders].[Config],
		[Folders].[DTS],
		[Folders].[UsrID],
		[Folders].[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[FolderID]=[Folders].[FolderID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FolderID]=[Folders].[FolderID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] [Children] WHERE [Children].[ParentID]=[Folders].[FolderID]) [ChildCount]
	FROM [Folders]
	WHERE
		[Folders].[DBID]=@DBID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFoldersByDBID Succeeded'
ELSE PRINT 'Procedure Creation: getFoldersByDBID Error on Creation'
GO

/****** Object:  StoredProcedure [getFoldersByFormatID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFoldersByFormatID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFoldersByFormatID];
GO
	
CREATE PROCEDURE [dbo].[getFoldersByFormatID]

(
	@FormatID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Folders].[FolderID],
		[Folders].[ParentID],
		[Folders].[DBID],
		[Folders].[Name],
		[Folders].[Title],
		[Folders].[ShortName],
		[Folders].[FormatID],
		[Folders].[ManualOrder],
		[Folders].[Config],
		[Folders].[DTS],
		[Folders].[UsrID],
		[Folders].[LastChanged],
		[Connections].[Name] [Connection_Name],
		[Connections].[Title] [Connection_Title],
		[Connections].[ConnectionString] [Connection_ConnectionString],
		[Connections].[ServerType] [Connection_ServerType],
		[Connections].[Config] [Connection_Config],
		[Connections].[DTS] [Connection_DTS],
		[Connections].[UsrID] [Connection_UsrID],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[FolderID]=[Folders].[FolderID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FolderID]=[Folders].[FolderID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] [Children] WHERE [Children].[ParentID]=[Folders].[FolderID]) [ChildCount]
	FROM [Folders]
		JOIN [Connections]  ON
			[Connections].[DBID]=[Folders].[DBID]
	WHERE
		[Folders].[FormatID]=@FormatID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFoldersByFormatID Succeeded'
ELSE PRINT 'Procedure Creation: getFoldersByFormatID Error on Creation'
GO

/****** Object:  StoredProcedure [getFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFormat]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFormat];
GO
	
CREATE PROCEDURE [dbo].[getFormat]

(
	@FormatID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FormatID],
		[ParentID],
		[Name],
		[Description],
		[Data],
		[GenMac],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Contents] WHERE [Contents].[FormatID]=[Formats].[FormatID]) [ContentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FormatID]=[Formats].[FormatID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] WHERE [Folders].[FormatID]=[Formats].[FormatID]) [FolderCount],
		(SELECT COUNT(*) FROM [Formats] [Children] WHERE [Children].[ParentID]=[Formats].[FormatID]) [ChildCount]
	FROM [Formats]
	WHERE [FormatID]=@FormatID

	SELECT
		[Contents].[ContentID],
		[Contents].[Number],
		[Contents].[Text],
		[Contents].[Type],
		[Contents].[FormatID],
		[Contents].[Config],
		[Contents].[DTS],
		[Contents].[UserID],
		[Contents].[LastChanged]
	FROM [Contents]
	WHERE
		[Contents].[FormatID]=@FormatID


	SELECT
		[DocVersions].[VersionID],
		[DocVersions].[FolderID],
		[DocVersions].[VersionType],
		[DocVersions].[Name],
		[DocVersions].[Title],
		[DocVersions].[ItemID],
		[DocVersions].[FormatID],
		[DocVersions].[Config],
		[DocVersions].[DTS],
		[DocVersions].[UserID],
		[DocVersions].[LastChanged],
		[Folders].[ParentID] [Folder_ParentID],
		[Folders].[DBID] [Folder_DBID],
		[Folders].[Name] [Folder_Name],
		[Folders].[Title] [Folder_Title],
		[Folders].[ShortName] [Folder_ShortName],
		[Folders].[FormatID] [Folder_FormatID],
		[Folders].[ManualOrder] [Folder_ManualOrder],
		[Folders].[Config] [Folder_Config],
		[Folders].[DTS] [Folder_DTS],
		[Folders].[UsrID] [Folder_UsrID]
	FROM [DocVersions]
		JOIN [Folders]  ON
			[Folders].[FolderID]=[DocVersions].[FolderID]
	WHERE
		[DocVersions].[FormatID]=@FormatID


	SELECT
		[Folders].[FolderID],
		[Folders].[ParentID],
		[Folders].[DBID],
		[Folders].[Name],
		[Folders].[Title],
		[Folders].[ShortName],
		[Folders].[FormatID],
		[Folders].[ManualOrder],
		[Folders].[Config],
		[Folders].[DTS],
		[Folders].[UsrID],
		[Folders].[LastChanged],
		[Connections].[Name] [Connection_Name],
		[Connections].[Title] [Connection_Title],
		[Connections].[ConnectionString] [Connection_ConnectionString],
		[Connections].[ServerType] [Connection_ServerType],
		[Connections].[Config] [Connection_Config],
		[Connections].[DTS] [Connection_DTS],
		[Connections].[UsrID] [Connection_UsrID]
	FROM [Folders]
		JOIN [Connections]  ON
			[Connections].[DBID]=[Folders].[DBID]
	WHERE
		[Folders].[FormatID]=@FormatID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFormat Succeeded'
ELSE PRINT 'Procedure Creation: getFormat Error on Creation'
GO

/****** Object:  StoredProcedure [getFormatByParentID_Name] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFormatByParentID_Name]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFormatByParentID_Name];
GO
	
CREATE PROCEDURE [dbo].[getFormatByParentID_Name]
(
	@ParentID int,
	@Name nvarchar(20)
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FormatID],
		[ParentID],
		[Name],
		[Description],
		[Data],
		[GenMac],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Contents] WHERE [Contents].[FormatID]=[Formats].[FormatID]) [ContentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FormatID]=[Formats].[FormatID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] WHERE [Folders].[FormatID]=[Formats].[FormatID]) [FolderCount],
		(SELECT COUNT(*) FROM [Formats] [Children] WHERE [Children].[ParentID]=[Formats].[FormatID]) [ChildCount]
	FROM [Formats]
	WHERE [ParentID]=@ParentID AND [Name]=@Name
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFormatByParentID_Name Succeeded'
ELSE PRINT 'Procedure Creation: getFormatByParentID_Name Error on Creation'
GO

/****** Object:  StoredProcedure [getFormats] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getFormats]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getFormats];
GO
	
CREATE PROCEDURE [dbo].[getFormats]

WITH EXECUTE AS OWNER
AS
	SELECT
		[FormatID],
		[ParentID],
		[Name],
		[Description],
		[Data],
		[GenMac],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Contents] WHERE [Contents].[FormatID]=[Formats].[FormatID]) [ContentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FormatID]=[Formats].[FormatID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] WHERE [Folders].[FormatID]=[Formats].[FormatID]) [FolderCount],
		(SELECT COUNT(*) FROM [Formats] [Children] WHERE [Children].[ParentID]=[Formats].[FormatID]) [ChildCount]
	FROM [Formats]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getFormats Succeeded'
ELSE PRINT 'Procedure Creation: getFormats Error on Creation'
GO

/****** Object:  StoredProcedure [getGrid] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGrid]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGrid];
GO
	
CREATE PROCEDURE [dbo].[getGrid]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Grids]
	WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGrid Succeeded'
ELSE PRINT 'Procedure Creation: getGrid Error on Creation'
GO

/****** Object:  StoredProcedure [getGridAudit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGridAudit]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGridAudit];
GO
	
CREATE PROCEDURE [dbo].[getGridAudit]

(
	@AuditID bigint
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [GridAudits]
	WHERE [AuditID]=@AuditID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGridAudit Succeeded'
ELSE PRINT 'Procedure Creation: getGridAudit Error on Creation'
GO

/****** Object:  StoredProcedure [getGridAudits] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGridAudits]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGridAudits];
GO
	
CREATE PROCEDURE [dbo].[getGridAudits]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [GridAudits]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGridAudits Succeeded'
ELSE PRINT 'Procedure Creation: getGridAudits Error on Creation'
GO

/****** Object:  StoredProcedure [getGridAuditsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGridAuditsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGridAuditsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getGridAuditsByContentID]
(
	@ContentID int
)

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [GridAudits]
	WHERE ContentID = @ContentID
	ORDER BY AuditID DESC
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGridAuditsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getGridAuditsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getGrids] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGrids]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGrids];
GO
	
CREATE PROCEDURE [dbo].[getGrids]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Grids]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGrids Succeeded'
ELSE PRINT 'Procedure Creation: getGrids Error on Creation'
GO

/****** Object:  StoredProcedure [getGridsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGridsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGridsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getGridsByContentID]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Grids].[ContentID],
		[Grids].[Data],
		[Grids].[Config],
		[Grids].[DTS],
		[Grids].[UserID],
		[Grids].[LastChanged]
	FROM [Grids]
	WHERE
		[Grids].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGridsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getGridsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getGroup] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGroup]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGroup];
GO
	
CREATE PROCEDURE [dbo].[getGroup]

(
	@GID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[GID],
		[GroupName],
		[GroupType],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[GID]=[Groups].[GID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [Memberships] WHERE [Memberships].[GID]=[Groups].[GID]) [MembershipCount]
	FROM [Groups]
	WHERE [GID]=@GID

	SELECT
		[Assignments].[AID],
		[Assignments].[GID],
		[Assignments].[RID],
		[Assignments].[FolderID],
		[Assignments].[StartDate],
		[Assignments].[EndDate],
		[Assignments].[DTS],
		[Assignments].[UsrID],
		[Assignments].[LastChanged],
		[Folders].[ParentID] [Folder_ParentID],
		[Folders].[DBID] [Folder_DBID],
		[Folders].[Name] [Folder_Name],
		[Folders].[Title] [Folder_Title],
		[Folders].[ShortName] [Folder_ShortName],
		[Folders].[FormatID] [Folder_FormatID],
		[Folders].[ManualOrder] [Folder_ManualOrder],
		[Folders].[Config] [Folder_Config],
		[Folders].[DTS] [Folder_DTS],
		[Folders].[UsrID] [Folder_UsrID],
		[Roles].[Name] [Role_Name],
		[Roles].[Title] [Role_Title],
		[Roles].[DTS] [Role_DTS],
		[Roles].[UsrID] [Role_UsrID]
	FROM [Assignments]
		JOIN [Folders]  ON
			[Folders].[FolderID]=[Assignments].[FolderID]
		JOIN [Roles]  ON
			[Roles].[RID]=[Assignments].[RID]
	WHERE
		[Assignments].[GID]=@GID


	SELECT
		[Memberships].[UGID],
		[Memberships].[UID],
		[Memberships].[GID],
		[Memberships].[StartDate],
		[Memberships].[EndDate],
		[Memberships].[Config],
		[Memberships].[DTS],
		[Memberships].[UsrID],
		[Memberships].[LastChanged],
		[Users].[UserID] [User_UserID],
		[Users].[FirstName] [User_FirstName],
		[Users].[MiddleName] [User_MiddleName],
		[Users].[LastName] [User_LastName],
		[Users].[Suffix] [User_Suffix],
		[Users].[CourtesyTitle] [User_CourtesyTitle],
		[Users].[PhoneNumber] [User_PhoneNumber],
		[Users].[CFGName] [User_CFGName],
		[Users].[UserLogin] [User_UserLogin],
		[Users].[UserName] [User_UserName],
		[Users].[Config] [User_Config],
		[Users].[DTS] [User_DTS],
		[Users].[UsrID] [User_UsrID]
	FROM [Memberships]
		JOIN [Users]  ON
			[Users].[UID]=[Memberships].[UID]
	WHERE
		[Memberships].[GID]=@GID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGroup Succeeded'
ELSE PRINT 'Procedure Creation: getGroup Error on Creation'
GO

/****** Object:  StoredProcedure [getGroupByGroupName] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGroupByGroupName]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGroupByGroupName];
GO
	
CREATE PROCEDURE [dbo].[getGroupByGroupName]
(
	@GroupName nvarchar(50)
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[GID],
		[GroupName],
		[GroupType],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[GID]=[Groups].[GID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [Memberships] WHERE [Memberships].[GID]=[Groups].[GID]) [MembershipCount]
	FROM [Groups]
	WHERE [GroupName]=@GroupName
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGroupByGroupName Succeeded'
ELSE PRINT 'Procedure Creation: getGroupByGroupName Error on Creation'
GO

/****** Object:  StoredProcedure [getGroups] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getGroups]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getGroups];
GO
	
CREATE PROCEDURE [dbo].[getGroups]

WITH EXECUTE AS OWNER
AS
	SELECT
		[GID],
		[GroupName],
		[GroupType],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[GID]=[Groups].[GID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [Memberships] WHERE [Memberships].[GID]=[Groups].[GID]) [MembershipCount]
	FROM [Groups]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getGroups Succeeded'
ELSE PRINT 'Procedure Creation: getGroups Error on Creation'
GO

/****** Object:  StoredProcedure [getImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getImage];
GO
	
CREATE PROCEDURE [dbo].[getImage]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[ImageType],
		[FileName],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Images]
	WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getImage Succeeded'
ELSE PRINT 'Procedure Creation: getImage Error on Creation'
GO

/****** Object:  StoredProcedure [getImageAudit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getImageAudit]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getImageAudit];
GO
	
CREATE PROCEDURE [dbo].[getImageAudit]

(
	@AuditID bigint
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[ImageType],
		[FileName],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ImageAudits]
	WHERE [AuditID]=@AuditID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getImageAudit Succeeded'
ELSE PRINT 'Procedure Creation: getImageAudit Error on Creation'
GO

/****** Object:  StoredProcedure [getImageAudits] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getImageAudits]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getImageAudits];
GO
	
CREATE PROCEDURE [dbo].[getImageAudits]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[ImageType],
		[FileName],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ImageAudits]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getImageAudits Succeeded'
ELSE PRINT 'Procedure Creation: getImageAudits Error on Creation'
GO

/****** Object:  StoredProcedure [getImageAuditsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getImageAuditsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getImageAuditsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getImageAuditsByContentID]
(
	@ContentID int
)

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[ImageType],
		[FileName],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ImageAudits]
	WHERE ContentID = @ContentID
	ORDER BY AuditID DESC
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getImageAuditsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getImageAuditsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getImages] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getImages]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getImages];
GO
	
CREATE PROCEDURE [dbo].[getImages]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[ImageType],
		[FileName],
		[Data],
		[Config],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Images]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getImages Succeeded'
ELSE PRINT 'Procedure Creation: getImages Error on Creation'
GO

/****** Object:  StoredProcedure [getImagesByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getImagesByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getImagesByContentID];
GO
	
CREATE PROCEDURE [dbo].[getImagesByContentID]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Images].[ContentID],
		[Images].[ImageType],
		[Images].[FileName],
		[Images].[Data],
		[Images].[Config],
		[Images].[DTS],
		[Images].[UserID],
		[Images].[LastChanged]
	FROM [Images]
	WHERE
		[Images].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getImagesByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getImagesByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getItem] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItem]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItem];
GO
	
CREATE PROCEDURE [dbo].[getItem]

(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ItemID],
		[PreviousID],
		[ContentID],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[Items].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[Items].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[Items].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[Items].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[Items].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[Items].[ItemID]) [Transition_ToIDCount]
	FROM [Items]
	WHERE [ItemID]=@ItemID

	SELECT
		[Annotations].[AnnotationID],
		[Annotations].[ItemID],
		[Annotations].[TypeID],
		[Annotations].[RtfText],
		[Annotations].[SearchText],
		[Annotations].[Config],
		[Annotations].[DTS],
		[Annotations].[UserID],
		[Annotations].[LastChanged],
		[AnnotationTypes].[Name] [AnnotationType_Name],
		[AnnotationTypes].[Config] [AnnotationType_Config],
		[AnnotationTypes].[DTS] [AnnotationType_DTS],
		[AnnotationTypes].[UserID] [AnnotationType_UserID]
	FROM [Annotations]
		JOIN [AnnotationTypes]  ON
			[AnnotationTypes].[TypeID]=[Annotations].[TypeID]
	WHERE
		[Annotations].[ItemID]=@ItemID


	SELECT
		[DocVersions].[VersionID],
		[DocVersions].[FolderID],
		[DocVersions].[VersionType],
		[DocVersions].[Name],
		[DocVersions].[Title],
		[DocVersions].[ItemID],
		[DocVersions].[FormatID],
		[DocVersions].[Config],
		[DocVersions].[DTS],
		[DocVersions].[UserID],
		[DocVersions].[LastChanged],
		[Folders].[ParentID] [Folder_ParentID],
		[Folders].[DBID] [Folder_DBID],
		[Folders].[Name] [Folder_Name],
		[Folders].[Title] [Folder_Title],
		[Folders].[ShortName] [Folder_ShortName],
		[Folders].[FormatID] [Folder_FormatID],
		[Folders].[ManualOrder] [Folder_ManualOrder],
		[Folders].[Config] [Folder_Config],
		[Folders].[DTS] [Folder_DTS],
		[Folders].[UsrID] [Folder_UsrID]
	FROM [DocVersions]
		JOIN [Folders]  ON
			[Folders].[FolderID]=[DocVersions].[FolderID]
	WHERE
		[DocVersions].[ItemID]=@ItemID


	SELECT
		[Parts].[ContentID],
		[Parts].[FromType],
		[Parts].[ItemID],
		[Parts].[DTS],
		[Parts].[UserID],
		[Parts].[LastChanged],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [Parts]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[Parts].[ContentID]
	WHERE
		[Parts].[ItemID]=@ItemID


	SELECT
		[Transitions].[TransitionID],
		[Transitions].[FromID],
		[Transitions].[ToID],
		[Transitions].[RangeID],
		[Transitions].[IsRange],
		[Transitions].[TranType],
		[Transitions].[Config],
		[Transitions].[DTS],
		[Transitions].[UserID],
		[Transitions].[LastChanged],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [Transitions]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[Transitions].[FromID]
	WHERE
		[Transitions].[RangeID]=@ItemID


	SELECT
		[Transitions].[TransitionID],
		[Transitions].[FromID],
		[Transitions].[ToID],
		[Transitions].[RangeID],
		[Transitions].[IsRange],
		[Transitions].[TranType],
		[Transitions].[Config],
		[Transitions].[DTS],
		[Transitions].[UserID],
		[Transitions].[LastChanged],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [Transitions]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[Transitions].[FromID]
	WHERE
		[Transitions].[ToID]=@ItemID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItem Succeeded'
ELSE PRINT 'Procedure Creation: getItem Error on Creation'
GO

/****** Object:  StoredProcedure [getItemAndChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItemAndChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItemAndChildren];
GO
	
-- getItemAndChildren 111
CREATE PROCEDURE [dbo].[getItemAndChildren] (@ItemID int)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged]) as (
  Select 0 [Level], 0 [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
select I.[Level],I.[FromType],I.[Ordinal], I.[ParentID], I.[ItemID],I.[PreviousID],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged],
	C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged] from ItemZ I
 join Contents C on C.ContentID = I.ContentID
 order by I.[Level] , I.[FromType], I.[Ordinal]
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItemAndChildren Succeeded'
ELSE PRINT 'Procedure Creation: getItemAndChildren Error on Creation'
GO

/****** Object:  StoredProcedure [getItemAudit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItemAudit]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItemAudit];
GO
	
CREATE PROCEDURE [dbo].[getItemAudit]

(
	@AuditID bigint
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ItemID],
		[PreviousID],
		[ContentID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ItemAudits]
	WHERE [AuditID]=@AuditID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItemAudit Succeeded'
ELSE PRINT 'Procedure Creation: getItemAudit Error on Creation'
GO

/****** Object:  StoredProcedure [getItemAudits] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItemAudits]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItemAudits];
GO
	
CREATE PROCEDURE [dbo].[getItemAudits]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ItemID],
		[PreviousID],
		[ContentID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ItemAudits]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItemAudits Succeeded'
ELSE PRINT 'Procedure Creation: getItemAudits Error on Creation'
GO

/****** Object:  StoredProcedure [getItemAuditsByItemID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItemAuditsByItemID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItemAuditsByItemID];
GO
	
CREATE PROCEDURE [dbo].[getItemAuditsByItemID]
(
	@ItemID int
)

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ItemID],
		[PreviousID],
		[ContentID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [ItemAudits]
	WHERE ItemID = @ItemID
	ORDER BY AuditID DESC
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItemAuditsByItemID Succeeded'
ELSE PRINT 'Procedure Creation: getItemAuditsByItemID Error on Creation'
GO

/****** Object:  StoredProcedure [getItemNextAndChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItemNextAndChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItemNextAndChildren];
GO
	
-- getItemNextAndChildren 111
CREATE PROCEDURE [dbo].[getItemNextAndChildren] (@ItemID int)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged]) as (
  Select 0 [Level], 0 [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
)
select I.[Level],I.[FromType],I.[Ordinal], I.[ParentID], I.[ItemID],I.[PreviousID],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged],
	C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged] from ItemZ I
 join Contents C on C.ContentID = I.ContentID
 order by I.[Level] , I.[FromType], I.[Ordinal]
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItemNextAndChildren Succeeded'
ELSE PRINT 'Procedure Creation: getItemNextAndChildren Error on Creation'
GO

/****** Object:  StoredProcedure [getItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItems]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItems];
GO
	
CREATE PROCEDURE [dbo].[getItems]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ItemID],
		[PreviousID],
		[ContentID],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[Items].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[Items].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[Items].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[Items].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[Items].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[Items].[ItemID]) [Transition_ToIDCount]
	FROM [Items]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItems Succeeded'
ELSE PRINT 'Procedure Creation: getItems Error on Creation'
GO

/****** Object:  StoredProcedure [getItemsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItemsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItemsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getItemsByContentID]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Items].[ItemID],
		[Items].[PreviousID],
		[Items].[ContentID],
		[Items].[DTS],
		[Items].[UserID],
		[Items].[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[Items].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[Items].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[Items].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[Items].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[Items].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[Items].[ItemID]) [Transition_ToIDCount]
	FROM [Items]
	WHERE
		[Items].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItemsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getItemsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getItemsByPartType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItemsByPartType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItemsByPartType];
GO
	
/* samples:
  getItemsByPartType 7  // tables
  getItemsByPartType 1  // procedure
  getItemsByPartType 2  // section
  getItemsByPartType 3  // Cautions
  getItemsByPartType 4  // Notes
  getItemsByPartType 5  // RNOs
  getItemsByPartType 6  // Steps
 */

CREATE PROCEDURE [dbo].[getItemsByPartType](@FromType int)

WITH EXECUTE AS OWNER
AS
	SELECT
		ii.[ItemID],
		[PreviousID],
		ii.[ContentID],
		ii.[DTS],
		ii.[UserID],
		ii.[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=ii.[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=ii.[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=ii.[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=ii.[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=ii.[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=ii.[ItemID]) [Transition_ToIDCount]
	FROM [Items] ii
	JOIN [Parts] pp on pp.ItemID = ii.ItemID
	WHERE pp.Fromtype = @FromType
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItemsByPartType Succeeded'
ELSE PRINT 'Procedure Creation: getItemsByPartType Error on Creation'
GO

/****** Object:  StoredProcedure [getItemsByPartTypeAndContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getItemsByPartTypeAndContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getItemsByPartTypeAndContent];
GO
	
/* samples:
  getItemsByPartTypeAndContent 7  // tables
  getItemsByPartTypeAndContent 1  // procedure
  getItemsByPartTypeAndContent 2  // section
  getItemsByPartTypeAndContent 3  // Cautions
  getItemsByPartTypeAndContent 4  // Notes
  getItemsByPartTypeAndContent 5  // RNOs
  getItemsByPartTypeAndContent 6  // Steps
 */

CREATE PROCEDURE [dbo].[getItemsByPartTypeAndContent](@FromType int)

WITH EXECUTE AS OWNER
AS
	SELECT
		ii.[ItemID],
		[PreviousID],
		ii.[ContentID],
		ii.[DTS],
		ii.[UserID],
		ii.[LastChanged],
		C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=ii.[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=ii.[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=ii.[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=ii.[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=ii.[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=ii.[ItemID]) [Transition_ToIDCount],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[C].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[C].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[C].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[C].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[C].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[C].[ContentID]) [cPartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[C].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[C].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[C].[ContentID]) [ZContentCount]
	FROM [Items] ii
	JOIN [Parts] pp on pp.ItemID = ii.ItemID
	JOIN [Contents] C on C.ContentID = ii.ContentID
	WHERE pp.Fromtype = @FromType
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getItemsByPartTypeAndContent Succeeded'
ELSE PRINT 'Procedure Creation: getItemsByPartTypeAndContent Error on Creation'
GO

/****** Object:  StoredProcedure [getJustRODb] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getJustRODb]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getJustRODb];
GO
	
CREATE PROCEDURE [dbo].[getJustRODb]

(
	@RODbID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[RODbID],
		[ROName],
		[FolderPath],
		[DBConnectionString],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [DROUsages] WHERE [DROUsages].[RODbID]=[RODbs].[RODbID]) [DROUsageCount],
		(SELECT COUNT(*) FROM [ROFsts] WHERE [ROFsts].[RODbID]=[RODbs].[RODbID]) [ROFstCount],
		(SELECT COUNT(*) FROM [ROImages] WHERE [ROImages].[RODbID]=[RODbs].[RODbID]) [ROImageCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[RODbID]=[RODbs].[RODbID]) [RoUsageCount]
	FROM [RODbs]
	WHERE [RODbID]=@RODbID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getJustRODb Succeeded'
ELSE PRINT 'Procedure Creation: getJustRODb Error on Creation'
GO

/****** Object:  StoredProcedure [getLibraryDocuments] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getLibraryDocuments]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getLibraryDocuments];
GO
	
--getLibraryDocuments
CREATE PROCEDURE [dbo].[getLibraryDocuments]

WITH EXECUTE AS OWNER
AS
SELECT
[DocID],
[LibTitle],
[DocContent],
[DocAscii],
[FileExtension],
[Config],
[DTS],
[UserID],
[LastChanged],
(SELECT COUNT(*) FROM [DROUsages] WHERE [DROUsages].[DocID]=[Documents].[DocID]) [DROUsageCount],
(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[DocID]=[Documents].[DocID]) [EntryCount],
(SELECT COUNT(*) FROM [Pdfs] WHERE [Pdfs].[DocID]=[Documents].[DocID]) [PdfCount]
FROM [Documents] where [LibTitle] <> '' order by [LibTitle]
RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getLibraryDocuments Succeeded'
ELSE PRINT 'Procedure Creation: getLibraryDocuments Error on Creation'
GO

/****** Object:  StoredProcedure [getMembership] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getMembership]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getMembership];
GO
	
CREATE PROCEDURE [dbo].[getMembership]

(
	@UGID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[UGID],
		[UID],
		[GID],
		[StartDate],
		[EndDate],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged]
	FROM [Memberships]
	WHERE [UGID]=@UGID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getMembership Succeeded'
ELSE PRINT 'Procedure Creation: getMembership Error on Creation'
GO

/****** Object:  StoredProcedure [getMemberships] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getMemberships]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getMemberships];
GO
	
CREATE PROCEDURE [dbo].[getMemberships]

WITH EXECUTE AS OWNER
AS
	SELECT
		[UGID],
		[UID],
		[GID],
		[StartDate],
		[EndDate],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged]
	FROM [Memberships]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getMemberships Succeeded'
ELSE PRINT 'Procedure Creation: getMemberships Error on Creation'
GO

/****** Object:  StoredProcedure [getMembershipsByGID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getMembershipsByGID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getMembershipsByGID];
GO
	
CREATE PROCEDURE [dbo].[getMembershipsByGID]

(
	@GID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Memberships].[UGID],
		[Memberships].[UID],
		[Memberships].[GID],
		[Memberships].[StartDate],
		[Memberships].[EndDate],
		[Memberships].[Config],
		[Memberships].[DTS],
		[Memberships].[UsrID],
		[Memberships].[LastChanged],
		[Users].[UserID] [User_UserID],
		[Users].[FirstName] [User_FirstName],
		[Users].[MiddleName] [User_MiddleName],
		[Users].[LastName] [User_LastName],
		[Users].[Suffix] [User_Suffix],
		[Users].[CourtesyTitle] [User_CourtesyTitle],
		[Users].[PhoneNumber] [User_PhoneNumber],
		[Users].[CFGName] [User_CFGName],
		[Users].[UserLogin] [User_UserLogin],
		[Users].[UserName] [User_UserName],
		[Users].[Config] [User_Config],
		[Users].[DTS] [User_DTS],
		[Users].[UsrID] [User_UsrID]
	FROM [Memberships]
		JOIN [Users]  ON
			[Users].[UID]=[Memberships].[UID]
	WHERE
		[Memberships].[GID]=@GID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getMembershipsByGID Succeeded'
ELSE PRINT 'Procedure Creation: getMembershipsByGID Error on Creation'
GO

/****** Object:  StoredProcedure [getMembershipsByUID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getMembershipsByUID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getMembershipsByUID];
GO
	
CREATE PROCEDURE [dbo].[getMembershipsByUID]

(
	@UID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Memberships].[UGID],
		[Memberships].[UID],
		[Memberships].[GID],
		[Memberships].[StartDate],
		[Memberships].[EndDate],
		[Memberships].[Config],
		[Memberships].[DTS],
		[Memberships].[UsrID],
		[Memberships].[LastChanged],
		[Groups].[GroupName] [Group_GroupName],
		[Groups].[GroupType] [Group_GroupType],
		[Groups].[Config] [Group_Config],
		[Groups].[DTS] [Group_DTS],
		[Groups].[UsrID] [Group_UsrID]
	FROM [Memberships]
		JOIN [Groups]  ON
			[Groups].[GID]=[Memberships].[GID]
	WHERE
		[Memberships].[UID]=@UID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getMembershipsByUID Succeeded'
ELSE PRINT 'Procedure Creation: getMembershipsByUID Error on Creation'
GO

/****** Object:  StoredProcedure [getNextItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getNextItems]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getNextItems];
GO
	
CREATE PROCEDURE [dbo].[getNextItems]

(
	@PreviousID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ItemID],
		[PreviousID],
		[ContentID],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[Items].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[Items].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[Items].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[Items].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[Items].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[Items].[ItemID]) [Transition_ToIDCount]
	FROM [Items] WHERE [PreviousID]=@PreviousID AND [ItemID]<>@PreviousID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getNextItems Succeeded'
ELSE PRINT 'Procedure Creation: getNextItems Error on Creation'
GO

/****** Object:  StoredProcedure [getParentFolder] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getParentFolder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getParentFolder];
GO
	
CREATE PROCEDURE [dbo].[getParentFolder]
(
	@ParentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FolderID],
		[ParentID],
		[DBID],
		[Name],
		[Title],
		[ShortName],
		[FormatID],
		[ManualOrder],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[FolderID]=[Folders].[FolderID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FolderID]=[Folders].[FolderID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] [Children] WHERE [Children].[ParentID]=[Folders].[FolderID]) [ChildCount]
	FROM [Folders]
	WHERE
		[FolderID]=@ParentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getParentFolder Succeeded'
ELSE PRINT 'Procedure Creation: getParentFolder Error on Creation'
GO

/****** Object:  StoredProcedure [getParentFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getParentFormat]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getParentFormat];
GO
	
CREATE PROCEDURE [dbo].[getParentFormat]
(
	@ParentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[FormatID],
		[ParentID],
		[Name],
		[Description],
		[Data],
		[GenMac],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Contents] WHERE [Contents].[FormatID]=[Formats].[FormatID]) [ContentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FormatID]=[Formats].[FormatID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] WHERE [Folders].[FormatID]=[Formats].[FormatID]) [FolderCount],
		(SELECT COUNT(*) FROM [Formats] [Children] WHERE [Children].[ParentID]=[Formats].[FormatID]) [ChildCount]
	FROM [Formats]
	WHERE
		[FormatID]=@ParentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getParentFormat Succeeded'
ELSE PRINT 'Procedure Creation: getParentFormat Error on Creation'
GO

/****** Object:  StoredProcedure [getPart] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPart]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPart];
GO
	
CREATE PROCEDURE [dbo].[getPart]

(
	@ContentID int,
	@FromType int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[FromType],
		[ItemID],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Parts]
	WHERE [ContentID]=@ContentID AND [FromType]=@FromType
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPart Succeeded'
ELSE PRINT 'Procedure Creation: getPart Error on Creation'
GO

/****** Object:  StoredProcedure [getPartAudit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPartAudit]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPartAudit];
GO
	
CREATE PROCEDURE [dbo].[getPartAudit]

(
	@AuditID bigint
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[FromType],
		[ItemID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [PartAudits]
	WHERE [AuditID]=@AuditID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPartAudit Succeeded'
ELSE PRINT 'Procedure Creation: getPartAudit Error on Creation'
GO

/****** Object:  StoredProcedure [getPartAudits] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPartAudits]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPartAudits];
GO
	
CREATE PROCEDURE [dbo].[getPartAudits]

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[FromType],
		[ItemID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [PartAudits]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPartAudits Succeeded'
ELSE PRINT 'Procedure Creation: getPartAudits Error on Creation'
GO

/****** Object:  StoredProcedure [getPartAuditsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPartAuditsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPartAuditsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getPartAuditsByContentID]
(
	@ContentID int
)

WITH EXECUTE AS OWNER
AS
	SELECT
		[AuditID],
		[ContentID],
		[FromType],
		[ItemID],
		[DTS],
		[UserID],
		[DeleteStatus]
	FROM [PartAudits]
	WHERE ContentID = @ContentID
	ORDER BY AuditID DESC
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPartAuditsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getPartAuditsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getParts] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getParts]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getParts];
GO
	
CREATE PROCEDURE [dbo].[getParts]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[FromType],
		[ItemID],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Parts]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getParts Succeeded'
ELSE PRINT 'Procedure Creation: getParts Error on Creation'
GO

/****** Object:  StoredProcedure [getPartsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPartsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPartsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getPartsByContentID]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Parts].[ContentID],
		[Parts].[FromType],
		[Parts].[ItemID],
		[Parts].[DTS],
		[Parts].[UserID],
		[Parts].[LastChanged],
		[Items].[PreviousID] [Item_PreviousID],
		[Items].[ContentID] [Item_ContentID],
		[Items].[DTS] [Item_DTS],
		[Items].[UserID] [Item_UserID]
	FROM [Parts]
		JOIN [Items]  ON
			[Items].[ItemID]=[Parts].[ItemID]
	WHERE
		[Parts].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPartsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getPartsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getPartsByItemID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPartsByItemID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPartsByItemID];
GO
	
CREATE PROCEDURE [dbo].[getPartsByItemID]

(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Parts].[ContentID],
		[Parts].[FromType],
		[Parts].[ItemID],
		[Parts].[DTS],
		[Parts].[UserID],
		[Parts].[LastChanged],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [Parts]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[Parts].[ContentID]
	WHERE
		[Parts].[ItemID]=@ItemID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPartsByItemID Succeeded'
ELSE PRINT 'Procedure Creation: getPartsByItemID Error on Creation'
GO

/****** Object:  StoredProcedure [getPastedAffectedTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPastedAffectedTransitions]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPastedAffectedTransitions];
GO
	
CREATE PROCEDURE [dbo].[getPastedAffectedTransitions]
(
	@ItemID int
)
WITH EXECUTE AS OWNER
AS

SELECT
		TT.[TransitionID],
		[FromID],
		[ToID],
		[RangeID],
		[IsRange],
		[TranType],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=TT.[TransitionID]) [ZTransitionCount]
FROM [Transitions] TT join vefn_ChildItems(@ItemID) CC on CC.ContentID = TT.FromID
RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPastedAffectedTransitions Succeeded'
ELSE PRINT 'Procedure Creation: getPastedAffectedTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [getPdf] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPdf]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPdf];
GO
	
CREATE PROCEDURE [dbo].[getPdf]

(
	@DocID int,
	@DebugStatus int,
	@TopRow int,
	@PageLength int,
	@LeftMargin int,
	@PageWidth int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[DocID],
		[DebugStatus],
		[TopRow],
		[PageLength],
		[LeftMargin],
		[PageWidth],
		[PageCount],
		[DocPdf],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Pdfs]
	WHERE [DocID]=@DocID AND [DebugStatus]=@DebugStatus AND [TopRow]=@TopRow AND [PageLength]=@PageLength AND [LeftMargin]=@LeftMargin AND [PageWidth]=@PageWidth
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPdf Succeeded'
ELSE PRINT 'Procedure Creation: getPdf Error on Creation'
GO

/****** Object:  StoredProcedure [getPdfs] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPdfs]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPdfs];
GO
	
CREATE PROCEDURE [dbo].[getPdfs]

WITH EXECUTE AS OWNER
AS
	SELECT
		[DocID],
		[DebugStatus],
		[TopRow],
		[PageLength],
		[LeftMargin],
		[PageWidth],
		[PageCount],
		[DocPdf],
		[DTS],
		[UserID],
		[LastChanged]
	FROM [Pdfs]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPdfs Succeeded'
ELSE PRINT 'Procedure Creation: getPdfs Error on Creation'
GO

/****** Object:  StoredProcedure [getPdfsByDocID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPdfsByDocID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPdfsByDocID];
GO
	
CREATE PROCEDURE [dbo].[getPdfsByDocID]

(
	@DocID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Pdfs].[DocID],
		[Pdfs].[DebugStatus],
		[Pdfs].[TopRow],
		[Pdfs].[PageLength],
		[Pdfs].[LeftMargin],
		[Pdfs].[PageWidth],
		[Pdfs].[PageCount],
		[Pdfs].[DocPdf],
		[Pdfs].[DTS],
		[Pdfs].[UserID],
		[Pdfs].[LastChanged]
	FROM [Pdfs]
	WHERE
		[Pdfs].[DocID]=@DocID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPdfsByDocID Succeeded'
ELSE PRINT 'Procedure Creation: getPdfsByDocID Error on Creation'
GO

/****** Object:  StoredProcedure [getPermission] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPermission]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPermission];
GO
	
CREATE PROCEDURE [dbo].[getPermission]

(
	@PID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[PID],
		[RID],
		[PermLevel],
		[VersionType],
		[PermValue],
		[PermAD],
		[StartDate],
		[EndDate],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged]
	FROM [Permissions]
	WHERE [PID]=@PID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPermission Succeeded'
ELSE PRINT 'Procedure Creation: getPermission Error on Creation'
GO

/****** Object:  StoredProcedure [getPermissions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPermissions]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPermissions];
GO
	
CREATE PROCEDURE [dbo].[getPermissions]

WITH EXECUTE AS OWNER
AS
	SELECT
		[PID],
		[RID],
		[PermLevel],
		[VersionType],
		[PermValue],
		[PermAD],
		[StartDate],
		[EndDate],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged]
	FROM [Permissions]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPermissions Succeeded'
ELSE PRINT 'Procedure Creation: getPermissions Error on Creation'
GO

/****** Object:  StoredProcedure [getPermissionsByRID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPermissionsByRID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPermissionsByRID];
GO
	
CREATE PROCEDURE [dbo].[getPermissionsByRID]

(
	@RID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Permissions].[PID],
		[Permissions].[RID],
		[Permissions].[PermLevel],
		[Permissions].[VersionType],
		[Permissions].[PermValue],
		[Permissions].[PermAD],
		[Permissions].[StartDate],
		[Permissions].[EndDate],
		[Permissions].[Config],
		[Permissions].[DTS],
		[Permissions].[UsrID],
		[Permissions].[LastChanged]
	FROM [Permissions]
	WHERE
		[Permissions].[RID]=@RID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPermissionsByRID Succeeded'
ELSE PRINT 'Procedure Creation: getPermissionsByRID Error on Creation'
GO

/****** Object:  StoredProcedure [getPreviousItem] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getPreviousItem]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getPreviousItem];
GO
	
CREATE PROCEDURE [dbo].[getPreviousItem]
(
	@PreviousID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ItemID],
		[PreviousID],
		[ContentID],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[Items].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[Items].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[Items].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[Items].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[Items].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[Items].[ItemID]) [Transition_ToIDCount]
	FROM [Items]
	WHERE
		[ItemID]=@PreviousID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getPreviousItem Succeeded'
ELSE PRINT 'Procedure Creation: getPreviousItem Error on Creation'
GO

/****** Object:  StoredProcedure [getRODb] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRODb]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRODb];
GO
	
CREATE PROCEDURE [dbo].[getRODb]

(
	@RODbID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[RODbID],
		[ROName],
		[FolderPath],
		[DBConnectionString],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [DROUsages] WHERE [DROUsages].[RODbID]=[RODbs].[RODbID]) [DROUsageCount],
		(SELECT COUNT(*) FROM [ROFsts] WHERE [ROFsts].[RODbID]=[RODbs].[RODbID]) [ROFstCount],
		(SELECT COUNT(*) FROM [ROImages] WHERE [ROImages].[RODbID]=[RODbs].[RODbID]) [ROImageCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[RODbID]=[RODbs].[RODbID]) [RoUsageCount]
	FROM [RODbs]
	WHERE [RODbID]=@RODbID

	SELECT
		[DROUsages].[DROUsageID],
		[DROUsages].[DocID],
		[DROUsages].[ROID],
		[DROUsages].[Config],
		[DROUsages].[DTS],
		[DROUsages].[UserID],
		[DROUsages].[LastChanged],
		[DROUsages].[RODbID],
		[Documents].[LibTitle] [Document_LibTitle],
		[Documents].[DocContent] [Document_DocContent],
		[Documents].[DocAscii] [Document_DocAscii],
		[Documents].[Config] [Document_Config],
		[Documents].[DTS] [Document_DTS],
		[Documents].[UserID] [Document_UserID],
		[Documents].[FileExtension] [Document_FileExtension]
	FROM [DROUsages]
		JOIN [Documents]  ON
			[Documents].[DocID]=[DROUsages].[DocID]
	WHERE
		[DROUsages].[RODbID]=@RODbID


	SELECT
		[ROFsts].[ROFstID],
		[ROFsts].[RODbID],
		[ROFsts].[ROLookup],
		[ROFsts].[Config],
		[ROFsts].[DTS],
		[ROFsts].[UserID],
		[ROFsts].[LastChanged]
	FROM [ROFsts]
	WHERE
		[ROFsts].[RODbID]=@RODbID


	SELECT
		[ROImages].[ImageID],
		[ROImages].[RODbID],
		[ROImages].[FileName],
		[ROImages].[Content],
		[ROImages].[Config],
		[ROImages].[DTS],
		[ROImages].[UserID],
		[ROImages].[LastChanged]
	FROM [ROImages]
	WHERE
		[ROImages].[RODbID]=@RODbID


	SELECT
		[RoUsages].[ROUsageID],
		[RoUsages].[ContentID],
		[RoUsages].[ROID],
		[RoUsages].[Config],
		[RoUsages].[DTS],
		[RoUsages].[UserID],
		[RoUsages].[LastChanged],
		[RoUsages].[RODbID],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [RoUsages]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[RoUsages].[ContentID]
	WHERE
		[RoUsages].[RODbID]=@RODbID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRODb Succeeded'
ELSE PRINT 'Procedure Creation: getRODb Error on Creation'
GO

/****** Object:  StoredProcedure [getRODbByFolderPath] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRODbByFolderPath]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRODbByFolderPath];
GO
	
CREATE PROCEDURE [dbo].[getRODbByFolderPath]
(
	@FolderPath nvarchar(255)
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[RODbID],
		[ROName],
		[FolderPath],
		[DBConnectionString],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [DROUsages] WHERE [DROUsages].[RODbID]=[RODbs].[RODbID]) [DROUsageCount],
		(SELECT COUNT(*) FROM [ROFsts] WHERE [ROFsts].[RODbID]=[RODbs].[RODbID]) [ROFstCount],
		(SELECT COUNT(*) FROM [ROImages] WHERE [ROImages].[RODbID]=[RODbs].[RODbID]) [ROImageCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[RODbID]=[RODbs].[RODbID]) [RoUsageCount]
	FROM [RODbs]
	WHERE [FolderPath]=@FolderPath
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRODbByFolderPath Succeeded'
ELSE PRINT 'Procedure Creation: getRODbByFolderPath Error on Creation'
GO

/****** Object:  StoredProcedure [getRODbs] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRODbs]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRODbs];
GO
	
CREATE PROCEDURE [dbo].[getRODbs]

WITH EXECUTE AS OWNER
AS
	SELECT
		[RODbID],
		[ROName],
		[FolderPath],
		[DBConnectionString],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [DROUsages] WHERE [DROUsages].[RODbID]=[RODbs].[RODbID]) [DROUsageCount],
		(SELECT COUNT(*) FROM [ROFsts] WHERE [ROFsts].[RODbID]=[RODbs].[RODbID]) [ROFstCount],
		(SELECT COUNT(*) FROM [ROImages] WHERE [ROImages].[RODbID]=[RODbs].[RODbID]) [ROImageCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[RODbID]=[RODbs].[RODbID]) [RoUsageCount]
	FROM [RODbs]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRODbs Succeeded'
ELSE PRINT 'Procedure Creation: getRODbs Error on Creation'
GO

/****** Object:  StoredProcedure [getROFst] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROFst]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROFst];
GO
	
CREATE PROCEDURE [dbo].[getROFst]

(
	@ROFstID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ROFstID],
		[RODbID],
		[ROLookup],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[ROFstID]=[ROFsts].[ROFstID]) [AssociationCount],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ROFstID]=[ROFsts].[ROFstID]) [FigureCount]
	FROM [ROFsts]
	WHERE [ROFstID]=@ROFstID

	SELECT
		[Associations].[AssociationID],
		[Associations].[VersionID],
		[Associations].[ROFstID],
		[Associations].[Config],
		[Associations].[DTS],
		[Associations].[UserID],
		[Associations].[LastChanged],
		[DocVersions].[FolderID] [DocVersion_FolderID],
		[DocVersions].[VersionType] [DocVersion_VersionType],
		[DocVersions].[Name] [DocVersion_Name],
		[DocVersions].[Title] [DocVersion_Title],
		[DocVersions].[ItemID] [DocVersion_ItemID],
		[DocVersions].[FormatID] [DocVersion_FormatID],
		[DocVersions].[Config] [DocVersion_Config],
		[DocVersions].[DTS] [DocVersion_DTS],
		[DocVersions].[UserID] [DocVersion_UserID]
	FROM [Associations]
		JOIN [DocVersions]  ON
			[DocVersions].[VersionID]=[Associations].[VersionID]
	WHERE
		[Associations].[ROFstID]=@ROFstID


	SELECT
		[Figures].[FigureID],
		[Figures].[ROFstID],
		[Figures].[ImageID],
		[Figures].[Config],
		[Figures].[DTS],
		[Figures].[UserID],
		[Figures].[LastChanged],
		[ROImages].[RODbID] [ROImage_RODbID],
		[ROImages].[FileName] [ROImage_FileName],
		[ROImages].[Content] [ROImage_Content],
		[ROImages].[Config] [ROImage_Config],
		[ROImages].[DTS] [ROImage_DTS],
		[ROImages].[UserID] [ROImage_UserID]
	FROM [Figures]
		JOIN [ROImages]  ON
			[ROImages].[ImageID]=[Figures].[ImageID]
	WHERE
		[Figures].[ROFstID]=@ROFstID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROFst Succeeded'
ELSE PRINT 'Procedure Creation: getROFst Error on Creation'
GO

/****** Object:  StoredProcedure [getROFstByRODbID_DTS] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROFstByRODbID_DTS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROFstByRODbID_DTS];
GO
	
CREATE PROCEDURE [dbo].[getROFstByRODbID_DTS]
(
	@RODbID int,
	@DTS datetime
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ROFstID],
		[RODbID],
		[ROLookup],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[ROFstID]=[ROFsts].[ROFstID]) [AssociationCount],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ROFstID]=[ROFsts].[ROFstID]) [FigureCount]
	FROM [ROFsts]
	WHERE [RODbID]=@RODbID AND [DTS]=@DTS
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROFstByRODbID_DTS Succeeded'
ELSE PRINT 'Procedure Creation: getROFstByRODbID_DTS Error on Creation'
GO

/****** Object:  StoredProcedure [getRoFstBySize] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRoFstBySize]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRoFstBySize];
GO
	
/*
getRoFstBySize 1,74928
 */	
create PROCEDURE [dbo].[getRoFstBySize]
(
	@RODbID int,
	@Len int
)
WITH EXECUTE AS OWNER
AS
select
	[ROFstID],
		[RODbID],
		[ROLookup],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[ROFstID]=[ROFsts].[ROFstID]) [AssociationCount],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ROFstID]=[ROFsts].[ROFstID]) [FigureCount]
from [ROFsts]
where len(rolookup) = @len and [RODbID] = @RODbID
RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRoFstBySize Succeeded'
ELSE PRINT 'Procedure Creation: getRoFstBySize Error on Creation'
GO

/****** Object:  StoredProcedure [getROFsts] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROFsts]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROFsts];
GO
	
CREATE PROCEDURE [dbo].[getROFsts]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ROFstID],
		[RODbID],
		[ROLookup],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[ROFstID]=[ROFsts].[ROFstID]) [AssociationCount],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ROFstID]=[ROFsts].[ROFstID]) [FigureCount]
	FROM [ROFsts]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROFsts Succeeded'
ELSE PRINT 'Procedure Creation: getROFsts Error on Creation'
GO

/****** Object:  StoredProcedure [getROFstsByRODbID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROFstsByRODbID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROFstsByRODbID];
GO
	
CREATE PROCEDURE [dbo].[getROFstsByRODbID]

(
	@RODbID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[ROFsts].[ROFstID],
		[ROFsts].[RODbID],
		[ROFsts].[ROLookup],
		[ROFsts].[Config],
		[ROFsts].[DTS],
		[ROFsts].[UserID],
		[ROFsts].[LastChanged],
		(SELECT COUNT(*) FROM [Associations] WHERE [Associations].[ROFstID]=[ROFsts].[ROFstID]) [AssociationCount],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ROFstID]=[ROFsts].[ROFstID]) [FigureCount]
	FROM [ROFsts]
	WHERE
		[ROFsts].[RODbID]=@RODbID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROFstsByRODbID Succeeded'
ELSE PRINT 'Procedure Creation: getROFstsByRODbID Error on Creation'
GO

/****** Object:  StoredProcedure [getROImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROImage];
GO
	
CREATE PROCEDURE [dbo].[getROImage]

(
	@ImageID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ImageID],
		[RODbID],
		[FileName],
		[Content],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ImageID]=[ROImages].[ImageID]) [FigureCount]
	FROM [ROImages]
	WHERE [ImageID]=@ImageID

	SELECT
		[Figures].[FigureID],
		[Figures].[ROFstID],
		[Figures].[ImageID],
		[Figures].[Config],
		[Figures].[DTS],
		[Figures].[UserID],
		[Figures].[LastChanged],
		[ROFsts].[RODbID] [ROFst_RODbID],
		[ROFsts].[ROLookup] [ROFst_ROLookup],
		[ROFsts].[Config] [ROFst_Config],
		[ROFsts].[DTS] [ROFst_DTS],
		[ROFsts].[UserID] [ROFst_UserID]
	FROM [Figures]
		JOIN [ROFsts]  ON
			[ROFsts].[ROFstID]=[Figures].[ROFstID]
	WHERE
		[Figures].[ImageID]=@ImageID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROImage Succeeded'
ELSE PRINT 'Procedure Creation: getROImage Error on Creation'
GO

/****** Object:  StoredProcedure [getROImageByRODbID_FileName_DTS] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROImageByRODbID_FileName_DTS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROImageByRODbID_FileName_DTS];
GO
	
CREATE PROCEDURE [dbo].[getROImageByRODbID_FileName_DTS]
(
	@RODbID int,
	@FileName nvarchar(255),
	@DTS datetime
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ImageID],
		[RODbID],
		[FileName],
		[Content],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ImageID]=[ROImages].[ImageID]) [FigureCount]
	FROM [ROImages]
	WHERE [RODbID]=@RODbID AND [FileName]=@FileName AND [DTS]=@DTS
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROImageByRODbID_FileName_DTS Succeeded'
ELSE PRINT 'Procedure Creation: getROImageByRODbID_FileName_DTS Error on Creation'
GO

/****** Object:  StoredProcedure [getROImageByROFstID_FileName] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROImageByROFstID_FileName]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROImageByROFstID_FileName];
GO
	
CREATE PROCEDURE [dbo].[getROImageByROFstID_FileName]

(
	@ROFstID int,
	@FileName nvarchar(255)
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[ImageID],
		[RODbID],
		[FileName],
		[Content],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ImageID]=[ROImages].[ImageID]) [FigureCount]
		FROM [ROImages]
		--JOIN [Figures]  ON
		--	[Figures].[ImageID]=[ROImages].[ImageID]
	WHERE
		[ImageID] in (select ImageID from Figures where ROFstID=@ROFstID) AND
		[ROImages].[FileName]=@FileName

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROImageByROFstID_FileName Succeeded'
ELSE PRINT 'Procedure Creation: getROImageByROFstID_FileName Error on Creation'
GO

/****** Object:  StoredProcedure [getROImages] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROImages]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROImages];
GO
	
CREATE PROCEDURE [dbo].[getROImages]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ImageID],
		[RODbID],
		[FileName],
		[Content],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ImageID]=[ROImages].[ImageID]) [FigureCount]
	FROM [ROImages]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROImages Succeeded'
ELSE PRINT 'Procedure Creation: getROImages Error on Creation'
GO

/****** Object:  StoredProcedure [getROImagesByRODbID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getROImagesByRODbID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getROImagesByRODbID];
GO
	
CREATE PROCEDURE [dbo].[getROImagesByRODbID]

(
	@RODbID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[ROImages].[ImageID],
		[ROImages].[RODbID],
		[ROImages].[FileName],
		[ROImages].[Content],
		[ROImages].[Config],
		[ROImages].[DTS],
		[ROImages].[UserID],
		[ROImages].[LastChanged],
		(SELECT COUNT(*) FROM [Figures] WHERE [Figures].[ImageID]=[ROImages].[ImageID]) [FigureCount]
	FROM [ROImages]
	WHERE
		[ROImages].[RODbID]=@RODbID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getROImagesByRODbID Succeeded'
ELSE PRINT 'Procedure Creation: getROImagesByRODbID Error on Creation'
GO

/****** Object:  StoredProcedure [getRole] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRole];
GO
	
CREATE PROCEDURE [dbo].[getRole]

(
	@RID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[RID],
		[Name],
		[Title],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[RID]=[Roles].[RID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [Permissions] WHERE [Permissions].[RID]=[Roles].[RID]) [PermissionCount]
	FROM [Roles]
	WHERE [RID]=@RID

	SELECT
		[Assignments].[AID],
		[Assignments].[GID],
		[Assignments].[RID],
		[Assignments].[FolderID],
		[Assignments].[StartDate],
		[Assignments].[EndDate],
		[Assignments].[DTS],
		[Assignments].[UsrID],
		[Assignments].[LastChanged],
		[Folders].[ParentID] [Folder_ParentID],
		[Folders].[DBID] [Folder_DBID],
		[Folders].[Name] [Folder_Name],
		[Folders].[Title] [Folder_Title],
		[Folders].[ShortName] [Folder_ShortName],
		[Folders].[FormatID] [Folder_FormatID],
		[Folders].[ManualOrder] [Folder_ManualOrder],
		[Folders].[Config] [Folder_Config],
		[Folders].[DTS] [Folder_DTS],
		[Folders].[UsrID] [Folder_UsrID],
		[Groups].[GroupName] [Group_GroupName],
		[Groups].[GroupType] [Group_GroupType],
		[Groups].[Config] [Group_Config],
		[Groups].[DTS] [Group_DTS],
		[Groups].[UsrID] [Group_UsrID]
	FROM [Assignments]
		JOIN [Folders]  ON
			[Folders].[FolderID]=[Assignments].[FolderID]
		JOIN [Groups]  ON
			[Groups].[GID]=[Assignments].[GID]
	WHERE
		[Assignments].[RID]=@RID


	SELECT
		[Permissions].[PID],
		[Permissions].[RID],
		[Permissions].[PermLevel],
		[Permissions].[VersionType],
		[Permissions].[PermValue],
		[Permissions].[PermAD],
		[Permissions].[StartDate],
		[Permissions].[EndDate],
		[Permissions].[Config],
		[Permissions].[DTS],
		[Permissions].[UsrID],
		[Permissions].[LastChanged]
	FROM [Permissions]
	WHERE
		[Permissions].[RID]=@RID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRole Succeeded'
ELSE PRINT 'Procedure Creation: getRole Error on Creation'
GO

/****** Object:  StoredProcedure [getRoleByName] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRoleByName]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRoleByName];
GO
	
CREATE PROCEDURE [dbo].[getRoleByName]
(
	@Name nvarchar(50)
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[RID],
		[Name],
		[Title],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[RID]=[Roles].[RID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [Permissions] WHERE [Permissions].[RID]=[Roles].[RID]) [PermissionCount]
	FROM [Roles]
	WHERE [Name]=@Name
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRoleByName Succeeded'
ELSE PRINT 'Procedure Creation: getRoleByName Error on Creation'
GO

/****** Object:  StoredProcedure [getRoles] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRoles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRoles];
GO
	
CREATE PROCEDURE [dbo].[getRoles]

WITH EXECUTE AS OWNER
AS
	SELECT
		[RID],
		[Name],
		[Title],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[RID]=[Roles].[RID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [Permissions] WHERE [Permissions].[RID]=[Roles].[RID]) [PermissionCount]
	FROM [Roles]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRoles Succeeded'
ELSE PRINT 'Procedure Creation: getRoles Error on Creation'
GO

/****** Object:  StoredProcedure [getRoUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRoUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRoUsage];
GO
	
CREATE PROCEDURE [dbo].[getRoUsage]

(
	@ROUsageID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ROUsageID],
		[ContentID],
		[ROID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		[RODbID]
	FROM [RoUsages]
	WHERE [ROUsageID]=@ROUsageID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRoUsage Succeeded'
ELSE PRINT 'Procedure Creation: getRoUsage Error on Creation'
GO

/****** Object:  StoredProcedure [getRoUsages] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRoUsages]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRoUsages];
GO
	
CREATE PROCEDURE [dbo].[getRoUsages]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ROUsageID],
		[ContentID],
		[ROID],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		[RODbID]
	FROM [RoUsages]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRoUsages Succeeded'
ELSE PRINT 'Procedure Creation: getRoUsages Error on Creation'
GO

/****** Object:  StoredProcedure [getRoUsagesByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRoUsagesByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRoUsagesByContentID];
GO
	
CREATE PROCEDURE [dbo].[getRoUsagesByContentID]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[RoUsages].[ROUsageID],
		[RoUsages].[ContentID],
		[RoUsages].[ROID],
		[RoUsages].[Config],
		[RoUsages].[DTS],
		[RoUsages].[UserID],
		[RoUsages].[LastChanged],
		[RoUsages].[RODbID],
		[RODbs].[ROName] [RODb_ROName],
		[RODbs].[FolderPath] [RODb_FolderPath],
		[RODbs].[DBConnectionString] [RODb_DBConnectionString],
		[RODbs].[Config] [RODb_Config],
		[RODbs].[DTS] [RODb_DTS],
		[RODbs].[UserID] [RODb_UserID]
	FROM [RoUsages]
		JOIN [RODbs]  ON
			[RODbs].[RODbID]=[RoUsages].[RODbID]
	WHERE
		[RoUsages].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRoUsagesByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getRoUsagesByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getRoUsagesByRODbID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getRoUsagesByRODbID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getRoUsagesByRODbID];
GO
	
CREATE PROCEDURE [dbo].[getRoUsagesByRODbID]

(
	@RODbID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[RoUsages].[ROUsageID],
		[RoUsages].[ContentID],
		[RoUsages].[ROID],
		[RoUsages].[Config],
		[RoUsages].[DTS],
		[RoUsages].[UserID],
		[RoUsages].[LastChanged],
		[RoUsages].[RODbID],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID]
	FROM [RoUsages]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[RoUsages].[ContentID]
	WHERE
		[RoUsages].[RODbID]=@RODbID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getRoUsagesByRODbID Succeeded'
ELSE PRINT 'Procedure Creation: getRoUsagesByRODbID Error on Creation'
GO

/****** Object:  StoredProcedure [getTopFolder] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getTopFolder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getTopFolder];
GO
	
CREATE PROCEDURE [dbo].[getTopFolder]
WITH EXECUTE AS OWNER
AS
	SELECT
		[FolderID],
		[ParentID],
		[DBID],
		[Name],
		[Title],
		[ShortName],
		[FormatID],
		[ManualOrder],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Assignments] WHERE [Assignments].[FolderID]=[Folders].[FolderID]) [AssignmentCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[FolderID]=[Folders].[FolderID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Folders] [Children] WHERE [Children].[ParentID]=[Folders].[FolderID]) [ChildCount]
	FROM [Folders]
	WHERE [FolderID]=[ParentID]

	SELECT
		[Assignments].[AID],
		[Assignments].[GID],
		[Assignments].[RID],
		[Assignments].[FolderID],
		[Assignments].[StartDate],
		[Assignments].[EndDate],
		[Assignments].[DTS],
		[Assignments].[UsrID],
		[Assignments].[LastChanged],
		[Groups].[GroupName] [Group_GroupName],
		[Groups].[GroupType] [Group_GroupType],
		[Groups].[Config] [Group_Config],
		[Groups].[DTS] [Group_DTS],
		[Groups].[UsrID] [Group_UsrID],
		[Roles].[Name] [Role_Name],
		[Roles].[Title] [Role_Title],
		[Roles].[DTS] [Role_DTS],
		[Roles].[UsrID] [Role_UsrID]
	FROM [Assignments]
		JOIN [Groups]  ON
			[Groups].[GID]=[Assignments].[GID]
		JOIN [Roles]  ON
			[Roles].[RID]=[Assignments].[RID]
	WHERE
		[Assignments].[FolderID]=(Select [FolderID] from [Folders] where [FolderID]=[ParentID])


	SELECT
		[DocVersions].[VersionID],
		[DocVersions].[FolderID],
		[DocVersions].[VersionType],
		[DocVersions].[Name],
		[DocVersions].[Title],
		[DocVersions].[ItemID],
		[DocVersions].[FormatID],
		[DocVersions].[Config],
		[DocVersions].[DTS],
		[DocVersions].[UserID],
		[DocVersions].[LastChanged]
	FROM [DocVersions]
	WHERE
		[DocVersions].[FolderID]=(Select [FolderID] from [Folders] where [FolderID]=[ParentID])

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getTopFolder Succeeded'
ELSE PRINT 'Procedure Creation: getTopFolder Error on Creation'
GO

/****** Object:  StoredProcedure [getTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getTransition];
GO
	
CREATE PROCEDURE [dbo].[getTransition]

(
	@TransitionID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[TransitionID],
		[FromID],
		[ToID],
		[RangeID],
		[IsRange],
		[TranType],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=[Transitions].[TransitionID]) [ZTransitionCount]
	FROM [Transitions]
	WHERE [TransitionID]=@TransitionID

	SELECT
		[ZTransitions].[TransitionID],
		[ZTransitions].[oldto],
		[ZTransitions].[LastChanged]
	FROM [ZTransitions]
	WHERE
		[ZTransitions].[TransitionID]=@TransitionID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getTransition Succeeded'
ELSE PRINT 'Procedure Creation: getTransition Error on Creation'
GO

/****** Object:  StoredProcedure [getTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getTransitions]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getTransitions];
GO
	
CREATE PROCEDURE [dbo].[getTransitions]

WITH EXECUTE AS OWNER
AS
	SELECT
		[TransitionID],
		[FromID],
		[ToID],
		[RangeID],
		[IsRange],
		[TranType],
		[Config],
		[DTS],
		[UserID],
		[LastChanged],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=[Transitions].[TransitionID]) [ZTransitionCount]
	FROM [Transitions]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getTransitions Succeeded'
ELSE PRINT 'Procedure Creation: getTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [getTransitionsByFromID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getTransitionsByFromID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getTransitionsByFromID];
GO
	
CREATE PROCEDURE [dbo].[getTransitionsByFromID]

(
	@FromID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Transitions].[TransitionID],
		[Transitions].[FromID],
		[Transitions].[ToID],
		[Transitions].[RangeID],
		[Transitions].[IsRange],
		[Transitions].[TranType],
		[Transitions].[Config],
		[Transitions].[DTS],
		[Transitions].[UserID],
		[Transitions].[LastChanged],
		[Items_RangeID].[PreviousID] [Item_RangeID_PreviousID],
		[Items_RangeID].[ContentID] [Item_RangeID_ContentID],
		[Items_RangeID].[DTS] [Item_RangeID_DTS],
		[Items_RangeID].[UserID] [Item_RangeID_UserID],
		[Items_ToID].[PreviousID] [Item_ToID_PreviousID],
		[Items_ToID].[ContentID] [Item_ToID_ContentID],
		[Items_ToID].[DTS] [Item_ToID_DTS],
		[Items_ToID].[UserID] [Item_ToID_UserID],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=[Transitions].[TransitionID]) [ZTransitionCount]
	FROM [Transitions]
		JOIN [Items] [Items_RangeID] ON
			[Items_RangeID].[ItemID]=[Transitions].[RangeID]
		JOIN [Items] [Items_ToID] ON
			[Items_ToID].[ItemID]=[Transitions].[ToID]
	WHERE
		[Transitions].[FromID]=@FromID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getTransitionsByFromID Succeeded'
ELSE PRINT 'Procedure Creation: getTransitionsByFromID Error on Creation'
GO

/****** Object:  StoredProcedure [getTransitionsByRangeID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getTransitionsByRangeID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getTransitionsByRangeID];
GO
	
CREATE PROCEDURE [dbo].[getTransitionsByRangeID]

(
	@RangeID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Transitions].[TransitionID],
		[Transitions].[FromID],
		[Transitions].[ToID],
		[Transitions].[RangeID],
		[Transitions].[IsRange],
		[Transitions].[TranType],
		[Transitions].[Config],
		[Transitions].[DTS],
		[Transitions].[UserID],
		[Transitions].[LastChanged],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=[Transitions].[TransitionID]) [ZTransitionCount]
	FROM [Transitions]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[Transitions].[FromID]
	WHERE
		[Transitions].[RangeID]=@RangeID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getTransitionsByRangeID Succeeded'
ELSE PRINT 'Procedure Creation: getTransitionsByRangeID Error on Creation'
GO

/****** Object:  StoredProcedure [getTransitionsByToID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getTransitionsByToID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getTransitionsByToID];
GO
	
CREATE PROCEDURE [dbo].[getTransitionsByToID]

(
	@ToID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[Transitions].[TransitionID],
		[Transitions].[FromID],
		[Transitions].[ToID],
		[Transitions].[RangeID],
		[Transitions].[IsRange],
		[Transitions].[TranType],
		[Transitions].[Config],
		[Transitions].[DTS],
		[Transitions].[UserID],
		[Transitions].[LastChanged],
		[Contents].[Number] [Content_Number],
		[Contents].[Text] [Content_Text],
		[Contents].[Type] [Content_Type],
		[Contents].[FormatID] [Content_FormatID],
		[Contents].[Config] [Content_Config],
		[Contents].[DTS] [Content_DTS],
		[Contents].[UserID] [Content_UserID],
		(SELECT COUNT(*) FROM [ZTransitions] WHERE [ZTransitions].[TransitionID]=[Transitions].[TransitionID]) [ZTransitionCount]
	FROM [Transitions]
		JOIN [Contents]  ON
			[Contents].[ContentID]=[Transitions].[FromID]
	WHERE
		[Transitions].[ToID]=@ToID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getTransitionsByToID Succeeded'
ELSE PRINT 'Procedure Creation: getTransitionsByToID Error on Creation'
GO

/****** Object:  StoredProcedure [getUser] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getUser];
GO
	
CREATE PROCEDURE [dbo].[getUser]

(
	@UID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[UID],
		[UserID],
		[FirstName],
		[MiddleName],
		[LastName],
		[Suffix],
		[CourtesyTitle],
		[PhoneNumber],
		[CFGName],
		[UserLogin],
		[UserName],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Memberships] WHERE [Memberships].[UID]=[Users].[UID]) [MembershipCount]
	FROM [Users]
	WHERE [UID]=@UID

	SELECT
		[Memberships].[UGID],
		[Memberships].[UID],
		[Memberships].[GID],
		[Memberships].[StartDate],
		[Memberships].[EndDate],
		[Memberships].[Config],
		[Memberships].[DTS],
		[Memberships].[UsrID],
		[Memberships].[LastChanged],
		[Groups].[GroupName] [Group_GroupName],
		[Groups].[GroupType] [Group_GroupType],
		[Groups].[Config] [Group_Config],
		[Groups].[DTS] [Group_DTS],
		[Groups].[UsrID] [Group_UsrID]
	FROM [Memberships]
		JOIN [Groups]  ON
			[Groups].[GID]=[Memberships].[GID]
	WHERE
		[Memberships].[UID]=@UID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getUser Succeeded'
ELSE PRINT 'Procedure Creation: getUser Error on Creation'
GO

/****** Object:  StoredProcedure [getUsers] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getUsers]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getUsers];
GO
	
CREATE PROCEDURE [dbo].[getUsers]

WITH EXECUTE AS OWNER
AS
	SELECT
		[UID],
		[UserID],
		[FirstName],
		[MiddleName],
		[LastName],
		[Suffix],
		[CourtesyTitle],
		[PhoneNumber],
		[CFGName],
		[UserLogin],
		[UserName],
		[Config],
		[DTS],
		[UsrID],
		[LastChanged],
		(SELECT COUNT(*) FROM [Memberships] WHERE [Memberships].[UID]=[Users].[UID]) [MembershipCount]
	FROM [Users]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getUsers Succeeded'
ELSE PRINT 'Procedure Creation: getUsers Error on Creation'
GO

/****** Object:  StoredProcedure [getZContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getZContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getZContent];
GO
	
CREATE PROCEDURE [dbo].[getZContent]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[OldStepSequence],
		[LastChanged]
	FROM [ZContents]
	WHERE [ContentID]=@ContentID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getZContent Succeeded'
ELSE PRINT 'Procedure Creation: getZContent Error on Creation'
GO

/****** Object:  StoredProcedure [getZContents] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getZContents]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getZContents];
GO
	
CREATE PROCEDURE [dbo].[getZContents]

WITH EXECUTE AS OWNER
AS
	SELECT
		[ContentID],
		[OldStepSequence],
		[LastChanged]
	FROM [ZContents]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getZContents Succeeded'
ELSE PRINT 'Procedure Creation: getZContents Error on Creation'
GO

/****** Object:  StoredProcedure [getZContentsByContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getZContentsByContentID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getZContentsByContentID];
GO
	
CREATE PROCEDURE [dbo].[getZContentsByContentID]

(
	@ContentID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[ZContents].[ContentID],
		[ZContents].[OldStepSequence],
		[ZContents].[LastChanged]
	FROM [ZContents]
	WHERE
		[ZContents].[ContentID]=@ContentID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getZContentsByContentID Succeeded'
ELSE PRINT 'Procedure Creation: getZContentsByContentID Error on Creation'
GO

/****** Object:  StoredProcedure [getZTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getZTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getZTransition];
GO
	
CREATE PROCEDURE [dbo].[getZTransition]

(
	@TransitionID int
)
WITH EXECUTE AS OWNER
AS
	SELECT
		[TransitionID],
		[oldto],
		[LastChanged]
	FROM [ZTransitions]
	WHERE [TransitionID]=@TransitionID
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getZTransition Succeeded'
ELSE PRINT 'Procedure Creation: getZTransition Error on Creation'
GO

/****** Object:  StoredProcedure [getZTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getZTransitions]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getZTransitions];
GO
	
CREATE PROCEDURE [dbo].[getZTransitions]

WITH EXECUTE AS OWNER
AS
	SELECT
		[TransitionID],
		[oldto],
		[LastChanged]
	FROM [ZTransitions]
	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getZTransitions Succeeded'
ELSE PRINT 'Procedure Creation: getZTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [getZTransitionsByTransitionID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getZTransitionsByTransitionID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [getZTransitionsByTransitionID];
GO
	
CREATE PROCEDURE [dbo].[getZTransitionsByTransitionID]

(
	@TransitionID int
)
WITH EXECUTE AS OWNER
AS

	SELECT
		[ZTransitions].[TransitionID],
		[ZTransitions].[oldto],
		[ZTransitions].[LastChanged]
	FROM [ZTransitions]
	WHERE
		[ZTransitions].[TransitionID]=@TransitionID

	RETURN
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getZTransitionsByTransitionID Succeeded'
ELSE PRINT 'Procedure Creation: getZTransitionsByTransitionID Error on Creation'
GO

/****** Object:  StoredProcedure [PasteItemReplace] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[PasteItemReplace]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [PasteItemReplace];
GO
	
-- ItemID is item to replace
-- StartItemID is item to copy	
CREATE PROCEDURE [dbo].[PasteItemReplace]
(
	@ItemID int=null,	@StartItemID int=null,
	@Type int=null, @DTS datetime,	@UserID nvarchar(100),
	@NewItemID int output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
		DECLARE @ContentID AS INT
		DECLARE @NextItemID AS INT
		DECLARE @PreviousItemID AS INT
		DECLARE @ExternalChildCount AS INT
		DECLARE @ExternalCount AS INT
		DECLARE @Path AS VARCHAR(MAX)
		DECLARE @Children AS TABLE
		(
			ItemID INT PRIMARY KEY,
			ContentID INT
		)
		
		-- First check if the replaced item can be deleted, i.e. it doesn't have transitions
		-- pointing to it or children.

		DECLARE @ExternalTrans TABLE
		(
			[FromItemID] int,
			[TransitionID] [int] NOT NULL,
			[FromID] [int] NOT NULL,
			[ToID] [int] NOT NULL,
			[RangeID] [int] NOT NULL,
			[Config] [nvarchar](max) NULL
		)
		SET NOCOUNT ON
		SELECT @ContentID = ContentID, @PreviousItemID = PreviousID FROM Items WHERE ItemID = @ItemID
		SELECT @NextItemID = ItemID FROM Items WHERE PreviousID = @ItemID
		--SELECT @ExternalCount = count(*) FROM vefn_FindExternalTransitions(@ItemID)
		SELECT @ExternalChildCount = count(*) FROM vefn_FindExternalChildTransitions(@ItemID)
		SET @Path = [dbo].[ve_GetShortPath](@ItemID)

		--IF @ExternalCount > 0  AND @NextItemID is null
		--BEGIN
		--	RAISERROR ('###Cannot Delete Item###Step %d has External Transitions and has no next step - (%s)',16,1,@ItemID,@Path)
		--	RETURN
		--END

		IF @ExternalChildCount > 0
		BEGIN
			RAISERROR ('###Cannot Delete Item###Step %d has External Transitions to it''s children - (%s)',16,1,@ItemID,@Path)
			RETURN
		END

		-- Copy the item, 'NewItemID' represents the new item(s)
		-- DestFormatID is the formatid for the destination parent's format
		DECLARE @DestFormatID int
		SET @DestFormatID = .dbo.vefn_GetInheritedFormat(@ItemID, 0)
		EXECUTE CopyItemAndChildren @StartItemID, @DestFormatID, @UserID, @NewItemID OUTPUT

		-- Adjust the next/previous to point to the new item
		
		DECLARE @PreviousID int
		SELECT @PreviousID = [PreviousID]
			FROM [ITEMS] II
			WHERE [ItemID]=@ItemID
		UPDATE [ITEMS] SET [PreviousID]=@PreviousID where [ItemID]=@NewItemID
		UPDATE [CONTENTS] SET [Type]=@Type
			FROM [CONTENTS] CC JOIN [ITEMS] ii ON CC.[ContentID]=II.[ContentID]
			WHERE [ItemID]=@NewItemID
		UPDATE [ITEMS] SET [PreviousID]=@NewItemID where [PreviousID]=@ItemID
		UPDATE [PARTS] SET [ItemID]=@NewItemID where [ItemID]=@ItemID
		
		-- UPDATE DocVersion if this was a procedure
		UPDATE DocVersions SET ItemID=@NewItemID where ItemID = @ItemID
		
		-- If there were 'external transitions' that pointed to the original
		-- top replaced step, adjust them to point to the new top.
		INSERT INTO @ExternalTrans SELECT * FROM vefn_FindExternalTransitions(@ItemID)
		IF (SELECT COUNT(*) from @ExternalTrans) > 0
		BEGIN
			-- Update content records for the transitions
			Update CC
				Set Text = DBO.vefn_FixTransitionText(Text,TT.TransitionID,TT.TranType,TT.ToID,TT.RangeID,@ItemID,@NewItemID)
			From CONTENTS CC
				JOIN Transitions TT ON TT.FromID = CC.ContentID
				WHERE TransitionID in(Select TransitionID from @ExternalTrans)
			-- Update transitions that point to @ItemID to Point to @NextItemID
			UPDATE TRANSITIONS
				SET ToID = case when ToID = @ItemID then @NewItemID else ToID END,
				RangeID = case when RangeID = @ItemID then @NewItemID else RangeID END
				WHERE TransitionID in(Select TransitionID from @ExternalTrans)

			DECLARE @typeID int -- AnnotationType
			SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
			IF(@typeID IS NULL)
			BEGIN
				INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
				SELECT @typeID = SCOPE_IDENTITY()
			END
			-- Add 'Verification Required' annotions for transtions that pointed to top step
			-- and need to point to
			INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])	
			SELECT ItemID, @typeID,'Verify Replaced Step Transition Destination',@UserID
				FROM Items where ItemID in (SELECT FromItemID FROM @ExternalTrans)

		END
		-- Remove the old one
		
		-- Get list of Children
		INSERT INTO @Children SELECT * FROM vefn_ChildItems(@ItemID)
		-- Delete Annotations for @ItemID and children
		DELETE from Annotations where ItemID in(Select ItemID from @Children)
		-- Delete Details associated with @ContentID and children
		DELETE from Details where ContentID in(Select ContentID from @Children)
		-- Delete Grids associated with @ContentID and children
		DELETE from Grids where ContentID in(Select ContentID from @Children)
		-- Delete Images associated with @ContentID and children
		DELETE from Images where ContentID in(Select ContentID from @Children)
		-- Delete Entries associated with @ContentID and children
		DELETE from Entries where ContentID in(Select ContentID from @Children)
		-- Delete ROUsages associated with @ContentID and children
		DELETE from RoUsages where ContentID in(Select ContentID from @Children)
		-- Delete ZTransitions records associated with @ContentID and children
		DELETE FROM ZTransitions where TransitionID
			in(SELECT TransitionID from Transitions where FromID in(SELECT ContentID FROM @Children) or FromID = @ContentID)
		-- Delete Transitions associated with @ContentID and children
		DELETE FROM Transitions where FromID in(SELECT ContentID FROM @Children) or FromID = @ContentID
		-- Delete Parts associated with @ContentID and children
		DELETE from Parts where ContentID in(Select ContentID from @Children)
		-- Delete ZContents associated with @ContentID and children
		DELETE from ZContents where ContentID in(Select ContentID from @Children)
		-- Disconnect Items from Each Other
		DELETE from Items where ItemID in(Select ItemID from @Children) and PreviousID Is Not Null
		-- Disconnect Items to be deleted from each other
		Update Items set PreviousID = null where ItemID in (Select ItemID from @Children) and PreviousID Is Not Null
		-- Delete Item Records
		DELETE from Items where ItemID in(Select ItemID from @Children)
		-- DELETE Contents
		DELETE from Contents where ContentID in(Select ContentID from @Children)
	IF( @@TRANCOUNT > 0 ) COMMIT
	EXECUTE GetItem @NewItemID
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: PasteItemReplace Succeeded'
ELSE PRINT 'Procedure Creation: PasteItemReplace Error on Creation'
GO

/****** Object:  StoredProcedure [PasteItemSiblingAfter] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[PasteItemSiblingAfter]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [PasteItemSiblingAfter];
GO
	
CREATE PROCEDURE [dbo].[PasteItemSiblingAfter]
(
	@ItemID int=null,	@StartItemID int=null,		-- ItemID is destination, StartItemID is top of copy
	@Type int=null, @DTS datetime,	@UserID nvarchar(100),
	@NewItemID int output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	-- First make a copy of the input StartItemID
	-- DestFormatID is the formatid for the destination parent's format
	DECLARE @DestFormatID int
	SET @DestFormatID = .dbo.vefn_GetInheritedFormat(@ItemID, 0)
	EXECUTE CopyItemAndChildren @StartItemID, @DestFormatID, @UserID, @NewItemID OUTPUT
	-- Adjust previous field
	DECLARE @NextID int
	SELECT @NextID = [ItemID]
		FROM [ITEMS]
		WHERE [PreviousID]=@ItemID
	IF @NextID is not null  -- step after the copy point. Adjust it's previous to point to the new step
	BEGIN
		UPDATE [ITEMS] SET [PreviousID]=@NewItemID, [DTS]=@DTS, [UserID]=@UserID where [ItemID]=@NextID
	END
	UPDATE [ITEMS] SET [PreviousID]=@ItemID where [ItemID]=@NewItemID
	UPDATE [CONTENTS] SET [Type]=@Type
		FROM [CONTENTS] CC JOIN [ITEMS] ii ON CC.[ContentID]=II.[ContentID]
		WHERE [ItemID]=@NewItemID
	

  -- Check for Transitions that point to the Next Step
  BEGIN
		-- Get a list of Transitions which need to change children of @ItemID that point to @NextID
		DECLARE @NextStepTransitions TABLE
		(
			[TransitionID] int PRIMARY KEY,
			[FromID] [int],
			[ToID] [int],
			[RangeID] [int],
			[TranType] [int],
			[Config] [nvarchar](max)
		)
		Insert into @NextStepTransitions select * from vefn_NextStepTransitions(@NextID,@ItemID)
		IF (SELECT COUNT(*) from @NextStepTransitions) > 0 -- Next Step Transitions
		BEGIN
			-- Update all transitions in the list to point to @newItemID
			Update TT
				Set TT.ToID = CASE TT.ToID WHEN @NextID THEN @NewItemID ELSE TT.ToID END,
					TT.RangeID = CASE TT.RangeID WHEN @NextID THEN @NewItemID ELSE TT.RangeID END
			From TRANSITIONS TT
				JOIN @NextStepTransitions NS ON NS.TransitionID = TT.TransitionID
			-- Update content records for the transitions
			Update CC
				Set Text = DBO.vefn_FixTransitionText(Text,NS.TransitionID,NS.TranType,NS.ToID,NS.RangeID,@NextID,@NewItemID)
			From CONTENTS CC
				JOIN @NextStepTransitions NS ON NS.FromID = CC.ContentID
		END
	END
  -- Add 'Verification Required' AnnotationType
	DECLARE @typeID int
	SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
	IF(@typeID IS NULL)
	BEGIN
		INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
		SELECT @typeID = SCOPE_IDENTITY()
	END
	-- Add "Verification Required" Annotation for each Transition that points to @newItemID or @NextID
	INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT ItemID, @typeID,'Verify Next Step Transition Destination',@UserID
		FROM Items where CONTENTID in (SELECT FromID FROM TRANSITIONS
		where ToID IN(@newItemID) OR RangeID IN(@newItemID))
	INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT ItemID, @typeID,'Verify Transition Destination',@UserID
		FROM Items where CONTENTID in (SELECT FromID FROM TRANSITIONS
		where ToID IN(@NextID) OR RangeID IN(@NextID))
  -- Transition Text gets updated in ItemInsertExt.cs

	IF( @@TRANCOUNT > 0 ) COMMIT
	EXECUTE GetItem @NewItemID
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: PasteItemSiblingAfter Succeeded'
ELSE PRINT 'Procedure Creation: PasteItemSiblingAfter Error on Creation'
GO

/****** Object:  StoredProcedure [PasteItemSiblingBefore] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[PasteItemSiblingBefore]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [PasteItemSiblingBefore];
GO
	
CREATE PROCEDURE [dbo].[PasteItemSiblingBefore]
(
	@ItemID int=null,	@StartItemID int=null,
	@Type int=null, @DTS datetime,	@UserID nvarchar(100),
	@NewItemID int output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	-- First make a copy of the input CopyStartID
	-- DestFormatID is the formatid for the destination parent's format
	DECLARE @DestFormatID int
	SET @DestFormatID = .dbo.vefn_GetInheritedFormat(@ItemID, 0)
	EXECUTE CopyItemAndChildren @StartItemID, @DestFormatID, @UserID, @NewItemID OUTPUT
	-- First adjust previous fields, may also have to do parts, if before first one in list.
	DECLARE @PreviousID int, @ContentID int,	@newLastChanged timestamp, @NewType int
	SELECT @PreviousID = [PreviousID], @NewType=ISNULL(@Type,[Type])
		FROM [ITEMS] II
		JOIN [CONTENTS] CC ON CC.[ContentID]=II.[CONTENTID]
		WHERE [ItemID]=@ItemID
  UPDATE [ITEMS] SET [PreviousID]=@NewItemID where [ItemID]=@ItemID
  UPDATE [ITEMS] SET [PreviousID]=@PreviousID where [ItemID]=@NewItemID
  UPDATE [CONTENTS] SET [Type]=@Type
		FROM [CONTENTS] CC JOIN [ITEMS] ii ON CC.[ContentID]=II.[ContentID]
		WHERE [ItemID]=@NewItemID
  UPDATE [PARTS] SET [ItemID]=@NewItemID where [ItemID]=@ItemID
  UPDATE [DOCVERSIONS] SET [ItemID] = @NewItemID where [ItemID]=@ItemID

  IF @PreviousID is null -- The step is replacing the first step
  BEGIN
		-- Update content records for the transitions
		Update CC
			Set Text = DBO.vefn_FixTransitionText(Text,TT.TransitionID,TT.TranType,TT.ToID,TT.RangeID,@ItemID,@NewItemID)
		From CONTENTS CC
			JOIN Transitions TT ON TT.FromID = CC.ContentID
			WHERE TT.ToID = @ItemID OR TT.RangeID = @ItemID
		-- Update transitions that pointed to @ItemID to point to @newItemID
		Update TRANSITIONS
			Set ToID = CASE ToID WHEN @ItemID THEN @NewItemID ELSE ToID END,
				RangeID = CASE RangeID WHEN @ItemID THEN @NewItemID ELSE RangeID END
				WHERE ToID = @ItemID OR RangeID = @ItemID
  END
  ELSE -- Check for Transitions that point to the Next Step
  BEGIN
		-- Get a list of Transitions which need to change children of @ItemID that point to @NextID
		DECLARE @NextStepTransitions TABLE
		(
			[TransitionID] int PRIMARY KEY,
			[FromID] [int],
			[ToID] [int],
			[RangeID] [int],
			[TranType] [int],
			[Config] [nvarchar](max)
		)
		Insert into @NextStepTransitions select * from vefn_NextStepTransitions(@ItemID,@PreviousID)
		IF (SELECT COUNT(*) from @NextStepTransitions) > 0 -- Next Step Transitions
		BEGIN
			-- Update all transitions in the list to point to @newItemID
			Update TT
				Set TT.ToID = CASE TT.ToID WHEN @ItemID THEN @NewItemID ELSE TT.ToID END,
					TT.RangeID = CASE TT.RangeID WHEN @ItemID THEN @NewItemID ELSE TT.RangeID END
			From TRANSITIONS TT
				JOIN @NextStepTransitions NS ON NS.TransitionID = TT.TransitionID
			-- Update content records for the transitions
			Update CC
				Set Text = DBO.vefn_FixTransitionText(Text,NS.TransitionID,NS.TranType,NS.ToID,NS.RangeID,@ItemID,@NewItemID)
			From CONTENTS CC
				JOIN @NextStepTransitions NS ON NS.FromID = CC.ContentID
		END
	END
  -- Add 'Verification Required' AnnotationType
	DECLARE @typeID int
	SELECT @typeID = TypeID from AnnotationTypes where Name = 'Verification Required'
	IF(@typeID IS NULL)
	BEGIN
		INSERT INTO [AnnotationTypes]	([Name],[UserID])	VALUES	('Verification Required','Volian')
		SELECT @typeID = SCOPE_IDENTITY()
	END
  -- Add "Verification Required" Annotation for each Transition that points to @newItemID or @NextID
	INSERT INTO [Annotations] ([ItemID],[TypeID],[SearchText],[UserID])
		SELECT ItemID, @typeID,'Verify Transition Destination',@UserID
		FROM Items where CONTENTID in (SELECT FromID FROM TRANSITIONS
		where ToID IN(@ItemID,@NewItemID) OR RangeID IN(@ItemID,@NewItemID))
  -- Transition Text gets updated in ItemInsertExt.cs
	IF( @@TRANCOUNT > 0 ) COMMIT
	EXECUTE GetItem @NewItemID
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: PasteItemSiblingBefore Succeeded'
ELSE PRINT 'Procedure Creation: PasteItemSiblingBefore Error on Creation'
GO

/****** Object:  StoredProcedure [purgeData] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[purgeData]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [purgeData];
GO
	
CREATE PROCEDURE [dbo].[purgeData]

WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	delete from [Annotations]
	dbcc checkident([Annotations],reseed,0)
	delete from [AnnotationTypes]
	dbcc checkident([AnnotationTypes],reseed,0)
	delete from [Assignments]
	dbcc checkident([Assignments],reseed,0)
	delete from [Associations]
	dbcc checkident([Associations],reseed,0)
	delete from [Details]
	dbcc checkident([Details],reseed,0)
	delete from [DocVersions]
	dbcc checkident([DocVersions],reseed,0)
	delete from [DROUsages]
	dbcc checkident([DROUsages],reseed,0)
	delete from [Entries]
	delete from [Figures]
	dbcc checkident([Figures],reseed,0)
	delete from [Folders]
	dbcc checkident([Folders],reseed,0)
	delete from [Grids]
	delete from [Images]
	delete from [Memberships]
	dbcc checkident([Memberships],reseed,0)
	delete from [Parts]
	delete from [Pdfs]
	delete from [Permissions]
	dbcc checkident([Permissions],reseed,0)
	delete from [ROFsts]
	dbcc checkident([ROFsts],reseed,0)
	delete from [ROImages]
	dbcc checkident([ROImages],reseed,0)
	delete from [Roles]
	dbcc checkident([Roles],reseed,0)
	delete from [RoUsages]
	dbcc checkident([RoUsages],reseed,0)
	delete from [Users]
	dbcc checkident([Users],reseed,0)
	delete from [ZContents]
	delete from [ZTransitions]
	delete from [Connections]
	dbcc checkident([Connections],reseed,0)
	delete from [Documents]
	dbcc checkident([Documents],reseed,0)
	delete from [Groups]
	dbcc checkident([Groups],reseed,0)
	delete from [RODbs]
	dbcc checkident([RODbs],reseed,0)
	delete from [Transitions]
	dbcc checkident([Transitions],reseed,0)
	delete from [Items]
	dbcc checkident([Items],reseed,0)
	delete from [Contents]
	dbcc checkident([Contents],reseed,0)
	delete from [Formats]
	dbcc checkident([Formats],reseed,0)
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: purgeData Succeeded'
ELSE PRINT 'Procedure Creation: purgeData Error on Creation'
GO

/****** Object:  StoredProcedure [updateAnnotation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateAnnotation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateAnnotation];
GO
	
CREATE PROCEDURE [dbo].[updateAnnotation]

(
	@AnnotationID int,
	@ItemID int,
	@TypeID int,
	@RtfText nvarchar(MAX)=null,
	@SearchText nvarchar(MAX)=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Annotations]
		SET
			[ItemID]=@ItemID,
			[TypeID]=@TypeID,
			[RtfText]=@RtfText,
			[SearchText]=@SearchText,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [AnnotationID]=@AnnotationID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Annotations] WHERE [AnnotationID]=@AnnotationID)
			RAISERROR('Annotation record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Annotation has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Annotations] WHERE [AnnotationID]=@AnnotationID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateAnnotation Succeeded'
ELSE PRINT 'Procedure Creation: updateAnnotation Error on Creation'
GO

/****** Object:  StoredProcedure [updateAnnotationType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateAnnotationType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateAnnotationType];
GO
	
CREATE PROCEDURE [dbo].[updateAnnotationType]

(
	@TypeID int,
	@Name nvarchar(100),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [AnnotationTypes]
		SET
			[Name]=@Name,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [TypeID]=@TypeID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [AnnotationTypes] WHERE [TypeID]=@TypeID)
			RAISERROR('AnnotationType record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('AnnotationType has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [AnnotationTypes] WHERE [TypeID]=@TypeID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateAnnotationType Succeeded'
ELSE PRINT 'Procedure Creation: updateAnnotationType Error on Creation'
GO

/****** Object:  StoredProcedure [updateAssignment] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateAssignment]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateAssignment];
GO
	
CREATE PROCEDURE [dbo].[updateAssignment]

(
	@AID int,
	@GID int,
	@RID int,
	@FolderID int,
	@StartDate datetime,
	@EndDate datetime=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Assignments]
		SET
			[GID]=@GID,
			[RID]=@RID,
			[FolderID]=@FolderID,
			[StartDate]=@StartDate,
			[EndDate]=@EndDate,
			[DTS]=@DTS,
			[UsrID]=@UsrID
		WHERE [AID]=@AID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Assignments] WHERE [AID]=@AID)
			RAISERROR('Assignment record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Assignment has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Assignments] WHERE [AID]=@AID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateAssignment Succeeded'
ELSE PRINT 'Procedure Creation: updateAssignment Error on Creation'
GO

/****** Object:  StoredProcedure [updateAssociation] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateAssociation]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateAssociation];
GO
	
CREATE PROCEDURE [dbo].[updateAssociation]

(
	@AssociationID int,
	@VersionID int,
	@ROFstID int,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Associations]
		SET
			[VersionID]=@VersionID,
			[ROFstID]=@ROFstID,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [AssociationID]=@AssociationID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Associations] WHERE [AssociationID]=@AssociationID)
			RAISERROR('Association record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Association has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Associations] WHERE [AssociationID]=@AssociationID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateAssociation Succeeded'
ELSE PRINT 'Procedure Creation: updateAssociation Error on Creation'
GO

/****** Object:  StoredProcedure [updateConnection] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateConnection]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateConnection];
GO
	
CREATE PROCEDURE [dbo].[updateConnection]

(
	@DBID int,
	@Name nvarchar(100)=null,
	@Title nvarchar(510)=null,
	@ConnectionString nvarchar(510)=null,
	@ServerType int,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Connections]
		SET
			[Name]=@Name,
			[Title]=@Title,
			[ConnectionString]=@ConnectionString,
			[ServerType]=@ServerType,
			[Config]=@Config,
			[DTS]=@DTS,
			[UsrID]=@UsrID
		WHERE [DBID]=@DBID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Connections] WHERE [DBID]=@DBID)
			RAISERROR('Connection record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Connection has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Connections] WHERE [DBID]=@DBID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateConnection Succeeded'
ELSE PRINT 'Procedure Creation: updateConnection Error on Creation'
GO

/****** Object:  StoredProcedure [updateContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateContent];
GO
	
CREATE PROCEDURE [dbo].[updateContent]

(
	@ContentID int,
	@Number nvarchar(256)=null,
	@Text nvarchar(MAX)=null,
	@Type int=null,
	@FormatID int=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Contents]
		SET
			[Number]=@Number,
			[Text]=@Text,
			[Type]=@Type,
			[FormatID]=@FormatID,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [ContentID]=@ContentID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Contents] WHERE [ContentID]=@ContentID)
			RAISERROR('Content record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Content has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Contents] WHERE [ContentID]=@ContentID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateContent Succeeded'
ELSE PRINT 'Procedure Creation: updateContent Error on Creation'
GO

/****** Object:  StoredProcedure [updateDetail] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateDetail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateDetail];
GO
	
CREATE PROCEDURE [dbo].[updateDetail]

(
	@DetailID int,
	@ContentID int,
	@ItemType int,
	@Text nvarchar(MAX),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Details]
		SET
			[ContentID]=@ContentID,
			[ItemType]=@ItemType,
			[Text]=@Text,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [DetailID]=@DetailID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Details] WHERE [DetailID]=@DetailID)
			RAISERROR('Detail record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Detail has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Details] WHERE [DetailID]=@DetailID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateDetail Succeeded'
ELSE PRINT 'Procedure Creation: updateDetail Error on Creation'
GO

/****** Object:  StoredProcedure [updateDocument] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateDocument]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateDocument];
GO
	
CREATE PROCEDURE [dbo].[updateDocument]

(
	@DocID int,
	@LibTitle nvarchar(1024)=null,
	@DocContent varbinary(MAX)=null,
	@DocAscii nvarchar(MAX)=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@FileExtension nvarchar(10),
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Documents]
		SET
			[LibTitle]=@LibTitle,
			[DocContent]=@DocContent,
			[DocAscii]=@DocAscii,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID,
			[FileExtension]=@FileExtension
		WHERE [DocID]=@DocID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Documents] WHERE [DocID]=@DocID)
			RAISERROR('Document record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Document has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Documents] WHERE [DocID]=@DocID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateDocument Succeeded'
ELSE PRINT 'Procedure Creation: updateDocument Error on Creation'
GO

/****** Object:  StoredProcedure [updateDocVersion] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateDocVersion]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateDocVersion];
GO
	
CREATE PROCEDURE [dbo].[updateDocVersion]

(
	@VersionID int,
	@FolderID int,
	@VersionType int,
	@Name nvarchar(100),
	@Title nvarchar(510)=null,
	@ItemID int=null,
	@FormatID int=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [DocVersions]
		SET
			[FolderID]=@FolderID,
			[VersionType]=@VersionType,
			[Name]=@Name,
			[Title]=@Title,
			[ItemID]=@ItemID,
			[FormatID]=@FormatID,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [VersionID]=@VersionID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [DocVersions] WHERE [VersionID]=@VersionID)
			RAISERROR('DocVersion record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('DocVersion has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [DocVersions] WHERE [VersionID]=@VersionID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateDocVersion Succeeded'
ELSE PRINT 'Procedure Creation: updateDocVersion Error on Creation'
GO

/****** Object:  StoredProcedure [updateDROUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateDROUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateDROUsage];
GO
	
CREATE PROCEDURE [dbo].[updateDROUsage]

(
	@DROUsageID int,
	@DocID int,
	@ROID nvarchar(16),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@RODbID int,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [DROUsages]
		SET
			[DocID]=@DocID,
			[ROID]=@ROID,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID,
			[RODbID]=@RODbID
		WHERE [DROUsageID]=@DROUsageID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [DROUsages] WHERE [DROUsageID]=@DROUsageID)
			RAISERROR('DROUsage record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('DROUsage has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [DROUsages] WHERE [DROUsageID]=@DROUsageID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateDROUsage Succeeded'
ELSE PRINT 'Procedure Creation: updateDROUsage Error on Creation'
GO

/****** Object:  StoredProcedure [updateEntry] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateEntry]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateEntry];
GO
	
CREATE PROCEDURE [dbo].[updateEntry]

(
	@ContentID int,
	@DocID int,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Entries]
		SET
			[DocID]=@DocID,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [ContentID]=@ContentID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Entries] WHERE [ContentID]=@ContentID)
			RAISERROR('Entry record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Entry has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Entries] WHERE [ContentID]=@ContentID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateEntry Succeeded'
ELSE PRINT 'Procedure Creation: updateEntry Error on Creation'
GO

/****** Object:  StoredProcedure [updateFigure] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateFigure]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateFigure];
GO
	
CREATE PROCEDURE [dbo].[updateFigure]

(
	@FigureID int,
	@ROFstID int,
	@ImageID int,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Figures]
		SET
			[ROFstID]=@ROFstID,
			[ImageID]=@ImageID,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [FigureID]=@FigureID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Figures] WHERE [FigureID]=@FigureID)
			RAISERROR('Figure record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Figure has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Figures] WHERE [FigureID]=@FigureID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateFigure Succeeded'
ELSE PRINT 'Procedure Creation: updateFigure Error on Creation'
GO

/****** Object:  StoredProcedure [updateFolder] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateFolder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateFolder];
GO
	
CREATE PROCEDURE [dbo].[updateFolder]

(
	@FolderID int,
	@ParentID int,
	@DBID int,
	@Name nvarchar(100),
	@Title nvarchar(510)=null,
	@ShortName nvarchar(20),
	@FormatID int=null,
	@ManualOrder float=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Folders]
		SET
			[ParentID]=@ParentID,
			[DBID]=@DBID,
			[Name]=@Name,
			[Title]=@Title,
			[ShortName]=@ShortName,
			[FormatID]=@FormatID,
			[ManualOrder]=@ManualOrder,
			[Config]=@Config,
			[DTS]=@DTS,
			[UsrID]=@UsrID
		WHERE [FolderID]=@FolderID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Folders] WHERE [FolderID]=@FolderID)
			RAISERROR('Folder record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Folder has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Folders] WHERE [FolderID]=@FolderID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateFolder Succeeded'
ELSE PRINT 'Procedure Creation: updateFolder Error on Creation'
GO

/****** Object:  StoredProcedure [updateFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateFormat]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateFormat];
GO
	
CREATE PROCEDURE [dbo].[updateFormat]

(
	@FormatID int,
	@ParentID int,
	@Name nvarchar(20),
	@Description nvarchar(250)=null,
	@Data xml,
	@GenMac xml=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Formats]
		SET
			[ParentID]=@ParentID,
			[Name]=@Name,
			[Description]=@Description,
			[Data]=@Data,
			[GenMac]=@GenMac,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [FormatID]=@FormatID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Formats] WHERE [FormatID]=@FormatID)
			RAISERROR('Format record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Format has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Formats] WHERE [FormatID]=@FormatID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateFormat Succeeded'
ELSE PRINT 'Procedure Creation: updateFormat Error on Creation'
GO

/****** Object:  StoredProcedure [updateGrid] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateGrid]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateGrid];
GO
	
CREATE PROCEDURE [dbo].[updateGrid]

(
	@ContentID int,
	@Data xml,
	@Config xml=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Grids]
		SET
			[Data]=@Data,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [ContentID]=@ContentID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Grids] WHERE [ContentID]=@ContentID)
			RAISERROR('Grid record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Grid has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Grids] WHERE [ContentID]=@ContentID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateGrid Succeeded'
ELSE PRINT 'Procedure Creation: updateGrid Error on Creation'
GO

/****** Object:  StoredProcedure [updateGroup] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateGroup]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateGroup];
GO
	
CREATE PROCEDURE [dbo].[updateGroup]

(
	@GID int,
	@GroupName nvarchar(50),
	@GroupType int=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Groups]
		SET
			[GroupName]=@GroupName,
			[GroupType]=@GroupType,
			[Config]=@Config,
			[DTS]=@DTS,
			[UsrID]=@UsrID
		WHERE [GID]=@GID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Groups] WHERE [GID]=@GID)
			RAISERROR('Group record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Group has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Groups] WHERE [GID]=@GID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateGroup Succeeded'
ELSE PRINT 'Procedure Creation: updateGroup Error on Creation'
GO

/****** Object:  StoredProcedure [updateImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateImage];
GO
	
CREATE PROCEDURE [dbo].[updateImage]

(
	@ContentID int,
	@ImageType int,
	@FileName nvarchar(255),
	@Data varbinary(MAX),
	@Config xml=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Images]
		SET
			[ImageType]=@ImageType,
			[FileName]=@FileName,
			[Data]=@Data,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [ContentID]=@ContentID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Images] WHERE [ContentID]=@ContentID)
			RAISERROR('Image record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Image has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Images] WHERE [ContentID]=@ContentID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateImage Succeeded'
ELSE PRINT 'Procedure Creation: updateImage Error on Creation'
GO

/****** Object:  StoredProcedure [updateItem] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateItem]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateItem];
GO
	
CREATE PROCEDURE [dbo].[updateItem]

(
	@ItemID int,
	@PreviousID int=null,
	@ContentID int,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Items]
		SET
			[PreviousID]=@PreviousID,
			[ContentID]=@ContentID,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [ItemID]=@ItemID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Items] WHERE [ItemID]=@ItemID)
			RAISERROR('Item record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Item has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Items] WHERE [ItemID]=@ItemID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateItem Succeeded'
ELSE PRINT 'Procedure Creation: updateItem Error on Creation'
GO

/****** Object:  StoredProcedure [updateMembership] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateMembership]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateMembership];
GO
	
CREATE PROCEDURE [dbo].[updateMembership]

(
	@UGID int,
	@UID int,
	@GID int,
	@StartDate datetime,
	@EndDate datetime=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Memberships]
		SET
			[UID]=@UID,
			[GID]=@GID,
			[StartDate]=@StartDate,
			[EndDate]=@EndDate,
			[Config]=@Config,
			[DTS]=@DTS,
			[UsrID]=@UsrID
		WHERE [UGID]=@UGID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Memberships] WHERE [UGID]=@UGID)
			RAISERROR('Membership record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Membership has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Memberships] WHERE [UGID]=@UGID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateMembership Succeeded'
ELSE PRINT 'Procedure Creation: updateMembership Error on Creation'
GO

/****** Object:  StoredProcedure [updatePart] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updatePart]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updatePart];
GO
	
CREATE PROCEDURE [dbo].[updatePart]

(
	@ContentID int,
	@FromType int,
	@ItemID int,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Parts]
		SET
			[ItemID]=@ItemID,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [ContentID]=@ContentID AND [FromType]=@FromType AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Parts] WHERE [ContentID]=@ContentID AND [FromType]=@FromType)
			RAISERROR('Part record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Part has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Parts] WHERE [ContentID]=@ContentID AND [FromType]=@FromType		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updatePart Succeeded'
ELSE PRINT 'Procedure Creation: updatePart Error on Creation'
GO

/****** Object:  StoredProcedure [updatePdf] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updatePdf]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updatePdf];
GO
	
CREATE PROCEDURE [dbo].[updatePdf]

(
	@DocID int,
	@DebugStatus int,
	@TopRow int,
	@PageLength int,
	@LeftMargin int,
	@PageWidth int,
	@PageCount float,
	@DocPdf varbinary(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Pdfs]
		SET
			[PageCount]=@PageCount,
			[DocPdf]=@DocPdf,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [DocID]=@DocID AND [DebugStatus]=@DebugStatus AND [TopRow]=@TopRow AND [PageLength]=@PageLength AND [LeftMargin]=@LeftMargin AND [PageWidth]=@PageWidth AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Pdfs] WHERE [DocID]=@DocID AND [DebugStatus]=@DebugStatus AND [TopRow]=@TopRow AND [PageLength]=@PageLength AND [LeftMargin]=@LeftMargin AND [PageWidth]=@PageWidth)
			RAISERROR('Pdf record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Pdf has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Pdfs] WHERE [DocID]=@DocID AND [DebugStatus]=@DebugStatus AND [TopRow]=@TopRow AND [PageLength]=@PageLength AND [LeftMargin]=@LeftMargin AND [PageWidth]=@PageWidth		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updatePdf Succeeded'
ELSE PRINT 'Procedure Creation: updatePdf Error on Creation'
GO

/****** Object:  StoredProcedure [updatePermission] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updatePermission]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updatePermission];
GO
	
CREATE PROCEDURE [dbo].[updatePermission]

(
	@PID int,
	@RID int,
	@PermLevel int,
	@VersionType int,
	@PermValue int,
	@PermAD int,
	@StartDate datetime,
	@EndDate datetime=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Permissions]
		SET
			[RID]=@RID,
			[PermLevel]=@PermLevel,
			[VersionType]=@VersionType,
			[PermValue]=@PermValue,
			[PermAD]=@PermAD,
			[StartDate]=@StartDate,
			[EndDate]=@EndDate,
			[Config]=@Config,
			[DTS]=@DTS,
			[UsrID]=@UsrID
		WHERE [PID]=@PID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Permissions] WHERE [PID]=@PID)
			RAISERROR('Permission record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Permission has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Permissions] WHERE [PID]=@PID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updatePermission Succeeded'
ELSE PRINT 'Procedure Creation: updatePermission Error on Creation'
GO

/****** Object:  StoredProcedure [updateRODb] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateRODb]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateRODb];
GO
	
CREATE PROCEDURE [dbo].[updateRODb]

(
	@RODbID int,
	@ROName nvarchar(255),
	@FolderPath nvarchar(255),
	@DBConnectionString nvarchar(MAX),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [RODbs]
		SET
			[ROName]=@ROName,
			[FolderPath]=@FolderPath,
			[DBConnectionString]=@DBConnectionString,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [RODbID]=@RODbID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [RODbs] WHERE [RODbID]=@RODbID)
			RAISERROR('RODb record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('RODb has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [RODbs] WHERE [RODbID]=@RODbID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateRODb Succeeded'
ELSE PRINT 'Procedure Creation: updateRODb Error on Creation'
GO

/****** Object:  StoredProcedure [updateROFst] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateROFst]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateROFst];
GO
	
CREATE PROCEDURE [dbo].[updateROFst]

(
	@ROFstID int,
	@RODbID int,
	@ROLookup varbinary(MAX),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [ROFsts]
		SET
			[RODbID]=@RODbID,
			[ROLookup]=@ROLookup,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [ROFstID]=@ROFstID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [ROFsts] WHERE [ROFstID]=@ROFstID)
			RAISERROR('ROFst record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('ROFst has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [ROFsts] WHERE [ROFstID]=@ROFstID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateROFst Succeeded'
ELSE PRINT 'Procedure Creation: updateROFst Error on Creation'
GO

/****** Object:  StoredProcedure [updateROImage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateROImage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateROImage];
GO
	
CREATE PROCEDURE [dbo].[updateROImage]

(
	@ImageID int,
	@RODbID int,
	@FileName nvarchar(255),
	@Content varbinary(MAX),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [ROImages]
		SET
			[RODbID]=@RODbID,
			[FileName]=@FileName,
			[Content]=@Content,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [ImageID]=@ImageID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [ROImages] WHERE [ImageID]=@ImageID)
			RAISERROR('ROImage record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('ROImage has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [ROImages] WHERE [ImageID]=@ImageID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateROImage Succeeded'
ELSE PRINT 'Procedure Creation: updateROImage Error on Creation'
GO

/****** Object:  StoredProcedure [updateRole] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateRole];
GO
	
CREATE PROCEDURE [dbo].[updateRole]

(
	@RID int,
	@Name nvarchar(50),
	@Title nvarchar(250),
	@DTS datetime,
	@UsrID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Roles]
		SET
			[Name]=@Name,
			[Title]=@Title,
			[DTS]=@DTS,
			[UsrID]=@UsrID
		WHERE [RID]=@RID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Roles] WHERE [RID]=@RID)
			RAISERROR('Role record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Role has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Roles] WHERE [RID]=@RID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateRole Succeeded'
ELSE PRINT 'Procedure Creation: updateRole Error on Creation'
GO

/****** Object:  StoredProcedure [updateRoUsage] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateRoUsage]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateRoUsage];
GO
	
CREATE PROCEDURE [dbo].[updateRoUsage]

(
	@ROUsageID int,
	@ContentID int,
	@ROID nvarchar(16),
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@RODbID int,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [RoUsages]
		SET
			[ContentID]=@ContentID,
			[ROID]=@ROID,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID,
			[RODbID]=@RODbID
		WHERE [ROUsageID]=@ROUsageID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [RoUsages] WHERE [ROUsageID]=@ROUsageID)
			RAISERROR('RoUsage record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('RoUsage has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [RoUsages] WHERE [ROUsageID]=@ROUsageID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateRoUsage Succeeded'
ELSE PRINT 'Procedure Creation: updateRoUsage Error on Creation'
GO

/****** Object:  StoredProcedure [updateTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateTransition];
GO
	
CREATE PROCEDURE [dbo].[updateTransition]

(
	@TransitionID int,
	@FromID int,
	@ToID int,
	@RangeID int,
	@IsRange int,
	@TranType int,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UserID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Transitions]
		SET
			[FromID]=@FromID,
			[ToID]=@ToID,
			[RangeID]=@RangeID,
			[IsRange]=@IsRange,
			[TranType]=@TranType,
			[Config]=@Config,
			[DTS]=@DTS,
			[UserID]=@UserID
		WHERE [TransitionID]=@TransitionID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Transitions] WHERE [TransitionID]=@TransitionID)
			RAISERROR('Transition record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('Transition has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Transitions] WHERE [TransitionID]=@TransitionID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateTransition Succeeded'
ELSE PRINT 'Procedure Creation: updateTransition Error on Creation'
GO

/****** Object:  StoredProcedure [updateUser] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateUser];
GO
	
CREATE PROCEDURE [dbo].[updateUser]

(
	@UID int,
	@UserID nvarchar(100),
	@FirstName nvarchar(50)=null,
	@MiddleName nvarchar(50)=null,
	@LastName nvarchar(50)=null,
	@Suffix nvarchar(10)=null,
	@CourtesyTitle nvarchar(10)=null,
	@PhoneNumber nvarchar(30)=null,
	@CFGName nvarchar(8)=null,
	@UserLogin nvarchar(10)=null,
	@UserName nvarchar(32)=null,
	@Config nvarchar(MAX)=null,
	@DTS datetime,
	@UsrID nvarchar(100),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [Users]
		SET
			[UserID]=@UserID,
			[FirstName]=@FirstName,
			[MiddleName]=@MiddleName,
			[LastName]=@LastName,
			[Suffix]=@Suffix,
			[CourtesyTitle]=@CourtesyTitle,
			[PhoneNumber]=@PhoneNumber,
			[CFGName]=@CFGName,
			[UserLogin]=@UserLogin,
			[UserName]=@UserName,
			[Config]=@Config,
			[DTS]=@DTS,
			[UsrID]=@UsrID
		WHERE [UID]=@UID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [Users] WHERE [UID]=@UID)
			RAISERROR('User record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('User has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [Users] WHERE [UID]=@UID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateUser Succeeded'
ELSE PRINT 'Procedure Creation: updateUser Error on Creation'
GO

/****** Object:  StoredProcedure [updateZContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateZContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateZContent];
GO
	
CREATE PROCEDURE [dbo].[updateZContent]

(
	@ContentID int,
	@OldStepSequence nvarchar(32),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [ZContents]
		SET
			[OldStepSequence]=@OldStepSequence
		WHERE [ContentID]=@ContentID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [ZContents] WHERE [ContentID]=@ContentID)
			RAISERROR('ZContent record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('ZContent has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [ZContents] WHERE [ContentID]=@ContentID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateZContent Succeeded'
ELSE PRINT 'Procedure Creation: updateZContent Error on Creation'
GO

/****** Object:  StoredProcedure [updateZTransition] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[updateZTransition]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [updateZTransition];
GO
	
CREATE PROCEDURE [dbo].[updateZTransition]

(
	@TransitionID int,
	@Oldto nvarchar(32),
	@LastChanged timestamp,
	@newLastChanged timestamp output
)
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	UPDATE [ZTransitions]
		SET
			[oldto]=@Oldto
		WHERE [TransitionID]=@TransitionID AND [LastChanged]=@LastChanged
	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT exists(select * from [ZTransitions] WHERE [TransitionID]=@TransitionID)
			RAISERROR('ZTransition record has been deleted by another user', 16, 1)
		ELSE           	
			RAISERROR('ZTransition has been edited by another user', 16, 1)            	
	END

		SELECT 		@newLastChanged=[LastChanged]	
		FROM [ZTransitions] WHERE [TransitionID]=@TransitionID		

	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: updateZTransition Succeeded'
ELSE PRINT 'Procedure Creation: updateZTransition Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetChildCount] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetChildCount]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetChildCount];
GO
	
/*
-- Select Procedures with Children
select ItemID, dbo.ve_GetChildCount(ItemID)  ChildCount from [Items] II
Join [Contents] CC on II.ContentID = CC.ContentID and CC.Type = 0 and CC.ContentID in (Select ContentID from Parts)
order dbo.ve_GetChildCount(ItemID) desc
*/
CREATE FUNCTION [dbo].[ve_GetChildCount] (@ItemID int) RETURNS int
WITH EXECUTE AS OWNER
AS
BEGIN
declare @Count int;
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged]) as (
  Select 0 [Level], 0 [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
Select @Count = Count(*) from Itemz
OPTION (MAXRECURSION 10000)
return @Count END;
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetChildCount Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetChildCount Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetFolderPath] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetFolderPath]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetFolderPath];
GO
	
/*

Select VersionID,Name,dbo.ve_GetFolderPath(VersionID) from DocVersions order by VersionID

*/
CREATE FUNCTION [dbo].[ve_GetFolderPath] (@VersionID int) RETURNS varchar(MAX)
WITH EXECUTE AS OWNER
AS
BEGIN
declare @Path varchar(MAX);
with Folderz(Level, FolderID, Path) as (
  Select 1 Level, FolderID,CAST(Name as varchar(MAX))
    from DocVersions I
	  where VersionID = @VersionID
  Union All
--
  Select FS.ParentID - (Select ParentID from Folders where FolderID = FS.ParentID), ParentID, CAST(Name + char(7) + Path as varchar(MAX))
	from Folders FS
  join Folderz FZ on FS.FolderID = FZ.FolderID
  where FS.FolderID <> FS.ParentID
)
select @Path = path From Folderz where Level = 0
return @Path
END;
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetFolderPath Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetFolderPath Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetNextTranCount] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetNextTranCount]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetNextTranCount];
GO
	
/*
select dbo.ve_GetNextTranCount(251) NextTrans
select *, dbo.ve_GetNextTranCount(ItemID) NextTrans from vefn_AllHighLevelSteps()
Order By dbo.ve_GetNextTranCount(ItemID) DESC

		Select count(*) from Transitions TT
		join contents CC on TT.FromID = CC.ContentID
		where FromID in (Select ContentID from vefn_ChildItems(247))
		AND (ToID = 251 or RangeID = 251)

declare @ItemID int;
set @ItemID=251

	declare @Count int;
	declare @PreviousID as int
	select @PreviousID = PreviousID from items where ItemID = @ItemID
	Print @PreviousID
	if @PreviousID is not null
	BEGIN
		Select @Count = count(*) from vefn_ChildItems(247)
		--Select @Count = count(*) from Transitions TT
		--join contents CC on TT.FromID = CC.ContentID
		--where FromID in (Select ContentID from vefn_ChildItems(@PreviousID))
		--AND (ToID = @ItemID or RangeID = @ItemID)
	END
	--ELSE
		--set @Count=0
  Print 'I''m here'
	Print @Count

		Select  * from vefn_ChildItems(247)

*/



CREATE FUNCTION [dbo].[ve_GetNextTranCount] (@ItemID int) RETURNS int
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @Count int;
	declare @PreviousID as int
	select @PreviousID = PreviousID from items where ItemID = @ItemID
	if @PreviousID is not null
	BEGIN
		Select @Count = count(*) from Transitions TT
		join contents CC on TT.FromID = CC.ContentID
		where FromID in (Select ContentID from vefn_ChildItems(@PreviousID))
		AND (ToID = @ItemID or RangeID = @ItemID)
	END
	ELSE
		set @Count=0
	return @Count
END;
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetNextTranCount Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetNextTranCount Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetParts] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetParts]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetParts];
GO
	
--select .dbo.ve_GetParts(756,6)

CREATE FUNCTION [dbo].[ve_GetParts] (@ContentID int,@FromType int)
RETURNS varchar(max)
WITH EXECUTE AS OWNER
AS
BEGIN
declare @retval varchar(max)
begin
with ContentZ(AllContents,PreviousID,HasChildren) as (
  Select cast(II.ContentID as varchar(max)) AllContents,II.ItemID PreviousID, case when Exists(select ItemID from Items where PreviousID = II.ItemID) then 1 else 0 end HasChildren
    from Items II join Parts PP on II.ItemID=PP.ItemID
    where PP.ContentID=@ContentID and PP.FromType = @FromType
  Union All
--
  Select ZZ.AllContents + '.' + cast(II.ContentID as varchar(max)) AllContents,II.ItemID PreviousID, case when Exists(select ItemID from Items where PreviousID = II.ItemID) then 1 else 0 end HasChildren
    from Items II
    Join ContentZ ZZ on II.PreviousID = ZZ.PreviousID
)
Select @retval = AllContents from ContentZ where HasChildren=0
OPTION (MAXRECURSION 1000)
end
return @retval
end
/*
ALTER FUNCTION [dbo].[ve_GetPath] (@StructID int)
RETURNS varchar(max)
WITH EXECUTE AS OWNER
AS
BEGIN
-- declare @STructID int
--set @StructID=11
declare @Path varchar(max);
with Struct(FromType,FromID,Item,PPath,Path) as (
  Select FromType,FromID,0 Item,Cast('' as varchar(max)) PPath ,
	Cast(case FromType
	when 1 then 'PRC.000' when 2 then '.SEC.000'
	when 3 then '.CAU.000' when 4 then '.NOT.000'
	when 5 then '.RNO' when 7 then '.TAB'
	else '.000' end  as varchar(max)) Path
    from Structures
    where StructureID=@StructID
  Union All
-- Child
  Select A.FromType,A.FromID,0 as Item,Path,
	Cast(case A.FromType
	when 1 then 'PRC.000' when 2 then '.SEC.000'
	when 3 then '.CAU.000' when 4 then '.NOT.000'
	when 5 then '.RNO' when 7 then '.TAB'
	else '.000' end + Path as varchar(max)) Path
    from Structures A
    Join Struct C on C.FromID=A.StructureID	
    where C.FromType <> 0
  Union All
-- Sibling
  Select A.FromType,A.FromID,Item + 1 Item,PPath,
	case A.FromType
	when 1 then 'PRC.' when 2 then '.SEC.'
	when 3 then '.CAU.' when 4 then '.NOT.'
	when 5 then '.RNO.' when 7 then '.TAB.'
	else '.' end  + right('000' + cast(Item + 1 as varchar(3)),3) + PPath Path
    from Structures A
    Join Struct C on C.FromID=A.StructureID	
    where C.FromType = 0
)
--select * from Struct OPTION (MAXRECURSION 1000)
Select @Path = Path from Struct where FromID=0 OPTION (MAXRECURSION 1000)
--print @path
return @Path
END;
*/
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetParts Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetParts Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetPath] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetPath]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetPath];
GO
	
/*
select ItemID, CC.Type, dbo.ve_GetPath(ItemID)
from Items II join Contents CC on II.ContentID = CC.ContentID
where ItemID in(111,265,266,267)
*/
-- drop function ve_GetPath
CREATE FUNCTION [dbo].[ve_GetPath] (@ItemID int) RETURNS varchar(max)
WITH EXECUTE AS OWNER
AS
BEGIN
-- declare @STructID int
--set @StructID=11
declare @Path varchar(max);
with Itemz(ItemCount,ItemID,PreviousID,FromType,CType,Number,Text,PPath, Path) as (
  Select 1,ItemID,PreviousID,0,C.Type/10000,C.Number,C.Text,
		Cast(Case when C.Type < 20000 then '`' + C.Number +'`' + C.Text else '' end as nvarchar(max)) PPath,
		Cast(Case when C.Type < 20000 then '`' + C.Number +'`' + C.Text else '1' end as nvarchar(max)) Path
    from Items I
	join Contents C on I.ContentID = C.ContentID
    where ItemID=@ItemID
  Union All
-- siblings
  Select ItemCount+1,I.PreviousID,II.PreviousID,0,C.Type/10000,Z.Number,Z.Text,PPath,cast(ItemCount + 1 as nvarchar(3)) +  PPath
    from Items I
	join Contents C on I.ContentID = C.ContentID
	Join Items II on II.ItemID = I.PreviousID
    Join Itemz Z on I.ItemID=Z.ItemID
	where I.PreviousID != 0
  Union All
-- children
  select 1,I.ItemID,I.PreviousID,P.FromType,C.Type/10000,C.Number,C.Text,
	case C.Type/10000
	when 0 then '`' + C.Number +'`' + C.Text
	when 1 then '`' + C.Number +'`' + C.Text +'`' + cast(ItemCount + 0 as varchar(3))
	else
	case P.FromType
	when 1 then 'PRC`' + cast(ItemCount + 0 as varchar(3))
	when 2 then '`SEC`' + cast(ItemCount + 0 as varchar(3))
	when 3 then '`Caution`' + cast(ItemCount + 0 as varchar(3))
	when 4 then '`Note`' + cast(ItemCount + 0 as varchar(3))
	when 5 then '`RNO`'
	when 7 then '`Table`'
	else '`' + cast(ItemCount + 0 as varchar(3))
	end end  + PPath PPath,
	--'1' +
	case C.Type/10000
	when 0 then '`' + C.Number +'`' + C.Text
	when 1 then '`' + C.Number +'`' + C.Text +'`' + cast(ItemCount + 0 as varchar(3))
	else
	case P.FromType
	when 1 then 'PRC`' + cast(ItemCount + 0 as varchar(3))
	when 2 then '`SEC`' + cast(ItemCount + 0 as varchar(3))
	when 3 then '`Caution`' + cast(ItemCount + 0 as varchar(3))
	when 4 then '`Note`' + cast(ItemCount + 0 as varchar(3))
	when 5 then '`RNO'
	when 7 then '`Table'
	else '`' + cast(ItemCount + 0 as varchar(3))
	end end  + PPath Path

	from Parts P
	join Items I on I.ContentID = P.ContentID
	join Contents C on I.ContentID = C.ContentID
	join Itemz Z on P.ItemID=Z.ItemID
)
select @Path = path From Itemz where ItemCount=1 and CType=0
OPTION (MAXRECURSION 10000)
return @Path
END;
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetPath Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetPath Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetPathFromContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetPathFromContentID]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetPathFromContentID];
GO
	
/*
select top 5
[dbo].[ve_GetPathFromContentID](FromID)FromPath
,[dbo].[ve_GetPath](ToID) ToPath
,[dbo].[ve_GetPath](RangeID) RangePath
 from transitions
*/

CREATE FUNCTION [dbo].[ve_GetPathFromContentID] (@ContentID int) RETURNS varchar(max)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @ItemID int;
	select top 1 @ItemID=ItemID from Items where ContentID = @ContentID;
	return DBO.ve_GetPath(@ItemID)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetPathFromContentID Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetPathFromContentID Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetShortPart] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetShortPart]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetShortPart];
GO
	
Create FUNCTION [dbo].[ve_GetShortPart] (@Number varchar(max),@Title varchar(max)) RETURNS varchar(max)
WITH EXECUTE AS OWNER
AS
BEGIN
	if(isnull(@Number,'') = '') return @Title
	return @Number
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetShortPart Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetShortPart Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetShortPath] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetShortPath]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetShortPath];
GO
	
/*
select ItemID, CC.Type, dbo.ve_GetPath(ItemID)
from Items II join Contents CC on II.ContentID = CC.ContentID
where ItemID in(111,265,266,267)
*/
-- drop function ve_GetPath
CREATE FUNCTION [dbo].[ve_GetShortPath] (@ItemID int) RETURNS varchar(max)
WITH EXECUTE AS OWNER
AS
BEGIN
-- declare @STructID int
--set @StructID=11
declare @Path varchar(max);
with Itemz(ItemCount,ItemID,PreviousID,FromType,CType,Number,Text,PPath, Path) as (
  Select 1,ItemID,PreviousID,0,C.Type/10000,C.Number,C.Text,
		Cast(Case when C.Type < 20000 then '`' +  [dbo].[ve_GetShortPart](C.Number,C.Text) else '' end as nvarchar(max)) PPath,
		Cast(Case when C.Type < 20000 then '`' + [dbo].[ve_GetShortPart](C.Number,C.Text) else '1' end as nvarchar(max)) Path
    from Items I
	join Contents C on I.ContentID = C.ContentID
    where ItemID=@ItemID
  Union All
-- siblings
  Select ItemCount+1,I.PreviousID,II.PreviousID,0,C.Type/10000,Z.Number,Z.Text,PPath,cast(ItemCount + 1 as nvarchar(3)) +  PPath
    from Items I
	join Contents C on I.ContentID = C.ContentID
	Join Items II on II.ItemID = I.PreviousID
    Join Itemz Z on I.ItemID=Z.ItemID
	where I.PreviousID != 0
  Union All
-- children
  select 1,I.ItemID,I.PreviousID,P.FromType,C.Type/10000,C.Number,C.Text,
	case C.Type/10000
	when 0 then '`' + [dbo].[ve_GetShortPart](C.Number,C.Text)
	when 1 then '`' + [dbo].[ve_GetShortPart](C.Number,C.Text) +'`' + cast(ItemCount + 0 as varchar(3))
	else
	case P.FromType
	when 1 then 'PRC`' + cast(ItemCount + 0 as varchar(3))
	when 2 then '`SEC`' + cast(ItemCount + 0 as varchar(3))
	when 3 then '`Caution`' + cast(ItemCount + 0 as varchar(3))
	when 4 then '`Note`' + cast(ItemCount + 0 as varchar(3))
	when 5 then '`RNO`'
	when 7 then '`Table`'
	else '`' + cast(ItemCount + 0 as varchar(3))
	end end  + PPath PPath,
	--'1' +
	case C.Type/10000
	when 0 then '`' + [dbo].[ve_GetShortPart](C.Number,C.Text)
	when 1 then '`' + [dbo].[ve_GetShortPart](C.Number,C.Text) +'`' + cast(ItemCount + 0 as varchar(3))
	else
	case P.FromType
	when 1 then 'PRC`' + cast(ItemCount + 0 as varchar(3))
	when 2 then '`SEC`' + cast(ItemCount + 0 as varchar(3))
	when 3 then '`Caution`' + cast(ItemCount + 0 as varchar(3))
	when 4 then '`Note`' + cast(ItemCount + 0 as varchar(3))
	when 5 then '`RNO'
	when 7 then '`Table'
	else '`' + cast(ItemCount + 0 as varchar(3))
	end end  + PPath Path

	from Parts P
	join Items I on I.ContentID = P.ContentID
	join Contents C on I.ContentID = C.ContentID
	join Itemz Z on P.ItemID=Z.ItemID
)
select @Path = path From Itemz where ItemCount=1 and CType=0
OPTION (MAXRECURSION 10000)
return REPLACE(@Path,'\u8209?','-')
END;
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetShortPath Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetShortPath Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetShortPathFromContentID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetShortPathFromContentID]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetShortPathFromContentID];
GO
	
/*
select top 5
[dbo].[ve_GetShortPathFromContentID](FromID)FromPath
,[dbo].[ve_GetShortPath](ToID) ToPath
,[dbo].[ve_GetShortPath](RangeID) RangePath
 from transitions
*/

CREATE FUNCTION [dbo].[ve_GetShortPathFromContentID] (@ContentID int) RETURNS varchar(max)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @ItemID int;
	select top 1 @ItemID=ItemID from Items where ContentID = @ContentID;
	return DBO.ve_GetShortPath(@ItemID)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetShortPathFromContentID Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetShortPathFromContentID Error on Creation'
GO

/****** Object:  StoredProcedure [ve_GetSiblingCount] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ve_GetSiblingCount]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [ve_GetSiblingCount];
GO
	
/*
select top 5 CC.Number,CC.Text,Type,ItemID, dbo.ve_GetSiblingCount(ItemID) HLStepCount
from Contents CC
Join Parts PP on PP.ContentID = CC.ContentID
where CC.Type >= 10000 and CC.Type < 20000
order by dbo.ve_GetSiblingCount(ItemID) desc

select top 5 CC.Number,CC.Text,Type,ItemID, dbo.ve_GetSiblingCount(ItemID) SectionCount
from Contents CC
Join Parts PP on PP.ContentID = CC.ContentID
where CC.Type < 10000
order by dbo.ve_GetSiblingCount(ItemID) desc

select top 5 CC.Text,Type,ItemID, dbo.ve_GetSiblingCount(ItemID) SubStepCount
from Contents CC
Join Parts PP on PP.ContentID = CC.ContentID
where CC.Type >= 20000
order by dbo.ve_GetSiblingCount(ItemID) desc

*/
CREATE FUNCTION [dbo].[ve_GetSiblingCount] (@ItemID int) RETURNS int
WITH EXECUTE AS OWNER
AS
BEGIN
declare @Count int;
with Itemz([Direction], [ItemID], [PreviousID]) as (
  Select 0 Direction,[ItemID], [PreviousID]
	FROM [Items]
    where [ItemID]=@ItemID
-- Siblings Previous
Union All
  select -1 Direction,I.[ItemID], I.[PreviousID]
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.Direction <= 0
-- Siblings Next
Union All
  select 1 Direction,I.[ItemID], I.[PreviousID]
	from Itemz Z
	join Items I on I.ItemID = Z.PreviousID
	where Z.Direction >= 0
)
Select @Count = Count(*) from Itemz
return @Count END;
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: ve_GetSiblingCount Succeeded'
ELSE PRINT 'ScalarFunction Creation: ve_GetSiblingCount Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_AllHighLevelSteps] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_AllHighLevelSteps]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_AllHighLevelSteps];
GO
	
CREATE FUNCTION [dbo].[vefn_AllHighLevelSteps]()
RETURNS @HighLevelStepTransitions TABLE
(
	ParentID int
	,ItemID int PRIMARY KEY
	,Ordinal int
  ,Path varchar(max)
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], ParentID [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM (select II.ItemID ParentID, PP.ItemID, PreviousID, II.ContentID, II.DTS, II.UserID, II.LastChanged from Items II
Join Contents CC on II.ContentID = CC.ContentID
Join Parts PP on PP.ContentID = II.ContentID and FromType = 6
where CC.Type = 10000) TT
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	--where Z.[Level] > 0
)
Insert into @HighLevelStepTransitions
select [ParentID],ItemID,Ordinal,dbo.ve_GetPath([ItemID])  Path
from Itemz
Order by ParentID,ItemID
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_AllHighLevelSteps Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_AllHighLevelSteps Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_AllHighLevelStepTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_AllHighLevelStepTransitions]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_AllHighLevelStepTransitions];
GO
	
/*
select * from vefn_AllHighLevelStepTransitions()
where ExternalTransitions > 0
*/

CREATE  FUNCTION [dbo].[vefn_AllHighLevelStepTransitions]()
RETURNS @HighLevelStepTransitions TABLE
(
	ParentID int
	,ItemID int PRIMARY KEY
	,Ordinal int
  ,Path varchar(max)
	,TransCount int
	,ExternalTransitions int
	,ExternalChildTransitions int
	,InternalTransitions int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], ParentID [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM (select II.ItemID ParentID, PP.ItemID, PreviousID, II.ContentID, II.DTS, II.UserID, II.LastChanged from Items II
Join Contents CC on II.ContentID = CC.ContentID
Join Parts PP on PP.ContentID = II.ContentID and FromType = 6
where CC.Type = 10000) TT
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	--where Z.[Level] > 0
)
Insert into @HighLevelStepTransitions
select [ParentID],ItemID,Ordinal,dbo.ve_GetShortPath([ItemID])  Path,(Select Count(*) from Transitions where ToID=ItemID OR RangeID=ItemID ) TransCount
,(Select count(*) from vefn_FindExternalTransitions(ItemID)) ExternalTransitions
,(Select count(*) from vefn_FindExternalChildTransitions(ItemID)) ExternalChildTransitions
,(Select count(*) from vefn_FindInternalTransitions(ItemID)) InternalTransitions
from Itemz
where (Select Count(*) from Transitions where ToID=ItemID OR RangeID=ItemID ) > 0
OR(Select count(*) from vefn_FindExternalTransitions(ItemID)) > 0
OR(Select count(*) from vefn_FindInternalTransitions(ItemID)) > 0
Order by ParentID,ItemID
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_AllHighLevelStepTransitions Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_AllHighLevelStepTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_AllSections] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_AllSections]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_AllSections];
GO
	
-- Select .dbo.vefn_AllSections(10001) MyTypeSection, .dbo.vlnfn_AllSections(20001) MyTypeStep, .dbo.vlnfn_AllSections(5) MyTypeProc
CREATE FUNCTION [dbo].[vefn_AllSections](@type int)
RETURNS int
WITH EXECUTE AS OWNER
AS
BEGIN
	IF(@type < 20000 and @type >= 10000)
		RETURN 10000
	RETURN @type
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_AllSections Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_AllSections Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_AnnotationTypeSplit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_AnnotationTypeSplit]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_AnnotationTypeSplit];
GO
	
/*
select * from vefn_AnnotationTypeSplit('1,4')
select * from vefn_AnnotationTypeSplit(null)
select * from vefn_AnnotationTypeSplit('')
*/
CREATE  FUNCTION [dbo].[vefn_AnnotationTypeSplit](@AnnotationTypeList varchar(MAX))
RETURNS @IDs TABLE
(
  TypeID int PRIMARY KEY,
	Name varchar(100)
)
WITH EXECUTE AS OWNER
AS
BEGIN
IF(isnull(@AnnotationTypeList,'') = '')
	Insert into @IDs
	Select TypeID, Name
	from AnnotationTypes
else
	Insert into @IDs
	Select TypeID,NAME
	from AnnotationTypes
  where TypeID in(select ID from vefn_SplitInt(@AnnotationTypeList,','))
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_AnnotationTypeSplit Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_AnnotationTypeSplit Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_ChildItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_ChildItems]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_ChildItems];
GO
	
/*
declare @PreviousID as int
declare @ItemID as int
set @ItemID = 450
select @PreviousID = PreviousID from items where ItemID = @ItemID

Select * from Items where ItemID = @ItemID

select * from Transitions
where FromID in (Select ContentID from vefn_ChildItems(@PreviousID))
AND (ToID = @ItemID or RangeID = @ItemID)

select CC.Text from Transitions TT
join contents CC on TT.FromID = CC.ContentID
where FromID in (Select ContentID from vefn_ChildItems(@PreviousID))
AND (ToID = @ItemID or RangeID = @ItemID)

*/
CREATE  FUNCTION [dbo].[vefn_ChildItems](@ItemID int)
RETURNS @Children TABLE
(
  ItemID int PRIMARY KEY,
	ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ItemID], [ContentID]) as (
  Select 0 [Level], [ItemID], [ContentID]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1, I.[ItemID], I.[ContentID]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] , I.[ItemID], I.[ContentID]
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
insert into @Children select ItemID, ContentID from Itemz
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_ChildItems Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_ChildItems Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_ChildItemsRange] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_ChildItemsRange]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_ChildItemsRange];
GO
	
CREATE FUNCTION [dbo].[vefn_ChildItemsRange](@StartItemID int, @EndItemID int, @DestFormat int)
RETURNS @Children TABLE
(
ItemID int PRIMARY KEY,
ContentID int,
FormatID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
DECLARE @FormatID int
SELECT @FormatID = isnull(@DestFormat,.dbo.vefn_GetInheritedFormat(@StartItemID,1))
BEGIN
with Itemz([Level], [ItemID], [ContentID], [FormatID], [FoundEnd]) as (
Select 0 [Level], [ItemID], I.[ContentID], IsNull(C.[FormatID], @FormatID), case [ItemID] when @EndItemID then 1 else 0 end [FoundEnd]
FROM [Items] I
JOIN [Contents] C on I.ContentID = C.ContentID
where [ItemID]=@StartItemID
Union All
-- Children
select [Level] + 1, I.[ItemID], I.[ContentID], IsNull(C.[FormatID], Z.[FormatID]), case I.[ItemID] when @EndItemID then 1 else 0 end [FoundEnd]
from Itemz Z
join Parts P on P.ContentID = Z.ContentID
join Items I on I.ItemID = P.ItemID
JOIN [Contents] C on I.ContentID = C.ContentID
-- Siblings
Union All
select [Level] , I.[ItemID], I.[ContentID], IsNull(C.[FormatID], Z.[FormatID]), case I.[ItemID] when @EndItemID then 1 else 0 end [FoundEnd]
from Itemz Z
join Items I on I.PreviousID = Z.ItemID
JOIN [Contents] C on I.ContentID = C.ContentID
where FoundEnd = 0
)
insert into @Children select ItemID, ContentID, FormatID from Itemz
RETURN
END
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_ChildItemsRange Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_ChildItemsRange Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_ChildrenItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_ChildrenItems]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_ChildrenItems];
GO
	
/*
select * from Transitions
where (ToID in(select ItemID From dbo.vefn_ChildrenItems(185,184))) OR (RangeID in(select ItemID From dbo.vefn_ChildrenItems(185,184)))
AND NOT (FromID in(Select ContentID From dbo.vefn_ChildrenItems(185,184)))
*/

CREATE  FUNCTION [dbo].[vefn_ChildrenItems](@ItemID int, @ParentID int)
RETURNS @Children TABLE
(
  ItemID int PRIMARY KEY,
	ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], @ParentID [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
insert into @Children select ItemID, ContentID from Itemz
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_ChildrenItems Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_ChildrenItems Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_CompareTranFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_CompareTranFormat]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_CompareTranFormat];
GO
	
/*
  Determines if two transition formats are same string.
	returns 0 if identical, 1 if similar (range for range, item for item), 2 if totally different
*/
CREATE FUNCTION [dbo].[vefn_CompareTranFormat] (@FormatID int, @NewFormatID int, @TranType int) RETURNS int
WITH EXECUTE AS OWNER
AS
BEGIN
	--
	IF @FormatID = @NewFormatID
		RETURN 0 -- Exactly the same format file
	DECLARE @TransFormat varchar(max)
	DECLARE @NewTransFormat varchar(max)
	SET @TransFormat = isnull(.dbo.vefn_GetTransFormat(@FormatID, @TranType),'')
	SET @NewTransFormat = isnull(.dbo.vefn_GetTransFormat(@NewFormatID, @TranType),'')
	RETURN CASE
		WHEN @TransFormat = @NewTransFormat THEN 0   -- transition formats are identical
		WHEN @TransFormat LIKE '%{Last Step}%' THEN
			CASE
				WHEN @NewTransFormat LIKE '%{Last Step}%' THEN 1  -- both ranges, but different format
				ELSE 2		-- totally different format, not even same type (was single, changed to range)
			END
		ELSE
			CASE
				WHEN @NewTransFormat LIKE '%{Last Step}%' THEN 2 -- totally different format, not even same type (was range, changed to single)
				ELSE 1	-- both single, but different format
			END
	END
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_CompareTranFormat Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_CompareTranFormat Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_DocVersionSplit] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_DocVersionSplit]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_DocVersionSplit];
GO
	
/*
select * from vefn_DocVersionSplit('1,4')
select * from vefn_DocVersionSplit(null)
select * from vefn_DocVersionSplit('')
*/
CREATE  FUNCTION [dbo].[vefn_DocVersionSplit](@DocVersionList varchar(MAX))
RETURNS @IDs TABLE
(
  VersionID int PRIMARY KEY,
	ItemID int,
	DVPath varchar(MAX)
)
WITH EXECUTE AS OWNER
AS
BEGIN
IF(isnull(@DocVersionList,'') = '')
	Insert into @IDs
	Select VersionID, ItemID, dbo.ve_GetFolderPath(VersionID)
	from DocVersions where ItemID is not null
else
	Insert into @IDs
	Select ID, ItemID, dbo.ve_GetFolderPath(VersionID)
	from vefn_SplitInt(@DocVersionList,',') as T
  join DocVersions DV on VersionID = T.ID
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_DocVersionSplit Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_DocVersionSplit Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_DVContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_DVContent]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_DVContent];
GO
	
/*
select contentID from vefn_DVContent('1')
*/

CREATE  FUNCTION [dbo].[vefn_DVContent](@DocVersionList varchar(MAX))
RETURNS @DVContents TABLE
(
	ContentID int PRIMARY KEY
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], 0 [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID] in (select [ItemID] from vefn_DocVersionSplit(@DocVersionList))
Union All
-- Children
  select [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
)
insert into @DVContents select distinct ContentID from Itemz
OPTION (MAXRECURSION 10000)
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_DVContent Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_DVContent Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FindAffectedTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FindAffectedTransitions]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_FindAffectedTransitions];
GO
	
/*
select top 1 * from items order by itemid desc
Select
FromID,.dbo.ve_GetPathFromContentID(FromID) ContentPath
,ToID,dbo.ve_GetPath(ToID) ToPath
,RangeID,dbo.ve_GetPath(RangeID) RangePath
,cc.Text
from vefn_FindAffectedTransitions(2102) ttz
join transitions tt on ttz.TransitionID = tt.TransitionID
--join items ii on ii.ItemID =  tt.fromID
join contents cc on tt.FromID = cc.contentid
*/

CREATE  FUNCTION [dbo].[vefn_FindAffectedTransitions](@ItemID int)
RETURNS @Transitions TABLE
(
  TransitionID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- All Siblings
Union All
  select [Level] ,Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	--where Z.[Level] > 0 -- This would limit the siblings to the siblings of the children and not the initial ItemID
)
, Itemz2([Level], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
-- All Siblings
Union All
  select [Level] ,Z.[Ordinal] -1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz2 Z
	join Items I on Z.PreviousID = I.ItemID
	--where Z.[Level] > 0 -- This would limit the siblings to the siblings of the children and not the initial ItemID
)
insert into @Transitions
select TransitionID from Transitions TT
where (ToID in(select ItemID from Itemz) OR RangeID in(select ItemID from Itemz))
UNION
select TransitionID from Transitions TT
JOIN Itemz2 on ToID=ItemID and RangeID=ItemID and IsRange = 2
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_FindAffectedTransitions Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_FindAffectedTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FindContentText] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FindContentText]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_FindContentText];
GO
	
/*
SELECT * From vefn_FindContentText('1','%RCP%')
*/
CREATE  FUNCTION [dbo].[vefn_FindContentText](
@DocVersionList nvarchar(MAX)
,@SearchString varchar(MAX))
RETURNS @FoundContents TABLE
(
	ContentID int PRIMARY KEY
	,Type int
  ,Text varchar(max)
)
WITH EXECUTE AS OWNER
AS
BEGIN
IF(ISNULL(@DocVersionList,'')='')
	BEGIN
		INSERT INTO @FoundContents -- Do a case insensitive search
		select ContentID,Type,Text from contents
			where [Text] like @SearchString Collate SQL_Latin1_General_CP1_CI_AS
	END
ELSE
	BEGIN
		INSERT INTO @FoundContents -- Do a case insensitive search
		select ContentID,Type,Text from contents
			where [ContentID] in (select [ContentID] from vefn_DVContent(@DocVersionList))
			AND [Text] like @SearchString Collate SQL_Latin1_General_CP1_CI_AS
	END

RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_FindContentText Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_FindContentText Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FindExternalChildTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FindExternalChildTransitions]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_FindExternalChildTransitions];
GO
	
/*
Select * from vefn_FindExternalChildTransitions(185)
*/

CREATE  FUNCTION [dbo].[vefn_FindExternalChildTransitions](@ItemID int)
RETURNS @Children TABLE
(
  FromItemID int,
	ToID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
insert into @Children
select ItemID [FromItemID], case when TT.ToID in(select ItemID from Itemz) then TT.ToID else TT.RangeID end [ToID]
 from Transitions TT
 join Items II on II.ContentID=TT.FromID
where (ToID in(select ItemID from Itemz where Level > 0) OR RangeID in(select ItemID from Itemz where Level > 0))
AND FromID not in(Select ContentID from ItemZ)
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_FindExternalChildTransitions Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_FindExternalChildTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FindExternalTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FindExternalTransitions]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_FindExternalTransitions];
GO
	
/*
Select * from vefn_FindExternalTransitions(185)
*/

CREATE  FUNCTION [dbo].[vefn_FindExternalTransitions](@ItemID int)
RETURNS @Children TABLE
(
  [FromItemID] int,
	[TransitionID] [int] NOT NULL,
	[FromID] [int] NOT NULL,
	[ToID] [int] NOT NULL,
	[RangeID] [int] NOT NULL,
	[Config] [nvarchar](max) NULL
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
insert into @Children
select ItemID [FromItemID], TT.[TransitionID],	TT.[FromID],	TT.[ToID],	TT.[RangeID],	TT.[Config]
 from Transitions TT
 join Items II on II.ContentID=TT.FromID
where (ToID in(select ItemID from Itemz) OR RangeID in(select ItemID from Itemz))
AND FromID not in(Select ContentID from ItemZ)
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_FindExternalTransitions Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_FindExternalTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FindInternalTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FindInternalTransitions]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_FindInternalTransitions];
GO
	
/*
Select * from vefn_FindInternalTransitions(185)
*/
CREATE FUNCTION [dbo].[vefn_FindInternalTransitions](@ItemID int)
RETURNS @Children TABLE
(
  FromItemID int,
	ToID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
insert into @Children
select ItemID [FromItemID], case when TT.ToID in(select ItemID from Itemz) then TT.ToID else TT.RangeID end [ToID]
 from Transitions TT
 join Items II on II.ContentID=TT.FromID
where (ToID in(select ItemID from Itemz) OR RangeID in(select ItemID from Itemz))
AND FromID in(Select ContentID from ItemZ)
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_FindInternalTransitions Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_FindInternalTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FindInternalTransitionsForCopy] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FindInternalTransitionsForCopy]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_FindInternalTransitionsForCopy];
GO
	
/*
Select * from vefn_FindInternalTransitionsForCopy(10277)
*/
CREATE FUNCTION [dbo].[vefn_FindInternalTransitionsForCopy](@ItemID int)
RETURNS @Transitions TABLE
(
	TransitionID int,
	FromID int,
	TranType int,
	ToID int,
	RangeID int,
	OldTransition int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
insert into @Transitions
select TransitionID, FromID, TT.TranType, TT.ToID, TT.RangeID, CAST(TT.Config as int) --case when TT.ToID in(select ItemID from Itemz) then TT.ToID else TT.RangeID end [ToID]
 from Transitions TT
 join Items II on II.ContentID=TT.FromID
where (ToID in(select ItemID from Itemz) OR RangeID in(select ItemID from Itemz))
AND FromID in(Select ContentID from ItemZ)
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_FindInternalTransitionsForCopy Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_FindInternalTransitionsForCopy Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FindText] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FindText]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_FindText];
GO
	
/*
SELECT * From vefn_FindText('1','turbine-driven',0,0,0,1,'')
SELECT * From vefn_FindText('1','turbine\u8209?driven',0,0,0,0,'')
SELECT * From vefn_FindText('1','trip',0,0,0,0,'')
*/	
CREATE  FUNCTION [dbo].[vefn_FindText](
@DocVersionList nvarchar(MAX)
,@SearchString varchar(MAX)
,@CaseSensitive as int
,@IncludeLinks as int
,@IncludeRtfFormatting as int
,@IncludeSpecialCharacters as int
,@StepTypeList varchar(MAX))
RETURNS @FoundContents TABLE
(
	ContentID int PRIMARY KEY
)
WITH EXECUTE AS OWNER
AS
BEGIN
Set @SearchString = .dbo.vefn_FixSearchString(@SearchString)
IF isnull(@SearchString,'')=''
  BEGIN
			insert into @FoundContents
			select C.ContentID from (select * from Contents where ContentID in(select ContentID from vefn_DVContent(@DocVersionList))) C
			where(dbo.vefn_AllSections(C.Type)>=10000)
			or
			(dbo.vefn_AllSections(C.Type) in (Select ID from vefn_SplitInt(@StepTypeList,',')))
  END
ELSE
	Declare @SearchStringx nvarchar(200)  --kbr
	set @SearchStringx = replace(@SearchString,'-','\u8209?') --kbr
	IF @CaseSensitive = 0 -- Not Case Sensitive
		BEGIN
			insert into @FoundContents
				select C.ContentID from vefn_FindContentText(@DocVersionList,@SearchStringx) C
					where
					(.dbo.vefn_RemoveExtraText(C.Text,@IncludeLinks, @IncludeRtfFormatting, @IncludeSpecialCharacters) like @SearchStringx Collate SQL_Latin1_General_CP1_CI_AS)
					AND ((isnull(@StepTypeList,'') = '' and dbo.vefn_AllSections(C.Type)>=10000) or ((dbo.vefn_AllSections(C.Type) in (Select ID from vefn_SplitInt(@StepTypeList,',')))))
				UNION
				select C.ContentID from (select * from Contents where ContentID in(select ContentID from vefn_DVContent(@DocVersionList))) C
					join Entries E on C.ContentID = E.ContentID
					join Documents D on E.DocID = D.DocID
					where
					(D.DocAscii like @SearchString Collate SQL_Latin1_General_CP1_CI_AS)
					AND
					((isnull(@StepTypeList,'') = '' and dbo.vefn_AllSections(C.Type)>=10000) or ((dbo.vefn_AllSections(C.Type) in (Select ID from vefn_SplitInt(@StepTypeList,',')))))
		END
	ELSE
		BEGIN
			IF @CaseSensitive = 1 -- Case Sensitive
				BEGIN
					insert into @FoundContents
						select C.ContentID from vefn_FindContentText(@DocVersionList,@SearchStringx) C
							where
							(.dbo.vefn_RemoveExtraText(C.Text,@IncludeLinks, @IncludeRtfFormatting, @IncludeSpecialCharacters) like @SearchStringx Collate SQL_Latin1_General_CP1_CS_AS)
							AND ((isnull(@StepTypeList,'') = '' and dbo.vefn_AllSections(C.Type)>=10000) or ((dbo.vefn_AllSections(C.Type) in (Select ID from vefn_SplitInt(@StepTypeList,',')))))
						UNION
						select C.ContentID from (select * from Contents where ContentID in(select ContentID from vefn_DVContent(@DocVersionList))) C
							join Entries E on C.ContentID = E.ContentID
							join Documents D on E.DocID = D.DocID
							where
						(D.DocAscii like @SearchString Collate SQL_Latin1_General_CP1_CS_AS)
						AND
						((isnull(@StepTypeList,'') = '' and dbo.vefn_AllSections(C.Type)>=10000) or
						((dbo.vefn_AllSections(C.Type) in (Select ID from vefn_SplitInt(@StepTypeList,',')))))
				END
END
RETURN
END
 
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_FindText Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_FindText Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FirstLink] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FirstLink]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_FirstLink];
GO
	
/*
select .dbo.vefn_FirstLink('asdasdadsasd' + char(21) + 'asdasdasd\vasdasdasd', 2)
select .dbo.vefn_FirstLink('asdasdadsasd' + char(21) + 'asdasdasd\vasdasdasd', 1)
select .dbo.vefn_FirstLink('asdasdadsasd' + char(21) + 'asdasdasd\vasdasdasd', 0)
*/

-- This is only used for testing by vefn_RemoveExtraText
CREATE FUNCTION [dbo].[vefn_FirstLink](@text nvarchar(MAX),@includeLink int)
RETURNS int
WITH EXECUTE AS OWNER
AS
BEGIN
DECLARE @index int
SET @index = 0
if(@includeLink = 2)
	RETURN 0
if(@includeLink = 1)
	return CHARINDEX('\v' , @text)
DECLARE @index2 int
SET @index = PATINDEX('%[' + nchar(9574)+nchar(9516)+nchar(21) + ']%',@text)
return @index
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_FirstLink Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_FirstLink Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FixROData] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FixROData]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_FixROData];
GO
	
Create FUNCTION [dbo].[vefn_FixROData]
(@data XML,@ROUsageID int,@NewROUsageID int)
RETURNS XML
WITH EXECUTE AS OWNER
AS
BEGIN
	-- Build Search String and Replace String
	DECLARE @lookFor varchar(MAX)
	DECLARE @replaceWith varchar(MAX)
	SET @lookFor = '#Link:ReferencedObject:' + ltrim(str(@ROUsageID)) + ' '
	SET @replaceWith = '#Link:ReferencedObject:' + ltrim(str(@NewROUsageID)) + ' '
  return CAST(replace(CAST(@data AS VarChar(max)),@lookFor,@replaceWith) AS XML)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_FixROData Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_FixROData Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FixROText] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FixROText]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_FixROText];
GO
	
CREATE FUNCTION [dbo].[vefn_FixROText]
(@Text varchar(MAX),@ROUsageID int,@NewROUsageID int)
RETURNS varchar(MAX)
WITH EXECUTE AS OWNER
AS
BEGIN
	-- Build Search String and Replace String
	DECLARE @lookFor varchar(MAX)
	DECLARE @replaceWith varchar(MAX)
	SET @lookFor = '#Link:ReferencedObject:' + ltrim(str(@ROUsageID)) + ' '
	SET @replaceWith = '#Link:ReferencedObject:' + ltrim(str(@NewROUsageID)) + ' '
  return replace(@text,@lookFor,@replaceWith)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_FixROText Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_FixROText Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FixSearchString] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FixSearchString]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_FixSearchString];
GO
	
/*
select ID,ss,.dbo.vefn_FixSearchString(ss)
from (
select 1 ID,'*' ss union
select 2 ID,'50%' ss union
select 3 ID,'IF*' ss union
select 4 ID,'*then:' ss union
select 5 ID,'530`F' ss union
select 6 ID,'check' ss union
select 7 ID,'RCP*Cooling' ss union
select 8 ID,'14%[34%]' ss union
select 9 ID,'\*' ss union
select 10 ID,'\?' ss union
select 11 ID,'_' ss union
select 12 ID,'[' ss union
select 13 ID,']' ss union
select 14 ID,'%' ss union
select 15 ID,'_' ss union
select 16 ID,'-' ss
) tt order by ID
*/
CREATE FUNCTION [dbo].[vefn_FixSearchString](@SearchString nvarchar(MAX))
RETURNS nvarchar(MAX)
WITH EXECUTE AS OWNER
AS
BEGIN
  -- This code adds % at the beginning and end if the beginning and end
  -- of the search string if it does not have % at the beginning or end
  Set @SearchString = replace(@SearchString,'[','[[]')
  Set @SearchString = replace(@SearchString,'_','[_]')
  Set @SearchString = replace(@SearchString,'%','[%]')
  Set @SearchString = replace(@SearchString,'*','%')
  Set @SearchString = replace(@SearchString,'?','_')
  Set @SearchString = replace(@SearchString,'\%','*')
  Set @SearchString = replace(@SearchString,'\_','?')
  --Set @SearchString = replace(@SearchString,'-','[-'+nchar(8209)+']')
  IF(@SearchString like '[%]%') RETURN @SearchString
  IF(@SearchString like '%[%]') RETURN @SearchString
RETURN '%' + @SearchString + '%'
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_FixSearchString Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_FixSearchString Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FixTransitionDataForCopy] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FixTransitionDataForCopy]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_FixTransitionDataForCopy];
GO
	
CREATE FUNCTION [dbo].[vefn_FixTransitionDataForCopy]
(@data XML,@TransitionID int,@TranType int,@OldToID int,@OldRangeID int, @NewID int, @NewToID int, @NewRangeID int, @NewTranType int)
RETURNS XML
WITH EXECUTE AS OWNER
AS
BEGIN
	
	-- Build Search String and Replace String
	DECLARE @offset int
	DECLARE @lookFor varchar(MAX)
	DECLARE @replaceWith varchar(MAX)
	DECLARE @text varchar(MAX)
	SET @text = Cast(@data as varchar(max))
	SET @lookFor = '#Link:Transition:' + ltrim(str(@TranType)) + ' ' + ltrim(str(@TransitionID))
	SET @offset = CHARINDEX(@lookFor,@text)
	if(@offset = 0)
	BEGIN
		
		SET @lookFor = '#Link:TransitionRange:' + ltrim(str(@TranType)) + ' ' + ltrim(str(@TransitionID))
		SET @offset = CHARINDEX(@lookFor,@text)
		SET @replaceWith = '#Link:TransitionRange:' + ltrim(str(@NewTranType)) + ' ' + ltrim(str(@NewID))
				+ ' ' + ltrim(str(@NewToID)) + ' ' + ltrim(str(@NewRangeID))
		SET @lookFor = @lookFor + ' ' + ltrim(str(@OldToID)) + ' ' + ltrim(str(@OldRangeID))
	END
	ELSE
	BEGIN
		SET @replaceWith = '#Link:Transition:' + ltrim(str(@NewTranType)) + ' ' + ltrim(str(@NewID))
				+ ' ' + ltrim(str(@NewToID))
		SET @lookFor = @lookFor + ' ' + ltrim(str(@OldToID))		
	END
  return Cast(replace(@text,@lookFor,@replaceWith) as XML)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_FixTransitionDataForCopy Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_FixTransitionDataForCopy Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FixTransitionText] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FixTransitionText]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_FixTransitionText];
GO
	
/*
select top 5 * from contents order by contentid desc

DECLARE @Text1 varchar(MAX),@Text2 varchar(MAX),@Text3 varchar(MAX),@Text4 varchar(MAX)
SET @Text1='\v <START]\v0 1, #, #, # and 4\v #Link:TransitionRange:4 58 270 285[END>\v0  PERFORM the following:'
SET @Text2='\v <START]\v0 1, #, #, # and 4\v #Link:TransitionRange:2 58 265 270[END>\v0  PERFORM the following:'
SET @Text3='\v <START]\v0 1, #, #, # and 4\v #Link:TransitionRange:2 58 270 270[END>\v0  PERFORM the following:'
SET @Text4='\v <START]\v0 ST SC, step section 2\v #Link:Transition:1 8 270[END>\v0 IF reactor will NOT trip, THEN:'

Select @Text1 Before, dbo.vefn_FixTransitionText(@Text1,58,4,270,285,270,999) [After]
Union Select @Text2 Before, dbo.vefn_FixTransitionText(@Text2,58,2,265,270,270,999) [After]
Union Select @Text3 Before, dbo.vefn_FixTransitionText(@Text3,58,2,270,270,270,999) [After]
Union Select @Text4 Before, dbo.vefn_FixTransitionText(@Text4,8,1,270,270,270,999) [After]
*/
CREATE FUNCTION [dbo].[vefn_FixTransitionText]
(@Text varchar(MAX),@TransitionID int,@TranType int,@OldToID int,@OldRangeID int,@OldID int,@NewID int)
RETURNS varchar(MAX)
WITH EXECUTE AS OWNER
AS
BEGIN
	-- Build Search String and Replace String
	DECLARE @offset int
	DECLARE @lookFor varchar(MAX)
	DECLARE @replaceWith varchar(MAX)
	SET @lookFor = '#Link:Transition:' + ltrim(str(@TranType)) + ' ' + ltrim(str(@TransitionID))
	SET @offset = CHARINDEX(@lookFor,@Text)
	if(@offset = 0)
	BEGIN
		
		SET @lookFor = '#Link:TransitionRange:' + ltrim(str(@TranType)) + ' ' + ltrim(str(@TransitionID))
		SET @offset = CHARINDEX(@lookFor,@Text)
		SET @replaceWith = @lookFor
				+ ' ' + ltrim(str(case @OldToID when @OldID then @NewID else @OldToID end))
				+ ' ' + ltrim(str(case @OldRangeID when @OldID then @NewID else @OldRangeID end))
		SET @lookFor = @lookFor + ' ' + ltrim(str(@OldToID)) + ' ' + ltrim(str(@OldRangeID))
	END
	ELSE
	BEGIN
		SET @replaceWith = @lookFor
				+ ' ' + ltrim(str(case @OldToID when @OldID then @NewID else @OldToID end))
		SET @lookFor = @lookFor + ' ' + ltrim(str(@OldToID))		
	END
  return replace(@text,@lookFor,@replaceWith)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_FixTransitionText Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_FixTransitionText Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_FixTransitionTextForCopy] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_FixTransitionTextForCopy]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_FixTransitionTextForCopy];
GO
	
CREATE FUNCTION [dbo].[vefn_FixTransitionTextForCopy]
(@Text varchar(MAX),@TransitionID int,@TranType int,@OldToID int,@OldRangeID int, @NewID int, @NewToID int, @NewRangeID int, @NewTranType int)
RETURNS varchar(MAX)
WITH EXECUTE AS OWNER
AS
BEGIN
	
	-- Build Search String and Replace String
	DECLARE @offset int
	DECLARE @lookFor varchar(MAX)
	DECLARE @replaceWith varchar(MAX)
	SET @lookFor = '#Link:Transition:' + ltrim(str(@TranType)) + ' ' + ltrim(str(@TransitionID))
	SET @offset = CHARINDEX(@lookFor,@Text)
	if(@offset = 0)
	BEGIN
		
		SET @lookFor = '#Link:TransitionRange:' + ltrim(str(@TranType)) + ' ' + ltrim(str(@TransitionID))
		SET @offset = CHARINDEX(@lookFor,@Text)
		SET @replaceWith = '#Link:TransitionRange:' + ltrim(str(@NewTranType)) + ' ' + ltrim(str(@NewID))
				+ ' ' + ltrim(str(@NewToID)) + ' ' + ltrim(str(@NewRangeID))
		SET @lookFor = @lookFor + ' ' + ltrim(str(@OldToID)) + ' ' + ltrim(str(@OldRangeID))
	END
	ELSE
	BEGIN
		SET @replaceWith = '#Link:Transition:' + ltrim(str(@NewTranType)) + ' ' + ltrim(str(@NewID))
				+ ' ' + ltrim(str(@NewToID))
		SET @lookFor = @lookFor + ' ' + ltrim(str(@OldToID))		
	END
  return replace(@text,@lookFor,@replaceWith)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_FixTransitionTextForCopy Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_FixTransitionTextForCopy Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetDocumentPageLength] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetDocumentPageLength]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_GetDocumentPageLength];
GO
	
/*
print .dbo.[vefn_GetDocumentPageLength](1)
select DocID, .dbo.[vefn_GetDocumentPageLength](DocID) PageLength from Documents
*/

CREATE FUNCTION [dbo].[vefn_GetDocumentPageLength] (@DocID int) RETURNS float
WITH EXECUTE AS OWNER
AS
BEGIN
DECLARE @PageLength float
SET @PageLength = (select top 1 v.value('.', 'nvarchar(100)') [Length]
from (select DocID, cast (Config as xml) ConfigXML  from Documents) T1
CROSS APPLY ConfigXML.nodes('//@Length') TempXML(v)
WHERE DocID = @DocID)
return @PageLength
END;
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_GetDocumentPageLength Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_GetDocumentPageLength Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetFormatField] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetFormatField]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_GetFormatField];
GO
	
/*
Select * from vefn_GetFormatField('Font')
Select * from vefn_GetFormatField('PSADJBNGROW')
Select * from vefn_GetFormatField('SectionTitle')
Select * from vefn_GetFormatField('PrintNoTitle')
*/

CREATE FUNCTION [dbo].[vefn_GetFormatField](@find varchar(255))
RETURNS @FormatFields TABLE
(
	FormatID int
	,Name varchar(20)
	,Description varchar(250)
  ,Path varchar(max)
	,Value varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	INSERT INTO @FormatFields
	Select FormatID, Name, Description,
	case when v9.exist('.') is null THEN '' ELSE v9.value('local-name(.)','varchar(max)') + '/' END +
	case when v8.exist('.') is null THEN '' ELSE v8.value('local-name(.)','varchar(max)') + '/' END +
	case when v7.exist('.') is null THEN '' ELSE v7.value('local-name(.)','varchar(max)') + '/' END +
	case when v6.exist('.') is null THEN '' ELSE v6.value('local-name(.)','varchar(max)') + '/' END +
	case when v5.exist('.') is null THEN '' ELSE v5.value('local-name(.)','varchar(max)') + '/' END +
	case when v4.exist('.') is null THEN '' ELSE v4.value('local-name(.)','varchar(max)') + '/' END +
	case when v3.exist('.') is null THEN '' ELSE v3.value('local-name(.)','varchar(max)') + '/' END +
	case when v2.exist('.') is null THEN '' ELSE v2.value('local-name(.)','varchar(max)') + '/' END +
	case when v1.exist('.') is null THEN '' ELSE v1.value('local-name(.)','varchar(max)') + '/' END +
	+ '@' + v.value('local-name(.)','varchar(max)') Path
	, v.value('.', 'varchar(255)') Value
	FROM Formats
	CROSS APPLY Data.nodes('//*/@*') TempXML(v)
	OUTER APPLY v.nodes('..') TempXML1(v1)
	OUTER APPLY v1.nodes('..') TempXML2(v2)
	OUTER APPLY v2.nodes('..') TempXML3(v3)
	OUTER APPLY v3.nodes('..') TempXML4(v4)
	OUTER APPLY v4.nodes('..') TempXML5(v5)
	OUTER APPLY v5.nodes('..') TempXML6(v6)
	OUTER APPLY v6.nodes('..') TempXML7(v7)
	OUTER APPLY v7.nodes('..') TempXML8(v8)
	OUTER APPLY v8.nodes('..') TempXML9(v9)
	where v.value('local-name(.)', 'varchar(255)') like '%' + @find + '%'
	OR v.value('.', 'varchar(255)') like '%' + @find + '%'
	UNION
	Select FormatID, Name, Description,
	case when v9.exist('.') is null THEN '' ELSE v9.value('local-name(.)','varchar(max)') + '/' END +
	case when v8.exist('.') is null THEN '' ELSE v8.value('local-name(.)','varchar(max)') + '/' END +
	case when v7.exist('.') is null THEN '' ELSE v7.value('local-name(.)','varchar(max)') + '/' END +
	case when v6.exist('.') is null THEN '' ELSE v6.value('local-name(.)','varchar(max)') + '/' END +
	case when v5.exist('.') is null THEN '' ELSE v5.value('local-name(.)','varchar(max)') + '/' END +
	case when v4.exist('.') is null THEN '' ELSE v4.value('local-name(.)','varchar(max)') + '/' END +
	case when v3.exist('.') is null THEN '' ELSE v3.value('local-name(.)','varchar(max)') + '/' END +
	case when v2.exist('.') is null THEN '' ELSE v2.value('local-name(.)','varchar(max)') + '/' END +
	case when v1.exist('.') is null THEN '' ELSE v1.value('local-name(.)','varchar(max)') + '/' END +
	+ v.value('local-name(.)','varchar(max)') Path
	, '{node}'
	FROM Formats
	CROSS APPLY Data.nodes('//*') TempXML(v)
	OUTER APPLY v.nodes('..') TempXML1(v1)
	OUTER APPLY v1.nodes('..') TempXML2(v2)
	OUTER APPLY v2.nodes('..') TempXML3(v3)
	OUTER APPLY v3.nodes('..') TempXML4(v4)
	OUTER APPLY v4.nodes('..') TempXML5(v5)
	OUTER APPLY v5.nodes('..') TempXML6(v6)
	OUTER APPLY v6.nodes('..') TempXML7(v7)
	OUTER APPLY v7.nodes('..') TempXML8(v8)
	OUTER APPLY v8.nodes('..') TempXML9(v9)
	where v.value('local-name(.)', 'varchar(255)') like '%' + @find + '%'
	RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_GetFormatField Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_GetFormatField Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetFormatFieldByStepType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetFormatFieldByStepType]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_GetFormatFieldByStepType];
GO
	
/*
Select * from vefn_GetFormatFieldByStepType('Font')
Select * from vefn_GetFormatFieldByStepType('PSADJBNGROW')
Select * from vefn_GetFormatFieldByStepType('SectionTitle')
Select * from vefn_GetFormatFieldByStepType('PrintNoTitle')
Select * from vefn_GetFormatFieldByStepType('Off') where name ='AEP'

*/

CREATE FUNCTION [dbo].[vefn_GetFormatFieldByStepType](@find varchar(255))
RETURNS @FormatFields TABLE
(
	FormatID int
	,Name varchar(20)
	,Description varchar(250)
  ,Path varchar(max)
	,StepType varchar(255)
	,Value varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	INSERT INTO @FormatFields
	Select FormatID, Name, Description,
	case when v9.exist('.') is null THEN '' ELSE v9.value('local-name(.)','varchar(max)') + '/' END +
	case when v8.exist('.') is null THEN '' ELSE v8.value('local-name(.)','varchar(max)') + '/' END +
	case when v7.exist('.') is null THEN '' ELSE v7.value('local-name(.)','varchar(max)') + '/' END +
	case when v6.exist('.') is null THEN '' ELSE v6.value('local-name(.)','varchar(max)') + '/' END +
	case when v5.exist('.') is null THEN '' ELSE v5.value('local-name(.)','varchar(max)') + '/' END +
	case when v4.exist('.') is null THEN '' ELSE v4.value('local-name(.)','varchar(max)') + '/' END +
	case when v3.exist('.') is null THEN '' ELSE v3.value('local-name(.)','varchar(max)') + '/' END +
	case when v2.exist('.') is null THEN '' ELSE v2.value('local-name(.)','varchar(max)') + '/' END +
	case when v1.exist('.') is null THEN '' ELSE v1.value('local-name(.)','varchar(max)') + '/' END +
	.dbo.vefn_XmlPath(v1.query('.')) +
	+ '@' + v.value('local-name(.)','varchar(max)') Path
	, coalesce(v.value('../@Type','varchar(255)'),v.value('../../@Type','varchar(255)'),v.value('../../../@Type','varchar(255)')) StepType
	, v.value('.', 'varchar(255)') Value
	FROM Formats
	CROSS APPLY Data.nodes('//*/@*') TempXML(v)
	OUTER APPLY v.nodes('..') TempXML1(v1)
	OUTER APPLY v1.nodes('..') TempXML2(v2)
	OUTER APPLY v2.nodes('..') TempXML3(v3)
	OUTER APPLY v3.nodes('..') TempXML4(v4)
	OUTER APPLY v4.nodes('..') TempXML5(v5)
	OUTER APPLY v5.nodes('..') TempXML6(v6)
	OUTER APPLY v6.nodes('..') TempXML7(v7)
	OUTER APPLY v7.nodes('..') TempXML8(v8)
	OUTER APPLY v8.nodes('..') TempXML9(v9)
	where v.value('local-name(.)', 'varchar(255)') like '%' + @find + '%'
	OR v.value('.', 'varchar(255)') like '%' + @find + '%'
	UNION ALL
	Select FormatID, Name, Description,
	case when v9.exist('.') is null THEN '' ELSE v9.value('local-name(.)','varchar(max)') + '/' END +
	case when v8.exist('.') is null THEN '' ELSE v8.value('local-name(.)','varchar(max)') + '/' END +
	case when v7.exist('.') is null THEN '' ELSE v7.value('local-name(.)','varchar(max)') + '/' END +
	case when v6.exist('.') is null THEN '' ELSE v6.value('local-name(.)','varchar(max)') + '/' END +
	case when v5.exist('.') is null THEN '' ELSE v5.value('local-name(.)','varchar(max)') + '/' END +
	case when v4.exist('.') is null THEN '' ELSE v4.value('local-name(.)','varchar(max)') + '/' END +
	case when v3.exist('.') is null THEN '' ELSE v3.value('local-name(.)','varchar(max)') + '/' END +
	case when v2.exist('.') is null THEN '' ELSE v2.value('local-name(.)','varchar(max)') + '/' END +
	case when v1.exist('.') is null THEN '' ELSE v1.value('local-name(.)','varchar(max)') + coalesce('[' + v1.value('@Index','varchar(255)')+']','') + '/' END +
	+ v.value('local-name(.)','varchar(max)') Path
	, coalesce(v.value('../@Type','varchar(255)'),v.value('../../@Type','varchar(255)'),v.value('../../../@Type','varchar(255)')) StepType
	, '{node}'
	FROM Formats
	CROSS APPLY Data.nodes('//*') TempXML(v)
	OUTER APPLY v.nodes('..') TempXML1(v1)
	OUTER APPLY v1.nodes('..') TempXML2(v2)
	OUTER APPLY v2.nodes('..') TempXML3(v3)
	OUTER APPLY v3.nodes('..') TempXML4(v4)
	OUTER APPLY v4.nodes('..') TempXML5(v5)
	OUTER APPLY v5.nodes('..') TempXML6(v6)
	OUTER APPLY v6.nodes('..') TempXML7(v7)
	OUTER APPLY v7.nodes('..') TempXML8(v8)
	OUTER APPLY v8.nodes('..') TempXML9(v9)
	where v.value('local-name(.)', 'varchar(255)') like '%' + @find + '%'
	RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_GetFormatFieldByStepType Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_GetFormatFieldByStepType Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetFormatFieldByStepType2] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetFormatFieldByStepType2]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_GetFormatFieldByStepType2];
GO
	
/*
Select * from vefn_GetFormatFieldByStepType2('Font')
Select * from vefn_GetFormatFieldByStepType2('PSADJBNGROW')
Select * from vefn_GetFormatFieldByStepType2('SectionTitle')
Select * from vefn_GetFormatFieldByStepType2('PrintNoTitle')
Select * from vefn_GetFormatFieldByStepType2('Off')

*/

CREATE FUNCTION [dbo].[vefn_GetFormatFieldByStepType2](@find varchar(255))
RETURNS @FormatFields TABLE
(
	FormatID int
	,Name varchar(20)
	,Description varchar(250)
  ,Path varchar(max)
	,StepType varchar(255)
	,Indx varchar(255)
	,Value varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	INSERT INTO @FormatFields
	Select FormatID, Name, Description,
	.dbo.vefn_XmlPath(v9.query('.')) +
	.dbo.vefn_XmlPath(v8.query('.')) +
	.dbo.vefn_XmlPath(v7.query('.')) +
	.dbo.vefn_XmlPath(v6.query('.')) +
	.dbo.vefn_XmlPath(v5.query('.')) +
	.dbo.vefn_XmlPath(v4.query('.')) +
	.dbo.vefn_XmlPath(v3.query('.')) +
	.dbo.vefn_XmlPath(v2.query('.')) +
	.dbo.vefn_XmlPath(v1.query('.')) +
	+ '@' + v.value('local-name(.)','varchar(max)') Path
	, coalesce(v.value('../@Type','varchar(255)'),v.value('../../@Type','varchar(255)'),v.value('../../../@Type','varchar(255)')) StepType
	, coalesce(v1.value('@Index','varchar(255)'),v2.value('@Index','varchar(255)'),v3.value('@Index','varchar(255)')) Indx
	, v.value('.', 'varchar(255)') Value
	FROM Formats
	CROSS APPLY Data.nodes('//*/@*') TempXML(v)
	OUTER APPLY v.nodes('..') TempXML1(v1)
	OUTER APPLY v1.nodes('..') TempXML2(v2)
	OUTER APPLY v2.nodes('..') TempXML3(v3)
	OUTER APPLY v3.nodes('..') TempXML4(v4)
	OUTER APPLY v4.nodes('..') TempXML5(v5)
	OUTER APPLY v5.nodes('..') TempXML6(v6)
	OUTER APPLY v6.nodes('..') TempXML7(v7)
	OUTER APPLY v7.nodes('..') TempXML8(v8)
	OUTER APPLY v8.nodes('..') TempXML9(v9)
	where v.value('local-name(.)', 'varchar(255)') like '%' + @find + '%'
	OR v.value('.', 'varchar(255)') like '%' + @find + '%'
	RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_GetFormatFieldByStepType2 Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_GetFormatFieldByStepType2 Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetFormatFieldNoValue] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetFormatFieldNoValue]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_GetFormatFieldNoValue];
GO
	
/*
Select * from vefn_GetFormatFieldNoValue('Font')
Select * from vefn_GetFormatFieldNoValue('PSADJBNGROW')
Select * from vefn_GetFormatFieldNoValue('SectionTitle')
Select * from vefn_GetFormatFieldNoValue('PrintNoTitle')
Select * from vefn_GetFormatFieldNoValue('Off')
*/

CREATE FUNCTION [dbo].[vefn_GetFormatFieldNoValue](@find varchar(255))
RETURNS @FormatFields TABLE
(
	FormatID int
	,Name varchar(20)
	,Description varchar(250)
  ,Path varchar(max)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	INSERT INTO @FormatFields
	Select FormatID, Name, Description,
	case when v9.exist('.') is null THEN '' ELSE v9.value('local-name(.)','varchar(max)') + '/' END +
	case when v8.exist('.') is null THEN '' ELSE v8.value('local-name(.)','varchar(max)') + '/' END +
	case when v7.exist('.') is null THEN '' ELSE v7.value('local-name(.)','varchar(max)') + '/' END +
	case when v6.exist('.') is null THEN '' ELSE v6.value('local-name(.)','varchar(max)') + '/' END +
	case when v5.exist('.') is null THEN '' ELSE v5.value('local-name(.)','varchar(max)') + '/' END +
	case when v4.exist('.') is null THEN '' ELSE v4.value('local-name(.)','varchar(max)') + '/' END +
	case when v3.exist('.') is null THEN '' ELSE v3.value('local-name(.)','varchar(max)') + '/' END +
	case when v2.exist('.') is null THEN '' ELSE v2.value('local-name(.)','varchar(max)') + '/' END +
	case when v1.exist('.') is null THEN '' ELSE v1.value('local-name(.)','varchar(max)') + '/' END +
	+ '@' + v.value('local-name(.)','varchar(max)') Path
	FROM Formats
	CROSS APPLY Data.nodes('//*/@*') TempXML(v)
	OUTER APPLY v.nodes('..') TempXML1(v1)
	OUTER APPLY v1.nodes('..') TempXML2(v2)
	OUTER APPLY v2.nodes('..') TempXML3(v3)
	OUTER APPLY v3.nodes('..') TempXML4(v4)
	OUTER APPLY v4.nodes('..') TempXML5(v5)
	OUTER APPLY v5.nodes('..') TempXML6(v6)
	OUTER APPLY v6.nodes('..') TempXML7(v7)
	OUTER APPLY v7.nodes('..') TempXML8(v8)
	OUTER APPLY v8.nodes('..') TempXML9(v9)
	where v.value('local-name(.)', 'varchar(255)') like '%' + @find + '%'
	RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_GetFormatFieldNoValue Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_GetFormatFieldNoValue Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetFormatValues] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetFormatValues]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_GetFormatValues];
GO
	
/*

SELECT * from vefn_GetFormatValues('WidSAdjByLevel')
SELECT * from vefn_GetFormatValues('MatchProcNumber')
SELECT * from vefn_GetFormatValues('TofCPositionAdj')

*/


CREATE  FUNCTION [dbo].[vefn_GetFormatValues](@FieldName as varchar(255))
RETURNS @AllValues TABLE
(
  FormatID int,
	Name varchar(100),
	ParentNode XML,
	Node XML,
	FieldValue varchar(MAX)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @NodeName as varchar(255)
	set @NodeName = (Select distinct v.value('local-name(..)', 'varchar(255)') MyName
		FROM Formats CROSS APPLY Data.nodes('(*//@*[local-name()=sql:variable("@FieldName")])') TempXML(v))
	Insert into @AllValues
		Select FormatID, Name, v.query('..') ParentNode, v.query('.') Node,
		v.value('(./@*[local-name()=sql:variable("@FieldName")])[1]','varchar(255)') FieldValue
		FROM Formats CROSS APPLY Data.nodes('(//*[local-name()=sql:variable("@NodeName")])') TempXML(v)
	RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_GetFormatValues Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_GetFormatValues Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetGenMacMacros] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetGenMacMacros]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_GetGenMacMacros];
GO
	
/*
Select * from vefn_GetGenMacMacros()
*/

CREATE FUNCTION [dbo].[vefn_GetGenMacMacros]()
RETURNS @GenMacMacros TABLE
(
	FormatID int
	,Name varchar(20)
	,Description varchar(250)
	,MacroName varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	INSERT INTO @GenMacMacros
	Select FormatID, Name, Description,v.value('@id','varchar(20)') MacroName
	FROM Formats CROSS APPLY GenMac.nodes('//g') TempXML(v)
	RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_GetGenMacMacros Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_GetGenMacMacros Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetInheritedFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetInheritedFormat]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_GetInheritedFormat];
GO
	
/* Samples
Select TranType, .dbo.vefn_GetInheritedFormat(355) TransFormat
	from(Select 1 TranType UNION Select 2 TranType UNION Select 3 TranType UNION
	Select 4 TranType UNION Select 5 TranType UNION Select 6 TranType UNION
	Select 7 TranType UNION Select 8 TranType UNION Select 9 TranType UNION Select 10 TranType) TT

Select top 25 ItemID, TranType, .dbo.vefn_GetInheritedFormat(ItemID) TransFormat
  From Transitions TR
  Join Items II on II.ContentID = TR.FromID

*/
/*
	local is a 'boolean' (0=false, 1=true) to state whether to look at the item itself or
	only its parent
*/
CREATE FUNCTION [dbo].[vefn_GetInheritedFormat] (@ItemID int, @local int) RETURNS int
WITH EXECUTE AS OWNER
AS
BEGIN
	DECLARE @FormatID as int
	-- First get the Active Format
	begin
	with Itemz([Level], [PreviousID], [ItemID], [ParentID], [FolderID], [FormatID]) as (
		Select 0 [Level], [PreviousID], [ItemID], null, null,
		case when @local = 1 then (Select FormatID from Contents CC where [CC].[ContentID] = [II].[ContentID])
			 else null end FormatID
		FROM [Items] II
			where [ItemID]=@ItemID
	Union All
	-- Parent Item
		select [Level] + 1, I.[PreviousID], I.[ItemID], null, null, C.FormatID
		from Itemz Z
		join Parts P on P.ItemID = Z.ItemID
		join Items I on I.ContentID = P.ContentID
		join Contents C on C.ContentID = P.ContentID
		where Z.FormatID is null
	-- Siblings Item
	Union All
		select [Level] , I.[PreviousID] , I.[ItemID], null, null, Z.FormatID
		from Itemz Z
		join Items I on Z.PreviousID = I.ItemID
		where Z.FormatID is null
	Union All
	-- DocVersion From Item
		select [Level] + 1, null, null, DV.FolderID, null, DV.FormatID
		from Itemz Z
		join DocVersions DV on DV.ItemID = Z.ItemID
		where Z.FormatID is null
	Union All
	-- Folders
		select [Level] + 1, null, null, FF.ParentID, FF.FolderID, FF.FormatID
		from Itemz Z
		join Folders FF on FF.FolderID = Z.ParentID and FF.ParentID <> FF.FolderID
		where Z.FormatID is null
	)
	Select @FormatID = FormatID from Itemz ZZ Where FormatID is not null
	
	RETURN @FormatID
	END
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_GetInheritedFormat Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_GetInheritedFormat Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetNewTranType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetNewTranType]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_GetNewTranType];
GO
	
/* Samples

SELECT .dbo.[vefn_GetNewTranType] (1, 2, 6)
SELECT .dbo.[vefn_GetNewTranType] (1, 2, 7)
SELECT .dbo.[vefn_GetNewTranType] (27, 29, 10)
SELECT .dbo.[vefn_GetNewTranType] (29, 27, 10)
SELECT .dbo.[vefn_GetNewTranType] (27, 31, 10)
--SELECT .dbo.[vefn_GetNewTranType] (29, 27, 10)

*/
CREATE FUNCTION [dbo].[vefn_GetNewTranType] (@FormatID int, @NewFormatID int, @TranType int) RETURNS int
WITH EXECUTE AS OWNER
AS
BEGIN
	--
	IF @FormatID = @NewFormatID
		RETURN @TranType
	DECLARE @TransFormat varchar(max)
	DECLARE @NewTransFormat varchar(max)
	SET @TransFormat = isnull(.dbo.vefn_GetTransFormat(@FormatID, @TranType),'')
	SET @NewTransFormat = isnull(.dbo.vefn_GetTransFormat(@NewFormatID, @TranType),'')
	RETURN CASE
		WHEN @TransFormat = @NewTransFormat THEN @TranType
		WHEN @TransFormat LIKE '%{Last Step}%' THEN
			CASE
				WHEN @NewTransFormat LIKE '%{Last Step}%' THEN @TranType
				ELSE 3		-- This is a default 'range' type, all transition formats have it!
			END
		ELSE
			CASE
				WHEN @NewTransFormat LIKE '%{Last Step}%' THEN 0
				ELSE @TranType	-- This is a default 'single' type, all transition formats have it!
			END
	END
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_GetNewTranType Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_GetNewTranType Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetNullFormatValues] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetNullFormatValues]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_GetNullFormatValues];
GO
	
/*

SELECT * from vefn_GetNullFormatValues('WidSAdjByLevel')
SELECT * from vefn_GetNullFormatValues('MatchProcNumber')
SELECT * from vefn_GetNullFormatValues('TofCPositionAdj')

*/


CREATE  FUNCTION [dbo].[vefn_GetNullFormatValues](@FieldName as varchar(255))
RETURNS @NullValues TABLE
(
  FormatID int,
	Name varchar(100),
	ParentNode XML,
	Node XML
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @NodeName as varchar(255)
	set @NodeName = (Select distinct v.value('local-name(..)', 'varchar(255)') MyName
		FROM Formats CROSS APPLY Data.nodes('(*//@*[local-name()=sql:variable("@FieldName")])') TempXML(v))
	Insert into @NullValues
		Select FormatID, Name, ParentNode, Node FROM (
			Select FormatID, Name, v.query('..') ParentNode, v.query('.') Node,
			v.value('(./@*[local-name()=sql:variable("@FieldName")])[1]','varchar(255)') FieldValue
			FROM Formats CROSS APPLY Data.nodes('(//*[local-name()=sql:variable("@NodeName")])') TempXML(v)
		) t1 WHERE FieldValue is null
	RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_GetNullFormatValues Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_GetNullFormatValues Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetTokens] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetTokens]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_GetTokens];
GO
	
/*
select * from vefn_GetTokens('abc{Header1}def{Header2}ghi')
*/
CREATE  FUNCTION [dbo].[vefn_GetTokens](@text varchar(64))
RETURNS @Tokens TABLE
(
	Token varchar(64)
)
WITH EXECUTE AS OWNER
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
  BEGIN
    SET @index = CHARINDEX('{' , @text)
    IF @index = 0
      BREAK
		DECLARE @index2 int
		SET @index2 = CHARINDEX('}' , @text)
		if @index2 = 0
			BREAK
    INSERT INTO @Tokens VALUES (substring(@text, @index,1+@index2-@index))
    SET @text = RIGHT(@text, (LEN(@text) - @index2))
  END
  RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_GetTokens Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_GetTokens Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_GetTransFormat] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_GetTransFormat]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_GetTransFormat];
GO
	
/* Samples
select .dbo.vefn_GetTransFormat(1,6)
select .dbo.vefn_GetTransFormat(1,1)
select .dbo.vefn_GetTransFormat(1,2)
select .dbo.vefn_GetTransFormat(1,3)

*/
CREATE FUNCTION [dbo].[vefn_GetTransFormat] (@FormatID int, @TranType int) RETURNS varchar(max)
WITH EXECUTE AS OWNER
AS
BEGIN
	
  -- Walk up the Formats (inheritance) looking for the TransFormat
	Declare @TransFormat as varchar(MAX)
	BEGIN
	with Formatz([MyOrder],[FormatID],[ParentID],[Data]) as (
		Select 0,FormatID, ParentID, Data From Formats where FormatID=@FormatID
	Union All
		Select [MyOrder]+1,FF.FormatID, FF.ParentID, FF.Data From Formats FF
			Join Formatz ZZ on ZZ.ParentID=FF.FormatID
				Where ZZ.FormatID <> ZZ.ParentID)
	Select  Top 1 @TransFormat=v.value('./@TransFormat', 'varchar(MAX)')
	FROM Formatz
	CROSS APPLY Data.nodes('//TransTypes') TempXML(v)
	where v.value('./@TransType', 'int')=@TranType
	order by [MyOrder]
	END
	return @TransFormat
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_GetTransFormat Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_GetTransFormat Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_HighLevelStepTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_HighLevelStepTransitions]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_HighLevelStepTransitions];
GO
	
/*
select * from vefn_HighLevelStepTransitions(105,104)
where TransCount > 0
*/

CREATE  FUNCTION [dbo].[vefn_HighLevelStepTransitions](@ItemID int, @ParentID int)
RETURNS @HighLevelStepTransitions TABLE
(
	ParentID int
	,ItemID int PRIMARY KEY
  ,Path varchar(max)
	,TransCount int
	,ExternalTransitions int
	,InternalTransitions int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], @ParentID [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	--where Z.[Level] > 0
)
Insert into @HighLevelStepTransitions
select [ParentID],ItemID,dbo.ve_GetPath([ItemID]) ,(Select Count(*) from Transitions where ToID=ItemID OR RangeID=ItemID ) TransCount
,(Select count(*) from vefn_FindExternalTransitions(ItemID)) ExternalTransitions
,(Select count(*) from vefn_FindInternalTransitions(ItemID)) InternalTransitions
from Itemz
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_HighLevelStepTransitions Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_HighLevelStepTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_NextStepTransitions] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_NextStepTransitions]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_NextStepTransitions];
GO
	
/*
select * from vefn_NextStepTransitions(450,443)
*/

CREATE  FUNCTION [dbo].[vefn_NextStepTransitions](@ItemID int, @PreviousID int)
RETURNS @Transitions TABLE
(
  [TransitionID] int PRIMARY KEY,
	[FromID] [int],
	[ToID] [int],
	[RangeID] [int],
	[TranType] [int],
	[Config] [nvarchar](max)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	INSERT INTO @Transitions
	SELECT [TransitionID],[FromID],[ToID],[RangeID],[TranType],[Config]
		FROM [Transitions] where FromID in (Select ContentID from vefn_ChildItems(@PreviousID))
		AND (ToID = @ItemID OR RangeID = @ItemID)
	RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_NextStepTransitions Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_NextStepTransitions Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_RemoveExtraText] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_RemoveExtraText]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_RemoveExtraText];
GO
	
/*
select text, .dbo.vefn_RemoveExtraText(text,2,0,0) StrippedText from Contents where ContentID=373
select text, .dbo.vefn_RemoveExtraText(text,1,0,0) StrippedText from Contents where ContentID=373
select text, .dbo.vefn_RemoveExtraText(text,0,0,0) StrippedText ,.dbo.vefn_FirstLink(text,0), PATINDEX('%[' + nchar(9516) + nchar(9574) + char(21) + ']%' , text)  from Contents where ContentID=373
select .dbo.vefn_RemoveExtraText('\b Bold\b0',0,0,0)
select .dbo.vefn_RemoveExtraText('\b Bold\b0',0,1,0)
select .dbo.vefn_RemoveExtraText('A\u1?B\u12?C\u123?D\u1234?E',0,0,0)
select .dbo.vefn_RemoveExtraText('A\u1?B\u12?C\u123?D\u1234?E',0,0,1)
*/


CREATE FUNCTION [dbo].[vefn_RemoveExtraText](@text nvarchar(MAX),@includeLink int, @includeRtfFormatting int , @includeSpecialCharacters int)
RETURNS varchar(MAX)
WITH EXECUTE AS OWNER
AS
BEGIN
DECLARE @index int
DECLARE @index2 int
-- Strip Links
IF @includeLink = 0 -- Remove Links
	SET @text = [dbo].[vefn_RemoveRange](@text,'<START]' ,'[END>')
IF @includeLink < 2 -- Remove Comments
	SET @text = [dbo].[vefn_RemoveRange](@text,'\v' ,'\v0')
if(@includeRtfFormatting=0)
	-- Remove Rtf Formatting
	BEGIN
			SET @text = Replace(@text, '\b0 ', '');
			SET @text = Replace(@text, '\b ', '');
			SET @text = Replace(@text, '\ul0 ', '');
			SET @text = Replace(@text, '\ul ', '');
			SET @text = Replace(@text, '\i0 ', '');
			SET @text = Replace(@text, '\i ', '');
			SET @text = Replace(@text, '\super ', '');
			SET @text = Replace(@text, '\sub ', '');
			SET @text = Replace(@text, '\nosupersub ', '');
			SET @text = Replace(@text, '\b0', '');
			SET @text = Replace(@text, '\b', '');
			SET @text = Replace(@text, '\ul0', '');
			SET @text = Replace(@text, '\ul', '');
			SET @text = Replace(@text, '\i0', '');
			SET @text = Replace(@text, '\i', '');
			SET @text = Replace(@text, '\super', '');
			SET @text = Replace(@text, '\sub', '');
			SET @text = Replace(@text, '\nosupersub', '');
	END
if(@includeSpecialCharacters=0)
  -- Remove Special Characters
  BEGIN
		SET @index = PATINDEX('%\u[0-9]?%',@text)
		while(@index != 0)
			BEGIN
				SET @text = substring(@text,1,@index-1) + substring(@text,@index+4,len(@text))
				SET @index = PATINDEX('%\u[0-9]?%',@text)
			END
		SET @index = PATINDEX('%\u[0-9][0-9]?%',@text)
		while(@index != 0)
			BEGIN
				SET @text = substring(@text,1,@index-1) + substring(@text,@index+5,len(@text))
				SET @index = PATINDEX('%\u[0-9][0-9]?%',@text)
			END
		SET @index = PATINDEX('%\u[0-9][0-9][0-9]?%',@text)
		while(@index != 0)
			BEGIN
				SET @text = substring(@text,1,@index-1) + substring(@text,@index+6,len(@text))
				SET @index = PATINDEX('%\u[0-9][0-9][0-9]?%',@text)
			END
		SET @index = PATINDEX('%\u[0-9][0-9][0-9][0-9]?%',@text)
		while(@index != 0)
			BEGIN
				SET @text = substring(@text,1,@index-1) + substring(@text,@index+7,len(@text))
				SET @index = PATINDEX('%\u[0-9][0-9][0-9][0-9]?%',@text)
			END
		SET @index = PATINDEX('%\''[0-9A-Fa-f][0-9A-Fa-f]%',@text)
		while(@index != 0)
			BEGIN
				SET @text = substring(@text,1,@index-1) + substring(@text,@index+4,len(@text))
				SET @index = PATINDEX('%\''[0-9A-Fa-f][0-9A-Fa-f]%',@text)
			END

  END
RETURN @text
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_RemoveExtraText Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_RemoveExtraText Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_RemoveRange] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_RemoveRange]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_RemoveRange];
GO
	
/*
SELECT ContentID, text, [dbo].[vefn_RemoveRange](text,'<START]','[END>') StrippedText
from contents
where contentid in (select top 25 ContentID from contents where text like '%[[]END>%')

select top 25 * from contents where text like '%[[]END>%'

SELECT ContentID, [dbo].[vefn_RemoveRange](text,'<START]','[END>') StrippedText
from contents
where contentid =189
*/

CREATE FUNCTION [dbo].[vefn_RemoveRange](@text nvarchar(MAX),@startToken nvarchar(MAX), @endToken nvarchar(MAX))
RETURNS varchar(MAX)
WITH EXECUTE AS OWNER
AS
BEGIN
	DECLARE @index int
	DECLARE @index2 int
	DECLARE @lenStartToken int
	DECLARE @lenEndToken int
	SET @lenStartToken = len(@startToken)
	SET @lenEndToken = len(@endToken)
	SET @index = CHARINDEX(@startToken , @text)
	while (@index != 0)
		BEGIN
			SET @index2 = CHARINDEX(@endToken , @text, @index + @lenStartToken)
			SET @text = substring(@text,1,@index-1) + substring(@text,@index2+@lenEndToken,len(@text))
			SET @index = CHARINDEX(@startToken , @text)
		END
	RETURN @text
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_RemoveRange Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_RemoveRange Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_SectionFormats] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_SectionFormats]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_SectionFormats];
GO
	
--select FormatID
--,10000 + v.value('../@Index', 'int') [SectionType]
--,[Name]
--,v.value('../@Name', 'varchar(255)') [SectionFormatName]
--,v.value('@TopRow', 'int') TopRow
--,v.value('@PageLength', 'int') PageLength
--,v.value('@FooterLength', 'int') FooterLength
--,v.value('@LeftMargin', 'int') LeftMargin
--,v.value('@PageWidth', 'int') PageWidth
--from Formats
--CROSS APPLY Data.nodes('//DocStyle/Layout') TempXML(v)

/*

select * from vefn_SectionFormats() where Name = 'OHLP'

*/

CREATE FUNCTION [dbo].[vefn_SectionFormats]()
RETURNS @SectionFormats TABLE
(
	[FormatID] int
	,[SectionType] int
	,[Name] nvarchar(20)
	,[SectionFormatName] nvarchar(max)
	,[TopRow] int
	,[PageLength] int
	,[FooterLength] int
	,[LeftMargin] int
	,[PageWidth] int
)
WITH EXECUTE AS OWNER
AS
BEGIN
Insert into @SectionFormats
select FormatID
,10000 + v.value('../@Index', 'int') [SectionType]
,[Name]
,v.value('../@Name', 'varchar(255)') [SectionFormatName]
,v.value('@TopRow', 'int') TopRow
,v.value('@PageLength', 'int') PageLength
,v.value('@FooterLength', 'int') FooterLength
,v.value('@LeftMargin', 'int') LeftMargin
,v.value('@PageWidth', 'int') PageWidth
from Formats
CROSS APPLY Data.nodes('//DocStyle/Layout') TempXML(v)
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_SectionFormats Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_SectionFormats Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_SiblingAndChildrenItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_SiblingAndChildrenItems]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_SiblingAndChildrenItems];
GO
	
/*
select * from vefn_SiblingAndChildrenItems('3') II
join
*/

CREATE  FUNCTION [dbo].[vefn_SiblingAndChildrenItems](@DocVersionList varchar(10))
RETURNS @SiblingAndChildren TABLE
(
		[ItemID] int PRIMARY KEY
	, [DVPath] nvarchar(max)
	, [Path] nvarchar(max)
	, [Level] int
	, [FromType] int
	, [Ordinal] int
	, [ParentID] int
	, [PreviousID] int
	, [ContentID] int
	, [DTS] datetime
	, [UserID] nvarchar(100)
	, [pContentID] int
	, [pDTS] datetime
	, [pUserID] nvarchar(100)
	, [IsRNO] int

--	, [PPath] nvarchar(max)
--	, [POrdinalPath] nvarchar(max)
	, [OrdinalPath] nvarchar(max)
)
WITH EXECUTE AS OWNER
AS
BEGIN
Declare @Delim char(1)
Set @Delim=char(7)
Declare @DelimNumber char(1)
Set @DelimNumber=char(17)
Declare @DelimStep char(1)
Set @DelimStep='.'
BEGIN
with Itemz([ItemID], [DVPath], [Level], [ParentID], [Ordinal], [PreviousID], [FromType], [ContentID], [DTS], [UserID],[pContentID],
  [pDTS],[pUserID],PPath, [Path], [IsRNO], [POrdinalPath], [OrdinalPath]) as (
  Select [I].[ItemID], DVPath, 0 [Level], 0 [ParentID], 0 [Ordinal], [PreviousID],0 [FromType],[I].[ContentID],[I].[DTS],[I].[UserID]
	,0 [pContentID],[I].[DTS] [pDTS], [I].[UserID] [pUserID],
		Cast('' as nvarchar(max)) [PPath],
		Cast(Case when C.Type < 20000 then @Delim + C.Number + @DelimNumber + C.Text else '1' end as nvarchar(max)) [Path],
		0 IsRNO, Cast('' as nvarchar(max)) [POrdinalPath], Cast('0001' as nvarchar(max)) [OrdinalPath]
	FROM [Items] I
  Join Contents C on C.ContentID=I.ContentID
  JOIN vefn_DocVersionSplit(@DocVersionList) DV
    ON I.[ItemID] = DV.[ItemID]
Union All
-- Children
  select I.[ItemID], DVPath, [Level] + 1,Z.ItemID,0, I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],
	P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID]
	,PATH + --''
	case C.Type/10000
	when 2 then
	case P.FromType
	when 3 then @DelimStep + 'Caution'
	when 4 then @DelimStep + 'Note'
  else '' end
	else '' end
	PPath,
	Path + case C.Type/10000
	when 0 then @Delim +C.Number + @DelimNumber + C.Text
	when 1 then @Delim +C.Number + @DelimNumber + C.Text
	else
	case P.FromType
	--when 1 then 'PRC' + @Delim + cast(1 as varchar(3))
	--when 2 then 'SEC' + @Delim + cast(1 as varchar(3))
	when 3 then @DelimStep +'Caution' + @DelimStep + cast(1 as varchar(3))
	when 4 then @DelimStep +'Note' + @DelimStep + cast(1 as varchar(3))
	when 5 then @DelimStep +'RNO' + @DelimStep
	when 7 then @DelimStep +'Table' + @DelimStep
	else case when Z.FromType < 3 then @Delim else @DelimStep end + cast(1 as varchar(3))
	end end Path,
  case when P.FromType = 5 then -1 else 0 end IsRNO,
	OrdinalPath + '.' + Right('000' + Cast(P.FromType as varchar(4)), 4) + '-' ,
	OrdinalPath + '.' + Right('000' + Cast(P.FromType as varchar(4)), 4) + '-00001'
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
  join Contents C on C.ContentID = I.ContentID
Union All
-- Siblings
  select I.[ItemID], DVPath, [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID]
	,null,null,null,
	PPath,
	--'1' +
	PPath  + case C.Type/10000
	when 0 then @Delim + C.Number + @DelimNumber + C.Text
	when 1 then @Delim + C.Number + @DelimNumber + C.Text
	else case when Path like '%.%' then @DelimStep else @Delim end + cast(Ordinal + 2 as varchar(3))
	end Path, 0,
	POrdinalPath,
	POrdinalPath + right('00000' + cast(Z.[Ordinal] + 2 as varchar(5)), 5)
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
  join Contents C on C.ContentID = I.ContentID
	--where Z.[Level] > 0

)
insert into @SiblingAndChildren
select I.[ItemID], [DvPath], [Path], I.[Level],I.[FromType],I.[Ordinal], I.[ParentID], I.[PreviousID],I.[ContentID],I.[DTS],I.[UserID],
		[pContentID],[pDTS],[pUserID],[IsRNO]/*,[PPath],[POrdinalPath]*/,[OrdinalPath]
 from ItemZ I
OPTION (MAXRECURSION 10000)
END
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_SiblingAndChildrenItems Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_SiblingAndChildrenItems Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_SiblingChildrenItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_SiblingChildrenItems]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_SiblingChildrenItems];
GO
	
/*
select * from Transitions
where (ToID in(select ItemID From dbo.vefn_ChildrenItems(185,184))) OR (RangeID in(select ItemID From dbo.vefn_ChildrenItems(185,184)))
AND NOT (FromID in(Select ContentID From dbo.vefn_ChildrenItems(185,184)))
*/

CREATE  FUNCTION [dbo].[vefn_SiblingChildrenItems](@ItemID int)
RETURNS @SiblingChildren TABLE
(
  ItemID int PRIMARY KEY,
	ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], 0 [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 as [pContentID],[DTS] As [pDTS], [UserID] As [pUserID], [LastChanged] As [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] as [pContentID],P.[DTS] As [pDTS],P.[UserID] As [pUserID],P.[LastChanged] As [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
)
insert into @SiblingChildren select ItemID, ContentID from Itemz
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_SiblingChildrenItems Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_SiblingChildrenItems Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_SiblingItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_SiblingItems]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_SiblingItems];
GO
	
/*
select * from Transitions
where (ToID in(select ItemID From dbo.vefn_ChildrenItems(185,184))) OR (RangeID in(select ItemID From dbo.vefn_ChildrenItems(185,184)))
AND NOT (FromID in(Select ContentID From dbo.vefn_ChildrenItems(185,184)))
*/

CREATE  FUNCTION [dbo].[vefn_SiblingItems](@ItemID int, @ParentID int)
RETURNS @Siblings TABLE
(
  ItemID int PRIMARY KEY,
	ContentID int
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], @ParentID [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
)
insert into @Siblings select ItemID, ContentID from Itemz
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_SiblingItems Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_SiblingItems Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_SplitInt] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_SplitInt]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_SplitInt];
GO
	
--select * from DocVersions where VersionID in(select * from vefn_SplitInt('1,2,4',','))
--select Type, Count(*) from Contents where Type in(select * from vefn_SplitInt('20001,20002,20004',',')) group by Type
CREATE  FUNCTION [dbo].[vefn_SplitInt](@text varchar(MAX), @delimiter varchar(20) = ',')
RETURNS @IDs TABLE
(
  ID int PRIMARY KEY
)
WITH EXECUTE AS OWNER
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
  BEGIN
    SET @index = CHARINDEX(@delimiter , @text)
    IF (@index = 0) AND (LEN(@text) > 0)
      BEGIN
        INSERT INTO @IDs VALUES (CAST(@text AS INT ))
          BREAK
      END
    IF (@index > 1)
      BEGIN
        INSERT INTO @IDs VALUES (CAST(LEFT(@text, @index - 1) AS INT))
        SET @text = RIGHT(@text, (LEN(@text) - @index))
      END
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_SplitInt Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_SplitInt Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_SplitROSearch] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_SplitROSearch]') AND OBJECTPROPERTY(id,N'IsTableFunction') = 1)
    DROP FUNCTION [vefn_SplitROSearch];
GO
	
/*
select * from vefn_SplitROSearch(null)
select * from vefn_SplitROSearch('')
select * from vefn_SplitROSearch('1')
select * from vefn_SplitROSearch('1:0001')
select * from vefn_SplitROSearch('1:0001000019C')
select * from vefn_SplitROSearch('1:0001000019C,0001000019D')
*/
CREATE FUNCTION [dbo].[vefn_SplitROSearch](@text varchar(MAX)='')
RETURNS @ROIDSearch TABLE
(
	RODBID int,
  ROID varchar(16)
	--,CONSTRAINT ROIDSearchPK PRIMARY KEY(RODBID, ROID)
)
WITH EXECUTE AS OWNER
AS
BEGIN
DECLARE @index int
IF(isnull(@text,'') = '')
BEGIN
	Insert into @ROIDSearch
	Select RODBID, ''
	from RODbs
  RETURN
END
SET @index = CHARINDEX(':' , @text)
DECLARE @RODBID int
IF (@index = 0) AND (LEN(@text) > 0)
	BEGIN
		SET @RODBID = CAST(@text AS INT)
    INSERT INTO @ROIDSearch VALUES (@RODBID,'')
    SET @Text=''
	END
ELSE
	BEGIN
		SET @RODBID = CAST(LEFT(@text, @index - 1) AS INT)
		SET @text = RIGHT(@text, (LEN(@text) - @index))
		SET @index = -1
	END
SET @text = RIGHT(@text, (LEN(@text) - @index))
WHILE (LEN(@text) > 0)
  BEGIN
    SET @index = CHARINDEX(',' , @text)
    IF (@index = 0) AND (LEN(@text) > 0)
      BEGIN
        INSERT INTO @ROIDSearch VALUES (@RODBID,@text)
          BREAK
      END
    IF (@index > 1)
      BEGIN
        INSERT INTO @ROIDSearch VALUES (@RODBID,LEFT(@text, @index - 1))
        SET @text = RIGHT(@text, (LEN(@text) - @index))
      END
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'TableFunction Creation: vefn_SplitROSearch Succeeded'
ELSE PRINT 'TableFunction Creation: vefn_SplitROSearch Error on Creation'
GO

/****** Object:  StoredProcedure [vefn_XmlPath] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vefn_XmlPath]') AND OBJECTPROPERTY(id,N'IsScalarFunction') = 1)
    DROP FUNCTION [vefn_XmlPath];
GO
	
CREATE FUNCTION [dbo].[vefn_XmlPath] (@xml XML) RETURNS varchar(255)
WITH EXECUTE AS OWNER
AS
BEGIN
	return case when @xml.exist('*[1]') is null THEN '' ELSE @xml.value('local-name(*[1])','varchar(max)') +
	coalesce('[' + @xml.value('*[1]/@Type','varchar(255)')+']','[' + @xml.value('*[1]/@Index','varchar(255)')+']','') + '/' END
END;
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'ScalarFunction Creation: vefn_XmlPath Succeeded'
ELSE PRINT 'ScalarFunction Creation: vefn_XmlPath Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_CleanUpItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_CleanUpItems]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_CleanUpItems];
GO
	
/*
select *, .dbo.ve_GetParts(ContentID,6) SubSteps from items
where contentid in(select contentid from contents where text like 'DISPATCH operator to open breaker%')


select * from items
where itemid in(298,299,436,440)

select itemid from items
where previousid is null and itemid not in (select itemid from parts)

--select * from contents where text like 'foldout cip%'

select count(*) from parts
*/
CREATE procedure [dbo].[vesp_CleanUpItems]
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
	BEGIN
with Itemz(ItemID) as(
select itemid from items
where previousid is null
and itemid not in(1)
and itemid not in (select itemid from parts)
UNION ALL
select ii.itemid from items ii join itemz zz on zz.itemid = ii.previousid
)
delete from items where itemid in (select itemid from itemz)
	END
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_CleanUpItems Succeeded'
ELSE PRINT 'Procedure Creation: vesp_CleanUpItems Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetFormatFields] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetFormatFields]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetFormatFields];
GO
	
/*
vesp_GetFormatFields 'PrintNoTitle'
vesp_GetFormatFields 'Sep'
vesp_GetFormatFields 'TabFormat'
vesp_GetFormatFields 'ShowSectionTitles'
vesp_GetFormatFields 'Caution'
vesp_GetFormatFields 'Ident'
*/

CREATE PROCEDURE [dbo].[vesp_GetFormatFields]
(
	@find varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + [Name] + ']' from vefn_GetFormatField(@find)
					order by ',[' + [Name] + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select Name,''Format Description'' Path,'''' Value, Description From Formats) T1 PIVOT ( Max(Description) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,''FormatID'' Path,'''' Value, FormatID From Formats) T1 PIVOT ( Max(FormatID) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,Path,Value From vefn_GetFormatField(''' + @find + ''')) T1 PIVOT ( Count(Name) FOR [Name] IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY PATH,VALUE'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetFormatFields Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetFormatFields Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetFormatFieldsAll] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetFormatFieldsAll]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetFormatFieldsAll];
GO
	
/*
vesp_GetFormatFieldsAll 'PrintNoTitle'
vesp_GetFormatFieldsAll 'Sep'
vesp_GetFormatFieldsAll 'TabFormat'
vesp_GetFormatFieldsAll 'ShowSectionTitles'
vesp_GetFormatFieldsAll 'Caution'
vesp_GetFormatFieldsAll 'Ident'
*/

CREATE PROCEDURE [dbo].[vesp_GetFormatFieldsAll]
(
	@find varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + [Name] + ']' from Formats
					order by ',[' + [Name] + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select Name,Path,Value From vefn_GetFormatField(''' + @find + ''')) T1 PIVOT ( Count(Name) FOR [Name] IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY PATH,VALUE'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetFormatFieldsAll Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetFormatFieldsAll Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetFormatFieldsByStepType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetFormatFieldsByStepType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetFormatFieldsByStepType];
GO
	
/*
vesp_GetFormatFieldsByStepType 'PrintNoTitle'
vesp_GetFormatFieldsByStepType 'Sep'
vesp_GetFormatFieldsByStepType 'TabFormat'
vesp_GetFormatFieldsByStepType 'ShowSectionTitles'
vesp_GetFormatFieldsByStepType 'Caution'
vesp_GetFormatFieldsByStepType 'Ident'
vesp_GetFormatFieldsByStepType 'Off'
*/

CREATE PROCEDURE [dbo].[vesp_GetFormatFieldsByStepType]
(
	@find varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + [Name] + ']' from vefn_GetFormatField(@find)
					order by ',[' + [Name] + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select Name,''Format Description'' Path,'''' StepType, '''' Value, Description From Formats) T1 PIVOT ( Max(Description) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,''FormatID'' Path, '''' StepType,'''' Value, FormatID From Formats) T1 PIVOT ( Max(FormatID) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,Path,StepType,Value From vefn_GetFormatFieldByStepType(''' + @find + ''')) T1 PIVOT ( Count(Name) FOR [Name] IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY PATH,StepType,VALUE'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetFormatFieldsByStepType Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetFormatFieldsByStepType Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetFormatFieldsByStepType2] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetFormatFieldsByStepType2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetFormatFieldsByStepType2];
GO
	
/*
vesp_GetFormatFieldsByStepType2 'PrintNoTitle'
vesp_GetFormatFieldsByStepType2 'Sep'
vesp_GetFormatFieldsByStepType2 'TabFormat'
vesp_GetFormatFieldsByStepType2 'ShowSectionTitles'
vesp_GetFormatFieldsByStepType2 'Caution'
vesp_GetFormatFieldsByStepType2 'Ident'
vesp_GetFormatFieldsByStepType2 'Off'
*/

Create PROCEDURE [dbo].[vesp_GetFormatFieldsByStepType2]
(
	@find varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + [Name] + ']' from vefn_GetFormatFieldByStepType2(@find)
					order by ',[' + [Name] + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select Name,''Format Description'' Path,'''' StepType, '''' Value, Description From Formats) T1 PIVOT ( Max(Description) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,''FormatID'' Path, '''' StepType,'''' Value, FormatID From Formats) T1 PIVOT ( Max(FormatID) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,Path,StepType,Value From vefn_GetFormatFieldByStepType2(''' + @find + ''')) T1 PIVOT ( Count(Name) FOR [Name] IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY PATH,StepType,VALUE'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetFormatFieldsByStepType2 Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetFormatFieldsByStepType2 Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetFormatFieldsNoValue] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetFormatFieldsNoValue]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetFormatFieldsNoValue];
GO
	
/*
vesp_GetFormatFieldsNoValue 'PrintNoTitle'
vesp_GetFormatFieldsNoValue 'Sep'
vesp_GetFormatFieldsNoValue 'TabFormat'
vesp_GetFormatFieldsNoValue 'ShowSectionTitles'
vesp_GetFormatFieldsNoValue 'Caution'
vesp_GetFormatFieldsNoValue 'Ident'
vesp_GetFormatFieldsNoValue 'Off'
*/

CREATE PROCEDURE [dbo].[vesp_GetFormatFieldsNoValue]
(
	@find varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + [Name] + ']' from vefn_GetFormatField(@find)
					order by ',[' + [Name] + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select Name,''Format Description'' Path, Description From Formats) T1 PIVOT ( Max(Description) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,''FormatID'' Path, FormatID From Formats) T1 PIVOT ( Max(FormatID) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,Path From vefn_GetFormatFieldNoValue(''' + @find + ''')) T1 PIVOT ( Count(Name) FOR [Name] IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY PATH'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetFormatFieldsNoValue Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetFormatFieldsNoValue Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetFormatGroupFields] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetFormatGroupFields]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetFormatGroupFields];
GO
	
/*
vesp_GetFormatGroupFields 'PrintNoTitle'
vesp_GetFormatGroupFields 'Sep'
vesp_GetFormatGroupFields 'TabFormat'
vesp_GetFormatGroupFields 'ShowSectionTitles'
vesp_GetFormatGroupFields 'Caution'
vesp_GetFormatGroupFields 'Ident'
vesp_GetFormatGroupFields 'SectionTitleLen'
*/

CREATE PROCEDURE [dbo].[vesp_GetFormatGroupFields]
(
	@find varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + substring([Name],1,3) + ']' from vefn_GetFormatField(@find)
					order by ',[' + substring([Name],1,3) + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select substring([Name],1,3) FormatGroup,Path,Value From vefn_GetFormatField(''' + @find + ''')) T1 PIVOT ( Count(FormatGroup) FOR FormatGroup IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY PATH,VALUE'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetFormatGroupFields Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetFormatGroupFields Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetFormatGroupFieldsByStepType] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetFormatGroupFieldsByStepType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetFormatGroupFieldsByStepType];
GO
	
/*
vesp_GetFormatGroupFieldsByStepType 'PrintNoTitle'
vesp_GetFormatGroupFieldsByStepType 'Sep'
vesp_GetFormatGroupFieldsByStepType 'TabFormat'
vesp_GetFormatGroupFieldsByStepType 'ShowSectionTitles'
vesp_GetFormatGroupFieldsByStepType 'Caution'
vesp_GetFormatGroupFieldsByStepType 'Ident'
vesp_GetFormatGroupFieldsByStepType 'SectionTitleLen'
vesp_GetFormatGroupFieldsByStepType 'Off'
*/

CREATE PROCEDURE [dbo].[vesp_GetFormatGroupFieldsByStepType]
(
	@find varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + substring([Name],1,3) + ']' from vefn_GetFormatField(@find)
					order by ',[' + substring([Name],1,3) + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select substring([Name],1,3) FormatGroup,Path,StepType,Value From vefn_GetFormatFieldByStepType(''' + @find + ''')) T1 PIVOT ( Count(FormatGroup) FOR FormatGroup IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY PATH, StepType,VALUE'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetFormatGroupFieldsByStepType Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetFormatGroupFieldsByStepType Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetFormatGroupFieldsNoValues] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetFormatGroupFieldsNoValues]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetFormatGroupFieldsNoValues];
GO
	
/*
vesp_GetFormatGroupFieldsNoValues 'PrintNoTitle'
vesp_GetFormatGroupFieldsNoValues 'Sep'
vesp_GetFormatGroupFieldsNoValues 'TabFormat'
vesp_GetFormatGroupFieldsNoValues 'ShowSectionTitles'
vesp_GetFormatGroupFieldsNoValues 'Caution'
vesp_GetFormatGroupFieldsNoValues 'Ident'
vesp_GetFormatGroupFieldsNoValues 'SectionTitleLen'
vesp_GetFormatGroupFieldsNoValues 'Off'
*/

CREATE PROCEDURE [dbo].[vesp_GetFormatGroupFieldsNoValues]
(
	@find varchar(255)
)
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + substring([Name],1,3) + ']' from vefn_GetFormatFieldNoValue(@find)
					order by ',[' + substring([Name],1,3) + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select substring([Name],1,3) FormatGroup,Path From vefn_GetFormatFieldNoValue(''' + @find + ''')) T1 PIVOT ( Count(FormatGroup) FOR FormatGroup IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY PATH'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetFormatGroupFieldsNoValues Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetFormatGroupFieldsNoValues Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_GetGenMacMacros] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_GetGenMacMacros]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_GetGenMacMacros];
GO
	
/*
vesp_GetGenMacMacros
*/

CREATE PROCEDURE [dbo].[vesp_GetGenMacMacros]
WITH EXECUTE AS OWNER
AS
BEGIN
	declare @pivotlist varchar(max)
	select @pivotlist = stuff((select distinct ',[' + [Name] + ']' from vefn_GetGenMacMacros()
					order by ',[' + [Name] + ']' for xml path('')),1,1,'')
	DECLARE @query VARCHAR(max)
	SET @query = 'SELECT * FROM (Select Name,''Format Description'' Path, Description From Formats) T1 PIVOT ( Max(Description) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,''FormatID'' Path, FormatID From Formats) T1 PIVOT ( Max(FormatID) FOR [Name] IN (' + @pivotlist + ') ) As Pivot2'
	EXECUTE(@query)
	SET @query = 'SELECT * FROM (Select Name,MacroName From vefn_GetGenMacMacros()) T1 PIVOT ( Count(Name) FOR [Name] IN (' + @pivotlist + ') ) AS Pivot1 ORDER BY MacroName'
	print @Query
	EXECUTE(@query)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_GetGenMacMacros Succeeded'
ELSE PRINT 'Procedure Creation: vesp_GetGenMacMacros Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListChildren];
GO
	
-- vesp_ListChildren 17
-- drop procedure [getItemAndChildren]
CREATE PROCEDURE [dbo].[vesp_ListChildren] (@ItemID int)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged]) as (
  Select 0 [Level], 0 [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
select I.[Level],I.[FromType],I.[Ordinal], I.[ParentID], I.[ItemID],I.[PreviousID],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged],
	C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[I].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[I].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Children] WHERE [Children].[PreviousID]=[I].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[I].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[I].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[I].[ItemID]) [Transition_ToIDCount]
 from ItemZ I
 join Contents C on C.ContentID = I.ContentID
 order by I.[Level] , I.[FromType], I.[Ordinal]
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListChildren Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListChildren Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListContentPath] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListContentPath]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListContentPath];
GO
	
-- vesp_ListContentPath 148
create PROCEDURE [dbo].[vesp_ListContentPath]
	(
		@ContentID int
	)
WITH EXECUTE AS OWNER
AS
BEGIN
with ContentZ(BaseID,ContentID,ItemID,Number,Text,Item,Level,PreviousID) as (
  Select II.ItemID,CC.ContentID,II.ItemID,CC.Number,CC.Text,1,1,II.PreviousID
    from Items II join Contents CC on CC.ContentID=II.ContentID where @ContentID=II.ContentID
  Union All
--
  Select  BaseID,CC.ContentID,II.ItemID,CC.Number,CC.Text,ZZ.Item+1,ZZ.Level,II.PreviousID
	FROM ContentZ ZZ
    Join Items II on II.ItemID = ZZ.PreviousID
	Join Contents CC on II.ContentID = CC.ContentID
	where ZZ.PreviousID is not null
  Union All
  Select  BaseID,CC.ContentID,II.ItemID,CC.Number,CC.Text,1,ZZ.Level+1,II.PreviousID
	FROM ContentZ ZZ
	Join Parts PP on ZZ.ItemID = PP.ItemID
	Join Contents CC on PP.ContentID = CC.ContentID
    Join Items II on II.ContentID = CC.ContentID
	where ZZ.PreviousID is null --and ZZ.ItemID in(717,715,711,662)
)
Select ZZ.BaseID,ZZ.Level,MaxItem,ZZ.Number,ZZ.Text from ContentZ ZZ
join (select BaseID, Level, max(item) MaxItem from ContentZ group by BaseID,Level) T1 on T1.BaseID=ZZ.BaseID and T1.Level = ZZ.Level
where Item=1
order by ZZ.BaseID,ZZ.Level Desc, Item Desc
end
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListContentPath Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListContentPath Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListContentsByItemID] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListContentsByItemID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListContentsByItemID];
GO
	
--vesp_ListContentsByItemID 1

CREATE PROCEDURE [dbo].[vesp_ListContentsByItemID]
(
@ItemID int = 0
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz(ItemID,PreviousID,ContentID,[DTS],[UserID],[LastChanged]) as (
  Select ItemID,PreviousID,ContentID,[DTS],[UserID],[LastChanged]
    from Items
    where ItemID=@ItemID
  Union All
--
  Select C.ItemID,C.PreviousID,C.ContentID,C.[DTS],C.[UserID],C.[LastChanged]
    from Items C
    Join Itemz Z on C.PreviousID=Z.ItemID
)
	SELECT
		cc.[ContentID],
		cc.[Number],
		cc.[Text],
		cc.[Type],
		cc.[FormatID],
		cc.[Config],
		cc.[DTS],
		cc.[UserID],
		cc.[LastChanged],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=cc.[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=cc.[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=cc.[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=cc.[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=cc.[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=cc.[ContentID]) [PartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=cc.[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=cc.[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=cc.[ContentID]) [ZContentCount]
	FROM [Contents] cc
	join itemz zz on cc.contentid=zz.contentid
OPTION (MAXRECURSION 1000)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListContentsByItemID Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListContentsByItemID Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListItemAndChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListItemAndChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListItemAndChildren];
GO
	
-- vesp_ListItemAndChildren 1,0
-- drop procedure [vesp_ListItemAndChildren]
CREATE PROCEDURE [dbo].[vesp_ListItemAndChildren] (@ItemID int, @ParentID int)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz([Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID], [pDTS],[pUserID],[pLastChanged]) as (
  Select 0 [Level], @ParentID [ParentID], 0 [Ordinal], [ItemID], [PreviousID],0 [FromType],[ContentID],[DTS],[UserID],[LastChanged]
	,0 [pContentID],[DTS] [pDTS], [UserID] [pUserID], [LastChanged] [pLastChanged]
	FROM [Items]
    where [ItemID]=@ItemID
Union All
-- Children
  select [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
-- Siblings
Union All
  select [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
	where Z.[Level] > 0
)
select I.[Level],I.[FromType],I.[Ordinal], I.[ParentID], I.[ItemID],I.[PreviousID],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged],
		C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged],
		[pContentID],[pDTS],[pUserID],[pLastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[I].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[I].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[I].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[I].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[I].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[I].[ItemID]) [Transition_ToIDCount],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[C].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[C].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[C].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[C].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[C].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[C].[ContentID]) [cPartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[C].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[C].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[C].[ContentID]) [ZContentCount]
 from ItemZ I
 join Contents C on C.ContentID = I.ContentID
 order by I.[Level] , I.[FromType], I.[Ordinal]
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListItemAndChildren Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListItemAndChildren Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListItems] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListItems]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListItems];
GO
	
--vesp_ListItems 1

CREATE PROCEDURE [dbo].[vesp_ListItems]
(
@ItemID int = 0
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz(ItemID,PreviousID,ContentID,[DTS],[UserID],[LastChanged]) as (
  Select ItemID,PreviousID,ContentID,[DTS],[UserID],[LastChanged]
    from Items
    where ItemID=@ItemID
  Union All
--
  Select C.ItemID,C.PreviousID,C.ContentID,C.[DTS],C.[UserID],C.[LastChanged]
    from Items C
    Join Itemz Z on C.PreviousID=Z.ItemID
)
Select ItemID,PreviousID,ContentID,[DTS],[UserID],[LastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[Itemz].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[Itemz].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Children] WHERE [Children].[PreviousID]=[Itemz].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[Itemz].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[Itemz].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[Itemz].[ItemID]) [Transition_ToIDCount]
from Itemz
OPTION (MAXRECURSION 1000)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListItems Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListItems Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListItemsAndContent] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListItemsAndContent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListItemsAndContent];
GO
	
--vesp_ListItemsAndContent 1

CREATE PROCEDURE [dbo].[vesp_ListItemsAndContent]
(
@ItemID int = 0
)
WITH EXECUTE AS OWNER
AS
BEGIN
with Itemz(ItemID,PreviousID,ContentID,[DTS],[UserID],[LastChanged]) as (
  Select ItemID,PreviousID,ContentID,[DTS],[UserID],[LastChanged]
    from Items
    where ItemID=@ItemID
  Union All
--
  Select I.ItemID,I.PreviousID,I.ContentID,I.[DTS],I.[UserID],I.[LastChanged]
    from Items I
    Join Itemz Z on I.PreviousID=Z.ItemID
)
Select I.ItemID,I.PreviousID,I.ContentID,I.[DTS],I.[UserID],I.[LastChanged],
	C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[I].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[I].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Children] WHERE [Children].[PreviousID]=[I].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[I].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[I].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[I].[ItemID]) [Transition_ToIDCount],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[C].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[C].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[C].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[C].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[C].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[C].[ContentID]) [cPartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[C].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[C].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[C].[ContentID]) [ZContentCount]
from Itemz I Join Contents C on I.ContentID = C.ContentID
OPTION (MAXRECURSION 1000)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListItemsAndContent Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListItemsAndContent Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListTables] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListTables]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListTables];
GO
	
create procedure [dbo].[vesp_ListTables]
WITH EXECUTE AS OWNER
AS
begin
select o.name TableName,c.name ColumnName,
case c.xtype
 when 56 then 'int'
 when 231 then 'nvarchar(' + case c.length when -1 then 'Max' else cast(c.length/2 as varchar(10)) end + ')'
 when 165 then 'varbinary(' + case c.length when -1 then 'Max' else cast(c.length as varchar(10)) end + ')'
 when 239 then 'nchar(' + case c.length when -1 then 'Max' else cast(c.length/2 as varchar(10)) end + ')'
 when 175 then 'char(' + case c.length when -1 then 'Max' else cast(c.length as varchar(10)) end + ')'
 when 61 then 'datetime'
 when 104 then 'bit'
 when 48 then 'TinyInt'
 when 189 then 'timestamp'
 else '???' + cast(c.xtype as varchar(10)) end ItemType,
 case when c.isnullable=1 then 'Yes' else '' end AllowNulls,
 case when c.colstat=1 then 'Identity' else dc.definition end DefaultValue
from sysobjects o
join syscolumns c on o.id=c.id
left join sysconstraints cn on o.id=cn.id and c.colid=cn.colid
left join sys.default_constraints dc on dc.object_id = cn.constid
where o.xtype='U'
order by o.name,c.colid
end
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListTables Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListTables Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListTables2] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListTables2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListTables2];
GO
	
create procedure [dbo].[vesp_ListTables2]
WITH EXECUTE AS OWNER
AS
begin
select o.name TableName,c.name ColumnName,
case c.xtype
 when 56 then 'int'
 when 231 then 'nvarchar'
 when 165 then 'varbinary'
 when 239 then 'nchar'
 when 175 then 'char'
 when 61 then 'datetime'
 when 104 then 'bit'
 when 48 then 'TinyInt'
 when 189 then 'timestamp'
 else '???' + cast(c.xtype as varchar(10)) end ItemType,
case c.xtype
 when 56 then '0'
 when 231 then case c.length when -1 then 'Max' else cast(c.length/2 as varchar(10)) end
 when 165 then case c.length when -1 then 'Max' else cast(c.length/2 as varchar(10)) end
 when 239 then case c.length when -1 then 'Max' else cast(c.length/2 as varchar(10)) end
 when 175 then case c.length when -1 then 'Max' else cast(c.length/2 as varchar(10)) end
 when 61 then '0'
 when 104 then '0'
 when 48 then '0'
 when 189 then '0'
 else '0' end ItemSize,

 case when c.isnullable=1 then 'Yes' else '' end AllowNulls,
 case when c.colstat=1 then 'Identity' else dc.definition end DefaultValue
from sysobjects o
join syscolumns c on o.id=c.id
left join sysconstraints cn on o.id=cn.id and c.colid=cn.colid
left join sys.default_constraints dc on dc.object_id = cn.constid
where o.xtype='U'
order by o.name,c.colid
end
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListTables2 Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListTables2 Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ListTables3] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ListTables3]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ListTables3];
GO
	
CREATE procedure [dbo].[vesp_ListTables3]
WITH EXECUTE AS OWNER
AS
begin
select o.name TableName,c.name ColumnName,
case c.system_type_id
 when 56 then 'int'
 when 231 then 'nvarchar'
 when 165 then 'varbinary'
 when 167 then 'varchar'
 when 239 then 'nchar'
 when 175 then 'char'
 when 61 then 'datetime'
 when 104 then 'bit'
 when 48 then 'TinyInt'
 when 189 then 'timestamp'
 else '???' + cast(c.system_type_id as varchar(10)) end ItemType,
case c.system_type_id
 when 56 then '0'
 when 231 then case c.max_length when -1 then 'Max' else cast(c.max_length/2 as varchar(10)) end
 when 165 then case c.max_length when -1 then 'Max' else cast(c.max_length as varchar(10)) end
 when 167 then case c.max_length when -1 then 'Max' else cast(c.max_length as varchar(10)) end
 when 239 then case c.max_length when -1 then 'Max' else cast(c.max_length/2 as varchar(10)) end
 when 175 then case c.max_length when -1 then 'Max' else cast(c.max_length as varchar(10)) end
 when 61 then '0'
 when 104 then '0'
 when 48 then '0'
 when 189 then '0'
 else '0' end ItemSize,

 case when c.is_nullable=1 then 'Yes' else '' end AllowNulls,
 case when c.is_identity=1 then 'Identity' else dc.definition end DefaultValue,
 x.value Description
from sys.objects o
join sys.columns c on o.object_id=c.object_id
left join sysconstraints cn on o.object_id=cn.id and c.column_id=cn.colid
left join sys.default_constraints dc on dc.object_id = cn.constid
left join sys.extended_properties x on x.major_id = o.OBJECT_ID AND x.minor_id=c.column_id AND x.Name='MS_Description'
where o.type='U'
order by o.name,c.column_id
end
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ListTables3 Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ListTables3 Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_ResetFolderManualOrder] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_ResetFolderManualOrder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_ResetFolderManualOrder];
GO
	
CREATE PROCEDURE [dbo].[vesp_ResetFolderManualOrder]
WITH EXECUTE AS OWNER
AS
BEGIN TRY -- Try Block
	BEGIN TRANSACTION
update fld
 set  Fld.ManualOrder =Fld.MyRow
from (Select ROW_NUMBER() OVER(Partition by ParentID Order BY FolderID) MyRow,* from folders ) fld
	IF( @@TRANCOUNT > 0 ) COMMIT
END TRY
BEGIN CATCH -- Catch Block
	IF( @@TRANCOUNT = 1 ) ROLLBACK -- Only rollback if top level
 	ELSE IF( @@TRANCOUNT > 1 ) COMMIT -- Otherwise commit.  Top level will rollback
	EXEC vlnErrorHandler
END CATCH

IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ResetFolderManualOrder Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ResetFolderManualOrder Error on Creation'
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_ResetFolderManualOrder Succeeded'
ELSE PRINT 'Procedure Creation: vesp_ResetFolderManualOrder Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_SearchAnnotationItemAndChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_SearchAnnotationItemAndChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_SearchAnnotationItemAndChildren];
GO
	
/*
exec vesp_SearchAnnotationItemAndChildren Null,Null,'1',Null,0
exec vesp_SearchAnnotationItemAndChildren Null,Null,'2',Null,0
exec vesp_SearchAnnotationItemAndChildren Null,Null,'3',Null,0
exec vesp_SearchAnnotationItemAndChildren Null,Null,'4',Null,0
exec vesp_SearchAnnotationItemAndChildren Null,Null,'5',Null,0
exec vesp_SearchAnnotationItemAndChildren Null,Null,'',Null,0
*/
CREATE PROCEDURE [dbo].[vesp_SearchAnnotationItemAndChildren] (@DocVersionList varchar(MAX), @StepTypeList varchar(MAX), @AnnotationTypeList varchar(MAX), @SearchString nvarchar(MAX), @CaseSensitive as int)
WITH EXECUTE AS OWNER
AS
BEGIN
Declare @Delim char(1)
Set @Delim=char(7)
Declare @DelimNumber char(1)
Set @DelimNumber=char(17)
Declare @DelimStep char(1)
Set @DelimStep='.'
Set @SearchString = .dbo.vefn_FixSearchString(@SearchString)
begin
with Itemz(DVPath, [Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID],
  [pDTS],[pUserID],[pLastChanged],PPath, Path, IsRNO, POrdinalPath, OrdinalPath) as (
  Select DVPath, 0 [Level], 0 [ParentID], 0 [Ordinal], [I].[ItemID], [PreviousID],0 [FromType],[I].[ContentID],[I].[DTS],[I].[UserID],[I].[LastChanged]
	,0 [pContentID],[I].[DTS] [pDTS], [I].[UserID] [pUserID], [I].[LastChanged] [pLastChanged],
		Cast('' as nvarchar(max)) PPath,
		Cast(Case when C.Type < 20000 then @Delim + C.Number + @DelimNumber + C.Text else '1' end as nvarchar(max)) Path,
		0 IsRNO, Cast('' as nvarchar(max)) POrdinalPath, Cast('0001' as nvarchar(max)) OrdinalPath
	FROM [Items] I
  Join Contents C on C.ContentID=I.ContentID
  JOIN vefn_DocVersionSplit(@DocVersionList) DV
    ON I.[ItemID] = DV.[ItemID]
Union All
-- Children
  select DVPath, [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	,PATH + --''
	case C.Type/10000
	when 2 then
	case P.FromType
	when 3 then @DelimStep + 'Caution'
	when 4 then @DelimStep + 'Note'
  else '' end
	else '' end
	PPath,
	Path + case C.Type/10000
	when 0 then @Delim +C.Number + @DelimNumber + C.Text
	when 1 then @Delim +C.Number + @DelimNumber + C.Text
	else
	case P.FromType
	--when 1 then 'PRC' + @Delim + cast(1 as varchar(3))
	--when 2 then 'SEC' + @Delim + cast(1 as varchar(3))
	when 3 then @DelimStep +'Caution' + @DelimStep + cast(1 as varchar(3))
	when 4 then @DelimStep +'Note' + @DelimStep + cast(1 as varchar(3))
	when 5 then @DelimStep +'RNO' + @DelimStep
	when 7 then @DelimStep +'Table' + @DelimStep
	else case when Z.FromType < 3 then @Delim else @DelimStep end + cast(1 as varchar(3))
	end end Path,
  case when P.FromType = 5 then -1 else 0 end IsRNO,
	OrdinalPath + '.' + Right('0000' + Cast(P.FromType as varchar(4)), 4) + '-' ,
	OrdinalPath + '.' + Right('0000' + Cast(P.FromType as varchar(4)), 4) + '-0001'
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
  join Contents C on C.ContentID = I.ContentID
Union All
-- Siblings
  select DVPath, [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	,PPath,
	--'1' +
	PPath  + case C.Type/10000
	when 0 then @Delim + C.Number + @DelimNumber + C.Text
	when 1 then @Delim + C.Number + @DelimNumber + C.Text
	else case when Path like '%.%' then @DelimStep else @Delim end + cast(Ordinal + 2 as varchar(3))
	end Path, 0,
	POrdinalPath,
	POrdinalPath + right('0000' + cast(Z.[Ordinal] + 2 as varchar(4)), 4)
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
  join Contents C on C.ContentID = I.ContentID
	--where Z.[Level] > 0
)
select DvPath, Path, I.[Level],I.[FromType],I.[Ordinal], I.[ParentID], I.[ItemID],I.[PreviousID],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged],
		C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged],
		[pContentID],[pDTS],[pUserID],[pLastChanged],AnnotationID SearchAnnotationID, SearchText, TT.Name AnnotationType,
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[I].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[I].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[I].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[I].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[I].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[I].[ItemID]) [Transition_ToIDCount],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[C].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[C].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[C].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[C].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[C].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[C].[ContentID]) [cPartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[C].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[C].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[C].[ContentID]) [ZContentCount]
 from ItemZ I
 join Contents C on C.ContentID = I.ContentID
 left join Entries E on C.ContentID = E.ContentID
 left join Documents D on E.DocID = D.DocID
 join Annotations A on A.ItemID = I.ItemID
 join vefn_AnnotationTypeSplit(@AnnotationTypeList) TT on TT.TypeID=A.TypeID
where
  (isnull(@SearchString,'')=''
    OR (@CaseSensitive = 1 AND A.SearchText like @SearchString Collate SQL_Latin1_General_CP1_CS_AS)
    OR (@CaseSensitive = 0 AND A.SearchText like @SearchString Collate SQL_Latin1_General_CP1_CI_AS))
  AND
  ((isnull(@StepTypeList,'') = '' and dbo.vefn_AllSections(C.Type)>=10000)
    or
   ((dbo.vefn_AllSections(C.Type) in (Select ID from vefn_SplitInt(@StepTypeList,',')))
    or
	 (@StepTypeList like '%20040%' AND IsRNO = -1)))
 order by DvPath,OrdinalPath
OPTION (MAXRECURSION 10000)
END
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_SearchAnnotationItemAndChildren Succeeded'
ELSE PRINT 'Procedure Creation: vesp_SearchAnnotationItemAndChildren Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_SearchItemAndChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_SearchItemAndChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_SearchItemAndChildren];
GO
	
/*
exec vesp_SearchItemAndChildren '1,2,4','20007','#Link:Transition',1,0,0,0
exec vesp_SearchItemAndChildren '1,2,4','20007','#Link:Transition',1,1,0,0
exec vesp_SearchItemAndChildren '1,2,4','20007','#Link:Transition',1,2,0,0
exec vesp_SearchItemAndChildren '4','','#Link:Refer',1,2,0,0
exec vesp_SearchItemAndChildren '4','','200`F',0,1,0,0
exec vesp_SearchItemAndChildren '4','10000','',0,0,0,0
exec vesp_SearchItemAndChildren '4','','[0-9]`F',0,1,0,0
exec vesp_SearchItemAndChildren '','','RCP',0,0,0,0
exec vesp_SearchItemAndChildren '','','%',0,0,0,0
exec vesp_SearchItemAndChildren '','20040','',0,0,0,0
exec vesp_SearchItemAndChildren '','10000','XYZZY',0,0,0,0
exec vesp_SearchItemAndChildren '','10000','XYZZY',1,0,0,0
exec vesp_SearchItemAndChildren '','','%IF%',0,0,0,0
exec vesp_SearchItemAndChildren '','','%IF%',1,0,0,0
exec vesp_SearchItemAndChildren '','','%47%',1,0,0,0
exec vesp_SearchItemAndChildren '','','%47%',1,0,0,1
exec vesp_SearchItemAndChildren '','','condenser not av',0,0,0,0
exec vesp_SearchItemAndChildren '','','(SG OR LHSI) AND DISPATCH',2,0,0,0
exec vesp_SearchItemAndChildren '','','DISPATCH NEAR SG',2,0,0,0
exec vesp_SearchItemAndChildren '','','PORV NEAR SG',2,0,0,0
exec vesp_SearchItemAndChildren '','','CHECK NORMAL',0,0,0,0
exec vesp_SearchItemAndChildren '','','turbine-driven',0,0,0,0
*/
CREATE PROCEDURE [dbo].[vesp_SearchItemAndChildren] (@DocVersionList varchar(MAX), @StepTypeList varchar(MAX),
@SearchString varchar(MAX), @CaseSensitive as int, @IncludeLinks as int, @IncludeRtfFormatting as int, @IncludeSpecialCharacters as int)
WITH EXECUTE AS OWNER
AS
BEGIN
Declare @Delim char(1)
Set @Delim=char(7)
Declare @DelimNumber char(1)
Set @DelimNumber=char(17)
Declare @DelimStep char(1)
Set @DelimStep='.'
Set @SearchString = .dbo.vefn_FixSearchString(@SearchString)
begin
with Itemz(DVPath, [Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID],
  [pDTS],[pUserID],[pLastChanged],PPath, Path, IsRNO, POrdinalPath, OrdinalPath) as (
  Select DVPath, 0 [Level], 0 [ParentID], 0 [Ordinal], [I].[ItemID], [PreviousID],0 [FromType],[I].[ContentID],[I].[DTS],[I].[UserID],[I].[LastChanged]
	,0 [pContentID],[I].[DTS] [pDTS], [I].[UserID] [pUserID], [I].[LastChanged] [pLastChanged],
		Cast('' as nvarchar(max)) PPath,
		Cast(Case when C.Type < 20000 then @Delim + C.Number + @DelimNumber + C.Text else '1' end as nvarchar(max)) Path,
		0 IsRNO, Cast('' as nvarchar(max)) POrdinalPath, Cast('0001' as nvarchar(max)) OrdinalPath
	FROM [Items] I
  Join Contents C on C.ContentID=I.ContentID
  JOIN vefn_DocVersionSplit(@DocVersionList) DV
    ON I.[ItemID] = DV.[ItemID]
Union All
-- Children
  select DVPath, [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	,PATH + --''
	case C.Type/10000
	when 2 then
	case P.FromType
	when 3 then @DelimStep + 'Caution'
	when 4 then @DelimStep + 'Note'
  else '' end
	else '' end
	PPath,
	Path + case C.Type/10000
	when 0 then @Delim +C.Number + @DelimNumber + C.Text
	when 1 then @Delim +C.Number + @DelimNumber + C.Text
	else
	case P.FromType
	--when 1 then 'PRC' + @Delim + cast(1 as varchar(3))
	--when 2 then 'SEC' + @Delim + cast(1 as varchar(3))
	when 3 then @DelimStep +'Caution' + @DelimStep + cast(1 as varchar(3))
	when 4 then @DelimStep +'Note' + @DelimStep + cast(1 as varchar(3))
	when 5 then @DelimStep +'RNO' + @DelimStep
	when 7 then @DelimStep +'Table' + @DelimStep
	else case when Z.FromType < 3 then @Delim else @DelimStep end + cast(1 as varchar(3))
	end end Path,
  case when P.FromType = 5 then -1 else 0 end IsRNO,
	OrdinalPath + '.' + Right('0000' + Cast(P.FromType as varchar(4)), 4) + '-' ,
	OrdinalPath + '.' + Right('0000' + Cast(P.FromType as varchar(4)), 4) + '-0001'
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
  join Contents C on C.ContentID = I.ContentID
Union All
-- Siblings
  select DVPath, [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	,PPath,
	--'1' +
	PPath  + case C.Type/10000
	when 0 then @Delim + C.Number + @DelimNumber + C.Text
	when 1 then @Delim + C.Number + @DelimNumber + C.Text
	else case when Path like '%.%' then @DelimStep else @Delim end + cast(Ordinal + 2 as varchar(3))
	end Path, 0,
	POrdinalPath,
	POrdinalPath + right('0000' + cast(Z.[Ordinal] + 2 as varchar(4)), 4)
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
  join Contents C on C.ContentID = I.ContentID
	--where Z.[Level] > 0
)
select DvPath, Path, I.[Level],I.[FromType],I.[Ordinal], I.[ParentID], I.[ItemID],I.[PreviousID],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged],
		C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged],
		[pContentID],[pDTS],[pUserID],[pLastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[I].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[I].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[I].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[I].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[I].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[I].[ItemID]) [Transition_ToIDCount],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[C].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[C].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[C].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[C].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[C].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[C].[ContentID]) [cPartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[C].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[C].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[C].[ContentID]) [ZContentCount]
 from ItemZ I
 join Contents C on C.ContentID = I.ContentID
 left join Entries E on C.ContentID = E.ContentID
 left join Documents D on E.DocID = D.DocID
 where
	(isnull(@SearchString,'')=''
    OR (@CaseSensitive = 1 AND .dbo.vefn_RemoveExtraText(C.Text,@IncludeLinks, @IncludeRtfFormatting, @IncludeSpecialCharacters) like @SearchString Collate SQL_Latin1_General_CP1_CS_AS)
    OR (@CaseSensitive = 0 AND .dbo.vefn_RemoveExtraText(C.Text,@IncludeLinks, @IncludeRtfFormatting, @IncludeSpecialCharacters) like @SearchString Collate SQL_Latin1_General_CP1_CI_AS)
    OR (@CaseSensitive = 1 AND D.DocAscii like @SearchString Collate SQL_Latin1_General_CP1_CS_AS)
    OR (@CaseSensitive = 0 AND D.DocAscii like @SearchString Collate SQL_Latin1_General_CP1_CI_AS)
	)
  AND
  ((isnull(@StepTypeList,'') = '' and dbo.vefn_AllSections(C.Type)>=10000)
    or
   ((dbo.vefn_AllSections(C.Type) in (Select ID from vefn_SplitInt(@StepTypeList,',')))
    or
	 (@StepTypeList like '%20040%' AND IsRNO = -1)))
 order by DvPath,OrdinalPath
OPTION (MAXRECURSION 10000)
END
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_SearchItemAndChildren Succeeded'
ELSE PRINT 'Procedure Creation: vesp_SearchItemAndChildren Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_SearchItemAndChildrenNew] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_SearchItemAndChildrenNew]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_SearchItemAndChildrenNew];
GO
	
/*
exec vesp_SearchItemAndChildrenNew  '1,2,4','20007','#Link:Transition',1,0,0,0
exec vesp_SearchItemAndChildrenNew  '1,2,4','20007','#Link:Transition',1,1,0,0
exec vesp_SearchItemAndChildrenNew  '1,2,4','20007','#Link:Transition',1,2,0,0
exec vesp_SearchItemAndChildrenNew  '4','','#Link:Refer',1,2,0,0
exec vesp_SearchItemAndChildrenNew  '4','','200`F',0,1,0,0
exec vesp_SearchItemAndChildrenNew  '4','10000','',0,0,0,0
exec vesp_SearchItemAndChildrenNew  '4','','[0-9]`F',0,1,0,0
exec vesp_SearchItemAndChildrenNew '1','','"RCP"',2,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','"RCP"',2,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','%',0,0,0,0
exec vesp_SearchItemAndChildrenNew  '','20040','',0,0,0,0
exec vesp_SearchItemAndChildrenNew  '','10000','XYZZY',0,0,0,0
exec vesp_SearchItemAndChildrenNew  '','10000','XYZZY',1,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','%IF%',0,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','%IF%',1,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','%47%',1,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','%47%',1,0,0,1
exec vesp_SearchItemAndChildrenNew  '','','condenser not av',0,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','(SG OR LHSI) AND DISPATCH',2,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','DISPATCH NEAR SG',2,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','PORV NEAR SG',2,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','CHECK NORMAL',0,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','(Resolved Transition Text)',0,0,0,0
exec vesp_SearchItemAndChildrenNew  '','','%turbine-driven%',0,0,0,0
*/

CREATE PROCEDURE [dbo].[vesp_SearchItemAndChildrenNew] (@DocVersionList varchar(MAX), @StepTypeList varchar(MAX),
@SearchString varchar(MAX), @CaseSensitive as int, @IncludeLinks as int, @IncludeRtfFormatting as int, @IncludeSpecialCharacters as int)
WITH EXECUTE AS OWNER
AS
select ZZ.DvPath, ZZ.Path, ZZ.[Level],ZZ.[FromType],ZZ.[Ordinal], ZZ.[ParentID], ZZ.[ItemID],ZZ.[PreviousID],ZZ.[ContentID],ZZ.[DTS],ZZ.[UserID]
		,II.[LastChanged]
	  ,CC.[Number],CC.[Text],CC.[Type],CC.[FormatID],CC.[Config],CC.[DTS] [cDTS],CC.[UserID] [cUserID]
		,CC.[LastChanged] [cLastChanged],
		PP.[ContentID] [pContentID], PP.[DTS] [pDTS],PP.[UserID] [pUserID], PP.[LastChanged] [pLastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=ZZ.[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=ZZ.[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=ZZ.[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=ZZ.[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=ZZ.[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=ZZ.[ItemID]) [Transition_ToIDCount],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=CC.[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=CC.[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=CC.[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=CC.[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=CC.[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=CC.[ContentID]) [cPartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=CC.[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=CC.[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=CC.[ContentID]) [ZContentCount]
from vefn_SiblingAndChildrenItems(@DocVersionList) ZZ
  Join Items II on ZZ.ItemID=II.ItemID
  Left Join Parts PP on ZZ.PContentID=PP.ContentID and ZZ.FromType = PP.FromType
  Join Contents CC on CC.ContentID=ZZ.ContentID
where  ZZ.ContentID in (select ContentID from vefn_FindText(@DocVersionList,@SearchString,@CaseSensitive,@IncludeLinks,@IncludeRtfFormatting,@IncludeSpecialCharacters,@StepTypeList))
 order by DvPath,OrdinalPath
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_SearchItemAndChildrenNew Succeeded'
ELSE PRINT 'Procedure Creation: vesp_SearchItemAndChildrenNew Error on Creation'
GO

/****** Object:  StoredProcedure [vesp_SearchROItemAndChildren] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vesp_SearchROItemAndChildren]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vesp_SearchROItemAndChildren];
GO
	
/*
exec vesp_SearchROItemAndChildren '1,2,4','20007','1:00010000019C,0001000002AE'
exec vesp_SearchROItemAndChildren '1,2,4','','1:00010000019C,0001000002AE'
exec vesp_SearchROItemAndChildren '1,2,4','20007','1:0001'
exec vesp_SearchROItemAndChildren '1,2,4','20006','1'
exec vesp_SearchROItemAndChildren '1,2,4','20006',''
exec vesp_SearchROItemAndChildren '1,2,4',Null,Null
*/
CREATE PROCEDURE [dbo].[vesp_SearchROItemAndChildren] (@DocVersionList varchar(MAX), @StepTypeList varchar(MAX), @ROSearchString varchar(MAX))
WITH EXECUTE AS OWNER
AS
BEGIN
Declare @Delim char(1)
Set @Delim=char(7)
Declare @DelimNumber char(1)
Set @DelimNumber=char(17)
Declare @DelimStep char(1)
Set @DelimStep='.'
begin
with Itemz(DVPath, [Level], [ParentID], [Ordinal], [ItemID], [PreviousID], [FromType], [ContentID], [DTS], [UserID], [LastChanged],[pContentID],
  [pDTS],[pUserID],[pLastChanged],PPath, Path, IsRNO, POrdinalPath, OrdinalPath) as (
  Select DVPath, 0 [Level], 0 [ParentID], 0 [Ordinal], [I].[ItemID], [PreviousID],0 [FromType],[I].[ContentID],[I].[DTS],[I].[UserID],[I].[LastChanged]
	,0 [pContentID],[I].[DTS] [pDTS], [I].[UserID] [pUserID], [I].[LastChanged] [pLastChanged],
		Cast('' as nvarchar(max)) PPath,
		Cast(Case when C.Type < 20000 then @Delim + C.Number + @DelimNumber + C.Text else '1' end as nvarchar(max)) Path,
		0 IsRNO, Cast('' as nvarchar(max)) POrdinalPath, Cast('0001' as nvarchar(max)) OrdinalPath

	FROM [Items] I
  Join Contents C on C.ContentID=I.ContentID
  JOIN vefn_DocVersionSplit(@DocVersionList) DV
    ON I.[ItemID] = DV.[ItemID]
Union All
-- Children
  select DVPath, [Level] + 1,Z.ItemID,0, I.[ItemID], I.[PreviousID], P.[FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,P.[ContentID] [pContentID],P.[DTS] [pDTS],P.[UserID] [pUserID],P.[LastChanged] [pLastChanged]
	,PATH + --''
	case C.Type/10000
	when 2 then
	case P.FromType
	when 3 then @DelimStep + 'Caution'
	when 4 then @DelimStep + 'Note'
  else '' end
	else '' end
	PPath,
	--Path + case when Z.FromType < 3 then @Delim else @DelimStep end + case C.Type/10000
	Path + case C.Type/10000
	when 0 then @Delim +C.Number + @DelimNumber + C.Text
	when 1 then @Delim +C.Number + @DelimNumber + C.Text
	else
	case P.FromType
	--when 1 then 'PRC' + @Delim + cast(1 as varchar(3))
	--when 2 then 'SEC' + @Delim + cast(1 as varchar(3))
	when 3 then @DelimStep +'Caution' + @DelimStep + cast(1 as varchar(3))
	when 4 then @DelimStep +'Note' + @DelimStep + cast(1 as varchar(3))
	when 5 then @DelimStep +'RNO' + @DelimStep
	when 7 then @DelimStep +'Table' + @DelimStep
	else case when Z.FromType < 3 then @Delim else @DelimStep end + cast(1 as varchar(3))
	end end Path,
  case when P.FromType = 5 then -1 else 0 end IsRNO,
	OrdinalPath + '.' + Right('0000' + Cast(P.FromType as varchar(4)), 4) + '-' ,
	OrdinalPath + '.' + Right('0000' + Cast(P.FromType as varchar(4)), 4) + '-0001'
	from Itemz Z
	join Parts P on P.ContentID = Z.ContentID
	join Items I on I.ItemID = P.ItemID
  join Contents C on C.ContentID = I.ContentID
Union All
-- Siblings
  select DVPath, [Level] ,Z.[ParentID],Z.[Ordinal] +1, I.[ItemID], I.[PreviousID], [FromType],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged]
	,null,null,null,null
	,PPath,
	--'1' +
	PPath  + case C.Type/10000
	when 0 then @Delim + C.Number + @DelimNumber + C.Text
	when 1 then @Delim + C.Number + @DelimNumber + C.Text
	else case when Path like '%.%' then @DelimStep else @Delim end + cast(Ordinal + 2 as varchar(3))
	end Path, 0,
	POrdinalPath,
	POrdinalPath + right('0000' + cast(Z.[Ordinal] + 2 as varchar(4)), 4)
	from Itemz Z
	join Items I on I.PreviousID = Z.ItemID
  join Contents C on C.ContentID = I.ContentID
	--where Z.[Level] > 0
)
select DvPath, Path, I.[Level],I.[FromType],I.[Ordinal], I.[ParentID], I.[ItemID],I.[PreviousID],I.[ContentID],I.[DTS],I.[UserID],I.[LastChanged],
		C.[Number],C.[Text],C.[Type],C.[FormatID],C.[Config],C.[DTS] [cDTS],C.[UserID] [cUserID],C.[LastChanged] [cLastChanged],
		[pContentID],[pDTS],[pUserID],[pLastChanged],
		(SELECT COUNT(*) FROM [Annotations] WHERE [Annotations].[ItemID]=[I].[ItemID]) [AnnotationCount],
		(SELECT COUNT(*) FROM [DocVersions] WHERE [DocVersions].[ItemID]=[I].[ItemID]) [DocVersionCount],
		(SELECT COUNT(*) FROM [Items] [Next] WHERE [Next].[PreviousID]=[I].[ItemID]) [NextCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ItemID]=[I].[ItemID]) [PartCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[RangeID]=[I].[ItemID]) [Transition_RangeIDCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[ToID]=[I].[ItemID]) [Transition_ToIDCount],
		(SELECT COUNT(*) FROM [Details] WHERE [Details].[ContentID]=[C].[ContentID]) [DetailCount],
		(SELECT COUNT(*) FROM [Entries] WHERE [Entries].[ContentID]=[C].[ContentID]) [EntryCount],
		(SELECT COUNT(*) FROM [Grids] WHERE [Grids].[ContentID]=[C].[ContentID]) [GridCount],
		(SELECT COUNT(*) FROM [Images] WHERE [Images].[ContentID]=[C].[ContentID]) [ImageCount],
		(SELECT COUNT(*) FROM [Items] WHERE [Items].[ContentID]=[C].[ContentID]) [ItemCount],
		(SELECT COUNT(*) FROM [Parts] WHERE [Parts].[ContentID]=[C].[ContentID]) [cPartCount],
		(SELECT COUNT(*) FROM [RoUsages] WHERE [RoUsages].[ContentID]=[C].[ContentID]) [RoUsageCount],
		(SELECT COUNT(*) FROM [Transitions] WHERE [Transitions].[FromID]=[C].[ContentID]) [TransitionCount],
		(SELECT COUNT(*) FROM [ZContents] WHERE [ZContents].[ContentID]=[C].[ContentID]) [ZContentCount]
 from ItemZ I
 join Contents C on C.ContentID = I.ContentID
 left join Entries E on C.ContentID = E.ContentID
 left join Documents D on E.DocID = D.DocID
 where
  I.ContentID in(select ContentID from ROUsages RU
		join vefn_SplitROSearch(@ROSearchString) RR
		ON RR.RODBID = RU.RODBID and
		RU.ROID like RR.ROID + '%' Collate SQL_Latin1_General_CP1_CI_AS
UNION
select Distinct ContentID from Entries EE
	Join DROUsages RU on RU.DocID = EE.DocID
		join vefn_SplitROSearch(@ROSearchString) RR
		ON RR.RODBID = RU.RODBID and
		RU.ROID = RR.ROID)
  AND
  ((isnull(@StepTypeList,'') = '' and dbo.vefn_AllSections(C.Type)>=10000)
    or
   ((dbo.vefn_AllSections(C.Type) in (Select ID from vefn_SplitInt(@StepTypeList,',')))
    or
	 (@StepTypeList like '%20040%' AND IsRNO = -1)))
 order by DvPath,OrdinalPath
OPTION (MAXRECURSION 10000)
END
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vesp_SearchROItemAndChildren Succeeded'
ELSE PRINT 'Procedure Creation: vesp_SearchROItemAndChildren Error on Creation'
GO

/****** Object:  StoredProcedure [vlnErrorHandler] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[vlnErrorHandler]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
    DROP PROCEDURE [vlnErrorHandler];
GO
	
CREATE PROCEDURE [dbo].[vlnErrorHandler]
	(@ExpectedCount int=-1
	,@MessageFormat nvarchar(512)=N'Expected RowCount (%d) not met (%d)')
WITH EXECUTE AS OWNER
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000),	@ErrorNumber INT, @ErrorSeverity INT, @ErrorState INT, @ErrorProcedure NVARCHAR(126)
		, @ErrorLine INT, @RowCount INT;
	SELECT @ErrorMessage = ERROR_MESSAGE(),	@ErrorSeverity = ERROR_SEVERITY(),	@ErrorState = ERROR_STATE(),@ErrorNumber = ERROR_NUMBER()
		, @ErrorLine = ERROR_LINE(), @ErrorProcedure = ERROR_PROCEDURE(), @RowCount = @@RowCount;
	IF @ErrorNumber > 0
		BEGIN
			IF @ErrorProcedure = OBJECT_NAME(@@PROCID) -- If the Procedure is the current procedure just pass the error message
				RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState)
			ELSE -- Add in the procedure name and line as well as the error number
				RAISERROR (N'%s[%d] - (%d) %s', @ErrorSeverity, @ErrorState, @ErrorProcedure, @ErrorLine, @ErrorNumber, @ErrorMessage)
		END
	ELSE IF @ExpectedCount <> -1 AND @ExpectedCount <> @RowCount
		RAISERROR (@MessageFormat, 16, 1, @ExpectedCount, @RowCount)
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: vlnErrorHandler Succeeded'
ELSE PRINT 'Procedure Creation: vlnErrorHandler Error on Creation'
GO
