/*
Deployment script for ProcessDirector_FEMA

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/

GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;

SET NUMERIC_ROUNDABORT OFF;


GO
:setvar DatabaseName "ProcessDirector_FEMA"
:setvar DefaultFilePrefix "ProcessDirector_FEMA"
:setvar DefaultDataPath "C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\DATA\"
:setvar DefaultLogPath "C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\DATA\"

GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF; 
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
    BEGIN
        PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
        SET NOEXEC ON;
    END


GO
USE [master];


GO

IF (DB_ID(N'$(DatabaseName)') IS NOT NULL) 
BEGIN
    ALTER DATABASE [$(DatabaseName)]
    SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    DROP DATABASE [$(DatabaseName)];
END

GO
PRINT N'Creating database $(DatabaseName)...'
GO
CREATE DATABASE [$(DatabaseName)]
    ON 
    PRIMARY(NAME = [$(DatabaseName)], FILENAME = N'$(DefaultDataPath)$(DefaultFilePrefix)_Primary.mdf')
    LOG ON (NAME = [$(DatabaseName)_log], FILENAME = N'$(DefaultLogPath)$(DefaultFilePrefix)_Primary.ldf') COLLATE SQL_Latin1_General_CP1_CI_AS
GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET AUTO_CLOSE OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
USE [$(DatabaseName)];


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET ANSI_NULLS ON,
                ANSI_PADDING ON,
                ANSI_WARNINGS ON,
                ARITHABORT ON,
                CONCAT_NULL_YIELDS_NULL ON,
                NUMERIC_ROUNDABORT OFF,
                QUOTED_IDENTIFIER ON,
                ANSI_NULL_DEFAULT ON,
                CURSOR_DEFAULT LOCAL,
                RECOVERY FULL,
                CURSOR_CLOSE_ON_COMMIT OFF,
                AUTO_CREATE_STATISTICS ON,
                AUTO_SHRINK OFF,
                AUTO_UPDATE_STATISTICS ON,
                RECURSIVE_TRIGGERS OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET ALLOW_SNAPSHOT_ISOLATION OFF;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET READ_COMMITTED_SNAPSHOT OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET AUTO_UPDATE_STATISTICS_ASYNC OFF,
                PAGE_VERIFY NONE,
                DATE_CORRELATION_OPTIMIZATION OFF,
                DISABLE_BROKER,
                PARAMETERIZATION SIMPLE,
                SUPPLEMENTAL_LOGGING OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
    BEGIN
        IF EXISTS (SELECT 1
                   FROM   [master].[dbo].[sysdatabases]
                   WHERE  [name] = N'$(DatabaseName)')
            BEGIN
                EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
    SET TRUSTWORTHY OFF,
        DB_CHAINING OFF 
    WITH ROLLBACK IMMEDIATE';
            END
    END
ELSE
    BEGIN
        PRINT N'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
    END


GO
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
    BEGIN
        IF EXISTS (SELECT 1
                   FROM   [master].[dbo].[sysdatabases]
                   WHERE  [name] = N'$(DatabaseName)')
            BEGIN
                EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
    SET HONOR_BROKER_PRIORITY OFF 
    WITH ROLLBACK IMMEDIATE';
            END
    END
ELSE
    BEGIN
        PRINT N'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
    END


GO
ALTER DATABASE [$(DatabaseName)]
    SET TARGET_RECOVERY_TIME = 0 SECONDS 
    WITH ROLLBACK IMMEDIATE;


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF),
                CONTAINMENT = NONE 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET AUTO_CREATE_STATISTICS ON(INCREMENTAL = OFF),
                MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT = OFF,
                DELAYED_DURABILITY = DISABLED 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET QUERY_STORE (QUERY_CAPTURE_MODE = ALL, DATA_FLUSH_INTERVAL_SECONDS = 900, INTERVAL_LENGTH_MINUTES = 60, MAX_PLANS_PER_QUERY = 200, CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 367), MAX_STORAGE_SIZE_MB = 100) 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET QUERY_STORE = OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;
        ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;
        ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;
        ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;
        ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;
        ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;
        ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;
        ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET TEMPORAL_HISTORY_RETENTION ON 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF fulltextserviceproperty(N'IsFulltextInstalled') = 1
    EXECUTE sp_fulltext_database 'enable';


GO
PRINT N'Creating Table [dbo].[ATAssigmentType]...';


GO
CREATE TABLE [dbo].[ATAssigmentType] (
    [Id]   INT           IDENTITY (0, 1) NOT NULL,
    [Name] NVARCHAR (32) NOT NULL,
    CONSTRAINT [PK_AtAssigmentType] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATBarcodeFont]...';


GO
CREATE TABLE [dbo].[ATBarcodeFont] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (100) NOT NULL,
    [Description] NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATBarcodeFont] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_ATBarcodeFont_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATButton]...';


GO
CREATE TABLE [dbo].[ATButton] (
    [Id]          INT              IDENTITY (1, 1) NOT NULL,
    [ButtonName]  NVARCHAR (255)   NOT NULL,
    [ButtonValue] NVARCHAR (255)   NULL,
    [ButtonIndex] INT              NOT NULL,
    [QueueId]     INT              NOT NULL,
    [HelpText]    NVARCHAR (255)   NULL,
    [Tag]         NVARCHAR (255)   NULL,
    [ObjectId]    UNIQUEIDENTIFIER NOT NULL,
    [EventId]     INT              NOT NULL,
    CONSTRAINT [PK_ATButton] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UK_ATButton] UNIQUE NONCLUSTERED ([ObjectId] ASC),
    CONSTRAINT [UK_Name_Queue] UNIQUE NONCLUSTERED ([ButtonName] ASC, [QueueId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATCode]...';


GO
CREATE TABLE [dbo].[ATCode] (
    [EventID]   INT            NOT NULL,
    [ProcessID] INT            NOT NULL,
    [CodeName]  NVARCHAR (128) NULL,
    [CodePath]  NVARCHAR (256) NULL,
    [CodeArgs]  NVARCHAR (256) NULL
);


GO
PRINT N'Creating Table [dbo].[ATConnection]...';


GO
CREATE TABLE [dbo].[ATConnection] (
    [Id]               INT            IDENTITY (1, 1) NOT NULL,
    [Name]             NVARCHAR (50)  NOT NULL,
    [Type]             INT            NOT NULL,
    [ConnectionString] NVARCHAR (255) NOT NULL,
    [UserName]         NVARCHAR (50)  NOT NULL,
    [Password]         NVARCHAR (50)  NOT NULL,
    [Options]          NVARCHAR (50)  NULL,
    [Description]      NVARCHAR (255) NULL,
    [DefaultFrom]      NVARCHAR (255) NULL,
    [DefaultReplyTo]   NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATConnection] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATConnectionType]...';


GO
CREATE TABLE [dbo].[ATConnectionType] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (50)  NOT NULL,
    [Description] NVARCHAR (200) NULL,
    CONSTRAINT [PK_ATConnectionType] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATConvertDefinition]...';


GO
CREATE TABLE [dbo].[ATConvertDefinition] (
    [Id]              INT IDENTITY (1, 1) NOT NULL,
    [ProcessID]       INT NOT NULL,
    [TemplateId]      INT NOT NULL,
    [SourceDocTypeId] INT NULL,
    [ExportDocTypeId] INT NULL,
    [MergeOrderId]    INT NULL,
    [MergeDocs]       BIT NULL,
    [KeepInMemory]    BIT NULL,
    [CoverSheet]      BIT NULL,
    [Barcodes]        BIT NULL,
    [BarcodesFontId]  INT NULL,
    [ReplaceDocument] BIT NOT NULL,
    CONSTRAINT [PK_ATConvertDefinition] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATConvertEvent]...';


GO
CREATE TABLE [dbo].[ATConvertEvent] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [EventId]     INT            NOT NULL,
    [TemplateId]  INT            NOT NULL,
    [Order]       INT            NOT NULL,
    [Description] NVARCHAR (500) NOT NULL,
    CONSTRAINT [PK_ATConvertEvent] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UK_ATConvertEvent_EventId_TemplateId_Order] UNIQUE NONCLUSTERED ([EventId] ASC, [TemplateId] ASC, [Order] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATD_CFTemplate]...';


GO
CREATE TABLE [dbo].[ATD_CFTemplate] (
    [InstanceId] INT           NULL,
    [DocumentId] INT           NULL,
    [RevNum]     INT           NULL,
    [RevStatus]  VARCHAR (255) NULL,
    [RegId]      VARCHAR (50)  NULL,
    [DisasterNo] VARCHAR (50)  NULL,
    [DocType]    VARCHAR (50)  NULL,
    [FirstName]  VARCHAR (50)  NULL,
    [LastName]   VARCHAR (50)  NULL,
    [Address]    VARCHAR (100) NULL,
    [City]       VARCHAR (50)  NULL,
    [State]      VARCHAR (50)  NULL,
    [Zip]        VARCHAR (50)  NULL,
    [RecDate]    DATE          NULL
);


GO
PRINT N'Creating Table [dbo].[ATD_DefaultTemplate]...';


GO
CREATE TABLE [dbo].[ATD_DefaultTemplate] (
    [InstanceID]  INT            NULL,
    [DocumentID]  INT            NULL,
    [RevNum]      INT            NULL,
    [RevStatus]   NVARCHAR (255) NULL,
    [Description] NVARCHAR (255) NULL,
    [DocDate]     DATETIME       NULL
);


GO
PRINT N'Creating Table [dbo].[ATD_EMARK_DOC_TEMPLATE]...';


GO
CREATE TABLE [dbo].[ATD_EMARK_DOC_TEMPLATE] (
    [InstanceId]             INT            NULL,
    [DocumentId]             INT            NULL,
    [RevNum]                 INT            NULL,
    [RevStatus]              VARCHAR (255)  NULL,
    [DOC_TYPE_ID]            INT            NULL,
    [DOC_TYPE_NAME]          NVARCHAR (50)  NULL,
    [DOC_ID]                 INT            NULL,
    [DOC_NUMBER]             NVARCHAR (15)  NULL,
    [DOC_DATE]               DATETIME       NULL,
    [INSTITUTE_ID]           INT            NULL,
    [INSTITUTE_ABRNAME]      NVARCHAR (15)  NULL,
    [ACADEMIC_YEAR_ID]       INT            NULL,
    [ACADEMIC_YEAR_NAME]     NVARCHAR (15)  NULL,
    [YEAR_SEMESTER_ID]       INT            NULL,
    [YEAR_SEMESTER_NAME]     NVARCHAR (15)  NULL,
    [STUDENT_EDULEVEL_ID]    INT            NULL,
    [STUDENT_EDULEVEL_NAME]  NVARCHAR (25)  NULL,
    [STUDENT_GROUP]          NVARCHAR (15)  NULL,
    [SUBJECT_ID]             INT            NULL,
    [SUBJECT_NAME]           NVARCHAR (50)  NULL,
    [TEACHER_ID]             INT            NULL,
    [TEACHER_NAME]           NVARCHAR (50)  NULL,
    [TEACHER_DEPARTMENT_ID]  INT            NULL,
    [TEACHER_DEPARTMENT]     NVARCHAR (50)  NULL,
    [TEACHER_USERID]         NVARCHAR (50)  NULL,
    [TEACHER_EMAIL]          NVARCHAR (50)  NULL,
    [REQUEST_DATE]           DATETIME       NULL,
    [SIGNED_DATE]            DATETIME       NULL,
    [SIGNATORY_ID]           INT            NULL,
    [SIGNATORY_NAME]         NVARCHAR (50)  NULL,
    [SIGNATORY_INSTITUTE_ID] INT            NULL,
    [SIGNATORY_INSTITUTE]    NVARCHAR (50)  NULL,
    [SIGNATORY_USERID]       INT            NULL,
    [SIGNATORY_EMAIL]        NVARCHAR (50)  NULL,
    [DOC_COMMENTS]           NVARCHAR (512) NULL
);


GO
PRINT N'Creating Table [dbo].[ATD_Test_Dates]...';


GO
CREATE TABLE [dbo].[ATD_Test_Dates] (
    [InstanceId]  INT           NULL,
    [DocumentId]  INT           NULL,
    [RevNum]      INT           NULL,
    [RevStatus]   VARCHAR (255) NULL,
    [MO_DY_YR]    DATETIME      NULL,
    [MO_DY_YEAR]  DATETIME      NULL,
    [YEAR_MO_DY]  DATETIME      NULL,
    [DY_MON_YR]   DATETIME      NULL,
    [DY_MON_YEAR] DATETIME      NULL
);


GO
PRINT N'Creating Table [dbo].[ATD_Test_Integer]...';


GO
CREATE TABLE [dbo].[ATD_Test_Integer] (
    [InstanceId]      INT           NULL,
    [DocumentId]      INT           NULL,
    [RevNum]          INT           NULL,
    [RevStatus]       VARCHAR (255) NULL,
    [Ten]             INT           NULL,
    [Hundred]         INT           NULL,
    [HundredThousand] INT           NULL
);


GO
PRINT N'Creating Table [dbo].[ATD_Test_Mixed]...';


GO
CREATE TABLE [dbo].[ATD_Test_Mixed] (
    [InstanceId] INT           NULL,
    [DocumentId] INT           NULL,
    [RevNum]     INT           NULL,
    [RevStatus]  VARCHAR (255) NULL,
    [Date]       DATETIME      NULL,
    [Integer]    INT           NULL,
    [String]     NVARCHAR (50) NULL,
    [stringer]   NVARCHAR (50) NULL
);


GO
PRINT N'Creating Table [dbo].[ATDocumenctReviewStatus]...';


GO
CREATE TABLE [dbo].[ATDocumenctReviewStatus] (
    [Id]   INT           IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_ATDocumenctReviewStatus] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATDocument]...';


GO
CREATE TABLE [dbo].[ATDocument] (
    [DocumentId]     INT            IDENTITY (1, 1) NOT NULL,
    [DocumentName]   NVARCHAR (255) NULL,
    [ReviewStatusId] INT            NOT NULL,
    [ReviewNumber]   INT            NOT NULL,
    [CabinetId]      INT            NOT NULL,
    [WorkItemId]     INT            NOT NULL,
    [DocumentSize]   INT            NOT NULL,
    [DisplayOrder]   INT            NULL,
    [Document]       IMAGE          NULL,
    [DocumentLink]   NVARCHAR (255) NULL,
    [UserName]       NVARCHAR (255) NULL,
    [SignedBy]       NVARCHAR (255) NULL,
    [LastModified]   DATETIME       NOT NULL,
    CONSTRAINT [PK_ATDocument] PRIMARY KEY CLUSTERED ([DocumentId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATDocument].[ATDocument_IX_WorkItemId]...';


GO
CREATE NONCLUSTERED INDEX [ATDocument_IX_WorkItemId]
    ON [dbo].[ATDocument]([WorkItemId] ASC);


GO
PRINT N'Creating Table [dbo].[ATDocumentArc]...';


GO
CREATE TABLE [dbo].[ATDocumentArc] (
    [DocumentId]    INT            NOT NULL,
    [DocumentName]  NVARCHAR (255) NULL,
    [ContentTypeId] INT            NULL,
    [WorkItemId]    INT            NOT NULL,
    [DocumentSize]  INT            NOT NULL,
    [Document]      TEXT           NULL,
    [DocumentLink]  NVARCHAR (255) NULL,
    [UserName]      NVARCHAR (255) NULL,
    [LastModified]  DATETIME       NULL,
    CONSTRAINT [PK_ATDocumentArc] PRIMARY KEY NONCLUSTERED ([DocumentId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATDocumentCabinet]...';


GO
CREATE TABLE [dbo].[ATDocumentCabinet] (
    [CabinetID]          INT              IDENTITY (1, 1) NOT NULL,
    [CabinetName]        NVARCHAR (255)   NOT NULL,
    [CabinetDescription] NVARCHAR (255)   NULL,
    [TemplateTypeId]     INT              NOT NULL,
    [DbConnectionId]     INT              NULL,
    [DbName]             NVARCHAR (50)    NULL,
    [ObjectId]           UNIQUEIDENTIFIER NOT NULL,
    [CreateDate]         DATETIME         NOT NULL,
    [ModifyDate]         DATETIME         NOT NULL,
    CONSTRAINT [PK_ATDocumentCabinet] PRIMARY KEY CLUSTERED ([CabinetID] ASC),
    CONSTRAINT [UK_ATDocumentCabinet_CabinetName] UNIQUE NONCLUSTERED ([CabinetName] ASC),
    CONSTRAINT [UK_ATDocumentCabinet_ObjectId] UNIQUE NONCLUSTERED ([ObjectId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATDocumentCabinet].[ATDocumentCabinet_IX_CabinetID]...';


GO
CREATE NONCLUSTERED INDEX [ATDocumentCabinet_IX_CabinetID]
    ON [dbo].[ATDocumentCabinet]([CabinetID] ASC);


GO
PRINT N'Creating Table [dbo].[ATDocumentCabinetDef]...';


GO
CREATE TABLE [dbo].[ATDocumentCabinetDef] (
    [FieldID]          INT              IDENTITY (1, 1) NOT NULL,
    [CabinetID]        INT              NOT NULL,
    [FieldName]        NVARCHAR (255)   NOT NULL,
    [FieldDescription] NVARCHAR (255)   NULL,
    [FieldDataType]    NVARCHAR (255)   NOT NULL,
    [FieldDataTypeId]  INT              NULL,
    [FieldSize]        INT              NOT NULL,
    [DefaultValue]     NVARCHAR (255)   NULL,
    [ObjectId]         UNIQUEIDENTIFIER NOT NULL,
    [Display]          BIT              NOT NULL,
    CONSTRAINT [PK_ATDocumentCabinetDef] PRIMARY KEY CLUSTERED ([FieldID] ASC),
    CONSTRAINT [UK_ATDocumentCabinetDef_FieldName_CabinetId] UNIQUE NONCLUSTERED ([CabinetID] ASC, [FieldName] ASC),
    CONSTRAINT [UK_ATDocumentCabinetDef_ObjectId] UNIQUE NONCLUSTERED ([ObjectId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATDocumentCabinetDef].[ATDocumentCabinetDef_IX_FieldID]...';


GO
CREATE NONCLUSTERED INDEX [ATDocumentCabinetDef_IX_FieldID]
    ON [dbo].[ATDocumentCabinetDef]([FieldID] ASC);


GO
PRINT N'Creating Table [dbo].[ATDocumentCabinetFiledType]...';


GO
CREATE TABLE [dbo].[ATDocumentCabinetFiledType] (
    [Id]   INT            IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (255) NOT NULL,
    CONSTRAINT [PK_ATDocumentCabinetFiledType] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATEnterpriseConnection]...';


GO
CREATE TABLE [dbo].[ATEnterpriseConnection] (
    [ConnectionName] NVARCHAR (50)  NOT NULL,
    [Description]    NVARCHAR (255) NULL,
    [ServerName]     NVARCHAR (50)  NOT NULL,
    [UserName]       NVARCHAR (50)  NOT NULL,
    [Password]       NVARCHAR (50)  NOT NULL,
    CONSTRAINT [PK_ATEnterpriseConnection] PRIMARY KEY NONCLUSTERED ([ConnectionName] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATErrors]...';


GO
CREATE TABLE [dbo].[ATErrors] (
    [ErrorRecId]          INT             IDENTITY (1, 1) NOT NULL,
    [ErrorDate]           DATETIME        NOT NULL,
    [ProcessGroup]        NVARCHAR (255)  NOT NULL,
    [ProcessName]         NVARCHAR (255)  NOT NULL,
    [WorkItemName]        NVARCHAR (255)  NOT NULL,
    [WorkItemId]          INT             NOT NULL,
    [WorkItemReferenceId] INT             NOT NULL,
    [Event]               NVARCHAR (255)  NOT NULL,
    [Message]             NVARCHAR (2000) NULL,
    CONSTRAINT [PK_ATErrors] PRIMARY KEY CLUSTERED ([ErrorRecId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATEventDefinition]...';


GO
CREATE TABLE [dbo].[ATEventDefinition] (
    [EventID]            INT            IDENTITY (1, 1) NOT NULL,
    [ProcessID]          INT            NOT NULL,
    [EventName]          NVARCHAR (255) NOT NULL,
    [PositionX]          INT            NULL,
    [PositionY]          INT            NULL,
    [EventTypeID]        INT            NOT NULL,
    [Server]             NVARCHAR (255) NULL,
    [ExpirationInterval] INT            NULL,
    [JoinEventID]        INT            NULL,
    [ProcessAtServer]    INT            NOT NULL,
    [Script]             IMAGE          NULL,
    [ScriptLanguage]     INT            NULL,
    [ExScript]           IMAGE          NULL,
    [ExpirationInstance] NVARCHAR (50)  NULL,
    [NextEventID]        INT            NULL,
    [Action]             NVARCHAR (64)  NULL,
    CONSTRAINT [PK_EventDefinition] PRIMARY KEY NONCLUSTERED ([EventID] ASC),
    CONSTRAINT [UK_EventDefinition_Process_EventName_Action] UNIQUE NONCLUSTERED ([ProcessID] ASC, [EventName] ASC, [Action] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATEventDefinition].[ATEventDefinition_IX_Expire]...';


GO
CREATE NONCLUSTERED INDEX [ATEventDefinition_IX_Expire]
    ON [dbo].[ATEventDefinition]([ExpirationInterval] ASC);


GO
PRINT N'Creating Table [dbo].[ATEventTriggerDefinition]...';


GO
CREATE TABLE [dbo].[ATEventTriggerDefinition] (
    [Id]            INT            IDENTITY (1, 1) NOT NULL,
    [ProcessId]     INT            NOT NULL,
    [TemplateId]    INT            NOT NULL,
    [TriggerName]   NVARCHAR (255) NOT NULL,
    [HookId]        INT            NOT NULL,
    [ActionId]      INT            NOT NULL,
    [Description]   NVARCHAR (255) NULL,
    [TriggerAction] NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_ATEventTriggerDefinition] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATEventTriggerTemplate]...';


GO
CREATE TABLE [dbo].[ATEventTriggerTemplate] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [EventId]     INT            NOT NULL,
    [TemplateId]  INT            NOT NULL,
    [Order]       INT            NOT NULL,
    [Enabled]     BIT            NOT NULL,
    [Description] NVARCHAR (500) NOT NULL,
    CONSTRAINT [PK_ATEventTriggerTemplate] PRIMARY KEY NONCLUSTERED ([Id] ASC),
    CONSTRAINT [UK_ATEventTriggerTemplate_EventId_TemplateId_Order] UNIQUE NONCLUSTERED ([EventId] ASC, [TemplateId] ASC, [Order] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATEventTriggerTemplate].[IX_ATEventTriggerTemplate_EventId_Order_Clustered]...';


GO
CREATE CLUSTERED INDEX [IX_ATEventTriggerTemplate_EventId_Order_Clustered]
    ON [dbo].[ATEventTriggerTemplate]([EventId] ASC, [TemplateId] ASC);


GO
PRINT N'Creating Table [dbo].[ATEventType]...';


GO
CREATE TABLE [dbo].[ATEventType] (
    [Id]          INT            IDENTITY (0, 1) NOT NULL,
    [Description] NVARCHAR (255) NOT NULL,
    [ShortName]   NVARCHAR (16)  NOT NULL,
    CONSTRAINT [PK_ATEventType] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExceptionNote]...';


GO
CREATE TABLE [dbo].[ATExceptionNote] (
    [WorkItemReferenceID] INT            NOT NULL,
    [ExceptionReason]     NVARCHAR (255) NULL,
    [ExceptionUser]       NVARCHAR (255) NULL,
    [ExceptionType]       INT            NOT NULL,
    CONSTRAINT [PK_ATExceptionNote] PRIMARY KEY NONCLUSTERED ([WorkItemReferenceID] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExportDefinition]...';


GO
CREATE TABLE [dbo].[ATExportDefinition] (
    [Id]                 INT IDENTITY (1, 1) NOT NULL,
    [ProcessId]          INT NOT NULL,
    [ExportTypeId]       INT NULL,
    [DoneFlagId]         INT NULL,
    [ExportFileFormatId] INT NULL,
    [TemplateId]         INT NOT NULL,
    CONSTRAINT [PK_ATExportDefinition] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExportDefinition_ExportLocation]...';


GO
CREATE TABLE [dbo].[ATExportDefinition_ExportLocation] (
    [ExportDefinitionId] INT NOT NULL,
    [ExportLocationId]   INT NOT NULL,
    CONSTRAINT [PK_ATExportDefinition_ExportLocation] PRIMARY KEY CLUSTERED ([ExportDefinitionId] ASC, [ExportLocationId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExportEvent]...';


GO
CREATE TABLE [dbo].[ATExportEvent] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [EventId]     INT            NOT NULL,
    [TemplateId]  INT            NOT NULL,
    [Order]       INT            NOT NULL,
    [Description] NVARCHAR (500) NOT NULL,
    CONSTRAINT [PK_ATExportEvent] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UK_ATExportEvent_EventId_TemplateId_Order] UNIQUE NONCLUSTERED ([EventId] ASC, [TemplateId] ASC, [Order] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExportFlagTxt]...';


GO
CREATE TABLE [dbo].[ATExportFlagTxt] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (100) NOT NULL,
    [Description] NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATExportFlagTxt] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_ATExportFlagTxt_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExportLocation]...';


GO
CREATE TABLE [dbo].[ATExportLocation] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (100) NOT NULL,
    [Description] NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATExportLocation] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_ATExportLocation_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExportType]...';


GO
CREATE TABLE [dbo].[ATExportType] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (100) NOT NULL,
    [Description] NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATExportType] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_ATExportType_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExternalTrackingDefinition]...';


GO
CREATE TABLE [dbo].[ATExternalTrackingDefinition] (
    [Id]           INT            IDENTITY (1, 1) NOT NULL,
    [TemplateId]   INT            NOT NULL,
    [DBTableName]  NVARCHAR (255) NOT NULL,
    [SourceTypeId] INT            NOT NULL,
    [SourceValue]  NVARCHAR (255) NOT NULL,
    [DbColumnName] NVARCHAR (255) NOT NULL,
    [DBDataType]   NVARCHAR (50)  NOT NULL,
    CONSTRAINT [PK_ATExternalTrackingDefinition_Id] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATExternalTrackingSourceType]...';


GO
CREATE TABLE [dbo].[ATExternalTrackingSourceType] (
    [Id]   INT           IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_ATExternalTrackingSourceType] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATFAQ]...';


GO
CREATE TABLE [dbo].[ATFAQ] (
    [ID]         UNIQUEIDENTIFIER NOT NULL,
    [Question]   NVARCHAR (2000)  NOT NULL,
    [Answer]     NVARCHAR (4000)  NULL,
    [TargetType] INT              NOT NULL
);


GO
PRINT N'Creating Table [dbo].[ATFieldDefinition]...';


GO
CREATE TABLE [dbo].[ATFieldDefinition] (
    [FieldID]      INT              IDENTITY (1, 1) NOT NULL,
    [ProcessID]    INT              NOT NULL,
    [Index]        INT              NULL,
    [FieldName]    NVARCHAR (64)    NOT NULL,
    [Alias]        NVARCHAR (64)    NULL,
    [DataType]     TINYINT          NOT NULL,
    [InitialValue] NVARCHAR (MAX)   NULL,
    [Locked]       BIT              NOT NULL,
    [Display]      BIT              NOT NULL,
    [ObjectId]     UNIQUEIDENTIFIER NOT NULL,
    CONSTRAINT [PK_FieldDefinition] PRIMARY KEY NONCLUSTERED ([FieldID] ASC),
    CONSTRAINT [UQ_ATFieldDefinition_FieldName_ProcessID] UNIQUE NONCLUSTERED ([FieldName] ASC, [ProcessID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATFieldDefinition].[ATFieldDefinition_IX_ProcessId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldDefinition_IX_ProcessId]
    ON [dbo].[ATFieldDefinition]([ProcessID] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldDefinition].[ATFieldDefinition_ObjectId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldDefinition_ObjectId]
    ON [dbo].[ATFieldDefinition]([ObjectId] ASC);


GO
PRINT N'Creating Table [dbo].[ATFieldInstanceDate]...';


GO
CREATE TABLE [dbo].[ATFieldInstanceDate] (
    [FieldInstanceID] INT           IDENTITY (1, 1) NOT NULL,
    [FieldID]         INT           NOT NULL,
    [FieldValue]      DATETIME      NULL,
    [WorkItemID]      INT           NOT NULL,
    [FieldName]       NVARCHAR (64) NOT NULL,
    CONSTRAINT [PK_ATFieldInstanceDate] PRIMARY KEY NONCLUSTERED ([FieldInstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceDate].[ATFieldInstanceDate_IX_FId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceDate_IX_FId]
    ON [dbo].[ATFieldInstanceDate]([FieldID] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceDate].[ATFieldInstanceDate_IX_FName]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceDate_IX_FName]
    ON [dbo].[ATFieldInstanceDate]([FieldName] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceDate].[ATFieldInstanceDate_IX_WIId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceDate_IX_WIId]
    ON [dbo].[ATFieldInstanceDate]([WorkItemID] ASC);


GO
PRINT N'Creating Table [dbo].[ATFieldInstanceNumber]...';


GO
CREATE TABLE [dbo].[ATFieldInstanceNumber] (
    [FieldInstanceID] INT              IDENTITY (1, 1) NOT NULL,
    [FieldID]         INT              NOT NULL,
    [FieldValue]      NUMERIC (28, 14) NULL,
    [WorkItemID]      INT              NOT NULL,
    [FieldName]       NVARCHAR (64)    NOT NULL,
    CONSTRAINT [PK_ATFieldInstanceNumber] PRIMARY KEY NONCLUSTERED ([FieldInstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceNumber].[ATFieldInstanceNumber_IX_FId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceNumber_IX_FId]
    ON [dbo].[ATFieldInstanceNumber]([FieldID] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceNumber].[ATFieldInstanceNumber_IX_FName]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceNumber_IX_FName]
    ON [dbo].[ATFieldInstanceNumber]([FieldName] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceNumber].[ATFieldInstanceNumber_IX_WIId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceNumber_IX_WIId]
    ON [dbo].[ATFieldInstanceNumber]([WorkItemID] ASC);


GO
PRINT N'Creating Table [dbo].[ATFieldInstanceOption]...';


GO
CREATE TABLE [dbo].[ATFieldInstanceOption] (
    [FieldInstanceID] INT            IDENTITY (1, 1) NOT NULL,
    [FieldID]         INT            NOT NULL,
    [FieldValue]      NVARCHAR (MAX) NULL,
    [WorkItemID]      INT            NOT NULL,
    [FieldName]       NVARCHAR (64)  NOT NULL,
    CONSTRAINT [PK_ATFieldInstanceOption] PRIMARY KEY NONCLUSTERED ([FieldInstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceOption].[ATFieldInstanceOption_IX_FId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceOption_IX_FId]
    ON [dbo].[ATFieldInstanceOption]([FieldID] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceOption].[ATFieldInstanceOption_IX_FName]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceOption_IX_FName]
    ON [dbo].[ATFieldInstanceOption]([FieldName] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceOption].[ATFieldInstanceOption_IX_WIId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceOption_IX_WIId]
    ON [dbo].[ATFieldInstanceOption]([WorkItemID] ASC);


GO
PRINT N'Creating Table [dbo].[ATFieldInstanceString]...';


GO
CREATE TABLE [dbo].[ATFieldInstanceString] (
    [FieldInstanceID] INT            IDENTITY (1, 1) NOT NULL,
    [FieldID]         INT            NOT NULL,
    [FieldValue]      NVARCHAR (255) NULL,
    [WorkItemID]      INT            NOT NULL,
    [FieldName]       NVARCHAR (64)  NOT NULL,
    CONSTRAINT [PK_ATFieldInstanceString] PRIMARY KEY NONCLUSTERED ([FieldInstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceString].[ATFieldInstanceString_IX_FId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceString_IX_FId]
    ON [dbo].[ATFieldInstanceString]([FieldID] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceString].[ATFieldInstanceString_IX_FName]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceString_IX_FName]
    ON [dbo].[ATFieldInstanceString]([FieldName] ASC);


GO
PRINT N'Creating Index [dbo].[ATFieldInstanceString].[ATFieldInstanceString_IX_WIId]...';


GO
CREATE NONCLUSTERED INDEX [ATFieldInstanceString_IX_WIId]
    ON [dbo].[ATFieldInstanceString]([WorkItemID] ASC);


GO
PRINT N'Creating Table [dbo].[ATForm]...';


GO
CREATE TABLE [dbo].[ATForm] (
    [FormName]    NVARCHAR (255)   NOT NULL,
    [ProcessID]   INT              NOT NULL,
    [Type]        INT              NULL,
    [Path]        NVARCHAR (255)   NULL,
    [Description] NVARCHAR (255)   NULL,
    [ObjectId]    UNIQUEIDENTIFIER NULL,
    CONSTRAINT [PK_ATForm] PRIMARY KEY NONCLUSTERED ([FormName] ASC, [ProcessID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATForm].[ATForm_IX_ProcessId]...';


GO
CREATE NONCLUSTERED INDEX [ATForm_IX_ProcessId]
    ON [dbo].[ATForm]([ProcessID] ASC);


GO
PRINT N'Creating Table [dbo].[ATHistory]...';


GO
CREATE TABLE [dbo].[ATHistory] (
    [HistoryId]         INT            NOT NULL,
    [TransactionType]   INT            NOT NULL,
    [DateOfTransaction] DATETIME       NOT NULL,
    [UserName]          NVARCHAR (255) NOT NULL,
    [WorkItemName]      NVARCHAR (255) NOT NULL,
    [WorkItemId]        INT            NOT NULL,
    CONSTRAINT [PK_ATHistory] PRIMARY KEY NONCLUSTERED ([HistoryId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATHistoryEvent]...';


GO
CREATE TABLE [dbo].[ATHistoryEvent] (
    [HistoryEventId] INT            NOT NULL,
    [HistoryId]      INT            NOT NULL,
    [ProcessName]    NVARCHAR (255) NOT NULL,
    [EventName]      NVARCHAR (255) NOT NULL,
    [Queue]          NVARCHAR (32)  NULL,
    CONSTRAINT [PK_ATHistoryEvent] PRIMARY KEY NONCLUSTERED ([HistoryEventId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATHistoryParameter]...';


GO
CREATE TABLE [dbo].[ATHistoryParameter] (
    [HistoryParameterId]   INT            NOT NULL,
    [HistoryId]            INT            NOT NULL,
    [HistoryParameterType] INT            NOT NULL,
    [HistoryParameter]     NVARCHAR (255) NOT NULL,
    CONSTRAINT [PK_ATHistoryParameter] PRIMARY KEY NONCLUSTERED ([HistoryParameterId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATImportDocumentType]...';


GO
CREATE TABLE [dbo].[ATImportDocumentType] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [TypeName]    NVARCHAR (16)  NOT NULL,
    [Description] NVARCHAR (128) NULL,
    [IsActive]    BIT            NOT NULL,
    [Convertible] BIT            NOT NULL,
    CONSTRAINT [PK_ATImportDocumentType] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATImporterConfiguration]...';


GO
CREATE TABLE [dbo].[ATImporterConfiguration] (
    [Id]                       INT            IDENTITY (1, 1) NOT NULL,
    [Name]                     NVARCHAR (64)  NOT NULL,
    [DocumentPath]             NVARCHAR (512) NOT NULL,
    [ArchivePath]              NVARCHAR (512) NOT NULL,
    [ErrorPath]                NVARCHAR (512) NOT NULL,
    [LogPath]                  NVARCHAR (512) NOT NULL,
    [LoopPauseMinutes]         INT            NOT NULL,
    [LogRetentionDays]         INT            NOT NULL,
    [LogFileMaxSizeMB]         INT            NOT NULL,
    [CpuUsagePercentLimit]     INT            NOT NULL,
    [MaxPDFSizeMB]             INT            NOT NULL,
    [CleanArchiveIntervalDays] INT            NOT NULL,
    [IsActive]                 BIT            NOT NULL,
    CONSTRAINT [PK_ATImporterConfiguration] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UK_ATImporterConfiguration_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATInboxEvent]...';


GO
CREATE TABLE [dbo].[ATInboxEvent] (
    [Id]               INT           IDENTITY (1, 1) NOT NULL,
    [InboxAssignment]  NVARCHAR (32) NULL,
    [EventID]          INT           NOT NULL,
    [InboxId]          INT           NULL,
    [AssignmentTypeId] INT           NOT NULL,
    CONSTRAINT [PK_ATInboxEvent] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATInboxEvent].[IX_ATInboxEvent_EventID]...';


GO
CREATE NONCLUSTERED INDEX [IX_ATInboxEvent_EventID]
    ON [dbo].[ATInboxEvent]([EventID] ASC);


GO
PRINT N'Creating Index [dbo].[ATInboxEvent].[IX_ATInboxEvent_Inbox]...';


GO
CREATE NONCLUSTERED INDEX [IX_ATInboxEvent_Inbox]
    ON [dbo].[ATInboxEvent]([InboxId] ASC);


GO
PRINT N'Creating Table [dbo].[ATLabel]...';


GO
CREATE TABLE [dbo].[ATLabel] (
    [LabelID]   INT            NOT NULL,
    [ProcessID] INT            NOT NULL,
    [Label]     NVARCHAR (255) NULL,
    [Style]     NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATLabel] PRIMARY KEY NONCLUSTERED ([LabelID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATLabel].[ATLabel_IX_LabelID]...';


GO
CREATE NONCLUSTERED INDEX [ATLabel_IX_LabelID]
    ON [dbo].[ATLabel]([LabelID] ASC);


GO
PRINT N'Creating Index [dbo].[ATLabel].[ATLabel_IX_ProcessID]...';


GO
CREATE NONCLUSTERED INDEX [ATLabel_IX_ProcessID]
    ON [dbo].[ATLabel]([ProcessID] ASC);


GO
PRINT N'Creating Table [dbo].[ATLink]...';


GO
CREATE TABLE [dbo].[ATLink] (
    [ProcessID]   INT            NOT NULL,
    [FromEventID] INT            NOT NULL,
    [ToEventID]   INT            NOT NULL,
    [LinkStyle]   NVARCHAR (255) NULL,
    [Label]       NVARCHAR (255) NULL,
    [LabelStyle]  NVARCHAR (255) NULL,
    CONSTRAINT [PK_Link] PRIMARY KEY NONCLUSTERED ([ProcessID] ASC, [FromEventID] ASC, [ToEventID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATLink].[ATLink_IX_FromEventId]...';


GO
CREATE NONCLUSTERED INDEX [ATLink_IX_FromEventId]
    ON [dbo].[ATLink]([FromEventID] ASC);


GO
PRINT N'Creating Index [dbo].[ATLink].[ATLink_IX_ToEventId]...';


GO
CREATE NONCLUSTERED INDEX [ATLink_IX_ToEventId]
    ON [dbo].[ATLink]([ToEventID] ASC);


GO
PRINT N'Creating Table [dbo].[ATMail]...';


GO
CREATE TABLE [dbo].[ATMail] (
    [Id]           INT            IDENTITY (1, 1) NOT NULL,
    [Description]  NVARCHAR (256) NULL,
    [EventID]      INT            NOT NULL,
    [ProcessID]    INT            NOT NULL,
    [ConnectionId] INT            NULL,
    [Recipient]    NVARCHAR (512) NOT NULL,
    [CC]           NVARCHAR (256) NULL,
    [BCC]          NVARCHAR (256) NULL,
    [From]         NVARCHAR (256) NULL,
    [Reply]        NVARCHAR (256) NULL,
    [Subject]      NVARCHAR (256) NULL,
    [Message]      NVARCHAR (MAX) NULL,
    [Enable]       BIT            NOT NULL,
    [Priority]     TINYINT        NOT NULL,
    CONSTRAINT [PK_ATMail] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATMaintenance]...';


GO
CREATE TABLE [dbo].[ATMaintenance] (
    [RunDate]    DATETIME       NOT NULL,
    [Type]       INT            NOT NULL,
    [ObjectName] NVARCHAR (255) NOT NULL,
    [ItemCount]  INT            NOT NULL,
    [Result]     INT            NOT NULL,
    [Error]      NVARCHAR (255) NOT NULL
);


GO
PRINT N'Creating Table [dbo].[ATMergeOrder]...';


GO
CREATE TABLE [dbo].[ATMergeOrder] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (100) NOT NULL,
    [Description] NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATMergeOrder] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_ATMergeOrder_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATNote]...';


GO
CREATE TABLE [dbo].[ATNote] (
    [NoteId]     INT             IDENTITY (1, 1) NOT NULL,
    [WorkItemId] INT             NOT NULL,
    [DocumentId] INT             NULL,
    [Submitter]  NVARCHAR (50)   NOT NULL,
    [SubmitDate] DATETIME        NOT NULL,
    [Note]       NVARCHAR (1024) NOT NULL,
    CONSTRAINT [PK_ATNote] PRIMARY KEY NONCLUSTERED ([NoteId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATNote].[ATNote_WorkitemId]...';


GO
CREATE NONCLUSTERED INDEX [ATNote_WorkitemId]
    ON [dbo].[ATNote]([WorkItemId] ASC);


GO
PRINT N'Creating Table [dbo].[ATPendingWorkItemReference]...';


GO
CREATE TABLE [dbo].[ATPendingWorkItemReference] (
    [Id]                         INT      IDENTITY (1, 1) NOT NULL,
    [PendingWorkItemReferenceId] INT      NOT NULL,
    [ExpirationTime]             DATETIME NOT NULL,
    [CreatedTime]                DATETIME NOT NULL,
    CONSTRAINT [PK_ATPendingWorkItemReference] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_ATPendingWorkItemReference_WorkItemReferenceId] UNIQUE NONCLUSTERED ([PendingWorkItemReferenceId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATProcessDefinition]...';


GO
CREATE TABLE [dbo].[ATProcessDefinition] (
    [ProcessID]          INT              IDENTITY (1, 1) NOT NULL,
    [ProcessName]        NVARCHAR (255)   NOT NULL,
    [ProcessVersion]     INT              NOT NULL,
    [Description]        NVARCHAR (255)   NULL,
    [Versioning]         INT              NULL,
    [Status]             INT              NOT NULL,
    [Creator]            NVARCHAR (255)   NULL,
    [ProcessType]        INT              NOT NULL,
    [ExpirationInterval] INT              NULL,
    [LockedBy]           NVARCHAR (255)   NULL,
    [StopQueue]          NVARCHAR (32)    NULL,
    [ProcessGroupID]     INT              NULL,
    [StartEventID]       INT              NULL,
    [Script]             IMAGE            NULL,
    [Synchronous]        INT              NULL,
    [ScriptLanguage]     INT              NULL,
    [ExScript]           IMAGE            NULL,
    [WindowStyle]        NVARCHAR (1024)  NULL,
    [ObjectId]           UNIQUEIDENTIFIER NOT NULL,
    [Created]            DATETIME         NULL,
    [Map]                IMAGE            NULL,
    [DefaultDocTemplate] INT              NOT NULL,
    CONSTRAINT [PK_ProcessDefinition] PRIMARY KEY NONCLUSTERED ([ProcessID] ASC),
    CONSTRAINT [UK_ATProcessDefinition_ObjectId] UNIQUE NONCLUSTERED ([ObjectId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATProcessDefinition].[ATProcessDefinition_IX_ObjectId]...';


GO
CREATE NONCLUSTERED INDEX [ATProcessDefinition_IX_ObjectId]
    ON [dbo].[ATProcessDefinition]([ObjectId] ASC);


GO
PRINT N'Creating Index [dbo].[ATProcessDefinition].[ATProcessDefinition_IX_Creator]...';


GO
CREATE NONCLUSTERED INDEX [ATProcessDefinition_IX_Creator]
    ON [dbo].[ATProcessDefinition]([Creator] ASC);


GO
PRINT N'Creating Index [dbo].[ATProcessDefinition].[ATProcessDefinition_IX_GroupId]...';


GO
CREATE NONCLUSTERED INDEX [ATProcessDefinition_IX_GroupId]
    ON [dbo].[ATProcessDefinition]([ProcessGroupID] ASC);


GO
PRINT N'Creating Index [dbo].[ATProcessDefinition].[ATProcessDefinition_IX_Status]...';


GO
CREATE NONCLUSTERED INDEX [ATProcessDefinition_IX_Status]
    ON [dbo].[ATProcessDefinition]([Status] ASC);


GO
PRINT N'Creating Index [dbo].[ATProcessDefinition].[ATProcessDefinition_IX_Type]...';


GO
CREATE NONCLUSTERED INDEX [ATProcessDefinition_IX_Type]
    ON [dbo].[ATProcessDefinition]([ProcessType] ASC);


GO
PRINT N'Creating Index [dbo].[ATProcessDefinition].[IX_ATProcessDefinition]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_ATProcessDefinition]
    ON [dbo].[ATProcessDefinition]([ProcessName] ASC, [ProcessVersion] ASC);


GO
PRINT N'Creating Table [dbo].[ATProcessDocumentTemplateRight]...';


GO
CREATE TABLE [dbo].[ATProcessDocumentTemplateRight] (
    [ProcessObjectId]          UNIQUEIDENTIFIER NOT NULL,
    [AllowRights]              INT              NOT NULL,
    [DocumentTemplateObjectid] UNIQUEIDENTIFIER NOT NULL,
    CONSTRAINT [PK_ATProcessDocumentTemplateRight] PRIMARY KEY CLUSTERED ([ProcessObjectId] ASC, [AllowRights] ASC, [DocumentTemplateObjectid] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATProcessDocumentTemplateRight].[IX_ATProcessDocumentTemplateRights_ProcessObjectId]...';


GO
CREATE NONCLUSTERED INDEX [IX_ATProcessDocumentTemplateRights_ProcessObjectId]
    ON [dbo].[ATProcessDocumentTemplateRight]([ProcessObjectId] ASC);


GO
PRINT N'Creating Table [dbo].[ATProcessGroup]...';


GO
CREATE TABLE [dbo].[ATProcessGroup] (
    [ProcessGroupID] INT            IDENTITY (1, 1) NOT NULL,
    [ProcessGroup]   NVARCHAR (32)  NOT NULL,
    [Description]    NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATProcessGroup] PRIMARY KEY NONCLUSTERED ([ProcessGroupID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATProcessGroup].[ATProcessGroup_IX_ProcessGroup]...';


GO
CREATE NONCLUSTERED INDEX [ATProcessGroup_IX_ProcessGroup]
    ON [dbo].[ATProcessGroup]([ProcessGroup] ASC);


GO
PRINT N'Creating Table [dbo].[ATProcessImportRule]...';


GO
CREATE TABLE [dbo].[ATProcessImportRule] (
    [Id]                INT            IDENTITY (1, 1) NOT NULL,
    [ProcessId]         INT            NOT NULL,
    [DoNotConvert]      NVARCHAR (128) NOT NULL,
    [MergeDocuments]    BIT            NOT NULL,
    [ConvertToFormatId] INT            NULL,
    [RenameWhenMerged]  BIT            NOT NULL,
    CONSTRAINT [PK_ATProcessImportRule] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATQueue]...';


GO
CREATE TABLE [dbo].[ATQueue] (
    [Id]          INT              IDENTITY (1, 1) NOT NULL,
    [Queue]       NVARCHAR (32)    NOT NULL,
    [EventId]     INT              NOT NULL,
    [ProcessId]   INT              NOT NULL,
    [Description] NVARCHAR (255)   NULL,
    [SortType]    INT              NOT NULL,
    [Type]        INT              NOT NULL,
    [Alias]       NVARCHAR (255)   NULL,
    [ObjectId]    UNIQUEIDENTIFIER NOT NULL,
    [Signable]    BIT              NOT NULL,
    CONSTRAINT [PK_Queue] PRIMARY KEY NONCLUSTERED ([Id] ASC),
    CONSTRAINT [UK_Queue_ProcessId] UNIQUE NONCLUSTERED ([Queue] ASC, [ProcessId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATQueue].[ATQueue_IX_Queue]...';


GO
CREATE NONCLUSTERED INDEX [ATQueue_IX_Queue]
    ON [dbo].[ATQueue]([Queue] ASC);


GO
PRINT N'Creating Index [dbo].[ATQueue].[ATQueue_IX_EventId]...';


GO
CREATE NONCLUSTERED INDEX [ATQueue_IX_EventId]
    ON [dbo].[ATQueue]([EventId] ASC);


GO
PRINT N'Creating Index [dbo].[ATQueue].[ATQueue_IX_ProcessId]...';


GO
CREATE NONCLUSTERED INDEX [ATQueue_IX_ProcessId]
    ON [dbo].[ATQueue]([ProcessId] ASC);


GO
PRINT N'Creating Index [dbo].[ATQueue].[ATQueue_ObjectID]...';


GO
CREATE NONCLUSTERED INDEX [ATQueue_ObjectID]
    ON [dbo].[ATQueue]([ObjectId] ASC);


GO
PRINT N'Creating Table [dbo].[ATReport]...';


GO
CREATE TABLE [dbo].[ATReport] (
    [ReportId]    INT             IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (50)   NOT NULL,
    [Description] NVARCHAR (255)  NULL,
    [SqlCode]     NVARCHAR (1024) NULL,
    [IsActive]    BIT             NOT NULL,
    CONSTRAINT [PK_ATReport] PRIMARY KEY CLUSTERED ([ReportId] ASC),
    CONSTRAINT [UQ_ATReport_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATRight]...';


GO
CREATE TABLE [dbo].[ATRight] (
    [UserGuid]    UNIQUEIDENTIFIER NOT NULL,
    [ObjectType]  INT              NOT NULL,
    [AllowRights] INT              NOT NULL,
    [ObjectGuid]  UNIQUEIDENTIFIER NOT NULL,
    CONSTRAINT [PK_ATRight] PRIMARY KEY CLUSTERED ([UserGuid] ASC, [ObjectType] ASC, [AllowRights] ASC, [ObjectGuid] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATRight].[ATRight_Composite1]...';


GO
CREATE NONCLUSTERED INDEX [ATRight_Composite1]
    ON [dbo].[ATRight]([ObjectType] ASC, [ObjectGuid] ASC, [UserGuid] ASC);


GO
PRINT N'Creating Index [dbo].[ATRight].[ATRight_Composite2]...';


GO
CREATE NONCLUSTERED INDEX [ATRight_Composite2]
    ON [dbo].[ATRight]([AllowRights] ASC, [UserGuid] ASC, [ObjectGuid] ASC);


GO
PRINT N'Creating Index [dbo].[ATRight].[ATRight_UserGuid]...';


GO
CREATE NONCLUSTERED INDEX [ATRight_UserGuid]
    ON [dbo].[ATRight]([UserGuid] ASC);


GO
PRINT N'Creating Table [dbo].[ATRightAllowRight]...';


GO
CREATE TABLE [dbo].[ATRightAllowRight] (
    [Id]   INT            NOT NULL,
    [Name] NVARCHAR (255) NOT NULL,
    CONSTRAINT [PK_ATRightAllowRight] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATRightObjectType]...';


GO
CREATE TABLE [dbo].[ATRightObjectType] (
    [Id]   INT           IDENTITY (0, 1) NOT NULL,
    [Name] NVARCHAR (64) NOT NULL,
    CONSTRAINT [PK_ATRightObjectType] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATRule]...';


GO
CREATE TABLE [dbo].[ATRule] (
    [EventID]   INT            NOT NULL,
    [ProcessID] INT            NOT NULL,
    [EventName] NVARCHAR (255) NOT NULL,
    [Type1]     NVARCHAR (64)  NULL,
    [Value1]    NVARCHAR (64)  NULL,
    [Compare]   NVARCHAR (64)  NULL,
    [Type2]     NVARCHAR (64)  NULL,
    [Value2]    NVARCHAR (64)  NULL
);


GO
PRINT N'Creating Table [dbo].[ATRunStatusType]...';


GO
CREATE TABLE [dbo].[ATRunStatusType] (
    [StatusId]   INT           IDENTITY (1, 1) NOT NULL,
    [StatusName] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_ATRunStatusType] PRIMARY KEY CLUSTERED ([StatusId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATSavedSearch]...';


GO
CREATE TABLE [dbo].[ATSavedSearch] (
    [Query_ID]      INT            NOT NULL,
    [ATName]        NVARCHAR (128) NULL,
    [UserName]      NVARCHAR (255) NULL,
    [QueryType]     SMALLINT       NULL,
    [QueryLevel]    SMALLINT       NULL,
    [GridString]    IMAGE          NULL,
    [ProcessID]     INT            NULL,
    [WorkItemType]  INT            NULL,
    [ShortcutKey]   INT            NULL,
    [ReferenceType] SMALLINT       NULL,
    CONSTRAINT [PK_ATSavedSearch] PRIMARY KEY NONCLUSTERED ([Query_ID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATSavedSearch].[ATSavedSearch_IX_ProcessID]...';


GO
CREATE NONCLUSTERED INDEX [ATSavedSearch_IX_ProcessID]
    ON [dbo].[ATSavedSearch]([ProcessID] ASC);


GO
PRINT N'Creating Table [dbo].[ATScheduledItem]...';


GO
CREATE TABLE [dbo].[ATScheduledItem] (
    [ScheduleId]           INT            IDENTITY (1, 1) NOT NULL,
    [ServerHost]           NVARCHAR (255) NOT NULL,
    [Name]                 NVARCHAR (255) NOT NULL,
    [Description]          NVARCHAR (255) NULL,
    [Enabled]              BIT            NOT NULL,
    [WaitForCompletion]    BIT            NOT NULL,
    [Priority]             INT            NULL,
    [ScheduleTypeId]       INT            NOT NULL,
    [RecurrenceExpression] NVARCHAR (MAX) NULL,
    [StartTime]            DATETIME2 (7)  NULL,
    [ExpireTime]           DATETIME2 (7)  NULL,
    [StatusId]             INT            NOT NULL,
    [LastRunStatusId]      INT            NULL,
    [LastRun]              DATETIME2 (7)  NULL,
    [CreatedAt]            DATETIME2 (7)  NOT NULL,
    [UpdatedAt]            DATETIME2 (7)  NOT NULL,
    CONSTRAINT [PK_ATScheduledItem] PRIMARY KEY CLUSTERED ([ScheduleId] ASC),
    CONSTRAINT [UQ_ATScheduledItem_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATScheduledItem-old]...';


GO
CREATE TABLE [dbo].[ATScheduledItem-old] (
    [ServerHost]    NVARCHAR (255) NULL,
    [Name]          NVARCHAR (255) NOT NULL,
    [Description]   NVARCHAR (255) NOT NULL,
    [Enabled]       INT            NOT NULL,
    [Wait]          INT            NOT NULL,
    [Schedule]      TEXT           NOT NULL,
    [Tasks]         TEXT           NOT NULL,
    [Status]        INT            NOT NULL,
    [LastRun]       DATETIME       NULL,
    [NextRun]       DATETIME       NULL,
    [Priority]      INT            NULL,
    [LastRunStatus] INT            NULL
);


GO
PRINT N'Creating Table [dbo].[ATScheduledTask]...';


GO
CREATE TABLE [dbo].[ATScheduledTask] (
    [TaskId]            INT             IDENTITY (1, 1) NOT NULL,
    [ScheduleId]        INT             NOT NULL,
    [TaskName]          NVARCHAR (255)  NOT NULL,
    [TaskTypeId]        INT             NOT NULL,
    [CommandText]       NVARCHAR (MAX)  NULL,
    [ExecutablePath]    NVARCHAR (1024) NULL,
    [OnSuccessActionId] INT             NULL,
    [OnFailureActionId] INT             NULL,
    [Enabled]           BIT             NOT NULL,
    [SortOrder]         INT             NOT NULL,
    CONSTRAINT [PK_ATScheduledTask] PRIMARY KEY CLUSTERED ([TaskId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATScheduleInstance-old]...';


GO
CREATE TABLE [dbo].[ATScheduleInstance-old] (
    [ServerInstance]    NVARCHAR (50) NULL,
    [RunScheduledTasks] INT           NULL
);


GO
PRINT N'Creating Table [dbo].[ATScheduleStatusType]...';


GO
CREATE TABLE [dbo].[ATScheduleStatusType] (
    [StatusId]   INT           NOT NULL,
    [StatusName] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_ATScheduleStatusType] PRIMARY KEY CLUSTERED ([StatusId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATScheduleType]...';


GO
CREATE TABLE [dbo].[ATScheduleType] (
    [ScheduleTypeId]   INT           IDENTITY (1, 1) NOT NULL,
    [ScheduleTypeName] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_ATScheduleType] PRIMARY KEY CLUSTERED ([ScheduleTypeId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATScript]...';


GO
CREATE TABLE [dbo].[ATScript] (
    [ScriptModuleName] NVARCHAR (255) NOT NULL,
    [ProcessID]        INT            NULL,
    [EventID]          INT            NULL,
    [ModuleType]       INT            NULL,
    [CODE]             IMAGE          NULL,
    [FRX]              IMAGE          NULL
);


GO
PRINT N'Creating Index [dbo].[ATScript].[ATScript_IX_EventId]...';


GO
CREATE NONCLUSTERED INDEX [ATScript_IX_EventId]
    ON [dbo].[ATScript]([EventID] ASC);


GO
PRINT N'Creating Index [dbo].[ATScript].[ATScript_IX_ProcessId]...';


GO
CREATE NONCLUSTERED INDEX [ATScript_IX_ProcessId]
    ON [dbo].[ATScript]([ProcessID] ASC);


GO
PRINT N'Creating Table [dbo].[ATSearch]...';


GO
CREATE TABLE [dbo].[ATSearch] (
    [SearchId]               INT              NOT NULL,
    [Name]                   NVARCHAR (255)   NOT NULL,
    [Description]            NVARCHAR (255)   NULL,
    [Type]                   INT              NULL,
    [Owner]                  NVARCHAR (255)   NULL,
    [LastRun]                DATETIME         NULL,
    [SQLString]              NVARCHAR (1024)  NULL,
    [PublicSearch]           TINYINT          NULL,
    [SortField]              NVARCHAR (50)    NULL,
    [SortDirection]          INT              NULL,
    [ObjectId]               UNIQUEIDENTIFIER NULL,
    [SearchRegistrationGuid] UNIQUEIDENTIFIER NULL,
    CONSTRAINT [PK_ATSearch] PRIMARY KEY NONCLUSTERED ([SearchId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATSearchCriterion]...';


GO
CREATE TABLE [dbo].[ATSearchCriterion] (
    [SearchId]   INT           NOT NULL,
    [FieldName]  NVARCHAR (50) NOT NULL,
    [FieldValue] NVARCHAR (50) NOT NULL,
    [FieldType]  INT           NOT NULL,
    [DataType]   INT           NOT NULL,
    [Compare]    INT           NOT NULL,
    [NestLevel]  INT           NOT NULL,
    [JoinType]   INT           NOT NULL,
    [ItemIndex]  INT           NOT NULL
);


GO
PRINT N'Creating Index [dbo].[ATSearchCriterion].[ATSearchCriterion_SearchId]...';


GO
CREATE NONCLUSTERED INDEX [ATSearchCriterion_SearchId]
    ON [dbo].[ATSearchCriterion]([SearchId] ASC);


GO
PRINT N'Creating Table [dbo].[ATSearchDisplayField]...';


GO
CREATE TABLE [dbo].[ATSearchDisplayField] (
    [ObjectGuid]             UNIQUEIDENTIFIER NOT NULL,
    [SearchRegistrationGuid] UNIQUEIDENTIFIER NOT NULL,
    [FieldName]              NVARCHAR (50)    NOT NULL,
    [FieldType]              NVARCHAR (50)    NOT NULL,
    [Attribute]              INT              NOT NULL,
    [IsLinkField]            INT              NULL
);


GO
PRINT N'Creating Table [dbo].[ATSearchParam]...';


GO
CREATE TABLE [dbo].[ATSearchParam] (
    [SearchId]   INT            NOT NULL,
    [ParamName]  NVARCHAR (50)  NOT NULL,
    [ParamValue] NVARCHAR (255) NOT NULL
);


GO
PRINT N'Creating Table [dbo].[ATSearchRegistration]...';


GO
CREATE TABLE [dbo].[ATSearchRegistration] (
    [ObjectGuid]     UNIQUEIDENTIFIER NOT NULL,
    [SearchLocation] NVARCHAR (50)    NOT NULL,
    [SearchType]     NVARCHAR (50)    NOT NULL,
    [ConnectionName] NVARCHAR (50)    NOT NULL,
    [DatabaseName]   NVARCHAR (50)    NOT NULL,
    [TableName]      NVARCHAR (50)    NOT NULL,
    [BaseLinkUrl]    NVARCHAR (255)   NULL,
    CONSTRAINT [PK_ATSearchRegistration] PRIMARY KEY NONCLUSTERED ([ObjectGuid] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATSearchTypeDefinition]...';


GO
CREATE TABLE [dbo].[ATSearchTypeDefinition] (
    [TypeName] NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating Table [dbo].[ATServer]...';


GO
CREATE TABLE [dbo].[ATServer] (
    [HostName]   NVARCHAR (255) NOT NULL,
    [LogLevel]   INT            NULL,
    [LogFile]    NVARCHAR (255) NULL,
    [Limit]      INT            NULL,
    [Interval]   INT            NULL,
    [Status]     NVARCHAR (20)  NULL,
    [RunExpired] BIT            NULL,
    CONSTRAINT [PK_ATServer] PRIMARY KEY NONCLUSTERED ([HostName] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATSetData]...';


GO
CREATE TABLE [dbo].[ATSetData] (
    [EventID]   INT            NOT NULL,
    [ProcessID] INT            NOT NULL,
    [EventName] NVARCHAR (255) NOT NULL,
    [ToType]    NVARCHAR (64)  NULL,
    [Variable]  NVARCHAR (64)  NULL,
    [FromType]  NVARCHAR (64)  NULL,
    [Value]     NVARCHAR (64)  NULL
);


GO
PRINT N'Creating Table [dbo].[ATSplit]...';


GO
CREATE TABLE [dbo].[ATSplit] (
    [SplitWorkItemRef]  INT NOT NULL,
    [SourceWorkItemRef] INT NOT NULL,
    [JoinEventId]       INT NULL,
    [Flag]              INT NULL,
    CONSTRAINT [PK_ATSplit] PRIMARY KEY NONCLUSTERED ([SplitWorkItemRef] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATSplit].[IX_ATSplit]...';


GO
CREATE NONCLUSTERED INDEX [IX_ATSplit]
    ON [dbo].[ATSplit]([SourceWorkItemRef] ASC);


GO
PRINT N'Creating Table [dbo].[ATStack]...';


GO
CREATE TABLE [dbo].[ATStack] (
    [WorkItemRef]  INT NOT NULL,
    [EventId]      INT NOT NULL,
    [SubProcessId] INT NOT NULL,
    CONSTRAINT [PK_ATStack] PRIMARY KEY NONCLUSTERED ([WorkItemRef] ASC, [EventId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATStack].[IX_ATStack]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_ATStack]
    ON [dbo].[ATStack]([WorkItemRef] ASC, [SubProcessId] ASC);


GO
PRINT N'Creating Table [dbo].[ATSystem]...';


GO
CREATE TABLE [dbo].[ATSystem] (
    [Guid]              UNIQUEIDENTIFIER NOT NULL,
    [ApplicationName]   NVARCHAR (255)   NOT NULL,
    [TrackingTableName] NVARCHAR (255)   NOT NULL,
    [Link]              NVARCHAR (255)   NULL,
    [LinkType]          NVARCHAR (255)   NULL
);


GO
PRINT N'Creating Index [dbo].[ATSystem].[GUID]...';


GO
CREATE NONCLUSTERED INDEX [GUID]
    ON [dbo].[ATSystem]([Guid] ASC);


GO
PRINT N'Creating Table [dbo].[ATSystemParameter]...';


GO
CREATE TABLE [dbo].[ATSystemParameter] (
    [ParamID]    INT            NOT NULL,
    [ParamName]  NVARCHAR (255) NOT NULL,
    [ParamValue] NVARCHAR (255) NOT NULL,
    CONSTRAINT [PK_ATSystemParameter] PRIMARY KEY NONCLUSTERED ([ParamID] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTaskActionType]...';


GO
CREATE TABLE [dbo].[ATTaskActionType] (
    [ActionId]    INT            IDENTITY (1, 1) NOT NULL,
    [ActionName]  NVARCHAR (50)  NOT NULL,
    [Description] NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATTaskActionType] PRIMARY KEY CLUSTERED ([ActionId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTaskDefinition]...';


GO
CREATE TABLE [dbo].[ATTaskDefinition] (
    [TaskID]    INT            NOT NULL,
    [EventID]   INT            NOT NULL,
    [TaskName]  NVARCHAR (255) NOT NULL,
    [Required]  INT            NOT NULL,
    [TaskIndex] INT            NOT NULL,
    CONSTRAINT [PK_TaskDefinition] PRIMARY KEY NONCLUSTERED ([TaskID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATTaskDefinition].[IX_ATTaskDefinition]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_ATTaskDefinition]
    ON [dbo].[ATTaskDefinition]([EventID] ASC, [TaskName] ASC);


GO
PRINT N'Creating Index [dbo].[ATTaskDefinition].[IX_ATTaskDefinition_1]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_ATTaskDefinition_1]
    ON [dbo].[ATTaskDefinition]([EventID] ASC, [TaskIndex] ASC);


GO
PRINT N'Creating Table [dbo].[ATTaskInstance]...';


GO
CREATE TABLE [dbo].[ATTaskInstance] (
    [TaskID]              INT            NOT NULL,
    [WorkItemReferenceID] INT            NOT NULL,
    [Status]              INT            NOT NULL,
    [CompletedBy]         NVARCHAR (255) NULL,
    [DateCompleted]       DATETIME       NULL,
    CONSTRAINT [PK_TaskInstance] PRIMARY KEY NONCLUSTERED ([TaskID] ASC, [WorkItemReferenceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATTaskInstance].[ATTaskinstance_IX_WIRId]...';


GO
CREATE NONCLUSTERED INDEX [ATTaskinstance_IX_WIRId]
    ON [dbo].[ATTaskInstance]([WorkItemReferenceID] ASC);


GO
PRINT N'Creating Table [dbo].[ATTaskType]...';


GO
CREATE TABLE [dbo].[ATTaskType] (
    [TaskTypeId]   INT            IDENTITY (1, 1) NOT NULL,
    [TaskTypeName] NVARCHAR (50)  NOT NULL,
    [Description]  NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATTaskType] PRIMARY KEY CLUSTERED ([TaskTypeId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTemplates]...';


GO
CREATE TABLE [dbo].[ATTemplates] (
    [Id]                INT              IDENTITY (1, 1) NOT NULL,
    [Name]              NVARCHAR (255)   NOT NULL,
    [Description]       NVARCHAR (255)   NULL,
    [ProcessId]         INT              NULL,
    [DocumentCabinetId] INT              NULL,
    [TemplateTypeId]    INT              NOT NULL,
    [DbConnectionId]    INT              NULL,
    [DbName]            NVARCHAR (50)    NULL,
    [ObjectId]          UNIQUEIDENTIFIER NOT NULL,
    [CreateDate]        DATETIME         NOT NULL,
    [ModifyDate]        DATETIME         NOT NULL,
    [HierarchyId]       INT              NULL,
    CONSTRAINT [PK_ATTemplates] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UK_ATTemplates_ObjectId] UNIQUE NONCLUSTERED ([ObjectId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATTemplates].[IX_ATTemplates_ProcessId]...';


GO
CREATE NONCLUSTERED INDEX [IX_ATTemplates_ProcessId]
    ON [dbo].[ATTemplates]([ProcessId] ASC);


GO
PRINT N'Creating Index [dbo].[ATTemplates].[IX_ATTemplates_DocumentCabinetId]...';


GO
CREATE NONCLUSTERED INDEX [IX_ATTemplates_DocumentCabinetId]
    ON [dbo].[ATTemplates]([DocumentCabinetId] ASC);


GO
PRINT N'Creating Table [dbo].[ATTemplateType]...';


GO
CREATE TABLE [dbo].[ATTemplateType] (
    [Id]   INT            IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (255) NOT NULL,
    CONSTRAINT [PK_ATTemplateType] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTimer]...';


GO
CREATE TABLE [dbo].[ATTimer] (
    [Id]        INT           IDENTITY (1, 1) NOT NULL,
    [EventID]   INT           NOT NULL,
    [ProcessID] INT           NOT NULL,
    [TimeValue] INT           NOT NULL,
    [ValueType] NVARCHAR (20) NOT NULL,
    CONSTRAINT [PK_ATTimer] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTrackingDefinition]...';


GO
CREATE TABLE [dbo].[ATTrackingDefinition] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [ProcessId]      INT            NOT NULL,
    [EventId]        INT            NOT NULL,
    [EventName]      NVARCHAR (255) NOT NULL,
    [Enable]         NVARCHAR (1)   NOT NULL,
    [EnableExternal] BIT            NOT NULL,
    [Description]    NVARCHAR (255) NULL,
    [Action]         NVARCHAR (255) NULL,
    [User]           NVARCHAR (255) NULL,
    [Message]        NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_ATTrackingDefinition] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTrackingDefinitionTemplates]...';


GO
CREATE TABLE [dbo].[ATTrackingDefinitionTemplates] (
    [TrackingDefinitionId] INT            NOT NULL,
    [TemplateId]           INT            NOT NULL,
    [Order]                INT            NOT NULL,
    [Description]          NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATTrackingDefinitionTemplates] PRIMARY KEY CLUSTERED ([TrackingDefinitionId] ASC, [TemplateId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTrackingRecord]...';


GO
CREATE TABLE [dbo].[ATTrackingRecord] (
    [Id]                   INT            IDENTITY (1, 1) NOT NULL,
    [TrackingDate]         DATETIME       NOT NULL,
    [WorkItemId]           INT            NOT NULL,
    [UserName]             NVARCHAR (255) NULL,
    [TrackingDefinitionId] INT            NULL,
    [LastActionId]         INT            NULL,
    [Message]              NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_ATTrackingRecord] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATTrackingRecord].[ATTrackingRecord_Composite1]...';


GO
CREATE NONCLUSTERED INDEX [ATTrackingRecord_Composite1]
    ON [dbo].[ATTrackingRecord]([UserName] ASC, [TrackingDate] ASC);


GO
PRINT N'Creating Index [dbo].[ATTrackingRecord].[ATTrackingRecord_Composite2]...';


GO
CREATE NONCLUSTERED INDEX [ATTrackingRecord_Composite2]
    ON [dbo].[ATTrackingRecord]([LastActionId] ASC, [TrackingDate] ASC);


GO
PRINT N'Creating Index [dbo].[ATTrackingRecord].[SYSIDGUIDOrderd]...';


GO
CREATE NONCLUSTERED INDEX [SYSIDGUIDOrderd]
    ON [dbo].[ATTrackingRecord]([Id] ASC, [WorkItemId] ASC);


GO
PRINT N'Creating Index [dbo].[ATTrackingRecord].[WorkitemIDandDate]...';


GO
CREATE NONCLUSTERED INDEX [WorkitemIDandDate]
    ON [dbo].[ATTrackingRecord]([TrackingDate] ASC, [WorkItemId] ASC);


GO
PRINT N'Creating Table [dbo].[ATTrackingRecordArc]...';


GO
CREATE TABLE [dbo].[ATTrackingRecordArc] (
    [TrackingRecordId] INT              NOT NULL,
    [TrackingDate]     DATETIME         NOT NULL,
    [WorkItemId]       INT              NOT NULL,
    [ProcessId]        INT              NOT NULL,
    [EventId]          INT              NOT NULL,
    [Queue]            NVARCHAR (32)    NULL,
    [UserName]         NVARCHAR (255)   NOT NULL,
    [LastAction]       NVARCHAR (32)    NOT NULL,
    [Message]          NVARCHAR (MAX)   NULL,
    [SystemGuid]       UNIQUEIDENTIFIER NULL,
    CONSTRAINT [PK_ATTrackingRecordArc] PRIMARY KEY NONCLUSTERED ([TrackingRecordId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTriggerAction]...';


GO
CREATE TABLE [dbo].[ATTriggerAction] (
    [Id]   INT            IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (255) NOT NULL,
    CONSTRAINT [PK_ATTriggerAction] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATTriggerHook]...';


GO
CREATE TABLE [dbo].[ATTriggerHook] (
    [Id]   INT            IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (255) NOT NULL,
    CONSTRAINT [PK_ATTriggerHook] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATUser]...';


GO
CREATE TABLE [dbo].[ATUser] (
    [UserName]    NVARCHAR (255)   NOT NULL,
    [DisplayName] NVARCHAR (255)   NULL,
    [UserStore]   INT              NULL,
    [Type]        INT              NULL,
    [Description] NVARCHAR (255)   NULL,
    [Status]      INT              NULL,
    [ObjectId]    UNIQUEIDENTIFIER NULL,
    [ADDomain]    NVARCHAR (255)   NULL,
    CONSTRAINT [PK_User] PRIMARY KEY NONCLUSTERED ([UserName] ASC),
    CONSTRAINT [UK_User] UNIQUE NONCLUSTERED ([ObjectId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATUserGroup]...';


GO
CREATE TABLE [dbo].[ATUserGroup] (
    [ObjectId] UNIQUEIDENTIFIER NOT NULL,
    [ParentId] UNIQUEIDENTIFIER NOT NULL,
    CONSTRAINT [PK_ATUserGroup] PRIMARY KEY CLUSTERED ([ObjectId] ASC, [ParentId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATUserProperty]...';


GO
CREATE TABLE [dbo].[ATUserProperty] (
    [UserName]      NVARCHAR (255) NOT NULL,
    [PropertyName]  NVARCHAR (255) NOT NULL,
    [PropertyValue] NVARCHAR (255) NOT NULL,
    CONSTRAINT [PK_ATUserProperty] PRIMARY KEY CLUSTERED ([UserName] ASC, [PropertyName] ASC, [PropertyValue] ASC),
    CONSTRAINT [UQ_ATUserProperty_UserName_PropertyName] UNIQUE NONCLUSTERED ([UserName] ASC, [PropertyName] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATUserProperty].[ATUserProperty_IX_UserName]...';


GO
CREATE NONCLUSTERED INDEX [ATUserProperty_IX_UserName]
    ON [dbo].[ATUserProperty]([UserName] ASC);


GO
PRINT N'Creating Table [dbo].[ATUserPropertyDefinition]...';


GO
CREATE TABLE [dbo].[ATUserPropertyDefinition] (
    [PropertyID]   INT            IDENTITY (1, 1) NOT NULL,
    [PropertyName] NVARCHAR (255) NOT NULL,
    [DefaultValue] NVARCHAR (255) NOT NULL,
    CONSTRAINT [UQ__ATUserPr__FDF7CF1B1BB57D33] UNIQUE NONCLUSTERED ([PropertyName] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATUserReport]...';


GO
CREATE TABLE [dbo].[ATUserReport] (
    [UserObjectID]   UNIQUEIDENTIFIER NOT NULL,
    [ReportObjectID] UNIQUEIDENTIFIER NOT NULL
);


GO
PRINT N'Creating Table [dbo].[ATUserSystemVariable]...';


GO
CREATE TABLE [dbo].[ATUserSystemVariable] (
    [Id]   INT           IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (32) NOT NULL,
    CONSTRAINT [PK_AtUserSystemVariable] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATVariableDefinition]...';


GO
CREATE TABLE [dbo].[ATVariableDefinition] (
    [VariableID] INT           NOT NULL,
    [Name]       NVARCHAR (50) NOT NULL,
    [Scope]      INT           NOT NULL,
    [DataType]   INT           NOT NULL,
    [ProcessID]  INT           NULL,
    [Value]      TEXT          NULL,
    CONSTRAINT [PK_ATVariableDefinition] PRIMARY KEY CLUSTERED ([VariableID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATVariableDefinition].[ScopeandPID]...';


GO
CREATE NONCLUSTERED INDEX [ScopeandPID]
    ON [dbo].[ATVariableDefinition]([Scope] ASC, [ProcessID] ASC);


GO
PRINT N'Creating Table [dbo].[ATVariableInstanceBinaryBlob]...';


GO
CREATE TABLE [dbo].[ATVariableInstanceBinaryBlob] (
    [InstanceID]  INT           NOT NULL,
    [VariableID]  INT           NOT NULL,
    [Value]       IMAGE         NOT NULL,
    [ReferenceID] INT           NULL,
    [Name]        NVARCHAR (50) NOT NULL,
    [DataType]    INT           NOT NULL,
    CONSTRAINT [PK_ATVariableInstanceBinaryBlob] PRIMARY KEY CLUSTERED ([InstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATVariableInstanceBinaryBlob].[RefID]...';


GO
CREATE NONCLUSTERED INDEX [RefID]
    ON [dbo].[ATVariableInstanceBinaryBlob]([ReferenceID] ASC);


GO
PRINT N'Creating Table [dbo].[ATVariableInstanceDate]...';


GO
CREATE TABLE [dbo].[ATVariableInstanceDate] (
    [InstanceID]  INT           NOT NULL,
    [VariableID]  INT           NOT NULL,
    [Value]       DATETIME      NOT NULL,
    [ReferenceID] INT           NULL,
    [Name]        NVARCHAR (50) NOT NULL,
    [DataType]    INT           NOT NULL,
    CONSTRAINT [PK_ATVariableInstanceDate] PRIMARY KEY CLUSTERED ([InstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATVariableInstanceDate].[RefID]...';


GO
CREATE NONCLUSTERED INDEX [RefID]
    ON [dbo].[ATVariableInstanceDate]([ReferenceID] ASC);


GO
PRINT N'Creating Table [dbo].[ATVariableInstanceNumber]...';


GO
CREATE TABLE [dbo].[ATVariableInstanceNumber] (
    [InstanceID]  INT              NOT NULL,
    [VariableID]  INT              NOT NULL,
    [Value]       NUMERIC (28, 14) NOT NULL,
    [ReferenceID] INT              NULL,
    [Name]        NVARCHAR (50)    NOT NULL,
    [DataType]    INT              NOT NULL,
    CONSTRAINT [PK_ATVariableInstanceNumber] PRIMARY KEY CLUSTERED ([InstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATVariableInstanceNumber].[RefID]...';


GO
CREATE NONCLUSTERED INDEX [RefID]
    ON [dbo].[ATVariableInstanceNumber]([ReferenceID] ASC);


GO
PRINT N'Creating Table [dbo].[ATVariableInstanceString]...';


GO
CREATE TABLE [dbo].[ATVariableInstanceString] (
    [InstanceID]  INT            NOT NULL,
    [VariableID]  INT            NOT NULL,
    [Value]       NVARCHAR (255) NOT NULL,
    [ReferenceID] INT            NULL,
    [Name]        NVARCHAR (50)  NOT NULL,
    [DataType]    INT            NOT NULL,
    CONSTRAINT [PK_ATVariableInstanceString] PRIMARY KEY CLUSTERED ([InstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATVariableInstanceString].[RefID]...';


GO
CREATE NONCLUSTERED INDEX [RefID]
    ON [dbo].[ATVariableInstanceString]([ReferenceID] ASC);


GO
PRINT N'Creating Table [dbo].[ATVariableInstanceTextBlob]...';


GO
CREATE TABLE [dbo].[ATVariableInstanceTextBlob] (
    [InstanceID]  INT           NOT NULL,
    [VariableID]  INT           NOT NULL,
    [Value]       TEXT          NOT NULL,
    [ReferenceID] INT           NULL,
    [Name]        NVARCHAR (50) NOT NULL,
    [DataType]    INT           NOT NULL,
    CONSTRAINT [PK_ATVariableInstanceTextBlob] PRIMARY KEY CLUSTERED ([InstanceID] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATVariableInstanceTextBlob].[RefID]...';


GO
CREATE NONCLUSTERED INDEX [RefID]
    ON [dbo].[ATVariableInstanceTextBlob]([ReferenceID] ASC);


GO
PRINT N'Creating Table [dbo].[ATWorkItem]...';


GO
CREATE TABLE [dbo].[ATWorkItem] (
    [WorkItemId]   INT              IDENTITY (1, 1) NOT NULL,
    [WorkItemName] NVARCHAR (255)   NOT NULL,
    [Creator]      NVARCHAR (255)   NOT NULL,
    [Created]      DATETIME         NOT NULL,
    [Priority]     INT              NOT NULL,
    [DueDate]      DATETIME         NULL,
    [ATComment]    NVARCHAR (255)   NULL,
    [LockedBy]     NVARCHAR (255)   NULL,
    [ProcessID]    INT              NOT NULL,
    [Expired]      INT              NULL,
    [ObjectId]     UNIQUEIDENTIFIER NULL,
    CONSTRAINT [PK_WorkItem] PRIMARY KEY NONCLUSTERED ([WorkItemId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATWorkItem].[ATWIAndLockedBy]...';


GO
CREATE NONCLUSTERED INDEX [ATWIAndLockedBy]
    ON [dbo].[ATWorkItem]([WorkItemId] ASC, [LockedBy] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItem].[ATWorkItem_Composite1]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItem_Composite1]
    ON [dbo].[ATWorkItem]([Creator] ASC, [Created] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItem].[ATWorkItem_IX_Creator]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItem_IX_Creator]
    ON [dbo].[ATWorkItem]([Creator] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItem].[ATWorkItem_IX_LockedBy]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItem_IX_LockedBy]
    ON [dbo].[ATWorkItem]([LockedBy] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItem].[ATWorkitem_IX_ProcessId]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkitem_IX_ProcessId]
    ON [dbo].[ATWorkItem]([ProcessID] ASC);


GO
PRINT N'Creating Table [dbo].[ATWorkItemArc]...';


GO
CREATE TABLE [dbo].[ATWorkItemArc] (
    [WorkItemId]   INT              NOT NULL,
    [WorkItemName] NVARCHAR (255)   NOT NULL,
    [Creator]      NVARCHAR (255)   NULL,
    [Created]      DATETIME         NULL,
    [Priority]     INT              NOT NULL,
    [DueDate]      DATETIME         NULL,
    [ATComment]    NVARCHAR (255)   NULL,
    [LockedBy]     NVARCHAR (255)   NULL,
    [ProcessID]    INT              NULL,
    [Expired]      INT              NULL,
    [ObjectId]     UNIQUEIDENTIFIER NULL,
    CONSTRAINT [PK_WorkItemArc] PRIMARY KEY NONCLUSTERED ([WorkItemId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATWorkItemReference]...';


GO
CREATE TABLE [dbo].[ATWorkItemReference] (
    [WorkItemReferenceId] INT            IDENTITY (1, 1) NOT NULL,
    [WorkItemId]          INT            NOT NULL,
    [QueueId]             INT            NULL,
    [SourceUser]          NVARCHAR (255) NULL,
    [SourceQueueId]       INT            NULL,
    [ArrivalDate]         DATETIME       NULL,
    [EventID]             INT            NULL,
    [ExpirationTime]      DATETIME       NULL,
    [Expired]             INT            NOT NULL,
    [Successor]           INT            NULL,
    [ServerRequest]       INT            NULL,
    [ServerRequestParam]  INT            NULL,
    [Status]              INT            NOT NULL,
    [AssignedTo]          NVARCHAR (255) NULL,
    [LastAction]          NVARCHAR (255) NULL,
    [PendEventId]         INT            NULL,
    [PendQueueId]         INT            NULL,
    [Draft]               INT            NULL,
    [Priority]            INT            NULL,
    [PendExpirationTime]  DATETIME       NULL,
    [LastActionDate]      DATETIME       NULL,
    [LastViewDate]        DATETIME       NULL,
    CONSTRAINT [PK_WorkItemReference] PRIMARY KEY NONCLUSTERED ([WorkItemReferenceId] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWIAndATWIRef]...';


GO
CREATE NONCLUSTERED INDEX [ATWIAndATWIRef]
    ON [dbo].[ATWorkItemReference]([WorkItemReferenceId] ASC, [WorkItemId] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReference_Composite1]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReference_Composite1]
    ON [dbo].[ATWorkItemReference]([QueueId] ASC, [SourceQueueId] ASC, [ServerRequest] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReference_Composite2]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReference_Composite2]
    ON [dbo].[ATWorkItemReference]([SourceUser] ASC, [ServerRequest] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReference_IX_EventId]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReference_IX_EventId]
    ON [dbo].[ATWorkItemReference]([EventID] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReference_IX_Queue]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReference_IX_Queue]
    ON [dbo].[ATWorkItemReference]([QueueId] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReference_IX_SQueue]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReference_IX_SQueue]
    ON [dbo].[ATWorkItemReference]([SourceQueueId] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReference_IX_Sucesor]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReference_IX_Sucesor]
    ON [dbo].[ATWorkItemReference]([Successor] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReference_IX_AssignedTo]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReference_IX_AssignedTo]
    ON [dbo].[ATWorkItemReference]([AssignedTo] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReference_IX_WIId]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReference_IX_WIId]
    ON [dbo].[ATWorkItemReference]([WorkItemId] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReferenceEventExpiredAndServer]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReferenceEventExpiredAndServer]
    ON [dbo].[ATWorkItemReference]([EventID] ASC, [Expired] ASC, [ServerRequest] ASC, [Status] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReferenceEventExpiredAndServerAndExpireDate]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReferenceEventExpiredAndServerAndExpireDate]
    ON [dbo].[ATWorkItemReference]([EventID] ASC, [ExpirationTime] ASC, [Expired] ASC, [ServerRequest] ASC, [Status] ASC);


GO
PRINT N'Creating Index [dbo].[ATWorkItemReference].[ATWorkItemReferenceEventExpiredAndServerWithOrder]...';


GO
CREATE NONCLUSTERED INDEX [ATWorkItemReferenceEventExpiredAndServerWithOrder]
    ON [dbo].[ATWorkItemReference]([WorkItemId] ASC, [ArrivalDate] ASC, [EventID] ASC, [Expired] ASC, [ServerRequest] ASC, [Status] ASC, [Priority] ASC);


GO
PRINT N'Creating Table [dbo].[ATWorkItemReferenceArc]...';


GO
CREATE TABLE [dbo].[ATWorkItemReferenceArc] (
    [WorkItemReferenceId] INT            NOT NULL,
    [WorkItemId]          INT            NOT NULL,
    [Queue]               NVARCHAR (32)  NULL,
    [SourceUser]          NVARCHAR (255) NULL,
    [SourceQueue]         NVARCHAR (32)  NULL,
    [ArrivalDate]         DATETIME       NULL,
    [EventID]             INT            NULL,
    [ExpirationTime]      DATETIME       NULL,
    [Expired]             INT            NOT NULL,
    [Successor]           INT            NULL,
    [ServerRequest]       INT            NULL,
    [ServerRequestParam]  INT            NULL,
    [Status]              INT            NOT NULL,
    [AssignedTo]          NVARCHAR (255) NULL,
    [LastAction]          NVARCHAR (255) NULL,
    [PendEventId]         INT            NULL,
    [PendQueue]           NVARCHAR (32)  NULL,
    [Draft]               INT            NULL,
    [Priority]            INT            NULL,
    [PendExpirationTime]  DATETIME       NULL,
    [DocumentBlob]        TEXT           NULL,
    [ArchiveSource]       NVARCHAR (255) NULL,
    [LastActionDate]      DATETIME       NULL,
    [LastViewDate]        DATETIME       NULL,
    CONSTRAINT [PK_WorkItemReferenceArc] PRIMARY KEY NONCLUSTERED ([WorkItemReferenceId] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATWorkItemTransmit]...';


GO
CREATE TABLE [dbo].[ATWorkItemTransmit] (
    [TransmitId]             INT           NULL,
    [SourceWorkItemId]       INT           NULL,
    [RemoteWorkItemId]       INT           NULL,
    [TransmitStatus]         INT           NULL,
    [TransmittedDate]        DATETIME      NULL,
    [RemoteURL]              NVARCHAR (50) NULL,
    [RemoteConnectionName]   NVARCHAR (50) NULL,
    [DestinationProcessName] NVARCHAR (50) NULL,
    [LoginName]              NVARCHAR (50) NULL,
    [Password]               NVARCHAR (50) NULL,
    [TransmitFields]         BIT           NULL,
    [TransmitDocuments]      BIT           NULL,
    [TransmitForms]          BIT           NULL
);


GO
PRINT N'Creating Table [dbo].[ATXmlHierarchy]...';


GO
CREATE TABLE [dbo].[ATXmlHierarchy] (
    [Id]            INT            IDENTITY (1, 1) NOT NULL,
    [HierarchyName] NVARCHAR (255) NOT NULL,
    [Description]   NVARCHAR (255) NULL,
    CONSTRAINT [PK_ATXmlHierarchy] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_ATXmlHierarchy_HierarchyName] UNIQUE NONCLUSTERED ([HierarchyName] ASC)
);


GO
PRINT N'Creating Table [dbo].[ATXmlHierarchyDefinition]...';


GO
CREATE TABLE [dbo].[ATXmlHierarchyDefinition] (
    [Id]         INT            IDENTITY (1, 1) NOT NULL,
    [Name]       NVARCHAR (255) NOT NULL,
    [Level]      INT            NOT NULL,
    [HierarchId] INT            NULL,
    [ParentId]   INT            NULL,
    CONSTRAINT [PK_ATXmlHierarchyDefinition] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Index [dbo].[ATXmlHierarchyDefinition].[IX_ATXmlHierarchyDefinition_ParentId]...';


GO
CREATE NONCLUSTERED INDEX [IX_ATXmlHierarchyDefinition_ParentId]
    ON [dbo].[ATXmlHierarchyDefinition]([ParentId] ASC);


GO
PRINT N'Creating Table [dbo].[ATXmlTemplateDefinition]...';


GO
CREATE TABLE [dbo].[ATXmlTemplateDefinition] (
    [Id]            INT            IDENTITY (1, 1) NOT NULL,
    [TemplateId]    INT            NOT NULL,
    [FieldName]     NVARCHAR (255) NOT NULL,
    [FieldSourceId] INT            NOT NULL,
    [XmlName]       NVARCHAR (255) NOT NULL,
    [XmlParentId]   INT            NULL,
    CONSTRAINT [PK_ATXmlTemplateDef] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [dbo].[POSTXML]...';


GO
CREATE TABLE [dbo].[POSTXML] (
    [DocUploadId]       INT            NOT NULL,
    [RegId]             INT            NULL,
    [DisasterNo]        INT            NULL,
    [DocumentId]        INT            NULL,
    [WorkItemId]        INT            NULL,
    [DocUploadDate]     DATETIME       NULL,
    [DocUploadStatusCd] NVARCHAR (100) NULL,
    [WorkItemQueue]     NVARCHAR (100) NULL,
    [WorkItemDate]      DATETIME       NULL
);


GO
PRINT N'Creating Table [dbo].[REDIRECT]...';


GO
CREATE TABLE [dbo].[REDIRECT] (
    [RGSN_ID]          NVARCHAR (100) NULL,
    [DSTR_NR]          NVARCHAR (100) NULL,
    [FILE_UPLOAD_ID]   NVARCHAR (100) NULL,
    [DOC_UPLOAD_ID]    NVARCHAR (100) NULL,
    [FILE_UPLOAD_NM]   NVARCHAR (300) NULL,
    [DOC_UPLOAD_DT]    NVARCHAR (200) NULL,
    [UPLOAD_STATUS_CD] NVARCHAR (200) NULL,
    [VRFN_ITEM_CD]     NVARCHAR (200) NULL,
    [DOC_ID]           NVARCHAR (100) NULL,
    [WORKITEM_ID]      NVARCHAR (100) NULL,
    [WORKITEM_NAME]    NVARCHAR (100) NULL,
    [STATUS]           NVARCHAR (100) NULL
);


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATConvertDefinition]...';


GO
ALTER TABLE [dbo].[ATConvertDefinition]
    ADD DEFAULT 0 FOR [ReplaceDocument];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_RegId]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_RegId] DEFAULT ('') FOR [RegId];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_DisasterNo]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_DisasterNo] DEFAULT ('') FOR [DisasterNo];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_DocType]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_DocType] DEFAULT ('') FOR [DocType];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_FirstName]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_FirstName] DEFAULT ('') FOR [FirstName];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_LastName]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_LastName] DEFAULT ('') FOR [LastName];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_Address]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_Address] DEFAULT ('') FOR [Address];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_City]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_City] DEFAULT ('') FOR [City];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_State]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_State] DEFAULT ('') FOR [State];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATD_CFTemplate_Zip]...';


GO
ALTER TABLE [dbo].[ATD_CFTemplate]
    ADD CONSTRAINT [DF_ATD_CFTemplate_Zip] DEFAULT ('') FOR [Zip];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocument]...';


GO
ALTER TABLE [dbo].[ATDocument]
    ADD DEFAULT (1) FOR [ReviewStatusId];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocument]...';


GO
ALTER TABLE [dbo].[ATDocument]
    ADD DEFAULT (1) FOR [ReviewNumber];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocument]...';


GO
ALTER TABLE [dbo].[ATDocument]
    ADD DEFAULT (GETDATE()) FOR [LastModified];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocumentCabinet]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinet]
    ADD DEFAULT (1) FOR [TemplateTypeId];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocumentCabinet]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinet]
    ADD DEFAULT (NEWID()) FOR [ObjectId];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocumentCabinet]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinet]
    ADD DEFAULT (GETDATE()) FOR [CreateDate];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocumentCabinet]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinet]
    ADD DEFAULT (GETDATE()) FOR [ModifyDate];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocumentCabinetDef]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinetDef]
    ADD DEFAULT (NEWID()) FOR [ObjectId];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATDocumentCabinetDef]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinetDef]
    ADD DEFAULT (1) FOR [Display];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATEventTriggerTemplate]...';


GO
ALTER TABLE [dbo].[ATEventTriggerTemplate]
    ADD DEFAULT 0 FOR [Enabled];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATExternalTrackingDefinition]...';


GO
ALTER TABLE [dbo].[ATExternalTrackingDefinition]
    ADD DEFAULT 3 FOR [SourceTypeId];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATFieldDefinition]...';


GO
ALTER TABLE [dbo].[ATFieldDefinition]
    ADD DEFAULT 5 FOR [DataType];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATFieldDefinition]...';


GO
ALTER TABLE [dbo].[ATFieldDefinition]
    ADD DEFAULT 0 FOR [Locked];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATFieldDefinition_Display]...';


GO
ALTER TABLE [dbo].[ATFieldDefinition]
    ADD CONSTRAINT [DF_ATFieldDefinition_Display] DEFAULT 1 FOR [Display];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATFieldDefinition]...';


GO
ALTER TABLE [dbo].[ATFieldDefinition]
    ADD DEFAULT NEWID() FOR [ObjectId];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImportDocumentType]...';


GO
ALTER TABLE [dbo].[ATImportDocumentType]
    ADD DEFAULT (1) FOR [IsActive];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImportDocumentType]...';


GO
ALTER TABLE [dbo].[ATImportDocumentType]
    ADD DEFAULT (0) FOR [Convertible];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImporterConfiguration]...';


GO
ALTER TABLE [dbo].[ATImporterConfiguration]
    ADD DEFAULT 30 FOR [LoopPauseMinutes];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImporterConfiguration]...';


GO
ALTER TABLE [dbo].[ATImporterConfiguration]
    ADD DEFAULT 7 FOR [LogRetentionDays];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImporterConfiguration]...';


GO
ALTER TABLE [dbo].[ATImporterConfiguration]
    ADD DEFAULT 100 FOR [LogFileMaxSizeMB];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImporterConfiguration]...';


GO
ALTER TABLE [dbo].[ATImporterConfiguration]
    ADD DEFAULT 80 FOR [CpuUsagePercentLimit];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImporterConfiguration]...';


GO
ALTER TABLE [dbo].[ATImporterConfiguration]
    ADD DEFAULT 20 FOR [MaxPDFSizeMB];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImporterConfiguration]...';


GO
ALTER TABLE [dbo].[ATImporterConfiguration]
    ADD DEFAULT 30 FOR [CleanArchiveIntervalDays];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATImporterConfiguration]...';


GO
ALTER TABLE [dbo].[ATImporterConfiguration]
    ADD DEFAULT (1) FOR [IsActive];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATInboxEvent]...';


GO
ALTER TABLE [dbo].[ATInboxEvent]
    ADD DEFAULT 0 FOR [AssignmentTypeId];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATMail]...';


GO
ALTER TABLE [dbo].[ATMail]
    ADD DEFAULT 1 FOR [Enable];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATMail]...';


GO
ALTER TABLE [dbo].[ATMail]
    ADD DEFAULT 0 FOR [Priority];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATPendingWorkItemReference]...';


GO
ALTER TABLE [dbo].[ATPendingWorkItemReference]
    ADD DEFAULT GETUTCDATE() FOR [CreatedTime];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATProcessDefinition]...';


GO
ALTER TABLE [dbo].[ATProcessDefinition]
    ADD DEFAULT 1 FOR [DefaultDocTemplate];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATProcessImportRule]...';


GO
ALTER TABLE [dbo].[ATProcessImportRule]
    ADD DEFAULT 0 FOR [MergeDocuments];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATProcessImportRule]...';


GO
ALTER TABLE [dbo].[ATProcessImportRule]
    ADD DEFAULT 0 FOR [RenameWhenMerged];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATQueue]...';


GO
ALTER TABLE [dbo].[ATQueue]
    ADD DEFAULT 0 FOR [Signable];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATReport]...';


GO
ALTER TABLE [dbo].[ATReport]
    ADD DEFAULT (0) FOR [IsActive];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledItem_Enabled]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [DF_ATScheduledItem_Enabled] DEFAULT (1) FOR [Enabled];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledItem_WaitForCompletion]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [DF_ATScheduledItem_WaitForCompletion] DEFAULT (0) FOR [WaitForCompletion];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledItem_Priority]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [DF_ATScheduledItem_Priority] DEFAULT (0) FOR [Priority];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledItem_ScheduleTypeId]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [DF_ATScheduledItem_ScheduleTypeId] DEFAULT (1) FOR [ScheduleTypeId];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledItem_StatusId]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [DF_ATScheduledItem_StatusId] DEFAULT (1) FOR [StatusId];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledItem_CreatedAt]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [DF_ATScheduledItem_CreatedAt] DEFAULT (GETUTCDATE()) FOR [CreatedAt];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledItem_UpdatedAt]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [DF_ATScheduledItem_UpdatedAt] DEFAULT (GETUTCDATE()) FOR [UpdatedAt];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledTask_Enabled]...';


GO
ALTER TABLE [dbo].[ATScheduledTask]
    ADD CONSTRAINT [DF_ATScheduledTask_Enabled] DEFAULT (1) FOR [Enabled];


GO
PRINT N'Creating Default Constraint [dbo].[DF_ATScheduledTask_SortOrder]...';


GO
ALTER TABLE [dbo].[ATScheduledTask]
    ADD CONSTRAINT [DF_ATScheduledTask_SortOrder] DEFAULT (0) FOR [SortOrder];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATTemplates]...';


GO
ALTER TABLE [dbo].[ATTemplates]
    ADD DEFAULT (NEWID()) FOR [ObjectId];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATTemplates]...';


GO
ALTER TABLE [dbo].[ATTemplates]
    ADD DEFAULT (GETDATE()) FOR [CreateDate];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATTemplates]...';


GO
ALTER TABLE [dbo].[ATTemplates]
    ADD DEFAULT (GETDATE()) FOR [ModifyDate];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATTrackingDefinition]...';


GO
ALTER TABLE [dbo].[ATTrackingDefinition]
    ADD DEFAULT 0 FOR [EnableExternal];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATTrackingDefinitionTemplates]...';


GO
ALTER TABLE [dbo].[ATTrackingDefinitionTemplates]
    ADD DEFAULT 0 FOR [Order];


GO
PRINT N'Creating Default Constraint unnamed constraint on [dbo].[ATWorkItem]...';


GO
ALTER TABLE [dbo].[ATWorkItem]
    ADD DEFAULT GETDATE() FOR [Created];


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATButton_ATQueue]...';


GO
ALTER TABLE [dbo].[ATButton]
    ADD CONSTRAINT [FK_ATButton_ATQueue] FOREIGN KEY ([QueueId]) REFERENCES [dbo].[ATQueue] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATButton_ATEvent]...';


GO
ALTER TABLE [dbo].[ATButton]
    ADD CONSTRAINT [FK_ATButton_ATEvent] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATConnection_ATConnectionType]...';


GO
ALTER TABLE [dbo].[ATConnection]
    ADD CONSTRAINT [FK_ATConnection_ATConnectionType] FOREIGN KEY ([Type]) REFERENCES [dbo].[ATConnectionType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_SourceDocTypeId]...';


GO
ALTER TABLE [dbo].[ATConvertDefinition]
    ADD CONSTRAINT [FK_ATExportDefinition_SourceDocTypeId] FOREIGN KEY ([SourceDocTypeId]) REFERENCES [dbo].[ATImportDocumentType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_ExportDocTypeId]...';


GO
ALTER TABLE [dbo].[ATConvertDefinition]
    ADD CONSTRAINT [FK_ATExportDefinition_ExportDocTypeId] FOREIGN KEY ([ExportDocTypeId]) REFERENCES [dbo].[ATImportDocumentType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_MergeOrderId]...';


GO
ALTER TABLE [dbo].[ATConvertDefinition]
    ADD CONSTRAINT [FK_ATExportDefinition_MergeOrderId] FOREIGN KEY ([MergeOrderId]) REFERENCES [dbo].[ATMergeOrder] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_BarcodesFontId]...';


GO
ALTER TABLE [dbo].[ATConvertDefinition]
    ADD CONSTRAINT [FK_ATExportDefinition_BarcodesFontId] FOREIGN KEY ([BarcodesFontId]) REFERENCES [dbo].[ATBarcodeFont] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATConvertEvent_EventId]...';


GO
ALTER TABLE [dbo].[ATConvertEvent]
    ADD CONSTRAINT [FK_ATConvertEvent_EventId] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATConvertEvent_TemplateId]...';


GO
ALTER TABLE [dbo].[ATConvertEvent]
    ADD CONSTRAINT [FK_ATConvertEvent_TemplateId] FOREIGN KEY ([TemplateId]) REFERENCES [dbo].[ATTemplates] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATDocument_FK_Cabinet]...';


GO
ALTER TABLE [dbo].[ATDocument]
    ADD CONSTRAINT [ATDocument_FK_Cabinet] FOREIGN KEY ([CabinetId]) REFERENCES [dbo].[ATDocumentCabinet] ([CabinetID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATDocument_FK_WorkItemId]...';


GO
ALTER TABLE [dbo].[ATDocument]
    ADD CONSTRAINT [ATDocument_FK_WorkItemId] FOREIGN KEY ([WorkItemId]) REFERENCES [dbo].[ATWorkItem] ([WorkItemId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATDocument_FK_ReviewStatusId]...';


GO
ALTER TABLE [dbo].[ATDocument]
    ADD CONSTRAINT [ATDocument_FK_ReviewStatusId] FOREIGN KEY ([ReviewStatusId]) REFERENCES [dbo].[ATDocumenctReviewStatus] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATDocumentCabinet_TemplateTypeId]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinet]
    ADD CONSTRAINT [FK_ATDocumentCabinet_TemplateTypeId] FOREIGN KEY ([TemplateTypeId]) REFERENCES [dbo].[ATTemplateType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATDocumentCabinet_DbConnectionId]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinet]
    ADD CONSTRAINT [FK_ATDocumentCabinet_DbConnectionId] FOREIGN KEY ([DbConnectionId]) REFERENCES [dbo].[ATConnection] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATDocumentCabinetDef_ATDocumentCabinet]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinetDef]
    ADD CONSTRAINT [FK_ATDocumentCabinetDef_ATDocumentCabinet] FOREIGN KEY ([CabinetID]) REFERENCES [dbo].[ATDocumentCabinet] ([CabinetID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATDocumentCabinetDef_ATDocumentCabinetFiledType]...';


GO
ALTER TABLE [dbo].[ATDocumentCabinetDef]
    ADD CONSTRAINT [FK_ATDocumentCabinetDef_ATDocumentCabinetFiledType] FOREIGN KEY ([FieldDataTypeId]) REFERENCES [dbo].[ATDocumentCabinetFiledType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATEventDefinition_ATEventType]...';


GO
ALTER TABLE [dbo].[ATEventDefinition]
    ADD CONSTRAINT [ATEventDefinition_ATEventType] FOREIGN KEY ([EventTypeID]) REFERENCES [dbo].[ATEventType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATEventDefinition_ATProcessDefinition]...';


GO
ALTER TABLE [dbo].[ATEventDefinition]
    ADD CONSTRAINT [ATEventDefinition_ATProcessDefinition] FOREIGN KEY ([ProcessID]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATEventDefinition_ATEventDefinition]...';


GO
ALTER TABLE [dbo].[ATEventDefinition]
    ADD CONSTRAINT [ATEventDefinition_ATEventDefinition] FOREIGN KEY ([JoinEventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATEventDefinition_ATServer]...';


GO
ALTER TABLE [dbo].[ATEventDefinition]
    ADD CONSTRAINT [ATEventDefinition_ATServer] FOREIGN KEY ([Server]) REFERENCES [dbo].[ATServer] ([HostName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATEventTrigger_ProcessDefinition]...';


GO
ALTER TABLE [dbo].[ATEventTriggerDefinition]
    ADD CONSTRAINT [ATEventTrigger_ProcessDefinition] FOREIGN KEY ([ProcessId]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATEventTrigger_Template]...';


GO
ALTER TABLE [dbo].[ATEventTriggerDefinition]
    ADD CONSTRAINT [ATEventTrigger_Template] FOREIGN KEY ([TemplateId]) REFERENCES [dbo].[ATTemplates] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATEventTrigger_Hook]...';


GO
ALTER TABLE [dbo].[ATEventTriggerDefinition]
    ADD CONSTRAINT [ATEventTrigger_Hook] FOREIGN KEY ([HookId]) REFERENCES [dbo].[ATTriggerHook] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATEventTrigger_Action]...';


GO
ALTER TABLE [dbo].[ATEventTriggerDefinition]
    ADD CONSTRAINT [ATEventTrigger_Action] FOREIGN KEY ([ActionId]) REFERENCES [dbo].[ATTriggerAction] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATEventTriggerTemplate_EventId]...';


GO
ALTER TABLE [dbo].[ATEventTriggerTemplate]
    ADD CONSTRAINT [FK_ATEventTriggerTemplate_EventId] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATEventTriggerTemplate_TemplateId]...';


GO
ALTER TABLE [dbo].[ATEventTriggerTemplate]
    ADD CONSTRAINT [FK_ATEventTriggerTemplate_TemplateId] FOREIGN KEY ([TemplateId]) REFERENCES [dbo].[ATTemplates] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATExceptionNote_FK1]...';


GO
ALTER TABLE [dbo].[ATExceptionNote]
    ADD CONSTRAINT [ATExceptionNote_FK1] FOREIGN KEY ([WorkItemReferenceID]) REFERENCES [dbo].[ATWorkItemReference] ([WorkItemReferenceId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATExceptionNote_FK2]...';


GO
ALTER TABLE [dbo].[ATExceptionNote]
    ADD CONSTRAINT [ATExceptionNote_FK2] FOREIGN KEY ([ExceptionUser]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_DoneFlag]...';


GO
ALTER TABLE [dbo].[ATExportDefinition]
    ADD CONSTRAINT [FK_ATExportDefinition_DoneFlag] FOREIGN KEY ([DoneFlagId]) REFERENCES [dbo].[ATExportFlagTxt] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_TemplateId]...';


GO
ALTER TABLE [dbo].[ATExportDefinition]
    ADD CONSTRAINT [FK_ATExportDefinition_TemplateId] FOREIGN KEY ([TemplateId]) REFERENCES [dbo].[ATTemplates] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_ExportTypeId]...';


GO
ALTER TABLE [dbo].[ATExportDefinition]
    ADD CONSTRAINT [FK_ATExportDefinition_ExportTypeId] FOREIGN KEY ([ExportTypeId]) REFERENCES [dbo].[ATExportType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_ExportFileFormatId]...';


GO
ALTER TABLE [dbo].[ATExportDefinition]
    ADD CONSTRAINT [FK_ATExportDefinition_ExportFileFormatId] FOREIGN KEY ([ExportFileFormatId]) REFERENCES [dbo].[ATImportDocumentType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_ExportLocation_Definition]...';


GO
ALTER TABLE [dbo].[ATExportDefinition_ExportLocation]
    ADD CONSTRAINT [FK_ATExportDefinition_ExportLocation_Definition] FOREIGN KEY ([ExportDefinitionId]) REFERENCES [dbo].[ATExportDefinition] ([Id]) ON DELETE CASCADE;


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportDefinition_ExportLocation_Location]...';


GO
ALTER TABLE [dbo].[ATExportDefinition_ExportLocation]
    ADD CONSTRAINT [FK_ATExportDefinition_ExportLocation_Location] FOREIGN KEY ([ExportLocationId]) REFERENCES [dbo].[ATExportLocation] ([Id]) ON DELETE CASCADE;


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportEvent_EventId]...';


GO
ALTER TABLE [dbo].[ATExportEvent]
    ADD CONSTRAINT [FK_ATExportEvent_EventId] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExportEvent_TemplateId]...';


GO
ALTER TABLE [dbo].[ATExportEvent]
    ADD CONSTRAINT [FK_ATExportEvent_TemplateId] FOREIGN KEY ([TemplateId]) REFERENCES [dbo].[ATTemplates] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExternalTrackingDefinition_TemplateId]...';


GO
ALTER TABLE [dbo].[ATExternalTrackingDefinition]
    ADD CONSTRAINT [FK_ATExternalTrackingDefinition_TemplateId] FOREIGN KEY ([TemplateId]) REFERENCES [dbo].[ATTemplates] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATExternalTrackingDefinition_SourceTypeId]...';


GO
ALTER TABLE [dbo].[ATExternalTrackingDefinition]
    ADD CONSTRAINT [FK_ATExternalTrackingDefinition_SourceTypeId] FOREIGN KEY ([SourceTypeId]) REFERENCES [dbo].[ATExternalTrackingSourceType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldDefinition_ProcessDefinition]...';


GO
ALTER TABLE [dbo].[ATFieldDefinition]
    ADD CONSTRAINT [ATFieldDefinition_ProcessDefinition] FOREIGN KEY ([ProcessID]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldInstanceDate_ATFieldDefinition]...';


GO
ALTER TABLE [dbo].[ATFieldInstanceDate]
    ADD CONSTRAINT [ATFieldInstanceDate_ATFieldDefinition] FOREIGN KEY ([FieldID]) REFERENCES [dbo].[ATFieldDefinition] ([FieldID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldInstanceDate_ATWorkItem]...';


GO
ALTER TABLE [dbo].[ATFieldInstanceDate]
    ADD CONSTRAINT [ATFieldInstanceDate_ATWorkItem] FOREIGN KEY ([WorkItemID]) REFERENCES [dbo].[ATWorkItem] ([WorkItemId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldInstanceNumber_ATFieldDefinition]...';


GO
ALTER TABLE [dbo].[ATFieldInstanceNumber]
    ADD CONSTRAINT [ATFieldInstanceNumber_ATFieldDefinition] FOREIGN KEY ([FieldID]) REFERENCES [dbo].[ATFieldDefinition] ([FieldID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldInstanceNumber_ATWorkItem]...';


GO
ALTER TABLE [dbo].[ATFieldInstanceNumber]
    ADD CONSTRAINT [ATFieldInstanceNumber_ATWorkItem] FOREIGN KEY ([WorkItemID]) REFERENCES [dbo].[ATWorkItem] ([WorkItemId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldInstanceOption_ATFieldDefinition]...';


GO
ALTER TABLE [dbo].[ATFieldInstanceOption]
    ADD CONSTRAINT [ATFieldInstanceOption_ATFieldDefinition] FOREIGN KEY ([FieldID]) REFERENCES [dbo].[ATFieldDefinition] ([FieldID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldInstanceOption_ATWorkItem]...';


GO
ALTER TABLE [dbo].[ATFieldInstanceOption]
    ADD CONSTRAINT [ATFieldInstanceOption_ATWorkItem] FOREIGN KEY ([WorkItemID]) REFERENCES [dbo].[ATWorkItem] ([WorkItemId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldInstanceString_ATFieldDefinition]...';


GO
ALTER TABLE [dbo].[ATFieldInstanceString]
    ADD CONSTRAINT [ATFieldInstanceString_ATFieldDefinition] FOREIGN KEY ([FieldID]) REFERENCES [dbo].[ATFieldDefinition] ([FieldID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATFieldInstanceString_ATWorkItem]...';


GO
ALTER TABLE [dbo].[ATFieldInstanceString]
    ADD CONSTRAINT [ATFieldInstanceString_ATWorkItem] FOREIGN KEY ([WorkItemID]) REFERENCES [dbo].[ATWorkItem] ([WorkItemId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATForm_FK1]...';


GO
ALTER TABLE [dbo].[ATForm]
    ADD CONSTRAINT [ATForm_FK1] FOREIGN KEY ([ProcessID]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATHistoryEvent_FK1]...';


GO
ALTER TABLE [dbo].[ATHistoryEvent]
    ADD CONSTRAINT [ATHistoryEvent_FK1] FOREIGN KEY ([HistoryId]) REFERENCES [dbo].[ATHistory] ([HistoryId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATHistoryParameter_FK1]...';


GO
ALTER TABLE [dbo].[ATHistoryParameter]
    ADD CONSTRAINT [ATHistoryParameter_FK1] FOREIGN KEY ([HistoryId]) REFERENCES [dbo].[ATHistory] ([HistoryId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATInboxEvent_ATEventDefinition]...';


GO
ALTER TABLE [dbo].[ATInboxEvent]
    ADD CONSTRAINT [FK_ATInboxEvent_ATEventDefinition] FOREIGN KEY ([EventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATInboxEvent_ATQueue]...';


GO
ALTER TABLE [dbo].[ATInboxEvent]
    ADD CONSTRAINT [FK_ATInboxEvent_ATQueue] FOREIGN KEY ([InboxId]) REFERENCES [dbo].[ATQueue] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATInboxEvent_ATAssignmentType]...';


GO
ALTER TABLE [dbo].[ATInboxEvent]
    ADD CONSTRAINT [FK_ATInboxEvent_ATAssignmentType] FOREIGN KEY ([AssignmentTypeId]) REFERENCES [dbo].[ATAssigmentType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATLink_FK1]...';


GO
ALTER TABLE [dbo].[ATLink]
    ADD CONSTRAINT [ATLink_FK1] FOREIGN KEY ([ProcessID]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATLink_FK2]...';


GO
ALTER TABLE [dbo].[ATLink]
    ADD CONSTRAINT [ATLink_FK2] FOREIGN KEY ([FromEventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATLink_FK3]...';


GO
ALTER TABLE [dbo].[ATLink]
    ADD CONSTRAINT [ATLink_FK3] FOREIGN KEY ([ToEventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_Process]...';


GO
ALTER TABLE [dbo].[ATMail]
    ADD CONSTRAINT [FK_Process] FOREIGN KEY ([ProcessID]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_Event]...';


GO
ALTER TABLE [dbo].[ATMail]
    ADD CONSTRAINT [FK_Event] FOREIGN KEY ([EventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATMail_ATConnection]...';


GO
ALTER TABLE [dbo].[ATMail]
    ADD CONSTRAINT [FK_ATMail_ATConnection] FOREIGN KEY ([ConnectionId]) REFERENCES [dbo].[ATConnection] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATNote_ATWorkItem]...';


GO
ALTER TABLE [dbo].[ATNote]
    ADD CONSTRAINT [FK_ATNote_ATWorkItem] FOREIGN KEY ([WorkItemId]) REFERENCES [dbo].[ATWorkItem] ([WorkItemId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATNote_ATDocument]...';


GO
ALTER TABLE [dbo].[ATNote]
    ADD CONSTRAINT [FK_ATNote_ATDocument] FOREIGN KEY ([DocumentId]) REFERENCES [dbo].[ATDocument] ([DocumentId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATPendingWorkItemReference_WorkItemReference]...';


GO
ALTER TABLE [dbo].[ATPendingWorkItemReference]
    ADD CONSTRAINT [FK_ATPendingWorkItemReference_WorkItemReference] FOREIGN KEY ([PendingWorkItemReferenceId]) REFERENCES [dbo].[ATWorkItemReference] ([WorkItemReferenceId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATProcessDefinition_Creator]...';


GO
ALTER TABLE [dbo].[ATProcessDefinition]
    ADD CONSTRAINT [ATProcessDefinition_Creator] FOREIGN KEY ([Creator]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATProcessDefinition_LockedBy]...';


GO
ALTER TABLE [dbo].[ATProcessDefinition]
    ADD CONSTRAINT [ATProcessDefinition_LockedBy] FOREIGN KEY ([LockedBy]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATProcessDefinition_ProcessGroupID]...';


GO
ALTER TABLE [dbo].[ATProcessDefinition]
    ADD CONSTRAINT [ATProcessDefinition_ProcessGroupID] FOREIGN KEY ([ProcessGroupID]) REFERENCES [dbo].[ATProcessGroup] ([ProcessGroupID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATProcessDefinition_StartEventID]...';


GO
ALTER TABLE [dbo].[ATProcessDefinition]
    ADD CONSTRAINT [ATProcessDefinition_StartEventID] FOREIGN KEY ([StartEventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATProcessDefinition_ATDocumentCabinet]...';


GO
ALTER TABLE [dbo].[ATProcessDefinition]
    ADD CONSTRAINT [ATProcessDefinition_ATDocumentCabinet] FOREIGN KEY ([DefaultDocTemplate]) REFERENCES [dbo].[ATDocumentCabinet] ([CabinetID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATProcessDocumentTemplateRights_ATProcessDefinition]...';


GO
ALTER TABLE [dbo].[ATProcessDocumentTemplateRight]
    ADD CONSTRAINT [FK_ATProcessDocumentTemplateRights_ATProcessDefinition] FOREIGN KEY ([ProcessObjectId]) REFERENCES [dbo].[ATProcessDefinition] ([ObjectId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATProcessDocumentTemplateRights_ATDocumentCabinet]...';


GO
ALTER TABLE [dbo].[ATProcessDocumentTemplateRight]
    ADD CONSTRAINT [FK_ATProcessDocumentTemplateRights_ATDocumentCabinet] FOREIGN KEY ([DocumentTemplateObjectid]) REFERENCES [dbo].[ATDocumentCabinet] ([ObjectId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATProcessDocumentTemplateRights_ATRightAllowRight]...';


GO
ALTER TABLE [dbo].[ATProcessDocumentTemplateRight]
    ADD CONSTRAINT [FK_ATProcessDocumentTemplateRights_ATRightAllowRight] FOREIGN KEY ([AllowRights]) REFERENCES [dbo].[ATRightAllowRight] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATProcessImportRule_Process]...';


GO
ALTER TABLE [dbo].[ATProcessImportRule]
    ADD CONSTRAINT [FK_ATProcessImportRule_Process] FOREIGN KEY ([ProcessId]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATProcessImportRule_ConvertToFormat]...';


GO
ALTER TABLE [dbo].[ATProcessImportRule]
    ADD CONSTRAINT [FK_ATProcessImportRule_ConvertToFormat] FOREIGN KEY ([ConvertToFormatId]) REFERENCES [dbo].[ATImportDocumentType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATQueue_ATEvent]...';


GO
ALTER TABLE [dbo].[ATQueue]
    ADD CONSTRAINT [FK_ATQueue_ATEvent] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATQueue_ATProcessDefinition]...';


GO
ALTER TABLE [dbo].[ATQueue]
    ADD CONSTRAINT [FK_ATQueue_ATProcessDefinition] FOREIGN KEY ([ProcessId]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATRight_ATUser]...';


GO
ALTER TABLE [dbo].[ATRight]
    ADD CONSTRAINT [FK_ATRight_ATUser] FOREIGN KEY ([UserGuid]) REFERENCES [dbo].[ATUser] ([ObjectId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATRight_ATRightObjectType]...';


GO
ALTER TABLE [dbo].[ATRight]
    ADD CONSTRAINT [FK_ATRight_ATRightObjectType] FOREIGN KEY ([ObjectType]) REFERENCES [dbo].[ATRightObjectType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATRight_ATRightAllowRight]...';


GO
ALTER TABLE [dbo].[ATRight]
    ADD CONSTRAINT [FK_ATRight_ATRightAllowRight] FOREIGN KEY ([AllowRights]) REFERENCES [dbo].[ATRightAllowRight] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATScheduledItem_ATServer]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [FK_ATScheduledItem_ATServer] FOREIGN KEY ([ServerHost]) REFERENCES [dbo].[ATServer] ([HostName]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATScheduledItem_ATScheduleStatusType]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [FK_ATScheduledItem_ATScheduleStatusType] FOREIGN KEY ([StatusId]) REFERENCES [dbo].[ATScheduleStatusType] ([StatusId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATScheduledItem_ATRunStatusType]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [FK_ATScheduledItem_ATRunStatusType] FOREIGN KEY ([LastRunStatusId]) REFERENCES [dbo].[ATRunStatusType] ([StatusId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATScheduledItem_ATScheduleType]...';


GO
ALTER TABLE [dbo].[ATScheduledItem]
    ADD CONSTRAINT [FK_ATScheduledItem_ATScheduleType] FOREIGN KEY ([ScheduleTypeId]) REFERENCES [dbo].[ATScheduleType] ([ScheduleTypeId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATScheduledTask_ATScheduledItem]...';


GO
ALTER TABLE [dbo].[ATScheduledTask]
    ADD CONSTRAINT [FK_ATScheduledTask_ATScheduledItem] FOREIGN KEY ([ScheduleId]) REFERENCES [dbo].[ATScheduledItem] ([ScheduleId]) ON DELETE CASCADE;


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATScheduledTask_ATTaskType]...';


GO
ALTER TABLE [dbo].[ATScheduledTask]
    ADD CONSTRAINT [FK_ATScheduledTask_ATTaskType] FOREIGN KEY ([TaskTypeId]) REFERENCES [dbo].[ATTaskType] ([TaskTypeId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_TaskAction_Success]...';


GO
ALTER TABLE [dbo].[ATScheduledTask]
    ADD CONSTRAINT [FK_TaskAction_Success] FOREIGN KEY ([OnSuccessActionId]) REFERENCES [dbo].[ATTaskActionType] ([ActionId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_TaskAction_Failure]...';


GO
ALTER TABLE [dbo].[ATScheduledTask]
    ADD CONSTRAINT [FK_TaskAction_Failure] FOREIGN KEY ([OnFailureActionId]) REFERENCES [dbo].[ATTaskActionType] ([ActionId]);


GO
PRINT N'Creating Foreign Key [dbo].[Atscript_FK1]...';


GO
ALTER TABLE [dbo].[ATScript]
    ADD CONSTRAINT [Atscript_FK1] FOREIGN KEY ([ProcessID]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[Atscript_FK2]...';


GO
ALTER TABLE [dbo].[ATScript]
    ADD CONSTRAINT [Atscript_FK2] FOREIGN KEY ([EventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATSearch_FK1]...';


GO
ALTER TABLE [dbo].[ATSearch]
    ADD CONSTRAINT [ATSearch_FK1] FOREIGN KEY ([SearchRegistrationGuid]) REFERENCES [dbo].[ATSearchRegistration] ([ObjectGuid]);


GO
PRINT N'Creating Foreign Key [dbo].[ATSearchDisplayField_FK1]...';


GO
ALTER TABLE [dbo].[ATSearchDisplayField]
    ADD CONSTRAINT [ATSearchDisplayField_FK1] FOREIGN KEY ([SearchRegistrationGuid]) REFERENCES [dbo].[ATSearchRegistration] ([ObjectGuid]);


GO
PRINT N'Creating Foreign Key [dbo].[ATSearchRegistration_FK1]...';


GO
ALTER TABLE [dbo].[ATSearchRegistration]
    ADD CONSTRAINT [ATSearchRegistration_FK1] FOREIGN KEY ([ConnectionName]) REFERENCES [dbo].[ATEnterpriseConnection] ([ConnectionName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATSplit_FK1]...';


GO
ALTER TABLE [dbo].[ATSplit]
    ADD CONSTRAINT [ATSplit_FK1] FOREIGN KEY ([JoinEventId]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATSplit_FK2]...';


GO
ALTER TABLE [dbo].[ATSplit]
    ADD CONSTRAINT [ATSplit_FK2] FOREIGN KEY ([SplitWorkItemRef]) REFERENCES [dbo].[ATWorkItemReference] ([WorkItemReferenceId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATSplit_FK3]...';


GO
ALTER TABLE [dbo].[ATSplit]
    ADD CONSTRAINT [ATSplit_FK3] FOREIGN KEY ([SourceWorkItemRef]) REFERENCES [dbo].[ATWorkItemReference] ([WorkItemReferenceId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATStack_FK1]...';


GO
ALTER TABLE [dbo].[ATStack]
    ADD CONSTRAINT [ATStack_FK1] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATStack_FK2]...';


GO
ALTER TABLE [dbo].[ATStack]
    ADD CONSTRAINT [ATStack_FK2] FOREIGN KEY ([WorkItemRef]) REFERENCES [dbo].[ATWorkItemReference] ([WorkItemReferenceId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATStack_FK3]...';


GO
ALTER TABLE [dbo].[ATStack]
    ADD CONSTRAINT [ATStack_FK3] FOREIGN KEY ([SubProcessId]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATTaskDefinition_FK1]...';


GO
ALTER TABLE [dbo].[ATTaskDefinition]
    ADD CONSTRAINT [ATTaskDefinition_FK1] FOREIGN KEY ([EventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATTaskInstance_FK1]...';


GO
ALTER TABLE [dbo].[ATTaskInstance]
    ADD CONSTRAINT [ATTaskInstance_FK1] FOREIGN KEY ([TaskID]) REFERENCES [dbo].[ATTaskDefinition] ([TaskID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATtaskInstance_FK2]...';


GO
ALTER TABLE [dbo].[ATTaskInstance]
    ADD CONSTRAINT [ATtaskInstance_FK2] FOREIGN KEY ([WorkItemReferenceID]) REFERENCES [dbo].[ATWorkItemReference] ([WorkItemReferenceId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATTaskInstance_FK3]...';


GO
ALTER TABLE [dbo].[ATTaskInstance]
    ADD CONSTRAINT [ATTaskInstance_FK3] FOREIGN KEY ([CompletedBy]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTemplates_ProcessId]...';


GO
ALTER TABLE [dbo].[ATTemplates]
    ADD CONSTRAINT [FK_ATTemplates_ProcessId] FOREIGN KEY ([ProcessId]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTemplates_DocumentCabinetId]...';


GO
ALTER TABLE [dbo].[ATTemplates]
    ADD CONSTRAINT [FK_ATTemplates_DocumentCabinetId] FOREIGN KEY ([DocumentCabinetId]) REFERENCES [dbo].[ATDocumentCabinet] ([CabinetID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTemplates_TemplateTypeId]...';


GO
ALTER TABLE [dbo].[ATTemplates]
    ADD CONSTRAINT [FK_ATTemplates_TemplateTypeId] FOREIGN KEY ([TemplateTypeId]) REFERENCES [dbo].[ATTemplateType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTemplates_DbConnectionId]...';


GO
ALTER TABLE [dbo].[ATTemplates]
    ADD CONSTRAINT [FK_ATTemplates_DbConnectionId] FOREIGN KEY ([DbConnectionId]) REFERENCES [dbo].[ATConnection] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTemplates_HierarchyId]...';


GO
ALTER TABLE [dbo].[ATTemplates]
    ADD CONSTRAINT [FK_ATTemplates_HierarchyId] FOREIGN KEY ([HierarchyId]) REFERENCES [dbo].[ATXmlHierarchy] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTimer_EventID]...';


GO
ALTER TABLE [dbo].[ATTimer]
    ADD CONSTRAINT [FK_ATTimer_EventID] FOREIGN KEY ([EventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTimer_ProcessID]...';


GO
ALTER TABLE [dbo].[ATTimer]
    ADD CONSTRAINT [FK_ATTimer_ProcessID] FOREIGN KEY ([ProcessID]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTrackingDefinition_ATProcessDefinition]...';


GO
ALTER TABLE [dbo].[ATTrackingDefinition]
    ADD CONSTRAINT [FK_ATTrackingDefinition_ATProcessDefinition] FOREIGN KEY ([ProcessId]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTrackingDefinition_ATEventDefinition]...';


GO
ALTER TABLE [dbo].[ATTrackingDefinition]
    ADD CONSTRAINT [FK_ATTrackingDefinition_ATEventDefinition] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTrackingDefinitionTemplates_TrackingDefinitionId]...';


GO
ALTER TABLE [dbo].[ATTrackingDefinitionTemplates]
    ADD CONSTRAINT [FK_ATTrackingDefinitionTemplates_TrackingDefinitionId] FOREIGN KEY ([TrackingDefinitionId]) REFERENCES [dbo].[ATTrackingDefinition] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTrackingDefinitionTemplates_TemplateId]...';


GO
ALTER TABLE [dbo].[ATTrackingDefinitionTemplates]
    ADD CONSTRAINT [FK_ATTrackingDefinitionTemplates_TemplateId] FOREIGN KEY ([TemplateId]) REFERENCES [dbo].[ATTemplates] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTrackingRecord_ATWorkItem]...';


GO
ALTER TABLE [dbo].[ATTrackingRecord]
    ADD CONSTRAINT [FK_ATTrackingRecord_ATWorkItem] FOREIGN KEY ([WorkItemId]) REFERENCES [dbo].[ATWorkItem] ([WorkItemId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTrackingRecord_ATUser]...';


GO
ALTER TABLE [dbo].[ATTrackingRecord]
    ADD CONSTRAINT [FK_ATTrackingRecord_ATUser] FOREIGN KEY ([UserName]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTrackingRecord_ATButton]...';


GO
ALTER TABLE [dbo].[ATTrackingRecord]
    ADD CONSTRAINT [FK_ATTrackingRecord_ATButton] FOREIGN KEY ([LastActionId]) REFERENCES [dbo].[ATButton] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATTrackingRecord_ATTrackingDefinition]...';


GO
ALTER TABLE [dbo].[ATTrackingRecord]
    ADD CONSTRAINT [FK_ATTrackingRecord_ATTrackingDefinition] FOREIGN KEY ([TrackingDefinitionId]) REFERENCES [dbo].[ATTrackingDefinition] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATUserGroup_ATUser_User]...';


GO
ALTER TABLE [dbo].[ATUserGroup]
    ADD CONSTRAINT [ATUserGroup_ATUser_User] FOREIGN KEY ([ObjectId]) REFERENCES [dbo].[ATUser] ([ObjectId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATUserGroup_ATUser_Group]...';


GO
ALTER TABLE [dbo].[ATUserGroup]
    ADD CONSTRAINT [ATUserGroup_ATUser_Group] FOREIGN KEY ([ParentId]) REFERENCES [dbo].[ATUser] ([ObjectId]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATUserProperty_ATUser]...';


GO
ALTER TABLE [dbo].[ATUserProperty]
    ADD CONSTRAINT [FK_ATUserProperty_ATUser] FOREIGN KEY ([UserName]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItem_LockedByUser]...';


GO
ALTER TABLE [dbo].[ATWorkItem]
    ADD CONSTRAINT [ATWorkItem_LockedByUser] FOREIGN KEY ([LockedBy]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItem_Creator]...';


GO
ALTER TABLE [dbo].[ATWorkItem]
    ADD CONSTRAINT [ATWorkItem_Creator] FOREIGN KEY ([Creator]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItem_Process]...';


GO
ALTER TABLE [dbo].[ATWorkItem]
    ADD CONSTRAINT [ATWorkItem_Process] FOREIGN KEY ([ProcessID]) REFERENCES [dbo].[ATProcessDefinition] ([ProcessID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItemReference_ATWorkItem]...';


GO
ALTER TABLE [dbo].[ATWorkItemReference]
    ADD CONSTRAINT [ATWorkItemReference_ATWorkItem] FOREIGN KEY ([WorkItemId]) REFERENCES [dbo].[ATWorkItem] ([WorkItemId]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItemReference_Queue]...';


GO
ALTER TABLE [dbo].[ATWorkItemReference]
    ADD CONSTRAINT [ATWorkItemReference_Queue] FOREIGN KEY ([QueueId]) REFERENCES [dbo].[ATQueue] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItemReference_SourceQueue]...';


GO
ALTER TABLE [dbo].[ATWorkItemReference]
    ADD CONSTRAINT [ATWorkItemReference_SourceQueue] FOREIGN KEY ([SourceQueueId]) REFERENCES [dbo].[ATQueue] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItemReference_SourceUser_ATUser]...';


GO
ALTER TABLE [dbo].[ATWorkItemReference]
    ADD CONSTRAINT [ATWorkItemReference_SourceUser_ATUser] FOREIGN KEY ([SourceUser]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItemReference_AssignTo_ATUser]...';


GO
ALTER TABLE [dbo].[ATWorkItemReference]
    ADD CONSTRAINT [ATWorkItemReference_AssignTo_ATUser] FOREIGN KEY ([AssignedTo]) REFERENCES [dbo].[ATUser] ([UserName]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItemReference_ATEventDefinition]...';


GO
ALTER TABLE [dbo].[ATWorkItemReference]
    ADD CONSTRAINT [ATWorkItemReference_ATEventDefinition] FOREIGN KEY ([EventID]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[ATWorkItemReference_ATEventDefinition_Successor]...';


GO
ALTER TABLE [dbo].[ATWorkItemReference]
    ADD CONSTRAINT [ATWorkItemReference_ATEventDefinition_Successor] FOREIGN KEY ([Successor]) REFERENCES [dbo].[ATEventDefinition] ([EventID]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATXmlHierarchyDefinition_ParentId]...';


GO
ALTER TABLE [dbo].[ATXmlHierarchyDefinition]
    ADD CONSTRAINT [FK_ATXmlHierarchyDefinition_ParentId] FOREIGN KEY ([ParentId]) REFERENCES [dbo].[ATXmlHierarchyDefinition] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATXmlHierarchyDefinition_HierarchId]...';


GO
ALTER TABLE [dbo].[ATXmlHierarchyDefinition]
    ADD CONSTRAINT [FK_ATXmlHierarchyDefinition_HierarchId] FOREIGN KEY ([HierarchId]) REFERENCES [dbo].[ATXmlHierarchy] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATXmlTemplateDef_TemplateId]...';


GO
ALTER TABLE [dbo].[ATXmlTemplateDefinition]
    ADD CONSTRAINT [FK_ATXmlTemplateDef_TemplateId] FOREIGN KEY ([TemplateId]) REFERENCES [dbo].[ATTemplates] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATXmlTemplateDef_FieldSourceId]...';


GO
ALTER TABLE [dbo].[ATXmlTemplateDefinition]
    ADD CONSTRAINT [FK_ATXmlTemplateDef_FieldSourceId] FOREIGN KEY ([FieldSourceId]) REFERENCES [dbo].[ATExportType] ([Id]);


GO
PRINT N'Creating Foreign Key [dbo].[FK_ATXmlTemplateDef_XmlParentId]...';


GO
ALTER TABLE [dbo].[ATXmlTemplateDefinition]
    ADD CONSTRAINT [FK_ATXmlTemplateDef_XmlParentId] FOREIGN KEY ([XmlParentId]) REFERENCES [dbo].[ATXmlHierarchyDefinition] ([Id]) ON DELETE SET NULL;


GO
PRINT N'Creating Check Constraint [dbo].[CK_ATFieldDefinition_DataType_AllowedValues]...';


GO
ALTER TABLE [dbo].[ATFieldDefinition]
    ADD CONSTRAINT [CK_ATFieldDefinition_DataType_AllowedValues] CHECK ([DataType] IN (1, /*Number*/ 5 /*String*/, 6 /*Date*/, 7 /*Option*/));


