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 DEFAULT (NEWID()),
    [CreateDate] DATETIME NOT NULL DEFAULT (GETDATE()),
    [ModifyDate] DATETIME NOT NULL DEFAULT (GETDATE()),
    [HierarchyId] INT NULL,

    CONSTRAINT [PK_ATTemplates] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UK_ATTemplates_ObjectId] UNIQUE ([ObjectId]),
    
    CONSTRAINT [FK_ATTemplates_ProcessId] FOREIGN KEY ([ProcessId]) 
        REFERENCES [dbo].[ATProcessDefinition] ([ProcessId]),

    CONSTRAINT [FK_ATTemplates_DocumentCabinetId] FOREIGN KEY ([DocumentCabinetId]) 
        REFERENCES [dbo].[ATDocumentCabinet] ([CabinetId]),

    CONSTRAINT [FK_ATTemplates_TemplateTypeId] FOREIGN KEY ([TemplateTypeId]) 
        REFERENCES [dbo].[ATTemplateType] ([Id]),

    CONSTRAINT [FK_ATTemplates_DbConnectionId] FOREIGN KEY ([DbConnectionId]) 
        REFERENCES [dbo].[ATConnection] ([Id]),

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

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

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