
/****** 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 [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 [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 [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
  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
	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
		EXECUTE AddPart 	@ParentContentID, @FromType, @newItemID, @DTS, @UserID, @newLastChanged output
	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 Transition Destination',@UserID
		FROM Items where CONTENTID in (SELECT FromID FROM TRANSITIONS
		where ToID IN(@NextID,@newItemID) OR RangeID IN(@NextID,@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: 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 [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,
	@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],
		[TranType],
		[Config],
		[DTS],
		[UserID]
	)
	VALUES
	(
		@FromID,
		@ToID,
		@RangeID,
		@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 [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 [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 [Entries]
		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 [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 [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 [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 @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
		-- 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 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
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 [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 [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 [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 [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 [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 [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 [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)
)
AS
	--if @Command='Deleted'
	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],
		[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 [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
		[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].[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 [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 [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 [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 [Entries] WHERE [Entries].[DocID]=[Documents].[DocID]) [EntryCount]
	FROM [Documents]
	WHERE [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

	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 [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 [Entries] WHERE [Entries].[DocID]=[Documents].[DocID]) [EntryCount]
	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 [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 [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.[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 [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 [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].[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].[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 [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 [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 [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 [Entries] WHERE [Entries].[DocID]=[Documents].[DocID]) [EntryCount]
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 [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 [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 [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
		[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 [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 [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 [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],
		[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],
		[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].[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].[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].[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 [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 [Entries]
	delete from [Figures]
	dbcc checkident([Figures],reseed,0)
	delete from [Folders]
	dbcc checkident([Folders],reseed,0)
	delete from [Memberships]
	dbcc checkident([Memberships],reseed,0)
	delete from [Parts]
	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 [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 [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 [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 [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,
	@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,
			[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_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_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
)
insert into @Transitions
select TransitionID from Transitions TT
where (ToID in(select ItemID from Itemz) OR RangeID in(select ItemID from Itemz))
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_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
	
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
Declare @SearchString2 nvarchar(200)
Set @SearchString2 = case when @CaseSensitive = 2 then Cast(@SearchString as nvarchar(200)) else 'IGNORE_FULL_TEXT_SEARCH' end
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
	IF @CaseSensitive = 0 -- Not Case Sensitive
		BEGIN
			insert into @FoundContents
				select C.ContentID from vefn_FindContentText(@DocVersionList,@SearchString) C
					where
					(.dbo.vefn_RemoveExtraText(C.Text,@IncludeLinks, @IncludeRtfFormatting, @IncludeSpecialCharacters) 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,',')))))
				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,@SearchString) C
							where
							(.dbo.vefn_RemoveExtraText(C.Text,@IncludeLinks, @IncludeRtfFormatting, @IncludeSpecialCharacters) 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,',')))))
						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
			ELSE -- @CaseSensitive = 2 -- FullText Search
				BEGIN
					insert into @FoundContents
						select C.ContentID from Contents C
							left join Entries E on C.ContentID = E.ContentID
							left join Documents D on E.DocID = D.DocID
							where
							(CONTAINS(C.text, @SearchString2) OR CONTAINS(D.DocAscii, @SearchString2))
							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_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_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_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_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_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_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
)
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 [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_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 [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 [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 [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 [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
*/
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='.'
Declare @SearchString2 nvarchar(200)
Set @SearchString2 = case when @CaseSensitive = 2 then Cast(@SearchString as nvarchar(200)) else 'IGNORE_FULL_TEXT_SEARCH' end
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 [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 = 2 AND CONTAINS(C.text, @SearchString2))
    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)
    OR (@CaseSensitive = 2 AND CONTAINS(D.DocAscii, @SearchString2))
	)
  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
*/

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 [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 [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 Distinct 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)
  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