GO
PRINT N'Creating Check Constraint [dbo].[CK_ATFieldDefinition_Option_InitialValue]...';


GO
ALTER TABLE [dbo].[ATFieldDefinition]
    ADD CONSTRAINT [CK_ATFieldDefinition_Option_InitialValue] CHECK ([DataType] <> 7 OR [InitialValue] IS NOT NULL);


GO
PRINT N'Creating Check Constraint [dbo].[CK_ATMail_Priority]...';


GO
ALTER TABLE [dbo].[ATMail]
    ADD CONSTRAINT [CK_ATMail_Priority] CHECK ([Priority] BETWEEN 0 AND 2);


GO
PRINT N'Creating Check Constraint [dbo].[CK_ATTimer_ValueType]...';


GO
ALTER TABLE [dbo].[ATTimer]
    ADD CONSTRAINT [CK_ATTimer_ValueType] CHECK ([ValueType] IN ('Minutes', 'Hours', 'Days', 'Months', 'Years'));


GO
PRINT N'Creating Check Constraint unnamed constraint on [dbo].[ATXmlHierarchyDefinition]...';


GO
ALTER TABLE [dbo].[ATXmlHierarchyDefinition]
    ADD CHECK ([Level] BETWEEN 1 AND 20);


GO
PRINT N'Creating Trigger [dbo].[ATDocumentCabinetModifiedDate]...';


GO

CREATE TRIGGER ATDocumentCabinetModifiedDate
ON  [dbo].[ATDocumentCabinet]
FOR UPDATE
AS BEGIN
   UPDATE [dbo].[ATDocumentCabinet] SET [dbo].[ATDocumentCabinet].[ModifyDate] = GETDATE()
   FROM INSERTED
   WHERE inserted.[CabinetID]=[ATDocumentCabinet].[CabinetID]
END
GO
PRINT N'Creating Procedure [dbo].[get_next_id]...';


GO
create procedure [dbo].[get_next_id] @id_entry int, @in_trans smallint as     declare @next int     IF @in_trans = 0        begin transaction     update AtSystemparameter Set paramvalue=convert(char(32), convert(int, paramvalue)+1) where paramid = @id_entry     select @next=(select convert(int,paramvalue) from AtSystemparameter where paramid = @id_entry)     IF @next = 2147483647     BEGIN        update AtSystemparameter Set paramvalue=0 where paramid=@id_entry     END     select paramvalue from AtSystemparameter where paramid =@id_entry     IF @in_trans = 0        commit transaction     return 1
GO
PRINT N'Creating Procedure [dbo].[now]...';


GO
create procedure [dbo].[now] as     select getdate() from atsystemparameter where Paramname ='REVISION'     return 1
GO
USE [$(DatabaseName)]

GO
SET IDENTITY_INSERT [dbo].[ATConnectionType] ON;

MERGE [dbo].[ATConnectionType] AS Target
USING (VALUES 
    (1, 'Email Connection'),
    (2, 'Database Connection'),
    (3, 'Fax Connection'),
    (4, 'Webservices Connection'),
    (5, 'Active Directory Connection'),
    (6, 'Printer Connection'),
    (7, 'Production Tracking Database Connection'),
    (8, 'Repository Database Connection')
) AS Source (Id, Name)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET Name = Source.Name
WHEN NOT MATCHED THEN
    INSERT (Id, Name) VALUES (Source.Id, Source.Name)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATConnectionType] OFF;

GO
SET IDENTITY_INSERT ATRightObjectType ON;
MERGE ATRightObjectType AS Target
USING (VALUES 
    (0, 'System'),
    (1, 'Process'),
    (2, 'Queue'),
    (3, 'Button'),
    (4, 'FolderField'),
    (5, 'DocumentField'),
    (6, 'DocumentCabinet')
) AS Source (Id, Name)
ON Target.Id = Source.Id
WHEN NOT MATCHED THEN
    INSERT (Id, Name) VALUES (Source.Id, Source.Name);
SET IDENTITY_INSERT ATRightObjectType OFF;

GO
SET IDENTITY_INSERT [dbo].[ATTemplateType] ON;

MERGE [dbo].[ATTemplateType] AS Target
USING (VALUES
           (1, 'Document'),
           (2, 'Tracking'),
           (3, 'Repository'),
           (4, 'XML'),
           (5, 'DocumentExport'),
           (6, 'DocumentConversion'),
           (7, 'Trigger')
) AS Source (Id, Name)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET
        Target.Name = Source.Name
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name)
    VALUES (Source.Id, Source.Name)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATTemplateType] OFF;
GO

MERGE ATRightAllowRight AS Target
USING (VALUES 
    (0,   'TheSystem'),
    (1,   'ViewFolderField'),
    (2,   'EditFolderField'),
    (3,   'ViewFieldOrButton'),
    (4,   'ListWorkitems'),
    (5,   'ForwardWorkitems'),
    (10,  'ProcessUseTemplate'),
    (11,  'ViewDocField'),
    (12,  'EditDocField'),
    (13,  'ChangeDocumentTemplate'),
    (20,  'UseQueue'),
    (21,  'ViewButton'),
    (22,  'ClickButton'),
    (30,  'UseProcess'),
    (31,  'CreateWorkitem'),
    (32,  'AttachDocument'),
    (33,  'DeleteDocument'),
    (34,  'EditDocument'),
    (35,  'DownloadDocument'),
    (36,  'ViewTracking'),
    (37,  'AddNote'),
    (38,  'CloneWorkitems'),
    (251, 'AdminaProcess'),
    (252, 'Designer'),
    (253, 'iAdmin'),
    (254, 'RapidWorkPlace'),
    (255, 'AllApplications')
) AS Source (Id, Name)
ON Target.Id = Source.Id
WHEN NOT MATCHED THEN
    INSERT (Id, Name) VALUES (Source.Id, Source.Name);
GO
SET IDENTITY_INSERT [dbo].[ATDocumentCabinetFiledType] ON;

MERGE [dbo].[ATDocumentCabinetFiledType] AS Target
USING (VALUES
    (1, 'Boolean'),
    (2, 'Integer'),
    (3, 'Number'),
    (4, 'Date'),
    (5, 'String')
) AS Source (Id, Name)
ON Target.Id = Source.Id

WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name)
    VALUES (Source.Id, Source.Name)

WHEN MATCHED THEN
    UPDATE SET Target.Name = Source.Name

WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATDocumentCabinetFiledType] OFF;

GO

UPDATE ATDocumentCabinetDef
SET FieldDataTypeId = 
    CASE 
        WHEN FieldDataType = 'String' THEN 5
        WHEN FieldDataType = 'Integer' THEN 2
        WHEN FieldDataType = 'Date' THEN 4
        WHEN FieldDataType = 'Number' THEN 3
        ELSE FieldDataTypeId -- Keep the current value if no match
    END;

    SET IDENTITY_INSERT [dbo].[ATDocumenctReviewStatus] ON;

MERGE INTO [dbo].[ATDocumenctReviewStatus] AS target
USING (VALUES
    (1, 'Submitted'),
    (2, 'Draft'),
    (3, 'In process'),
    (4, 'Pending approval'),
    (5, 'Approved'),
    (6, 'Cancelled'),
    (7, 'Rejected'),
    (8, 'Withdrawn'),
    (9, 'Expired'),
    (10, 'Deleted')
) AS source ([Id], [Name])
ON target.[Id] = source.[Id]
WHEN MATCHED THEN
    UPDATE SET target.[Name] = source.[Name]
WHEN NOT MATCHED BY TARGET THEN
    INSERT ([Id], [Name])
    VALUES (source.[Id], source.[Name])
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATDocumenctReviewStatus] OFF;

SET IDENTITY_INSERT [dbo].[ATAssigmentType] ON;

MERGE INTO [dbo].[ATAssigmentType] AS target
USING (VALUES
    (0, N'NoneSelected'),
    (1, N'FolderField'),
    (2, N'SystemVariable'),
    (3, N'AssignedName')
) AS source ([Id], [Name])
ON target.[Id] = source.[Id]
WHEN MATCHED THEN
    UPDATE SET [Name] = source.[Name]
WHEN NOT MATCHED BY TARGET THEN
    INSERT ([Id], [Name]) VALUES (source.[Id], source.[Name]);

SET IDENTITY_INSERT [dbo].[ATAssigmentType] OFF;

SET IDENTITY_INSERT [dbo].[ATUserSystemVariable] ON;

MERGE INTO [dbo].[ATUserSystemVariable] AS target
USING (VALUES
    (1, 'creator'),
    (2, 'lastActionUser'),
    (3, 'lockedBy'),
    (4, 'sourceUser')
) AS source ([Id], [Name])
ON target.[Id] = source.[Id]
WHEN MATCHED THEN
    UPDATE SET target.[Name] = source.[Name]
WHEN NOT MATCHED THEN
    INSERT ([Id], [Name])
    VALUES (source.[Id], source.[Name]);

SET IDENTITY_INSERT [dbo].[ATUserSystemVariable] OFF;

GO
SET IDENTITY_INSERT [dbo].[ATEventType] ON;

MERGE INTO [dbo].[ATEventType] AS target
USING (VALUES
    (0, 'Start', 'Start'),
    (1, 'Stop', 'Stop'),
    (2, 'Queue', 'Queue'),
    (3, 'User', 'User'),
    (4, 'Tracking', 'Tracking'),
    (5, 'Print', 'Print'),
    (6, 'Mail', 'Mail'),
    (7, 'Server', 'Server'),
    (8, 'Decision', 'Decision'),
    (9, 'SQL', 'SQL'),
    (10, 'Code', 'Code'),
    (11, 'Timer', 'Timer'),
    (12, 'FAX', 'FAX'),
    (13, 'Set Data', 'SetData'),
    (14, 'Rule', 'Rule'),
    (15, 'Export', 'Export'),
    (16, 'CallSubProcess', 'CallSubProcess'),
    (17, 'Convert', 'Convert')
) AS source ([Id], [Description], [ShortName])
ON target.[Id] = source.[Id]
WHEN MATCHED THEN
    UPDATE SET 
        target.[Description] = source.[Description],
        target.[ShortName] = source.[ShortName]
WHEN NOT MATCHED BY TARGET THEN
    INSERT ([Id], [Description], [ShortName])
    VALUES (source.[Id], source.[Description], source.[ShortName])
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATEventType] OFF;
GO

DECLARE @DefaultConnectionId INT
SELECT TOP 1 @DefaultConnectionId = [Id] FROM [dbo].[ATConnection] WHERE [Type] = 0 ORDER BY [Id]

UPDATE [dbo].[ATMail]
SET [ConnectionId] = @DefaultConnectionId
WHERE [ConnectionId] IS NULL;

SET IDENTITY_INSERT [dbo].[ATImportDocumentType] ON;

MERGE [dbo].[ATImportDocumentType] AS Target
USING (VALUES
    (1,  'pdf',  'Portable Document Format', 1),
    (2,  'xml',  'Extensible Markup Language', 1),
    (3,  'doc',  'Microsoft Word 97-2003 Document', 0),
    (4,  'docx', 'Microsoft Word Document', 1),
    (5,  'docm', 'Microsoft Word Macro-Enabled Document', 0),
    (6,  'rtf',  'Rich Text Format', 0),
    (7,  'txt',  'Plain Text File', 0),
    (8,  'md',   'Markdown File', 0),
    (9,  'html', 'HyperText Markup Language', 1),
    (10, 'xls',  'Microsoft Excel 97-2003 Spreadsheet', 0),
    (11, 'xlsx', 'Microsoft Excel Spreadsheet', 0),
    (12, 'pptx', 'Microsoft PowerPoint Presentation', 0),
    (13, 'jpg',  'JPEG Image', 1),
    (14, 'jpeg', 'JPEG Image', 1),
    (15, 'png',  'Portable Network Graphics Image', 1),
    (16, 'bmp',  'Bitmap Image', 0),
    (17, 'gif',  'Graphics Interchange Format Image', 0),
    (18, 'tif',  'Tagged Image File Format', 1),
    (19, 'tiff', 'Tagged Image File Format', 1)
) AS Source (Id, TypeName, Description, Convertible)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET 
        Target.TypeName = Source.TypeName,
        Target.Description = Source.Description,
        Target.Convertible = Source.Convertible
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, TypeName, Description, Convertible) 
    VALUES (Source.Id, Source.TypeName, Source.Description, Source.Convertible)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATImportDocumentType] OFF;


SET IDENTITY_INSERT [dbo].[ATBarcodeFont] ON;

MERGE [dbo].[ATBarcodeFont] AS Target
USING (
    VALUES
        (1, 'Libre Barccode128', 'LibreBarcode128-Regular.ttf - Standard Code 128 barcode font'),
        (2, '3 of 9 Barcode', 'LibreBarcode39-Regular.ttf / 3OF9.TTF - Standard Code 39 barcode font'),
        (3, 'Code 2 of 5 intervaled', 'code25I.ttf - Interleaved 2 of 5 (ITF) numeric-only barcode font'),
        (4, 'CodabarMedium', 'CodabarMedium.ttf - Codabar barcode font, often used in libraries or medical'),
        (5, 'CodabarLarge', 'CodabarLarge.ttf - Codabar barcode font, often used in libraries or medical'),
        (6, 'EAN13', 'LibreBarcodeEAN13Text-Regular.ttf - EAN-13 font for retail product labels')
) AS Source (Id, Name, Description)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET
        Target.Name = Source.Name,
        Target.Description = Source.Description
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name, Description)
    VALUES (Source.Id, Source.Name, Source.Description)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATBarcodeFont] OFF;
GO

SET IDENTITY_INSERT [dbo].[ATMergeOrder] ON;

MERGE [dbo].[ATMergeOrder] AS Target
USING (VALUES
    (1, 'Document Name Asc',  'Merge documents by name in ascending order'),
    (2, 'Document Name Desc', 'Merge documents by name in descending order'),
    (3, 'Document Order Asc', 'Merge documents by assigned order ascending'),
    (4, 'Document Order Desc','Merge documents by assigned order descending')
) AS Source (Id, Name, Description)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET 
        Target.Name = Source.Name,
        Target.Description = Source.Description
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name, Description)
    VALUES (Source.Id, Source.Name, Source.Description)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATMergeOrder] OFF;
GO

SET IDENTITY_INSERT [dbo].[ATExportFlagTxt] ON;

MERGE [dbo].[ATExportFlagTxt] AS Target
USING (VALUES
    (1, 'done.txt', 'Indicates export completion')
) AS Source (Id, Name, Description)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET
        Target.Name = Source.Name,
        Target.Description = Source.Description
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name, Description)
    VALUES (Source.Id, Source.Name, Source.Description)
 WHEN NOT MATCHED BY SOURCE THEN
     DELETE;

SET IDENTITY_INSERT [dbo].[ATExportFlagTxt] OFF;
GO

SET IDENTITY_INSERT [dbo].[ATExportType] ON;

MERGE [dbo].[ATExportType] AS Target
USING (VALUES
    (1, 'Documents', 'Exports document files only'),
    (2, 'Fields',    'Exports fields from document and folder definitions')
) AS Source (Id, Name, Description)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET
        Target.Name = Source.Name,
        Target.Description = Source.Description
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name, Description)
    VALUES (Source.Id, Source.Name, Source.Description)
 WHEN NOT MATCHED BY SOURCE THEN
     DELETE;

SET IDENTITY_INSERT [dbo].[ATExportType] OFF;
GO

SET IDENTITY_INSERT [dbo].[ATExternalTrackingSourceType] ON;

MERGE [dbo].[ATExternalTrackingSourceType] AS Target
USING (VALUES
           (1, 'PDSystemValue'),
           (2, 'FolderField'),
           (3, 'TextEntry')
) AS Source (Id, Name)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET
        Target.Name = Source.Name
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name)
    VALUES (Source.Id, Source.Name)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATExternalTrackingSourceType] OFF;
GO

SET IDENTITY_INSERT [dbo].[ATTriggerHook] ON;

MERGE [dbo].[ATTriggerHook] AS Target
USING (VALUES
           (1, N'OnArrival'),
           (2, N'OnError'),
           (3, N'OnOpenWorkItem'),
           (4, N'OnForwardWorkItem'),
           (5, N'OnCloseWorkItem'),
           (6, N'OnExpireWorkItem')
) AS Source (Id, Name)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET Target.Name = Source.Name
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name) VALUES (Source.Id, Source.Name)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATTriggerHook] OFF;
GO

SET IDENTITY_INSERT [dbo].[ATTriggerAction] ON;

MERGE [dbo].[ATTriggerAction] AS Target
USING (VALUES
           (1, N'SendEmail'),
           (2, N'SendToEvent'),
           (3, N'SentToProcess'),
           (4, N'RunSqlQueryWithResultInFolderField'),
           (5, N'RunCustomScript')
) AS Source (Id, Name)
ON Target.Id = Source.Id
WHEN MATCHED THEN
    UPDATE SET Target.Name = Source.Name
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Id, Name) VALUES (Source.Id, Source.Name)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

SET IDENTITY_INSERT [dbo].[ATTriggerAction] OFF;
GO

IF NOT EXISTS (
    SELECT 1
    FROM [dbo].[ATDocumentCabinet]
    WHERE [CabinetName] = N'DefaultTemplate'
)
BEGIN
    INSERT INTO [dbo].[ATDocumentCabinet] (
        [CabinetName],
        [CabinetDescription],
        [TemplateTypeId],
        [DbConnectionId],
        [DbName],
        [ObjectId],
        [CreateDate],
        [ModifyDate]
    )
    VALUES (
        N'DefaultTemplate',
        N'This is a DefaultTemplate',
        1,
        NULL,
        NULL,
        NEWID(),
        GETDATE(),
        GETDATE()
        );
END
GO

MERGE INTO [dbo].[ATSearchTypeDefinition] AS target
USING (VALUES
    (N'Tracking'),
    (N'User'),
    (N'UserGroup'),
    (N'Document'),
    (N'Folder'),
    (N'Other')
) AS source ([TypeName])
ON target.[TypeName] = source.[TypeName]
WHEN NOT MATCHED BY TARGET THEN
    INSERT ([TypeName]) VALUES (source.[TypeName]);
GO

DECLARE @SystemGuid UNIQUEIDENTIFIER = NULL;

SELECT @SystemGuid = [Guid]
FROM [dbo].[ATSystem]
WHERE [ApplicationName] = N'Process Director';

IF @SystemGuid IS NULL
BEGIN
    BEGIN TRY
        BEGIN TRANSACTION;

        BEGIN
            SET @SystemGuid = NEWID();

            INSERT INTO [dbo].[ATSystem] (
                [Guid],
                [ApplicationName],
                [TrackingTableName],
                [Link],
                [LinkType]
            )
            VALUES (
                @SystemGuid,
                N'Process Director',
                N'ATTrackingRecord',
                NULL,
                NULL
            );
        END;

        MERGE INTO [dbo].[ATUser] AS target
        USING (VALUES
                   (N'PDAdminGroup',    NEWID(), N'PD Administrator Group', 3, 2, N'System PD Administrator', 0, NULL),
                   (N'PDUserGroup',     NEWID(), N'PD User Group',          3, 2, N'System PD User Group',    0, NULL),
                   (N'PDDesignerGroup', NEWID(), N'PD Designer Group',      3, 2, N'System PD Designer',      0, NULL),
                   (N'IAdminGroup',     NEWID(), N'IAdmin Group',           3, 2, N'System IAdmin',           0, NULL),
                   (N'PDAdmin',         NEWID(), N'PD Admin',               3, 1, N'PD Admin',                0, NULL)
        ) AS source (
                     [UserName],
                     [ObjectId],
                     [DisplayName],
                     [UserStore],
                     [Type],
                     [Description],
                     [Status],
                     [ADDomain]
            )
        ON target.[UserName] = source.[UserName]
        WHEN MATCHED THEN
            UPDATE SET
                       target.[DisplayName] = source.[DisplayName],
                       target.[UserStore]   = source.[UserStore],
                       target.[Type]        = source.[Type],
                       target.[Description] = source.[Description],
                       target.[Status]      = source.[Status]
        WHEN NOT MATCHED BY TARGET THEN
            INSERT ([UserName], [ObjectId], [DisplayName], [UserStore], [Type], [Description], [Status], [ADDomain])
            VALUES (source.[UserName], source.[ObjectId], source.[DisplayName], source.[UserStore], source.[Type], source.[Description], source.[Status], source.[ADDomain]);

        DECLARE @PDAdminGroupGuid UNIQUEIDENTIFIER;
        DECLARE @PDUserGroupGuid UNIQUEIDENTIFIER;
        DECLARE @PDDesignerGroupGuid UNIQUEIDENTIFIER;
        DECLARE @IAdminGroupGuid UNIQUEIDENTIFIER;
        DECLARE @PDAdminGuid UNIQUEIDENTIFIER;

        SELECT @PDAdminGroupGuid = [ObjectId] FROM [dbo].[ATUser] WHERE [UserName] = N'PDAdminGroup';
        SELECT @PDUserGroupGuid = [ObjectId] FROM [dbo].[ATUser] WHERE [UserName] = N'PDUserGroup';
        SELECT @PDDesignerGroupGuid = [ObjectId] FROM [dbo].[ATUser] WHERE [UserName] = N'PDDesignerGroup';
        SELECT @IAdminGroupGuid = [ObjectId] FROM [dbo].[ATUser] WHERE [UserName] = N'IAdminGroup';
        SELECT @PDAdminGuid = [ObjectId] FROM [dbo].[ATUser] WHERE [UserName] = N'PDAdmin';

        MERGE INTO [dbo].[ATUserGroup] AS target
        USING (VALUES
                   (@PDAdminGuid, @PDAdminGroupGuid),
                   (@PDAdminGuid, @PDUserGroupGuid),
                   (@PDAdminGuid, @PDDesignerGroupGuid),
                   (@PDAdminGuid, @IAdminGroupGuid)
        ) AS source ([ObjectId], [ParentId])
        ON target.[ObjectId] = source.[ObjectId] AND target.[ParentId] = source.[ParentId]
        WHEN NOT MATCHED BY TARGET THEN
            INSERT ([ObjectId], [ParentId])
            VALUES (source.[ObjectId], source.[ParentId]);

        IF NOT EXISTS (
            SELECT 1 FROM [dbo].[ATRight]
            WHERE [ObjectGuid] = @SystemGuid
        )
        BEGIN
            INSERT INTO [dbo].[ATRight] ([UserGuid], [ObjectType], [AllowRights], [ObjectGuid])
            VALUES
                (@PDUserGroupGuid, 0, 254, @SystemGuid),
                (@PDAdminGroupGuid, 0, 252, @SystemGuid),
                (@PDAdminGroupGuid, 0, 253, @SystemGuid),
                (@PDAdminGroupGuid, 0, 255, @SystemGuid),
                (@PDDesignerGroupGuid, 0, 252, @SystemGuid),
                (@IAdminGroupGuid, 0, 253, @SystemGuid);
        END;

        IF NOT EXISTS (
            SELECT 1 FROM [dbo].[ATUserProperty]
            WHERE [UserName] = N'PDAdmin' AND [PropertyName] = N'Password'
        )
        BEGIN
            INSERT INTO [dbo].[ATUserProperty] ([UserName], [PropertyName], [PropertyValue])
            VALUES (N'PDAdmin', N'Password', N'4cb9c8a8048fd02294477fcb1a41191a');
        END;

        IF NOT EXISTS (
            SELECT 1 FROM [dbo].[ATReport]
        )
        BEGIN
            INSERT INTO [dbo].[ATReport] ([Name], [Description], [SqlCode], [IsActive])
            VALUES (N'Users List', N'Lists the users currently registered in the Process Director system.', N'SELECT * FROM ATUser', 1);
        END;

        MERGE INTO [dbo].[ATSystemParameter] AS target
        USING (VALUES
            (1,   N'NextEventID',                         N'5'),
            (8,   N'LockTest',                            N'TEST1'),
            (16,  N'DocumentID',                          N'5793'),
            (17,  N'LabelID',                             N'46'),
            (99,  N'Created',                             N'7/13/2018 12:10:01 PM'),
            (100, N'REVISION',                            N'40064'),
            (23,  N'NextReportId',                        N'7'),
            (102, N'ConfigFilePath',                      N'C:\Program Files\Process Director\Bin\config.xml'),
            (103, N'FileUploadPath',                      N'C:\Program Files\Process Director\Bin\UPLOAD'),
            (104, N'ServerLogMaxSizeInMB',                N'5'),
            (1001,N'SystemGuid',                          N'{AD673351-36C3-46EF-B668-0475461C6C68}'),
            (201, N'SchedulerLogfilepath',                N'C:\PROGRAM FILES\PROCESS DIRECTOR\Logs\CPMScheduler.log'),
            (202, N'SchedulerEnterpriseDsn',              N'Intellectus_Enterprise'),
            (203, N'SchedulerProcessDirectorDsn',         N'PD2012'),
            (204, N'SchedulerContentDirectorDsn',         N'CDDATABASE'),
            (205, N'SchedulerEnterpriseURL',              N'http://iws4pd2015.intellectus.com/enterprise.asmx'),
            (206, N'SchedulerProcessDirectorURL',         N'http://iws4pd2015.intellectus.com.com/processdirector.asmx'),
            (207, N'SchedulerUserID',                     N'DefaultPDScheduler'),
            (208, N'SchedulerPassword',                   N'W+(Ö°'),
            (209, N'SchedulerLogLevel',                   N'2'),
            (105, N'AD.Path',                             N''),
            (106, N'AD.DomainName',                       N''),
            (107, N'AD.UserName',                         N''),
            (108, N'AD.Password',                         N''),
            (109, N'AD.UserContainer',                    N''),
            (110, N'AD.Available',                        N'False'),
            (210, N'SchedulerEnterpriseUserName',         N'sa'),
            (211, N'SchedulerEnterprisePassword',         N'Bºê‡âæÏz'),
            (212, N'SchedulerProcessDirectorUserName',    N'sa'),
            (213, N'SchedulerProcessDirectorPassword',    N'Bºê‡âæÏz'),
            (214, N'SchedulerContentDirectorUserName',    N'sa'),
            (215, N'SchedulerContentDirectorPassword',    N'Bºê‡âæÏz'),
            (216, N'SchedulerEnterpriseServer',           N'idb\idb'),
            (217, N'SchedulerProcessDirectorServer',      N'IDB\IDB'),
            (218, N'SchedulerContentDirectorServer',      N'idb\idb'),
            (301, N'PrintableFileExtension',              N''),
            (219, N'SchedulerEnterpriseConnectionName',   N'Process Director'),
            (1002,N'DefaultPassword',                     N'4cb9c8a8048fd02294477fcb1a41191a'),
            (27,  N'SupportEmailAddress',                 N'helpdesk@intellectus.com'),
            (28,  N'RapidURL',                            N'http://workplace.intellectus.com'),
            (220, N'SchedulerDomain',                     N''),
            (221, N'SchedulerWorkplaceDsn',               N'Workplace'),
            (222, N'SchedulerWorkplaceServer',            N'idb\idb'),
            (223, N'SchedulerWorkplaceUserName',          N'sa'),
            (224, N'SchedulerWorkplacePassword',          N'iCorp@10'),
            (226, N'SchedulerContentDirectorURL',         N'http://cd2015.intellectus.com'),
            (29,  N'NextFieldId',                         N'2917'),
            (227, N'HelpURL',                             N''),
            (1003,N'HomePage',                            N'1')
        ) AS source ([ParamID], [ParamName], [ParamValue])
        ON target.[ParamID] = source.[ParamID]
        WHEN MATCHED THEN
            UPDATE SET
                target.[ParamName]  = source.[ParamName],
                target.[ParamValue] = source.[ParamValue]
        WHEN NOT MATCHED BY TARGET THEN
            INSERT ([ParamID], [ParamName], [ParamValue])
            VALUES (source.[ParamID], source.[ParamName], source.[ParamValue]);

        COMMIT TRANSACTION;
        PRINT 'Process Director initialization completed successfully.';
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        PRINT 'Error during Process Director initialization:';
        PRINT ERROR_MESSAGE();
    END CATCH;
END
ELSE
BEGIN
    PRINT 'No Process Director system record found in ATSystem. Skipping initialization.';
END;
GO

MERGE INTO [dbo].[ATScheduleStatusType] AS target
USING (VALUES
    (1, 'Pending'),
    (2, 'Running'),
    (3, 'Completed'),
    (4, 'Failed')
) AS source ([StatusId], [StatusName])
ON target.[StatusId] = source.[StatusId]
WHEN MATCHED THEN
    UPDATE SET target.[StatusName] = source.[StatusName]
WHEN NOT MATCHED THEN
    INSERT ([StatusId], [StatusName]) VALUES (source.[StatusId], source.[StatusName]);
GO

SET IDENTITY_INSERT [dbo].[ATRunStatusType] ON;
MERGE INTO [dbo].[ATRunStatusType] AS target
USING (VALUES
    (1, 'Success'),
    (2, 'Failed'),
    (3, 'Skipped')
) AS source ([StatusId], [StatusName])
ON target.[StatusId] = source.[StatusId]
WHEN MATCHED THEN
    UPDATE SET target.[StatusName] = source.[StatusName]
WHEN NOT MATCHED THEN
    INSERT ([StatusId], [StatusName]) VALUES (source.[StatusId], source.[StatusName]);
SET IDENTITY_INSERT [dbo].[ATRunStatusType] OFF;
GO

SET IDENTITY_INSERT [dbo].[ATScheduleType] ON;
MERGE INTO [dbo].[ATScheduleType] AS target
USING (VALUES
    (1, 'OneTime'),
    (2, 'Recurring')
) AS source ([ScheduleTypeId], [ScheduleTypeName])
ON target.[ScheduleTypeId] = source.[ScheduleTypeId]
WHEN MATCHED THEN
    UPDATE SET target.[ScheduleTypeName] = source.[ScheduleTypeName]
WHEN NOT MATCHED THEN
    INSERT ([ScheduleTypeId], [ScheduleTypeName])
    VALUES (source.[ScheduleTypeId], source.[ScheduleTypeName]);
SET IDENTITY_INSERT [dbo].[ATScheduleType] OFF;
GO

SET IDENTITY_INSERT [dbo].[ATTaskType] ON;
MERGE INTO [dbo].[ATTaskType] AS target
USING (VALUES
    (1, 'FileExecute',    'Executes a file or script on the server (EXE, BAT, PowerShell).'),
    (2, 'SqlScript',      'Runs a SQL script or stored procedure.'),
    (3, 'Email',          'Sends an email notification or report.'),
    (4, 'Unknown',        'Unknown')
) AS source ([TaskTypeId], [TaskTypeName], [Description])
ON target.[TaskTypeId] = source.[TaskTypeId]
WHEN MATCHED THEN
    UPDATE SET target.[TaskTypeName] = source.[TaskTypeName], target.[Description] = source.[Description]
WHEN NOT MATCHED THEN
    INSERT ([TaskTypeId], [TaskTypeName], [Description])
    VALUES (source.[TaskTypeId], source.[TaskTypeName], source.[Description]);
SET IDENTITY_INSERT [dbo].[ATTaskType] OFF;
GO

IF NOT EXISTS (
    SELECT 1 FROM sys.indexes 
    WHERE name = 'UQ_ATTemplates_ProcessCabinetType' 
      AND object_id = OBJECT_ID('dbo.ATTemplates')
)
BEGIN
    PRINT 'Creating filtered index: UQ_ATTemplates_ProcessCabinetType';
    CREATE UNIQUE INDEX [UQ_ATTemplates_ProcessCabinetType]
    ON [dbo].[ATTemplates] ([ProcessId], [DocumentCabinetId], [TemplateTypeId])
    WHERE [TemplateTypeId] <> 7;
END
GO

SET IDENTITY_INSERT [dbo].[ATTaskActionType] ON;
MERGE INTO [dbo].[ATTaskActionType] AS target
USING (VALUES
    (1, 'Next', 'Continue to next task'),
    (2, 'Retry', 'Retry this task once'),
    (3, 'Stop', 'Stop the whole schedule'),
    (4, 'Notify', 'Send email notification'),
    (5, 'Skip', 'Skip this task')
) AS source ([ActionId], [ActionName], [Description])
ON target.[ActionId] = source.[ActionId]
WHEN MATCHED THEN
    UPDATE SET target.[ActionName] = source.[ActionName], target.[Description] = source.[Description]
WHEN NOT MATCHED THEN
    INSERT ([ActionId], [ActionName], [Description])
    VALUES (source.[ActionId], source.[ActionName], source.[Description]);
SET IDENTITY_INSERT [dbo].[ATTaskActionType] OFF;
GO

GO
DECLARE @VarDecimalSupported AS BIT;

SELECT @VarDecimalSupported = 0;

IF ((ServerProperty(N'EngineEdition') = 3)
    AND (((@@microsoftversion / power(2, 24) = 9)
          AND (@@microsoftversion & 0xffff >= 3024))
         OR ((@@microsoftversion / power(2, 24) = 10)
             AND (@@microsoftversion & 0xffff >= 1600))))
    SELECT @VarDecimalSupported = 1;

IF (@VarDecimalSupported > 0)
    BEGIN
        EXECUTE sp_db_vardecimal_storage_format N'$(DatabaseName)', 'ON';
    END


GO
PRINT N'Update complete.';


GO
