-- SCHEMA: dbo

---------------------------------------------
--  TABLES
---------------------------------------------


---------------------------------------------
-- dbo.AMAssumptionView ------------------
---------------------------------------------
CREATE TABLE [dbo].[AMAssumptionView] (
    [AssumptionViewGUID] uniqueidentifier NOT NULL,
    [AssumptionGroupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [ColumnWidths] varchar(8000) NOT NULL,
    [AssumptionJoinDataGUID] uniqueidentifier NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [IsDistributionModeActive] bit NOT NULL,
    [DistributionInfo] xml NOT NULL,
    [ProviderGUID] uniqueidentifier NOT NULL,
    [CreatedDate] datetime NOT NULL,
    [CreatedBy] uniqueidentifier NOT NULL,
    [LastUsedDate] datetime NOT NULL,
    PRIMARY KEY ([AssumptionViewGUID])
);
GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_CreatedBy] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CreatedBy]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_LastUsedDate] DEFAULT (getdate()) FOR [LastUsedDate]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_Table_1_AssumptionViewGUID] DEFAULT (newid()) FOR [AssumptionViewGUID]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ASSUMPTIONGROUPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionGroupGUID]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_COLUMNWIDTHS] DEFAULT ('') FOR [ColumnWidths]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ASSUMPTIONCUBEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionJoinDataGUID]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ISDISTRIBUTIONMODEACTIVE] DEFAULT ((0)) FOR [IsDistributionModeActive]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_DISTRIBUTIONINFOXML] DEFAULT ('') FOR [DistributionInfo]; GO
ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_PROVIDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.AMCalculatedColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[AMCalculatedColumn] (
    [CalculatedColumnGUID] uniqueidentifier NOT NULL,
    [AssumptionViewGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [ColumnBase] nvarchar(4000) NOT NULL,
    [ColumnCompare] nvarchar(4000) NOT NULL,
    [Type] int NOT NULL,
    [IsEditable] bit NOT NULL,
    [Position] int NOT NULL,
    PRIMARY KEY ([CalculatedColumnGUID])
);
GO
ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_CALCULATEDCOLUMNGUID] DEFAULT (newid()) FOR [CalculatedColumnGUID]; GO
ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionViewGUID]; GO
ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_COLUMNBASE] DEFAULT ('') FOR [ColumnBase]; GO
ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_ISEDITABLE] DEFAULT ((0)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_POSITION] DEFAULT ((0)) FOR [Position]; GO

---------------------------------------------

---------------------------------------------
-- dbo.AMCorrelationGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[AMCorrelationGroup] (
    [CorrelationGroupGUID] uniqueidentifier NOT NULL,
    [AssumptionGroupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [IsGlobal] bit NOT NULL,
    [MembersXML] xml NOT NULL,
    PRIMARY KEY ([CorrelationGroupGUID])
);
GO
ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_CorrelationGroupGUID] DEFAULT (newid()) FOR [CorrelationGroupGUID]; GO
ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_AssumptionGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionGroupGUID]; GO
ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_IsGlobal] DEFAULT ((0)) FOR [IsGlobal]; GO
ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_MembersXML] DEFAULT ('') FOR [MembersXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.AMDimensionLevelBinding ------------------
---------------------------------------------
CREATE TABLE [dbo].[AMDimensionLevelBinding] (
    [DimensionLevelBindingGUID] uniqueidentifier NOT NULL,
    [DimensionSetupGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [LevelName] nvarchar(450) NOT NULL,
    [LevelIndex] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    [IsBound] bit NOT NULL,
    PRIMARY KEY ([DimensionLevelBindingGUID])
);
GO
ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [FK_AMDimensionLevelBinding_AMDimensionSetup] FOREIGN KEY ([DimensionSetupGUID]) REFERENCES [dbo].[AMDimensionSetup] ([DimensionSetupGUID]); GO
ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_DIMENSIONLEVELBINDINGGUID] DEFAULT (newid()) FOR [DimensionLevelBindingGUID]; GO
ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionSetupGUID]; GO
ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_DIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_LEVELNAME] DEFAULT ('') FOR [LevelName]; GO
ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_LEVELINDEX] DEFAULT ((0)) FOR [LevelIndex]; GO
ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_ISBOUND] DEFAULT ((0)) FOR [IsBound]; GO

---------------------------------------------

---------------------------------------------
-- dbo.AMDimensionSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[AMDimensionSetup] (
    [DimensionSetupGUID] uniqueidentifier NOT NULL,
    [AssumptionViewGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [DimensionName] nvarchar(450) NOT NULL,
    [IsFiltered] bit NOT NULL,
    [IsRequired] bit NOT NULL,
    [DisplayType] int NOT NULL,
    [IsFilterOnLoad] bit NOT NULL,
    PRIMARY KEY ([DimensionSetupGUID])
);

CREATE CLUSTERED INDEX [IX_AMDimensionSetup] ON [dbo].[AMDimensionSetup] ([AssumptionViewGUID]);
GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [FK_AMDimensionSetup_AMAssumptionView] FOREIGN KEY ([AssumptionViewGUID]) REFERENCES [dbo].[AMAssumptionView] ([AssumptionViewGUID]); GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_IsFilterOnLoad] DEFAULT ((0)) FOR [IsFilterOnLoad]; GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_DIMENSIONSETUPGUID] DEFAULT (newid()) FOR [DimensionSetupGUID]; GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionViewGUID]; GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_DIMENSIONID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_DIMENSIONNAME] DEFAULT ('') FOR [DimensionName]; GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_ISFILTERED] DEFAULT ((0)) FOR [IsFiltered]; GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_ISREQUIRED] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_DISPLAYTYPE] DEFAULT ((0)) FOR [DisplayType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.AMGridSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[AMGridSetting] (
    [GridSettingGUID] uniqueidentifier NOT NULL,
    [AssumptionViewGUID] uniqueidentifier NOT NULL,
    [Size] int NOT NULL,
    [SettingType] int NOT NULL,
    [FieldKey] nvarchar(4000) NOT NULL,
    [IsVisible] bit NOT NULL,
    PRIMARY KEY ([GridSettingGUID])
);

CREATE CLUSTERED INDEX [IX_AMGridSetting] ON [dbo].[AMGridSetting] ([AssumptionViewGUID]);
GO
ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [FK_AMGridSetting_AMAssumptionView] FOREIGN KEY ([AssumptionViewGUID]) REFERENCES [dbo].[AMAssumptionView] ([AssumptionViewGUID]); GO
ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_GRIDSETTINGGUID] DEFAULT (newid()) FOR [GridSettingGUID]; GO
ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionViewGUID]; GO
ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_COLUMNWIDTH] DEFAULT ((100)) FOR [Size]; GO
ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_SETTINGTYPE] DEFAULT ((0)) FOR [SettingType]; GO
ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_KEY] DEFAULT ('') FOR [FieldKey]; GO
ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_ISVISIBLE] DEFAULT ((1)) FOR [IsVisible]; GO

---------------------------------------------

---------------------------------------------
-- dbo.AMIncludedMember ------------------
---------------------------------------------
CREATE TABLE [dbo].[AMIncludedMember] (
    [IncludedMemberGUID] uniqueidentifier NOT NULL,
    [DimensionMemberID] nvarchar(450) NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [DimensionSetupGUID] uniqueidentifier NOT NULL,
    [IsDataMember] bit NOT NULL,
    [ParentIncludedMemberGUID] uniqueidentifier NOT NULL,
    [OutlineLevel] int NOT NULL,
    PRIMARY KEY ([IncludedMemberGUID])
);

CREATE CLUSTERED INDEX [IX_AMIncludedMember] ON [dbo].[AMIncludedMember] ([DimensionSetupGUID]);
GO
ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [FK_AMIncludedMember_AMDimensionSetup1] FOREIGN KEY ([DimensionSetupGUID]) REFERENCES [dbo].[AMDimensionSetup] ([DimensionSetupGUID]); GO
ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_INCLUDEDMEMBERGUID] DEFAULT (newid()) FOR [IncludedMemberGUID]; GO
ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_MEMBERID] DEFAULT ('') FOR [DimensionMemberID]; GO
ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_DIMENSIONSETUPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionSetupGUID]; GO
ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_ISDATAMEMBER] DEFAULT ((0)) FOR [IsDataMember]; GO
ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_PARENTINCLUDEDMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentIncludedMemberGUID]; GO
ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_OUTLINELEVEL] DEFAULT ((-1)) FOR [OutlineLevel]; GO

---------------------------------------------

---------------------------------------------
-- dbo.AMMultiEditGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[AMMultiEditGroup] (
    [MultiEditGroupGUID] uniqueidentifier NOT NULL,
    [AssumptionViewGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [KeyDimensionMemberID] nvarchar(450) NOT NULL,
    [IncludedMemberIDs] nvarchar(max) NOT NULL,
    [IsAbsolute] bit NOT NULL,
    [Mode] int NOT NULL,
    PRIMARY KEY ([MultiEditGroupGUID])
);
GO
ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_MULTIEDITGROUPGUID] DEFAULT (newid()) FOR [MultiEditGroupGUID]; GO
ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionViewGUID]; GO
ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_DIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_KEYDIMENSIONMEMBERID] DEFAULT ('') FOR [KeyDimensionMemberID]; GO
ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_INCLUDEDMEMBERIDS] DEFAULT ('') FOR [IncludedMemberIDs]; GO
ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_ISABSOLUTE] DEFAULT ((0)) FOR [IsAbsolute]; GO
ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_Mode] DEFAULT ((0)) FOR [Mode]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ActionLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[ActionLog] (
    [RowID] int NOT NULL,
    [Action] varchar(64) NOT NULL,
    [SubAction] varchar(400) NOT NULL,
    [Details] varchar(400) NOT NULL,
    [Username] varchar(64) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [Duration] int NOT NULL,
    [TokenGUID] uniqueidentifier NOT NULL,
    [DateTimeStampUtc] datetime NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_TokenGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TokenGUID]; GO
ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF__ActionLog__DateT__45DC8664] DEFAULT (getutcdate()) FOR [DateTimeStampUtc]; GO
ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_Action] DEFAULT ('') FOR [Action]; GO
ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_SubAction] DEFAULT ('') FOR [SubAction]; GO
ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_Detail] DEFAULT ('') FOR [Details]; GO
ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_Username] DEFAULT ('') FOR [Username]; GO
ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_Duration] DEFAULT ((0)) FOR [Duration]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ActionLogHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[ActionLogHistory] (
    [Year] int NULL,
    [Month] int NULL,
    [Day] int NULL,
    [Action] varchar(64) NOT NULL,
    [SubAction] varchar(64) NOT NULL,
    [SumDuration] int NULL,
    [AvgDuration] int NULL,
    [MinDuration] int NULL,
    [MaxDuration] int NULL,
    [StdevDuration] float NULL,
    [Count] int NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ActiveControllers ------------------
---------------------------------------------
CREATE TABLE [dbo].[ActiveControllers] (
    [ControllerID] uniqueidentifier NOT NULL,
    [WorkerID] uniqueidentifier NOT NULL,
    [TimeStamp] datetime NOT NULL
);
GO
ALTER TABLE [dbo].[ActiveControllers] ADD CONSTRAINT [DF_ActiveControllers_ControllerID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ControllerID]; GO
ALTER TABLE [dbo].[ActiveControllers] ADD CONSTRAINT [DF_ActiveControllers_WorkerID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkerID]; GO
ALTER TABLE [dbo].[ActiveControllers] ADD CONSTRAINT [DF_ActiveControllers_TimeStamp] DEFAULT (getdate()) FOR [TimeStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.Announcement ------------------
---------------------------------------------
CREATE TABLE [dbo].[Announcement] (
    [AnnouncementGUID] uniqueidentifier NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [Message] nvarchar(max) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [DateModified] datetime NOT NULL,
    [ModuleGUID_DEPRECATED] uniqueidentifier NOT NULL,
    [IsUrgent] bit NOT NULL,
    PRIMARY KEY ([AnnouncementGUID])
);
GO
ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__IsUrg__5513AB32] DEFAULT ((0)) FOR [IsUrgent]; GO
ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Annou__59CA45FB] DEFAULT (newid()) FOR [AnnouncementGUID]; GO
ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Autho__5ABE6A34] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Autho__5BB28E6D] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Messa__5CA6B2A6] DEFAULT ('') FOR [Message]; GO
ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__DateC__5D9AD6DF] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__DateM__5E8EFB18] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Modul__775AA8E2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID_DEPRECATED]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ApplicationMode ------------------
---------------------------------------------
CREATE TABLE [dbo].[ApplicationMode] (
    [ApplicationModeID] tinyint NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [AccessLevel] tinyint NOT NULL,
    PRIMARY KEY ([ApplicationModeID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ApplyAssumptionsHistoryDetail ------------------
---------------------------------------------
CREATE TABLE [dbo].[ApplyAssumptionsHistoryDetail] (
    [HistoryMemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [AssumptionGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [AssumptionSetName] nvarchar(100) NOT NULL,
    [AssumptionName] nvarchar(100) NOT NULL,
    [TimeClass] nvarchar(50) NOT NULL,
    [Dimensionality] nvarchar(max) NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [OldValueText] nvarchar(50) NULL,
    [NewValueText] nvarchar(50) NULL,
    [OldFormula] nvarchar(max) NOT NULL,
    [NewFormula] nvarchar(max) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [ValueDisplayType] int NOT NULL,
    PRIMARY KEY ([HistoryMemberGUID])
);
GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_ValueDisplayType] DEFAULT ((0)) FOR [ValueDisplayType]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_HistoryMemberGUID] DEFAULT (newid()) FOR [HistoryMemberGUID]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_AssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionGUID]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_AssumptionSetName] DEFAULT ('') FOR [AssumptionSetName]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_AssumptionName] DEFAULT ('') FOR [AssumptionName]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_TimeClass] DEFAULT ('') FOR [TimeClass]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_Dimensionality] DEFAULT ('') FOR [Dimensionality]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_OldValue] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_NewValue] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_OldValueText] DEFAULT ('') FOR [OldValueText]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_NewValueText] DEFAULT ('') FOR [NewValueText]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_OldFormula] DEFAULT ('d') FOR [OldFormula]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_NewFormula] DEFAULT ('') FOR [NewFormula]; GO
ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.BackupIsUsedScoreKeyLinkSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[BackupIsUsedScoreKeyLinkSetting] (
    [ScoreKeyLinkSettingGuid] uniqueidentifier NOT NULL,
    [KeyGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [IsUsed] bit NOT NULL,
    [IsCustom] bit NOT NULL,
    [IsMarkedForDeletion] bit NOT NULL,
    [IsRequired] bit NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.BackupIsUsedScoreMeasureSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[BackupIsUsedScoreMeasureSetting] (
    [ScoreMeasureSettingGuid] uniqueidentifier NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [IsUsed] bit NOT NULL,
    [IsCustom] bit NOT NULL,
    [IsMarkedForDeletion] bit NOT NULL,
    [ColumnName] nvarchar(128) NOT NULL,
    [IsRequired] bit NOT NULL,
    [ObjectName] nvarchar(128) NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.BudgetFileAttachment ------------------
---------------------------------------------
CREATE TABLE [dbo].[BudgetFileAttachment] (
    [FileAttachmentGUID] uniqueidentifier NOT NULL,
    [FileName] nvarchar(250) NOT NULL,
    [NumBytes] float NOT NULL,
    [DepartmentId] int NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DateCreated] datetime NOT NULL,
    [LastSeenpath] nvarchar(4000) NOT NULL,
    PRIMARY KEY ([FileAttachmentGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_BudgetFileAttachment_Unique] ON [dbo].[BudgetFileAttachment] ([DepartmentId], [FileName]);
GO
ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_FILEATTACHMENTGUID] DEFAULT (newid()) FOR [FileAttachmentGUID]; GO
ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_FILENAME] DEFAULT ('') FOR [FileName]; GO
ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_NUMBYTES] DEFAULT ((0)) FOR [NumBytes]; GO
ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_LASTSEENPATH] DEFAULT ('') FOR [LastSeenpath]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CECubeAlias ------------------
---------------------------------------------
CREATE TABLE [dbo].[CECubeAlias] (
    [CubeAliasGUID] uniqueidentifier NOT NULL,
    [CubeName] nvarchar(64) NOT NULL,
    [ObjectID] nvarchar(max) NOT NULL,
    [AliasName] nvarchar(max) NOT NULL,
    [AliasGUID] uniqueidentifier NOT NULL,
    [ObjectType] int NOT NULL,
    PRIMARY KEY ([CubeAliasGUID])
);
GO
ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_CubeAliasGUID] DEFAULT (newid()) FOR [CubeAliasGUID]; GO
ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_CubeName] DEFAULT ('') FOR [CubeName]; GO
ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_ObjectID] DEFAULT ('') FOR [ObjectID]; GO
ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_Alias] DEFAULT ('') FOR [AliasName]; GO
ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CECubeAlias_AliasGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AliasGUID]; GO
ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_ObjectType] DEFAULT ((0)) FOR [ObjectType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CECubeConnection ------------------
---------------------------------------------
CREATE TABLE [dbo].[CECubeConnection] (
    [CubeConnectionGUID] uniqueidentifier NOT NULL,
    [ServerName] nvarchar(64) NOT NULL,
    [DatabaseName] nvarchar(128) NOT NULL,
    [CubeName] nvarchar(64) NOT NULL,
    [ConnectionType] int NOT NULL,
    [IsActive] bit NOT NULL,
    [DataPath] nvarchar(max) NOT NULL,
    PRIMARY KEY ([CubeConnectionGUID])
);
GO
ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_ConnectionGUID] DEFAULT (newid()) FOR [CubeConnectionGUID]; GO
ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_ServerName] DEFAULT ('') FOR [ServerName]; GO
ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_DatabaseName] DEFAULT ('') FOR [DatabaseName]; GO
ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_CubeName] DEFAULT ('') FOR [CubeName]; GO
ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_Type] DEFAULT ((0)) FOR [ConnectionType]; GO
ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_IsActive] DEFAULT ((0)) FOR [IsActive]; GO
ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CECubeConnection_DataPath] DEFAULT ('') FOR [DataPath]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CECubeReportLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[CECubeReportLink] (
    [CubeReportLinkGUID] uniqueidentifier NOT NULL,
    [CubeGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CubeReportLinkGUID])
);
GO
ALTER TABLE [dbo].[CECubeReportLink] ADD CONSTRAINT [FK__CECubeRep__CubeG__4A0B4183] FOREIGN KEY ([CubeGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO
ALTER TABLE [dbo].[CECubeReportLink] ADD CONSTRAINT [FK__CECubeRep__Repor__4AFF65BC] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[CECubeReportLink] ADD CONSTRAINT [DF__CECubeRep__CubeR__49171D4A] DEFAULT (newid()) FOR [CubeReportLinkGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMBucket ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMBucket] (
    [BucketGUID] uniqueidentifier NOT NULL,
    [CategoryGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(50) NOT NULL,
    PRIMARY KEY ([BucketGUID])
);
GO
ALTER TABLE [dbo].[CMBucket] ADD CONSTRAINT [FK_ClassificationBucket_ClassificationCategory] FOREIGN KEY ([CategoryGUID]) REFERENCES [dbo].[CMCategory] ([CategoryGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMCategory ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMCategory] (
    [CategoryGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(50) NOT NULL,
    [Mutex] bit NOT NULL,
    PRIMARY KEY ([CategoryGUID])
);
GO
ALTER TABLE [dbo].[CMCategory] ADD CONSTRAINT [DF_ClassificationCategory_ClassificationCategoryGUID] DEFAULT (newid()) FOR [CategoryGUID]; GO
ALTER TABLE [dbo].[CMCategory] ADD CONSTRAINT [DF_ClassificationCategory_Mutex] DEFAULT ((0)) FOR [Mutex]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMCategoryFramework ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMCategoryFramework] (
    [CategoryGUID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    PRIMARY KEY ([CategoryGUID], [FrameworkID])
);
GO
ALTER TABLE [dbo].[CMCategoryFramework] ADD CONSTRAINT [FK_CMCategoryFramework_CMCategory] FOREIGN KEY ([CategoryGUID]) REFERENCES [dbo].[CMCategory] ([CategoryGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMCategoryTag ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMCategoryTag] (
    [CategoryGUID] uniqueidentifier NOT NULL,
    [TagGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CategoryGUID], [TagGUID])
);
GO
ALTER TABLE [dbo].[CMCategoryTag] ADD CONSTRAINT [FK_CMCategoryTag_CMCategory] FOREIGN KEY ([CategoryGUID]) REFERENCES [dbo].[CMCategory] ([CategoryGUID]); GO
ALTER TABLE [dbo].[CMCategoryTag] ADD CONSTRAINT [FK_CMCategoryTag_Tag] FOREIGN KEY ([TagGUID]) REFERENCES [dbo].[Tag] ([TagGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMFacts ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMFacts] (
    [DimensionGUID] uniqueidentifier NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [BucketGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [GroupingID] int NOT NULL,
    PRIMARY KEY ([DimensionGUID], [MemberGUID], [BucketGUID], [GroupingGUID])
);
GO
ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [FK_ClassificationFacts_ClassificationBucket] FOREIGN KEY ([BucketGUID]) REFERENCES [dbo].[CMBucket] ([BucketGUID]); GO
ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [FK_CMFacts_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO
ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [DF_CMFacts_MemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO
ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [DF_CMFacts_GroupingGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [DF_CMFacts_GroupingID] DEFAULT ((0)) FOR [GroupingID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMFlex ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMFlex] (
    [FlexGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    PRIMARY KEY ([FlexGUID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.CMFlexKeyLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMFlexKeyLink] (
    [FlexGUID] uniqueidentifier NOT NULL,
    [FlexKeyLinkGUID] uniqueidentifier NOT NULL,
    [IsUsedInFlex] bit NOT NULL,
    PRIMARY KEY ([FlexGUID], [FlexKeyLinkGUID])
);
GO
ALTER TABLE [dbo].[CMFlexKeyLink] ADD CONSTRAINT [FK_CMFlexKeyLink_CMFlex] FOREIGN KEY ([FlexGUID]) REFERENCES [dbo].[CMFlex] ([FlexGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMFlexMeasureMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMFlexMeasureMapping] (
    [MeasureMappingGUID] uniqueidentifier NOT NULL,
    [FlexGUID] uniqueidentifier NOT NULL,
    [TargetMeasureGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MeasureMappingGUID])
);
GO
ALTER TABLE [dbo].[CMFlexMeasureMapping] ADD CONSTRAINT [FK_CMFlexMeasureMapping_CMFlex] FOREIGN KEY ([FlexGUID]) REFERENCES [dbo].[CMFlex] ([FlexGUID]); GO
ALTER TABLE [dbo].[CMFlexMeasureMapping] ADD CONSTRAINT [FK_CMFlexMeasureMapping_CMFlexMeasureMapping] FOREIGN KEY ([MeasureMappingGUID]) REFERENCES [dbo].[CMFlexMeasureMapping] ([MeasureMappingGUID]); GO
ALTER TABLE [dbo].[CMFlexMeasureMapping] ADD CONSTRAINT [FK_CMFlexMeasureMapping_ScoreMeasure] FOREIGN KEY ([TargetMeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMFlexSourceMeasureMappingLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMFlexSourceMeasureMappingLink] (
    [MeasureMappingGUID] uniqueidentifier NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MeasureMappingGUID], [MeasureGUID])
);
GO
ALTER TABLE [dbo].[CMFlexSourceMeasureMappingLink] ADD CONSTRAINT [FK_CMFlexSourceMeasureMappingLink_ScoreMeasure] FOREIGN KEY ([MeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMFlexSourceTableLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMFlexSourceTableLink] (
    [FlexGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FlexGUID], [DataTableGUID])
);
GO
ALTER TABLE [dbo].[CMFlexSourceTableLink] ADD CONSTRAINT [FK_CMFlexSourceTableLink_CMFlex] FOREIGN KEY ([FlexGUID]) REFERENCES [dbo].[CMFlex] ([FlexGUID]); GO
ALTER TABLE [dbo].[CMFlexSourceTableLink] ADD CONSTRAINT [FK_CMFlexSourceTableLink_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMFlexTargetTableLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMFlexTargetTableLink] (
    [FlexGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FlexGUID], [DataTableGUID])
);
GO
ALTER TABLE [dbo].[CMFlexTargetTableLink] ADD CONSTRAINT [FK_CMFlexTargetTableLink_CMFlex] FOREIGN KEY ([FlexGUID]) REFERENCES [dbo].[CMFlex] ([FlexGUID]); GO
ALTER TABLE [dbo].[CMFlexTargetTableLink] ADD CONSTRAINT [FK_CMFlexTargetTableLink_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMMetric ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMMetric] (
    [MetricGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(50) NOT NULL,
    [MetricCode] nvarchar(50) NOT NULL,
    [IsAggregable] bit NOT NULL,
    [ToleranceValue] float NOT NULL,
    [TolerancePercent] float NOT NULL,
    [IsInverted] bit NOT NULL,
    [FormatString] nvarchar(100) NULL,
    [DisplayOrder] int NOT NULL,
    [Category] nvarchar(100) NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [Calculation] nvarchar(max) NOT NULL,
    [BucketGUID] uniqueidentifier NOT NULL,
    [IsCustomOverride] bit NOT NULL,
    [CalculationParts] nvarchar(max) NOT NULL,
    [CommentType] tinyint NOT NULL,
    [DimensionType] tinyint NOT NULL,
    [FriendlyName] nvarchar(256) NULL,
    [CalculationPartTypes] nvarchar(100) NOT NULL,
    [ClinicalIndicatorID] int NOT NULL,
    [IsPositiveFavorable] bit NOT NULL,
    [VarianceRule] tinyint NOT NULL,
    [IsHidden] bit NOT NULL,
    [UseBaselineTarget] bit NOT NULL,
    [DateCreated] datetime NOT NULL,
    [IsShownForSystem] bit NOT NULL,
    [IsShownForEntity] bit NOT NULL,
    [IsShownForDepartmentRollup1] bit NOT NULL,
    [IsShownForDepartmentRollup2] bit NOT NULL,
    [IsShownForDepartmentRollup3] bit NOT NULL,
    [IsShownForDepartmentRollup4] bit NOT NULL,
    [IsShownForDepartmentRollup5] bit NOT NULL,
    [IsShownForDepartmentRollup6] bit NOT NULL,
    [IsShownForDepartment] bit NOT NULL,
    [TimeFrame] tinyint NOT NULL,
    [Description] nvarchar(300) NOT NULL,
    [ThresholdMaterialityValue] float NULL,
    [DepartmentsType] tinyint NULL,
    [IsStandard] bit NOT NULL,
    [ToBeDeleted] bit NOT NULL,
    PRIMARY KEY ([MetricGUID])
);
GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [CHK_CMMetric_DepartmentsType] CHECK ([DepartmentsType]=(1) OR [DepartmentsType]=(0)); GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_UseBaselineTarget] DEFAULT ((0)) FOR [UseBaselineTarget]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_ClassificationMetric_ClassificationMetricGUID] DEFAULT (newid()) FOR [MetricGUID]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_MetricCode] DEFAULT ('') FOR [MetricCode]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_ClassificationMetric_IsAggregable] DEFAULT ((1)) FOR [IsAggregable]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_ToleranceValue] DEFAULT ((0)) FOR [ToleranceValue]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Commen__1523DCDC] DEFAULT ((0)) FOR [CommentType]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_TolerancePercent] DEFAULT ((0)) FOR [TolerancePercent]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsInverted] DEFAULT ((0)) FOR [IsInverted]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_FormatString] DEFAULT ('') FOR [FormatString]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Clinic__22C8BC14] DEFAULT ((0)) FOR [ClinicalIndicatorID]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Descri__28A4F021] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_CalculationParts] DEFAULT ('') FOR [CalculationParts]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Bucket__46CEB05B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BucketGUID]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_VarianceRule] DEFAULT ((0)) FOR [VarianceRule]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsHidden] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Measur__479D17D8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Calcul__49D53A38] DEFAULT ('') FOR [Calculation]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_DisplayOrder_1] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Catego__5561274A] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForSystem] DEFAULT ((1)) FOR [IsShownForSystem]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForEntity] DEFAULT ((1)) FOR [IsShownForEntity]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup1] DEFAULT ((1)) FOR [IsShownForDepartmentRollup1]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup2] DEFAULT ((1)) FOR [IsShownForDepartmentRollup2]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup3] DEFAULT ((1)) FOR [IsShownForDepartmentRollup3]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup4] DEFAULT ((1)) FOR [IsShownForDepartmentRollup4]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup5] DEFAULT ((1)) FOR [IsShownForDepartmentRollup5]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__IsCust__5C3ECE8D] DEFAULT ((0)) FOR [IsCustomOverride]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup6] DEFAULT ((1)) FOR [IsShownForDepartmentRollup6]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartment] DEFAULT ((1)) FOR [IsShownForDepartment]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsPositiveFavorable] DEFAULT ((1)) FOR [IsPositiveFavorable]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Calcul__661ED530] DEFAULT ('') FOR [CalculationPartTypes]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsStandard] DEFAULT ((0)) FOR [IsStandard]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_DimensionType] DEFAULT ((0)) FOR [DimensionType]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__TimeFr__7622C69E] DEFAULT ((0)) FOR [TimeFrame]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__ToBeDe__7777DAAB] DEFAULT ((0)) FOR [ToBeDeleted]; GO
ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__DateCr__79DB1B8D] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMMetricCommentDepartmentFilter ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMMetricCommentDepartmentFilter] (
    [MetricCommentDepartmentFilterGUID] uniqueidentifier NOT NULL,
    [MetricGUID] uniqueidentifier NOT NULL,
    [Value] nvarchar(256) NOT NULL,
    [NameValue] nvarchar(max) NULL,
    PRIMARY KEY ([MetricCommentDepartmentFilterGUID])
);
GO
ALTER TABLE [dbo].[CMMetricCommentDepartmentFilter] ADD CONSTRAINT [DF_CMMetricCommentDepartmentFilter_MetricCommentDepartmentFilterGUID] DEFAULT (newid()) FOR [MetricCommentDepartmentFilterGUID]; GO
ALTER TABLE [dbo].[CMMetricCommentDepartmentFilter] ADD CONSTRAINT [DF_CMMetricCommentDepartmentFilter_MetricGUID] DEFAULT (newid()) FOR [MetricGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMMetricCommentDepartmentFilterCache ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMMetricCommentDepartmentFilterCache] (
    [MetricGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    PRIMARY KEY ([MetricGUID], [DepartmentID])
);
GO
ALTER TABLE [dbo].[CMMetricCommentDepartmentFilterCache] ADD CONSTRAINT [FK_DBO_CMMetricCommentDepartmentFilterCache_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO
ALTER TABLE [dbo].[CMMetricCommentDepartmentFilterCache] ADD CONSTRAINT [FK_DBO_CMMetricCommentDepartmentFilterCache_DimDepartment] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMMetricFramework ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMMetricFramework] (
    [MetricGUID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    PRIMARY KEY ([MetricGUID], [FrameworkID])
);
GO
ALTER TABLE [dbo].[CMMetricFramework] ADD CONSTRAINT [FK_CMMetricFramework_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMMetricOverride ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMMetricOverride] (
    [MetricGUID] uniqueidentifier NOT NULL,
    [ItemID] int NOT NULL,
    [RollupLevel] nvarchar(100) NOT NULL,
    [ToleranceValue] float NOT NULL,
    [TolerancePercent] float NOT NULL,
    [CommentType] tinyint NOT NULL,
    [ThresholdMaterialityValue] float NULL,
    PRIMARY KEY ([MetricGUID], [ItemID], [RollupLevel])
);
GO
ALTER TABLE [dbo].[CMMetricOverride] ADD CONSTRAINT [FK_CMMetricOverride_MetricGUID] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO
ALTER TABLE [dbo].[CMMetricOverride] ADD CONSTRAINT [CK_CMMetricOverride_RollupLevel] CHECK ([RollupLevel]='DepartmentRollup6' OR [RollupLevel]='DepartmentRollup5' OR [RollupLevel]='DepartmentRollup4' OR [RollupLevel]='DepartmentRollup3' OR [RollupLevel]='DepartmentRollup2' OR [RollupLevel]='DepartmentRollup1' OR [RollupLevel]='Entity' OR [RollupLevel]='System'); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMMetricTag ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMMetricTag] (
    [MetricGUID] uniqueidentifier NOT NULL,
    [TagGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MetricGUID], [TagGUID])
);
GO
ALTER TABLE [dbo].[CMMetricTag] ADD CONSTRAINT [FK_CMMetricTag_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO
ALTER TABLE [dbo].[CMMetricTag] ADD CONSTRAINT [FK_CMMetricTag_Tag] FOREIGN KEY ([TagGUID]) REFERENCES [dbo].[Tag] ([TagGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMRule ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMRule] (
    [RuleGUID] uniqueidentifier NOT NULL,
    [BucketGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [RuleType] int NOT NULL,
    PRIMARY KEY ([RuleGUID])
);
GO
ALTER TABLE [dbo].[CMRule] ADD CONSTRAINT [FK_ClassificationRule_ClassificationBucket] FOREIGN KEY ([BucketGUID]) REFERENCES [dbo].[CMBucket] ([BucketGUID]); GO
ALTER TABLE [dbo].[CMRule] ADD CONSTRAINT [DF_ClassificationRule_ClassificationRuleGUID] DEFAULT (newid()) FOR [RuleGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMRuleTag ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMRuleTag] (
    [RuleGUID] uniqueidentifier NOT NULL,
    [TagGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RuleGUID], [TagGUID])
);
GO
ALTER TABLE [dbo].[CMRuleTag] ADD CONSTRAINT [FK__CMRuleTag__RuleG__3749B010] FOREIGN KEY ([RuleGUID]) REFERENCES [dbo].[CMRule] ([RuleGUID]); GO
ALTER TABLE [dbo].[CMRuleTag] ADD CONSTRAINT [FK__CMRuleTag__TagGU__383DD449] FOREIGN KEY ([TagGUID]) REFERENCES [dbo].[Tag] ([TagGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMRuleValue ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMRuleValue] (
    [RuleValueGUID] uniqueidentifier NOT NULL,
    [RuleGUID] uniqueidentifier NOT NULL,
    [Value] nvarchar(100) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsExcluding] bit NOT NULL,
    [GroupingID] int NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [NameValue] nvarchar(max) NULL,
    PRIMARY KEY ([RuleValueGUID])
);
GO
ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [FK_ClassificationRuleValue_ClassificationRule] FOREIGN KEY ([RuleGUID]) REFERENCES [dbo].[CMRule] ([RuleGUID]); GO
ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_ClassificationRuleValue_ClassificationRuleValueGUID] DEFAULT (newid()) FOR [RuleValueGUID]; GO
ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_CMRuleValue_IsExcluding] DEFAULT ((0)) FOR [IsExcluding]; GO
ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_CMRuleValue_GroupingID] DEFAULT ((0)) FOR [GroupingID]; GO
ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_CMRuleValue_GroupingGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_CMRuleValue_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMSampleTable ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMSampleTable] (
    [SampleTableGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [isLocked] bit NOT NULL,
    PRIMARY KEY ([SampleTableGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_ClassificationSampleTable] ON [dbo].[CMSampleTable] ([Name]);
GO
ALTER TABLE [dbo].[CMSampleTable] ADD CONSTRAINT [DF_ClassificationSampleTable_ClassificationSampleTableGUID] DEFAULT (newid()) FOR [SampleTableGUID]; GO
ALTER TABLE [dbo].[CMSampleTable] ADD CONSTRAINT [DF_ClassificationSampleTable_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[CMSampleTable] ADD CONSTRAINT [DF_CMSampleTable_isLocked] DEFAULT ((0)) FOR [isLocked]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMSampleTableDataLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMSampleTableDataLink] (
    [SampleTableDataLinkGUID] uniqueidentifier NOT NULL,
    [SampleTableGUID] uniqueidentifier NOT NULL,
    [ScoreDataTableGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SampleTableDataLinkGUID])
);
GO
ALTER TABLE [dbo].[CMSampleTableDataLink] ADD CONSTRAINT [FK_CMSampleTableDataLink_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO
ALTER TABLE [dbo].[CMSampleTableDataLink] ADD CONSTRAINT [FK_CMSampleTableDataLink_ScoreDataTable] FOREIGN KEY ([ScoreDataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO
ALTER TABLE [dbo].[CMSampleTableDataLink] ADD CONSTRAINT [DF_CMSampleTableDataLink_SampleTableDataLinkGUID] DEFAULT (newid()) FOR [SampleTableDataLinkGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMSampleTableFramework ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMSampleTableFramework] (
    [SampleTableGUID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    PRIMARY KEY ([SampleTableGUID], [FrameworkID])
);
GO
ALTER TABLE [dbo].[CMSampleTableFramework] ADD CONSTRAINT [FK_CMSampleTableFramework_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CMSampleTableKeyLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMSampleTableKeyLink] (
    [SampleTableKeyLinkGUID] uniqueidentifier NOT NULL,
    [SampleTableGUID] uniqueidentifier NOT NULL,
    [KeyGUID] uniqueidentifier NOT NULL,
    [KeyAlternateAttributeGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SampleTableKeyLinkGUID])
);
GO
ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [FK_CMSampleTableKeyLink_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO
ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [FK_CMSampleTableKeyLink_ScoreAttribute] FOREIGN KEY ([KeyGUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO
ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [DF_ClassificationSampleTableKeyLink_ClassificationSampleTableKeyLinkGUID] DEFAULT (newid()) FOR [SampleTableKeyLinkGUID]; GO
ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [DF_ClassificationSampleTableKeyLink_ClassificationSampleTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SampleTableGUID]; GO
ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [DF__CMSampleT__KeyAl__45B4CF66] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyAlternateAttributeGUID]; GO
ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [DF_CMSampleTableKeyLink_KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMSampleTableMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMSampleTableMeasure] (
    [MeasureGUID] uniqueidentifier NOT NULL,
    [SampleTableGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    PRIMARY KEY ([MeasureGUID])
);
GO
ALTER TABLE [dbo].[CMSampleTableMeasure] ADD CONSTRAINT [FK_CMSampleTableMeasure_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO
ALTER TABLE [dbo].[CMSampleTableMeasure] ADD CONSTRAINT [DF_CMSampleTableMeasure_MeasureGUID] DEFAULT (newid()) FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[CMSampleTableMeasure] ADD CONSTRAINT [DF_CMSampleTableMeasure_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[CMSampleTableMeasure] ADD CONSTRAINT [DF_CMSampleTableMeasure_SampleTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SampleTableGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMSampleTableMetricLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMSampleTableMetricLink] (
    [SampleTableGUID] uniqueidentifier NOT NULL,
    [MetricGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SampleTableGUID], [MetricGUID])
);
GO
ALTER TABLE [dbo].[CMSampleTableMetricLink] ADD CONSTRAINT [FK_CMSampleTableMetricLink_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO
ALTER TABLE [dbo].[CMSampleTableMetricLink] ADD CONSTRAINT [FK_CMSampleTableMetricLink_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO
ALTER TABLE [dbo].[CMSampleTableMetricLink] ADD CONSTRAINT [DF_Table_1_MetricGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MetricGUID]; GO
ALTER TABLE [dbo].[CMSampleTableMetricLink] ADD CONSTRAINT [DF_ClassificationSampleTableMetricLink_ClassificationSampleTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SampleTableGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMSampleTableMetricMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMSampleTableMetricMapping] (
    [SampleTableMetricMappingGUID] uniqueidentifier NOT NULL,
    [MetricGUID] uniqueidentifier NOT NULL,
    [SampleTableDataLinkGUID] uniqueidentifier NOT NULL,
    [ScoreMeasureGUID] uniqueidentifier NOT NULL,
    [SampleTableMeasureGUID] uniqueidentifier NOT NULL,
    [SampleTableGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SampleTableMetricMappingGUID])
);
GO
ALTER TABLE [dbo].[CMSampleTableMetricMapping] ADD CONSTRAINT [FK_CMSampleTableMetricMapping_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO
ALTER TABLE [dbo].[CMSampleTableMetricMapping] ADD CONSTRAINT [FK_CMSampleTableMetricMapping_ScoreMeasure] FOREIGN KEY ([ScoreMeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO
ALTER TABLE [dbo].[CMSampleTableMetricMapping] ADD CONSTRAINT [DF_CMSampleTableMetricMapping_SampleTableMetricMappingGUID] DEFAULT (newid()) FOR [SampleTableMetricMappingGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CMSampleTableTargetFilter ------------------
---------------------------------------------
CREATE TABLE [dbo].[CMSampleTableTargetFilter] (
    [TargetFilterGUID] uniqueidentifier NOT NULL,
    [SampleTableGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([TargetFilterGUID])
);
GO
ALTER TABLE [dbo].[CMSampleTableTargetFilter] ADD CONSTRAINT [FK_CMSampleTableTargetFilter_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO
ALTER TABLE [dbo].[CMSampleTableTargetFilter] ADD CONSTRAINT [FK_CMSampleTableTargetFilter_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.CSDimensionConstant ------------------
---------------------------------------------
CREATE TABLE [dbo].[CSDimensionConstant] (
    [DimensionConstantGUID] uniqueidentifier NOT NULL,
    [SetupGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [DimensionMemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([DimensionConstantGUID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ClientContact ------------------
---------------------------------------------
CREATE TABLE [dbo].[ClientContact] (
    [ClientContactGUID] uniqueidentifier NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    [ContactName] nvarchar(256) NOT NULL,
    [ContactInfo] nvarchar(max) NOT NULL,
    PRIMARY KEY ([ClientContactGUID])
);
GO
ALTER TABLE [dbo].[ClientContact] ADD CONSTRAINT [FK__ClientCon__Modul__25217392] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO
ALTER TABLE [dbo].[ClientContact] ADD CONSTRAINT [DF__ClientCon__Clien__242D4F59] DEFAULT (newid()) FOR [ClientContactGUID]; GO
ALTER TABLE [dbo].[ClientContact] ADD CONSTRAINT [DF__ClientCon__Conta__261597CB] DEFAULT ('') FOR [ContactName]; GO
ALTER TABLE [dbo].[ClientContact] ADD CONSTRAINT [DF__ClientCon__Conta__2709BC04] DEFAULT ('') FOR [ContactInfo]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ClientDefinedColumns ------------------
---------------------------------------------
CREATE TABLE [dbo].[ClientDefinedColumns] (
    [ClientDefinedColumnGUID] uniqueidentifier NOT NULL,
    [OptimizationPoolGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NULL,
    PRIMARY KEY ([ClientDefinedColumnGUID])
);
GO
ALTER TABLE [dbo].[ClientDefinedColumns] ADD CONSTRAINT [FK_ClientDefinedColumns_FormFieldGUID] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FE2FormField] ([FormFieldGUID]); GO
ALTER TABLE [dbo].[ClientDefinedColumns] ADD CONSTRAINT [FK_ClientDefinedColumns_OMZPool] FOREIGN KEY ([OptimizationPoolGUID]) REFERENCES [dbo].[OMZPool] ([PoolGUID]); GO
ALTER TABLE [dbo].[ClientDefinedColumns] ADD CONSTRAINT [DF__ClientDef__Clien__1AEA68C3] DEFAULT (newid()) FOR [ClientDefinedColumnGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ColumnStoreIndex ------------------
---------------------------------------------
CREATE TABLE [dbo].[ColumnStoreIndex] (
    [i] int NOT NULL
);

GO

---------------------------------------------

---------------------------------------------
-- dbo.ContentMigrationAttributeMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[ContentMigrationAttributeMapping] (
    [ContentMigrationAttributeMappingID] int NOT NULL,
    [ScoreDimensionGUID] uniqueidentifier NULL,
    [ScoreAttributeGUID] uniqueidentifier NULL,
    [ParentDimensionGUID] uniqueidentifier NULL,
    [ScoreDatatableGUID] uniqueidentifier NULL,
    [CubeDimensionName] nvarchar(200) NULL,
    [CubeAttributeName] nvarchar(200) NULL,
    [CubeDataType] nvarchar(200) NULL,
    [ParentSqlObjectDefinition] nvarchar(200) NULL,
    [BaseSqlObjectDefinition] nvarchar(200) NULL,
    [SqlObjectDefinition] nvarchar(200) NULL,
    [SqlColumnName] nvarchar(200) NULL,
    [SnowflakeObjectDefinition] nvarchar(200) NULL,
    [SnowflakeColumnName] nvarchar(200) NULL,
    [SisenseDataMart] nvarchar(200) NULL,
    [SisenseColumnName] nvarchar(200) NULL,
    [SisenseTableName] nvarchar(200) NULL,
    [SqlDataType] nvarchar(100) NOT NULL,
    [ScoreDimensionName] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ContentMigrationAttributeMappingID])
);
GO
ALTER TABLE [dbo].[ContentMigrationAttributeMapping] ADD CONSTRAINT [DF__ContentMi__SqlDa__3922751B] DEFAULT ('') FOR [SqlDataType]; GO
ALTER TABLE [dbo].[ContentMigrationAttributeMapping] ADD CONSTRAINT [DF__ContentMi__Score__69268DF8] DEFAULT ('') FOR [ScoreDimensionName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ContentMigrationCalculationMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[ContentMigrationCalculationMapping] (
    [CubeCalculationName] nvarchar(200) NULL,
    [CubeMeasureGroupName] nvarchar(200) NULL,
    [CubeCalculation] nvarchar(2000) NULL,
    [CubeIncludedMeasuresCSV] nvarchar(2000) NULL,
    [SisenseDataMart] nvarchar(200) NULL,
    [SisenseColumnName] nvarchar(200) NULL,
    [ContentMigrationCalculationMappingID] int NOT NULL,
    PRIMARY KEY ([ContentMigrationCalculationMappingID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ContentMigrationMeasureMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[ContentMigrationMeasureMapping] (
    [ContentMigrationMeasureMappingID] int NOT NULL,
    [ScoreDatatableGUID] uniqueidentifier NULL,
    [ScoreMeasureGUID] uniqueidentifier NULL,
    [CubeMeasureGroupName] nvarchar(200) NULL,
    [CubeMeasureName] nvarchar(200) NULL,
    [CubeDataType] nvarchar(200) NULL,
    [CubeAggregationType] nvarchar(200) NULL,
    [SqlObjectDefinition] nvarchar(200) NULL,
    [SqlColumnName] nvarchar(200) NULL,
    [SnowflakeObjectDefinition] nvarchar(200) NULL,
    [SnowflakeColumnName] nvarchar(200) NULL,
    [SisenseDataMart] nvarchar(200) NULL,
    [SisenseColumnName] nvarchar(200) NULL,
    [SisenseTableName] nvarchar(200) NULL,
    [SqlDataType] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ContentMigrationMeasureMappingID])
);
GO
ALTER TABLE [dbo].[ContentMigrationMeasureMapping] ADD CONSTRAINT [DF__ContentMi__SqlDa__3A169954] DEFAULT ('') FOR [SqlDataType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CubeDirtyPartitionInfo ------------------
---------------------------------------------
CREATE TABLE [dbo].[CubeDirtyPartitionInfo] (
    [CubeDirtyPartitionInfoGuid] uniqueidentifier NOT NULL,
    [Status] tinyint NOT NULL,
    [PartitionNames] nvarchar(max) NOT NULL,
    [StartTimeUtc] datetime NOT NULL,
    [EndTimeUtc] datetime NULL,
    [LastSuccessfulChangeTrackingID] bigint NOT NULL,
    [CurrentChangeTrackingID] bigint NOT NULL,
    [CubeProcessSuccess] bit NOT NULL,
    PRIMARY KEY ([CubeDirtyPartitionInfoGuid])
);
GO
ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__CubeD__24F3F30B] DEFAULT (newid()) FOR [CubeDirtyPartitionInfoGuid]; GO
ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__Statu__25E81744] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__Parti__26DC3B7D] DEFAULT ('') FOR [PartitionNames]; GO
ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__Start__27D05FB6] DEFAULT (getutcdate()) FOR [StartTimeUtc]; GO
ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__LastS__28C483EF] DEFAULT ((0)) FOR [LastSuccessfulChangeTrackingID]; GO
ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__Curre__29B8A828] DEFAULT ((0)) FOR [CurrentChangeTrackingID]; GO
ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__CubeP__2AACCC61] DEFAULT ((0)) FOR [CubeProcessSuccess]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CubeIncrementalProcessMeasureGroups ------------------
---------------------------------------------
CREATE TABLE [dbo].[CubeIncrementalProcessMeasureGroups] (
    [RowID] int NOT NULL,
    [MeasureGroupID] nvarchar(800) NOT NULL,
    PRIMARY KEY ([RowID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.CubeMeasureGroupDefaultMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[CubeMeasureGroupDefaultMeasure] (
    [CubeMeasureGroupDefaultMeasureID] int NOT NULL,
    [CubeName] nvarchar(100) NOT NULL,
    [MeasureGroupName] nvarchar(100) NOT NULL,
    [DefaultMeasureMDX] nvarchar(400) NOT NULL,
    PRIMARY KEY ([CubeMeasureGroupDefaultMeasureID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ_CUBENAMEMEASUREGROUPNAME] ON [dbo].[CubeMeasureGroupDefaultMeasure] ([CubeName], [MeasureGroupName]);
GO
ALTER TABLE [dbo].[CubeMeasureGroupDefaultMeasure] ADD CONSTRAINT [DF__CubeMeasu__Defau__00950485] DEFAULT ('') FOR [DefaultMeasureMDX]; GO
ALTER TABLE [dbo].[CubeMeasureGroupDefaultMeasure] ADD CONSTRAINT [DF__CubeMeasu__CubeN__7EACBC13] DEFAULT ('') FOR [CubeName]; GO
ALTER TABLE [dbo].[CubeMeasureGroupDefaultMeasure] ADD CONSTRAINT [DF__CubeMeasu__Measu__7FA0E04C] DEFAULT ('') FOR [MeasureGroupName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CubeUserRole ------------------
---------------------------------------------
CREATE TABLE [dbo].[CubeUserRole] (
    [CubeUserRoleGUID] uniqueidentifier NOT NULL,
    [RoleName] nvarchar(100) NOT NULL,
    [ServerName] nvarchar(400) NOT NULL,
    [DatabaseName] nvarchar(400) NOT NULL,
    [UserGroupGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CubeUserRoleGUID])
);
GO
ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [FK__CubeUserR__UserG__2BF9C16D] FOREIGN KEY ([UserGroupGUID]) REFERENCES [dbo].[UserGroup] ([UserGroupGUID]); GO
ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__Serve__258A58FB] DEFAULT ('') FOR [ServerName]; GO
ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__Datab__267E7D34] DEFAULT ('') FOR [DatabaseName]; GO
ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__CubeU__45380E7E] DEFAULT (newid()) FOR [CubeUserRoleGUID]; GO
ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__RoleN__48147B29] DEFAULT ('') FOR [RoleName]; GO
ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__UserG__2B059D34] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGroupGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CurrentUser ------------------
---------------------------------------------
CREATE TABLE [dbo].[CurrentUser] (
    [TokenGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [MachineGUID] uniqueidentifier NOT NULL,
    [TokenType] int NOT NULL,
    [UserName] nvarchar(64) NOT NULL,
    [IPAddress] nvarchar(100) NOT NULL,
    [LoginStampUtc] datetime NOT NULL,
    [LastActionStampUtc] datetime NOT NULL,
    [IdentityServerSessionId] nvarchar(100) NULL,
    PRIMARY KEY ([TokenGUID])
);
GO
ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF_CurrentUser_UserName] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF__CurrentUs__IPAdd__39D3430C] DEFAULT ('') FOR [IPAddress]; GO
ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF_CurrentUser_MachineGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MachineGUID]; GO
ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF_CurrentUser_TokenType] DEFAULT ((0)) FOR [TokenType]; GO
ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF__CurrentUs__Login__53368182] DEFAULT (getutcdate()) FOR [LoginStampUtc]; GO
ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF__CurrentUs__LastA__542AA5BB] DEFAULT (getutcdate()) FOR [LastActionStampUtc]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CustomAction ------------------
---------------------------------------------
CREATE TABLE [dbo].[CustomAction] (
    [ActionGUID] uniqueidentifier NOT NULL,
    [AssemblyName] nvarchar(450) NOT NULL,
    [ClassName] nvarchar(450) NOT NULL,
    [Metadata] nvarchar(max) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [ActionType] int NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [Confirmation] nvarchar(450) NOT NULL,
    [SuccessMessage] nvarchar(450) NOT NULL,
    [IsUsingContext] bit NOT NULL,
    [IconKey] int NOT NULL,
    PRIMARY KEY ([ActionGUID])
);
GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_ACTIONGUID] DEFAULT (newid()) FOR [ActionGUID]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_ASSEMBLYNAME] DEFAULT ('') FOR [AssemblyName]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_CLASSNAME] DEFAULT ('') FOR [ClassName]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_ICONKEY] DEFAULT ((0)) FOR [IconKey]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_METADATA] DEFAULT ('') FOR [Metadata]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_ACTIONTYPE] DEFAULT ((1)) FOR [ActionType]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_Confirmation] DEFAULT ('') FOR [Confirmation]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_SuccessMessage] DEFAULT ('') FOR [SuccessMessage]; GO
ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_IsUsingContext] DEFAULT ((1)) FOR [IsUsingContext]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CustomMenu ------------------
---------------------------------------------
CREATE TABLE [dbo].[CustomMenu] (
    [CustomMenuGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [PageID] nvarchar(64) NOT NULL,
    [Type] int NOT NULL,
    [IsGlobal] bit NOT NULL,
    PRIMARY KEY ([CustomMenuGUID])
);
GO
ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_Table_1_WORKSPACETOOLBARGUID] DEFAULT (newid()) FOR [CustomMenuGUID]; GO
ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_PAGEID] DEFAULT ('') FOR [PageID]; GO
ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_ISGLOBAL] DEFAULT ((0)) FOR [IsGlobal]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CustomMenuContent ------------------
---------------------------------------------
CREATE TABLE [dbo].[CustomMenuContent] (
    [CustomMenuContentGUID] uniqueidentifier NOT NULL,
    [CustomMenuGUID] uniqueidentifier NOT NULL,
    [ContentXML] xml NOT NULL,
    PRIMARY KEY ([CustomMenuContentGUID])
);
GO
ALTER TABLE [dbo].[CustomMenuContent] ADD CONSTRAINT [FK_CustomMenuContent_CustomMenu] FOREIGN KEY ([CustomMenuGUID]) REFERENCES [dbo].[CustomMenu] ([CustomMenuGUID]); GO
ALTER TABLE [dbo].[CustomMenuContent] ADD CONSTRAINT [DF_CustomMenuContent_CUSTOMMENUCONTENTGUID] DEFAULT (newid()) FOR [CustomMenuContentGUID]; GO
ALTER TABLE [dbo].[CustomMenuContent] ADD CONSTRAINT [DF_CustomMenuContent_CUSTOMMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomMenuGUID]; GO
ALTER TABLE [dbo].[CustomMenuContent] ADD CONSTRAINT [DF_CustomMenuContent_CONTENTXML] DEFAULT ('') FOR [ContentXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.CustomScript ------------------
---------------------------------------------
CREATE TABLE [dbo].[CustomScript] (
    [CustomScriptGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [TimeoutSeconds] int NOT NULL,
    [ScriptText] nvarchar(max) NOT NULL,
    [IsSynchronous] bit NOT NULL,
    [ScriptType] int NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CustomScriptGUID])
);
GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_Type] DEFAULT ((0)) FOR [ScriptType]; GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_IsSynchronous] DEFAULT ((1)) FOR [IsSynchronous]; GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF__CustomScr__Globa__5378DED8] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_CustomSCRIPT] DEFAULT (newid()) FOR [CustomScriptGUID]; GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_ScriptText] DEFAULT ('') FOR [ScriptText]; GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_TimeoutSeconds] DEFAULT ((60)) FOR [TimeoutSeconds]; GO
ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF__CustomScr__Folde__6776813B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DBSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[DBSetting] (
    [DBSettingGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [Setting] nvarchar(4000) NOT NULL,
    [LastModifiedDate] datetime NOT NULL,
    [IsUserEditable] bit NOT NULL,
    [IsUserReadable] bit NOT NULL,
    [FriendlyName] nvarchar(64) NOT NULL,
    PRIMARY KEY ([DBSettingGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_DBSetting] ON [dbo].[DBSetting] ([Name]);
GO
ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_IsUserEditable] DEFAULT ((0)) FOR [IsUserEditable]; GO
ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_IsUserReadDenied] DEFAULT ((0)) FOR [IsUserReadable]; GO
ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_DBSETTINGGUID] DEFAULT (newid()) FOR [DBSettingGUID]; GO
ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_LASTMODIFIEDDATE] DEFAULT (getdate()) FOR [LastModifiedDate]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DCInputConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[DCInputConfig] (
    [InputConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [InputPluginAssembly] nvarchar(256) NOT NULL,
    [InputPluginXML] nvarchar(max) NOT NULL,
    [DCTableGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([InputConfigGUID])
);
GO
ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_INPUTCONFIGGUID] DEFAULT (newid()) FOR [InputConfigGUID]; GO
ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_INPUTPLUGINSOURCE] DEFAULT ('') FOR [InputPluginAssembly]; GO
ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_INPUTPLUGINXML] DEFAULT ('') FOR [InputPluginXML]; GO
ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_DCTABLEGUID] DEFAULT (newid()) FOR [DCTableGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DCOutputConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[DCOutputConfig] (
    [OutputConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [OutputPluginAssembly] nvarchar(256) NOT NULL,
    [OutputPluginXML] nvarchar(max) NOT NULL,
    [LastRunDate] datetime NOT NULL,
    PRIMARY KEY ([OutputConfigGUID])
);
GO
ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_OUTPUTCONFIGGUID] DEFAULT (newid()) FOR [OutputConfigGUID]; GO
ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_OUTPUTPLUGINASSEMBLY] DEFAULT ('') FOR [OutputPluginAssembly]; GO
ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_OUTPUTPLUGINXML] DEFAULT ('') FOR [OutputPluginXML]; GO
ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_LASTRUNDATE] DEFAULT ('1/1/2000') FOR [LastRunDate]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DCTable ------------------
---------------------------------------------
CREATE TABLE [dbo].[DCTable] (
    [TableGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [Source] nvarchar(256) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [LastUpdatedDate] datetime NOT NULL,
    PRIMARY KEY ([TableGUID])
);
GO
ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DATACENTERTABLE_DATACENTERTABLEGUID] DEFAULT (newid()) FOR [TableGUID]; GO
ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DATACENTERTABLE_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DATACENTERTABLE_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DCTable_FILENAME] DEFAULT ('') FOR [Source]; GO
ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DCTable_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DCTable_LASTUPDATEDDATE] DEFAULT ('1/1/2000') FOR [LastUpdatedDate]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DashboardWidget ------------------
---------------------------------------------
CREATE TABLE [dbo].[DashboardWidget] (
    [DashboardWidgetGUID] uniqueidentifier NOT NULL,
    [DesktopTemplateGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Row] int NOT NULL,
    [Col] int NOT NULL,
    [Height] int NOT NULL,
    [Width] int NOT NULL,
    [WidgetJSON] nvarchar(max) NOT NULL,
    [WidgetClassName] nvarchar(100) NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([DashboardWidgetGUID])
);
GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [FK__Dashboard__Deskt__05EB2160] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Dashb__0402D8EE] DEFAULT (newid()) FOR [DashboardWidgetGUID]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Deskt__04F6FD27] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DesktopTemplateGUID]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__DashboardW__Name__06DF4599] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__DashboardWi__Row__07D369D2] DEFAULT ((0)) FOR [Row]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__DashboardWi__Col__08C78E0B] DEFAULT ((0)) FOR [Col]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Heigh__09BBB244] DEFAULT ((0)) FOR [Height]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Width__0AAFD67D] DEFAULT ((0)) FOR [Width]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Widge__0B39E662] DEFAULT ('') FOR [WidgetJSON]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Widge__0C2E0A9B] DEFAULT ('') FOR [WidgetClassName]; GO
ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__DataS__404D9876] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DashboardWidgetCache ------------------
---------------------------------------------
CREATE TABLE [dbo].[DashboardWidgetCache] (
    [DashboardWidgetCacheGUID] uniqueidentifier NOT NULL,
    [DashboardWidgetGUID] uniqueidentifier NOT NULL,
    [DesktopTemplateGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [Data] nvarchar(max) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    PRIMARY KEY ([DashboardWidgetCacheGUID])
);
GO
ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [FK__Dashboard__Dashb__38AC76AE] FOREIGN KEY ([DashboardWidgetGUID]) REFERENCES [dbo].[DashboardWidget] ([DashboardWidgetGUID]); GO
ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__Dashb__36C42E3C] DEFAULT (newid()) FOR [DashboardWidgetCacheGUID]; GO
ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__DateC__378E670D] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__Dashb__37B85275] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DashboardWidgetGUID]; GO
ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__Deskt__39A09AE7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DesktopTemplateGUID]; GO
ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__UserG__3A94BF20] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__DashboardW__Data__3B88E359] DEFAULT ('') FOR [Data]; GO
ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__DateC__3C7D0792] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataCenterCustomReportLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataCenterCustomReportLink] (
    [ReportLinkGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    [TileGlobalID] varchar(100) NOT NULL,
    PRIMARY KEY ([ReportLinkGUID])
);
GO
ALTER TABLE [dbo].[DataCenterCustomReportLink] ADD CONSTRAINT [FK__DataCente__Modul__1893E180] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO
ALTER TABLE [dbo].[DataCenterCustomReportLink] ADD CONSTRAINT [FK__DataCente__Repor__179FBD47] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[DataCenterCustomReportLink] ADD CONSTRAINT [DF__DataCente__Repor__16AB990E] DEFAULT (newid()) FOR [ReportLinkGUID]; GO
ALTER TABLE [dbo].[DataCenterCustomReportLink] ADD CONSTRAINT [DF__DataCente__TileG__22682FD4] DEFAULT ('') FOR [TileGlobalID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataCenterCustomReportWorkbookLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataCenterCustomReportWorkbookLink] (
    [ReportLinkGUID] uniqueidentifier NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    [TileGlobalID] nvarchar(100) NOT NULL,
    [WorkbookID] int NOT NULL,
    PRIMARY KEY ([ReportLinkGUID])
);
GO
ALTER TABLE [dbo].[DataCenterCustomReportWorkbookLink] ADD CONSTRAINT [FK_CustomReportWorkbook_Module] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO
ALTER TABLE [dbo].[DataCenterCustomReportWorkbookLink] ADD CONSTRAINT [DF__DataCente__Repor__7C3C8FC8] DEFAULT (newid()) FOR [ReportLinkGUID]; GO
ALTER TABLE [dbo].[DataCenterCustomReportWorkbookLink] ADD CONSTRAINT [DF__DataCente__TileG__7D30B401] DEFAULT ('') FOR [TileGlobalID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataCenterDimensionConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataCenterDimensionConfig] (
    [DimensionName] nvarchar(200) NOT NULL,
    [DataCenterPageName] nvarchar(200) NOT NULL,
    [SystemCenterStepGlobalIDExisting] nvarchar(100) NOT NULL,
    [SystemCenterStepGlobalIDNew] nvarchar(100) NOT NULL,
    PRIMARY KEY ([DimensionName])
);
GO
ALTER TABLE [dbo].[DataCenterDimensionConfig] ADD CONSTRAINT [DF__DataCente__DataC__02C4CDBC] DEFAULT ('') FOR [DataCenterPageName]; GO
ALTER TABLE [dbo].[DataCenterDimensionConfig] ADD CONSTRAINT [DF__DataCente__Syste__03B8F1F5] DEFAULT ('') FOR [SystemCenterStepGlobalIDExisting]; GO
ALTER TABLE [dbo].[DataCenterDimensionConfig] ADD CONSTRAINT [DF__DataCente__Syste__04AD162E] DEFAULT ('') FOR [SystemCenterStepGlobalIDNew]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataDictionaryFieldValueExample ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataDictionaryFieldValueExample] (
    [ScoreGUID] uniqueidentifier NOT NULL,
    [ExampleValue] nvarchar(4000) NOT NULL,
    PRIMARY KEY ([ScoreGUID])
);
GO
ALTER TABLE [dbo].[DataDictionaryFieldValueExample] ADD CONSTRAINT [DF_DataDictionaryFieldValueExample_ScoreGUID] DEFAULT (newid()) FOR [ScoreGUID]; GO
ALTER TABLE [dbo].[DataDictionaryFieldValueExample] ADD CONSTRAINT [DF_DataDictionaryFieldValueExample_ExampleValue] DEFAULT ('') FOR [ExampleValue]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataPathFile ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataPathFile] (
    [FileGUID] uniqueidentifier NOT NULL,
    [FullPath] varchar(450) NOT NULL,
    [FileName] varchar(450) NOT NULL,
    [CreationTime] datetime NOT NULL,
    [LastModifiedTime] datetime NOT NULL,
    [Data] varbinary(max) NOT NULL,
    [IsLocked] bit NOT NULL,
    [LockTime] datetime NOT NULL,
    [LockOwner] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FileGUID])
);

CREATE UNIQUE CLUSTERED INDEX [IDX_DataPathFile] ON [dbo].[DataPathFile] ([FullPath]);
GO
ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO
ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO
ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO
ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO
ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO
ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_FullPath] DEFAULT ('') FOR [FullPath]; GO
ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_FileName] DEFAULT ('') FOR [FileName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataPathFile_History ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataPathFile_History] (
    [FileGUID] uniqueidentifier NOT NULL,
    [FullPath] varchar(450) NOT NULL,
    [FileName] varchar(450) NOT NULL,
    [CreationTime] datetime NOT NULL,
    [LastModifiedTime] datetime NOT NULL,
    [Data] varbinary(max) NOT NULL,
    [IsLocked] bit NOT NULL,
    [LockTime] datetime NOT NULL,
    [LockOwner] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FileGUID])
);

CREATE CLUSTERED INDEX [C_DataPathFile_History] ON [dbo].[DataPathFile_History] ([FullPath], [LockOwner], [IsLocked]);
CREATE NONCLUSTERED INDEX [NCNU_FullPath] ON [dbo].[DataPathFile_History] ([FullPath]);
GO
ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO
ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_FullPath] DEFAULT ('') FOR [FullPath]; GO
ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_FileName] DEFAULT ('') FOR [FileName]; GO
ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO
ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO
ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO
ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataPathFile_Improv ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataPathFile_Improv] (
    [FileGUID] uniqueidentifier NOT NULL,
    [FullPath] varchar(450) NOT NULL,
    [FileName] varchar(450) NOT NULL,
    [CreationTime] datetime NOT NULL,
    [LastModifiedTime] datetime NOT NULL,
    [Data] varbinary(max) NOT NULL,
    [IsLocked] bit NOT NULL,
    [LockTime] datetime NOT NULL,
    [LockOwner] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FileGUID])
);

CREATE CLUSTERED INDEX [C_DataPathFile_Improv] ON [dbo].[DataPathFile_Improv] ([FullPath], [LockOwner], [IsLocked]);
CREATE NONCLUSTERED INDEX [NCNU_FullPath] ON [dbo].[DataPathFile_Improv] ([FullPath]);
GO
ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO
ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_FullPath] DEFAULT ('') FOR [FullPath]; GO
ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_FileName] DEFAULT ('') FOR [FileName]; GO
ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO
ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO
ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO
ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataPathFile_ModelTemplate ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataPathFile_ModelTemplate] (
    [FileGUID] uniqueidentifier NOT NULL,
    [FullPath] varchar(450) NOT NULL,
    [FileName] varchar(450) NOT NULL,
    [CreationTime] datetime NOT NULL,
    [LastModifiedTime] datetime NOT NULL,
    [Data] varbinary(max) NOT NULL,
    [IsLocked] bit NOT NULL,
    [LockTime] datetime NOT NULL,
    [LockOwner] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FileGUID])
);

CREATE NONCLUSTERED INDEX [NCNU_FullPath] ON [dbo].[DataPathFile_ModelTemplate] ([FullPath]);
GO
ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO
ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_FullPath] DEFAULT ('') FOR [FullPath]; GO
ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO
ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_FileName] DEFAULT ('') FOR [FileName]; GO
ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO
ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO
ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataPathFile_Reporting ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataPathFile_Reporting] (
    [FileGUID] uniqueidentifier NOT NULL,
    [FullPath] varchar(450) NOT NULL,
    [FileName] varchar(450) NOT NULL,
    [CreationTime] datetime NOT NULL,
    [LastModifiedTime] datetime NOT NULL,
    [Data] varbinary(max) NOT NULL,
    [IsLocked] bit NOT NULL,
    [LockTime] datetime NOT NULL,
    [LockOwner] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FileGUID])
);

CREATE CLUSTERED INDEX [C_DataPathFile_Reporting] ON [dbo].[DataPathFile_Reporting] ([FullPath], [LockOwner], [IsLocked]);
CREATE NONCLUSTERED INDEX [NCNU_FullPath] ON [dbo].[DataPathFile_Reporting] ([FullPath]);
GO
ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO
ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO
ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_FullPath] DEFAULT ('') FOR [FullPath]; GO
ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_FileName] DEFAULT ('') FOR [FileName]; GO
ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO
ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO
ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataSourceContent ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataSourceContent] (
    [DataSourceContentGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ParentGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [AssemblyQualifiedName] nvarchar(450) NOT NULL,
    [LastRefreshDate] datetime NOT NULL,
    [SetupXML] nvarchar(max) NOT NULL,
    [DataXML] nvarchar(max) NOT NULL,
    PRIMARY KEY ([DataSourceContentGUID])
);
GO
ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_DATASOURCECONTENTGUID] DEFAULT (newid()) FOR [DataSourceContentGUID]; GO
ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_DATASOURCEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO
ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_PARENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentGUID]; GO
ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO
ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_SETUPXML] DEFAULT ('') FOR [SetupXML]; GO
ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_DATAXML] DEFAULT ('') FOR [DataXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DataView ------------------
---------------------------------------------
CREATE TABLE [dbo].[DataView] (
    [DataViewGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [SQLViewName] nvarchar(450) NOT NULL,
    [SourceGUID] uniqueidentifier NOT NULL,
    [SourceType] int NOT NULL,
    [SecurityColumns] nvarchar(450) NOT NULL,
    [SampleTableGUID] uniqueidentifier NOT NULL,
    [MetricColumnName] nvarchar(50) NOT NULL,
    [PlanColumnName] nvarchar(100) NOT NULL,
    [Description] nvarchar(2000) NOT NULL,
    [FrameworkGUID] uniqueidentifier NOT NULL,
    [IsOptionRecompile] bit NOT NULL,
    PRIMARY KEY ([DataViewGUID])
);
GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_PlanColumnName] DEFAULT ('') FOR [PlanColumnName]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF__DataView__Descri__2A6519D2] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF__DataView__Framew__3F59743D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FrameworkGUID]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_DataViewGUID] DEFAULT (newid()) FOR [DataViewGUID]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SQLViewName] DEFAULT ('') FOR [SQLViewName]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SourceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceGUID]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SourceType] DEFAULT ((0)) FOR [SourceType]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SecurityColumns] DEFAULT ('') FOR [SecurityColumns]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SampleTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SampleTableGUID]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_MetricColumnName] DEFAULT ('') FOR [MetricColumnName]; GO
ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF__DataView__IsOpti__7B3F1545] DEFAULT ((0)) FOR [IsOptionRecompile]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DateMap ------------------
---------------------------------------------
CREATE TABLE [dbo].[DateMap] (
    [SourceDate] date NULL,
    [TargetDate] date NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.DemoUser ------------------
---------------------------------------------
CREATE TABLE [dbo].[DemoUser] (
    [UserGUID] uniqueidentifier NOT NULL,
    [DisplayName] nvarchar(100) NOT NULL,
    PRIMARY KEY ([UserGUID])
);
GO
ALTER TABLE [dbo].[DemoUser] ADD CONSTRAINT [FK_DemoUser_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[DemoUser] ADD CONSTRAINT [DF_DemoUser_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[DemoUser] ADD CONSTRAINT [DF_DemoUser_DisplayName] DEFAULT ('') FOR [DisplayName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DepartmentIDLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[DepartmentIDLog] (
    [RowID] int NOT NULL,
    [Step] nvarchar(100) NOT NULL,
    [Type] nvarchar(10) NOT NULL,
    [Script] nvarchar(max) NOT NULL,
    [StartTime] datetime NULL,
    [EndTime] datetime NULL,
    [IsComplete] bit NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[DepartmentIDLog] ADD CONSTRAINT [DF_DepartmentIDLog_Step] DEFAULT ('') FOR [Step]; GO
ALTER TABLE [dbo].[DepartmentIDLog] ADD CONSTRAINT [DF_DepartmentIDLog_Type] DEFAULT ('') FOR [Type]; GO
ALTER TABLE [dbo].[DepartmentIDLog] ADD CONSTRAINT [DF_DepartmentIDLog_Script] DEFAULT ('') FOR [Script]; GO
ALTER TABLE [dbo].[DepartmentIDLog] ADD CONSTRAINT [DF_DepartmentIDLog_IsComplete] DEFAULT ((0)) FOR [IsComplete]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DesktopCategory ------------------
---------------------------------------------
CREATE TABLE [dbo].[DesktopCategory] (
    [DesktopCategoryGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(50) NOT NULL,
    [IconCls] nvarchar(50) NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([DesktopCategoryGUID])
);
GO
ALTER TABLE [dbo].[DesktopCategory] ADD CONSTRAINT [DF__DesktopCa__Modul__1BE2221B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO
ALTER TABLE [dbo].[DesktopCategory] ADD CONSTRAINT [DF_DesktopCategory_DesktopCategoryGUID] DEFAULT (newid()) FOR [DesktopCategoryGUID]; GO
ALTER TABLE [dbo].[DesktopCategory] ADD CONSTRAINT [DF_DesktopTemplateCategory_CategoryIconCls] DEFAULT ('') FOR [IconCls]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DesktopColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[DesktopColumn] (
    [DesktopColumnGUID] uniqueidentifier NOT NULL,
    [DesktopTemplateGUID] uniqueidentifier NOT NULL,
    [WidthRatio] float NOT NULL,
    [ColumnIndex] int NOT NULL,
    PRIMARY KEY ([DesktopColumnGUID])
);
GO
ALTER TABLE [dbo].[DesktopColumn] ADD CONSTRAINT [FK_DesktopColumn_DesktopTemplate] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO
ALTER TABLE [dbo].[DesktopColumn] ADD CONSTRAINT [DF_DesktopColumn_DesktopColumnGUID] DEFAULT (newid()) FOR [DesktopColumnGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DesktopParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[DesktopParameter] (
    [DesktopParameterGUID] uniqueidentifier NOT NULL,
    [DesktopTemplateGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [ColumnName] nvarchar(200) NOT NULL,
    [ParameterXML] nvarchar(max) NOT NULL,
    [DimensionId] nvarchar(200) NOT NULL,
    [AttributeId] nvarchar(200) NOT NULL,
    [MeasureId] nvarchar(200) NOT NULL,
    [ParameterValueAQN] nvarchar(400) NOT NULL,
    [ReportGuidsCSV] nvarchar(max) NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DimensionName] nvarchar(200) NOT NULL,
    [AttributeName] nvarchar(200) NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ExcludedWidgetGuidsCSV] nvarchar(max) NOT NULL,
    PRIMARY KEY ([DesktopParameterGUID])
);
GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [FK__DesktopPa__Deskt__43084118] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Exclu__30C13C23] DEFAULT ('') FOR [ExcludedWidgetGuidsCSV]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__UserG__33E7C191] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Deskt__42141CDF] DEFAULT (newid()) FOR [DesktopParameterGUID]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPar__Name__43FC6551] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Colum__44F0898A] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Param__45E4ADC3] DEFAULT ('') FOR [ParameterXML]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Dimen__46D8D1FC] DEFAULT ('') FOR [DimensionId]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Attri__47CCF635] DEFAULT ('') FOR [AttributeId]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Measu__48C11A6E] DEFAULT ('') FOR [MeasureId]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Param__49B53EA7] DEFAULT ('') FOR [ParameterValueAQN]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Repor__4AA962E0] DEFAULT ('') FOR [ReportGuidsCSV]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Dimen__53606CEA] DEFAULT ('') FOR [DimensionName]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Attri__54549123] DEFAULT ('') FOR [AttributeName]; GO
ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__DataS__5548B55C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DesktopTemplate ------------------
---------------------------------------------
CREATE TABLE [dbo].[DesktopTemplate] (
    [DesktopTemplateGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [ReadableUserCount] int NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    [DateCreated] datetime NOT NULL,
    [IsLegacy] bit NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [StrataSphereDashboardGUID] uniqueidentifier NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    PRIMARY KEY ([DesktopTemplateGUID])
);
GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__Descr__0BA3FAB6] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_DesktopTemplateGUID_1] DEFAULT (newid()) FOR [DesktopTemplateGUID]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_Name_1] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_ReadableUserCount] DEFAULT ((1)) FOR [ReadableUserCount]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__DateC__38828B46] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__Modul__7C61B726] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__DateC__7D55DB5F] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__IsLeg__7E49FF98] DEFAULT ((0)) FOR [IsLegacy]; GO
ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_StrataSphereDashboardGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StrataSphereDashboardGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DesktopTemplateUserLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[DesktopTemplateUserLink] (
    [DesktopTemplateGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] smallint NOT NULL,
    [IsVisible] bit NOT NULL,
    PRIMARY KEY ([DesktopTemplateGUID], [UserGUID])
);
GO
ALTER TABLE [dbo].[DesktopTemplateUserLink] ADD CONSTRAINT [FK_DesktopTemplateUserLink_DesktopTemplate] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO
ALTER TABLE [dbo].[DesktopTemplateUserLink] ADD CONSTRAINT [DF_DesktopTemplateUserLink_Visible] DEFAULT ((1)) FOR [IsVisible]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DesktopWidget ------------------
---------------------------------------------
CREATE TABLE [dbo].[DesktopWidget] (
    [DesktopWidgetGUID] uniqueidentifier NOT NULL,
    [DesktopTemplateGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [HelpText] nvarchar(4000) NOT NULL,
    [IsCollapsed] bit NOT NULL,
    [IsCollapsible] bit NOT NULL,
    [IsMovable] bit NOT NULL,
    [RowIndex] int NOT NULL,
    [ColumnIndex] int NOT NULL,
    [WidgetFullName] nvarchar(4000) NOT NULL,
    [WidgetXML] nvarchar(max) NOT NULL,
    [Height] int NOT NULL,
    PRIMARY KEY ([DesktopWidgetGUID])
);
GO
ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [FK_DesktopWidget_DesktopTemplate] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO
ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_DesktopWidgetGUID] DEFAULT (newid()) FOR [DesktopWidgetGUID]; GO
ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_HelpText] DEFAULT ('') FOR [HelpText]; GO
ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_IsCollapsed] DEFAULT ((0)) FOR [IsCollapsed]; GO
ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_Collapsible] DEFAULT ((0)) FOR [IsCollapsible]; GO
ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_Movable] DEFAULT ((1)) FOR [IsMovable]; GO
ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_RowIndex] DEFAULT ((0)) FOR [RowIndex]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DimensionInfo ------------------
---------------------------------------------
CREATE TABLE [dbo].[DimensionInfo] (
    [DimensionGUID] uniqueidentifier NOT NULL,
    [CubeStubGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Type] int NOT NULL,
    PRIMARY KEY ([DimensionGUID], [CubeStubGUID])
);
GO
ALTER TABLE [dbo].[DimensionInfo] ADD CONSTRAINT [DF_DimensionInfo_DIMENSIONGUID] DEFAULT (newid()) FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[DimensionInfo] ADD CONSTRAINT [DF_DimensionInfo_CubeStubGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubGUID]; GO
ALTER TABLE [dbo].[DimensionInfo] ADD CONSTRAINT [DF_DimensionInfo_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[DimensionInfo] ADD CONSTRAINT [DF_DimensionInfo_DIMENSIONTYPE] DEFAULT ((0)) FOR [Type]; GO

---------------------------------------------

---------------------------------------------
-- dbo.DimensionMemberCleanupHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[DimensionMemberCleanupHistory] (
    [RowID] bigint NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [UserName] varchar(128) NOT NULL,
    [SourceTableName] varchar(200) NOT NULL,
    [BackupTableName] varchar(200) NOT NULL,
    [RequestDateTime] datetime NOT NULL,
    [SessionSuffix] varchar(20) NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_UserName] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_SourceTableName] DEFAULT ('') FOR [SourceTableName]; GO
ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_BackupTableName] DEFAULT ('') FOR [BackupTableName]; GO
ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_RequestDateTime] DEFAULT (getdate()) FOR [RequestDateTime]; GO
ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_SessionSuffix] DEFAULT ('') FOR [SessionSuffix]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ECRIComponent ------------------
---------------------------------------------
CREATE TABLE [dbo].[ECRIComponent] (
    [ECRIComponentGUID] uniqueidentifier NOT NULL,
    [ECRIDealGUID] uniqueidentifier NOT NULL,
    [CatalogNumber] varchar(64) NOT NULL,
    [Description] varchar(1000) NOT NULL,
    [Quantity] int NOT NULL,
    [QuotedPrice] float NOT NULL,
    PRIMARY KEY ([ECRIComponentGUID])
);
GO
ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [FK_ECRIComponent_ECRIDeal] FOREIGN KEY ([ECRIDealGUID]) REFERENCES [dbo].[ECRIDeal] ([ECRIDealGUID]); GO
ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_ECRICOMPONENTGUID] DEFAULT (newid()) FOR [ECRIComponentGUID]; GO
ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_ECRIDEALGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIDealGUID]; GO
ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_CatalogNumber] DEFAULT ('') FOR [CatalogNumber]; GO
ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_QUANTITY] DEFAULT ((1)) FOR [Quantity]; GO
ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_QUOTEDPRICE] DEFAULT ((0)) FOR [QuotedPrice]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ECRIDeal ------------------
---------------------------------------------
CREATE TABLE [dbo].[ECRIDeal] (
    [ECRIDealGUID] uniqueidentifier NOT NULL,
    [ECRIModelGUID] uniqueidentifier NOT NULL,
    [ReferenceNumber] int NOT NULL,
    [QuotedPrice] float NOT NULL,
    [ListPrice] float NOT NULL,
    [Units] float NOT NULL,
    [Comments] varchar(4000) NOT NULL,
    [Discount] float NOT NULL,
    [DealDate] nvarchar(64) NOT NULL,
    PRIMARY KEY ([ECRIDealGUID])
);
GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [FK_ECRIDeal_ECRIModel] FOREIGN KEY ([ECRIModelGUID]) REFERENCES [dbo].[ECRIModel] ([ECRIModelGUID]); GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_ECRIDEALGUID] DEFAULT (newid()) FOR [ECRIDealGUID]; GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_ECRIMODELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIModelGUID]; GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_ReferenceNumber] DEFAULT ((0)) FOR [ReferenceNumber]; GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_QUOTEDPRICE] DEFAULT ((0)) FOR [QuotedPrice]; GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_LISTPRICE] DEFAULT ((0)) FOR [ListPrice]; GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_UNITS] DEFAULT ((0)) FOR [Units]; GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_Comments] DEFAULT ('') FOR [Comments]; GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_Discount] DEFAULT ((0)) FOR [Discount]; GO
ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_Date] DEFAULT ('') FOR [DealDate]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ECRIDocument ------------------
---------------------------------------------
CREATE TABLE [dbo].[ECRIDocument] (
    [ECRIDocumentGUID] uniqueidentifier NOT NULL,
    [ECRIPackageGUID] uniqueidentifier NOT NULL,
    [Title] varchar(200) NOT NULL,
    [Source] int NOT NULL,
    [ResultID] varchar(64) NOT NULL,
    [RadarInfo] varchar(10) NOT NULL,
    [RadarComment1] varchar(8000) NOT NULL,
    [RadarComment2] varchar(8000) NOT NULL,
    [RadarComment3] varchar(8000) NOT NULL,
    [RadarComment4] varchar(8000) NOT NULL,
    [RadarComment5] varchar(8000) NOT NULL,
    PRIMARY KEY ([ECRIDocumentGUID])
);
GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [FK_ECRIDocument_ECRIPackage] FOREIGN KEY ([ECRIPackageGUID]) REFERENCES [dbo].[ECRIPackage] ([ECRIPackageGUID]); GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_ECRIDocumentGUID] DEFAULT (newid()) FOR [ECRIDocumentGUID]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_ECRIPackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIPackageGUID]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_Title] DEFAULT ('') FOR [Title]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_Source] DEFAULT ((0)) FOR [Source]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_Identifier] DEFAULT ('') FOR [ResultID]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarInfo] DEFAULT ('') FOR [RadarInfo]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment1] DEFAULT ('') FOR [RadarComment1]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment2] DEFAULT ('') FOR [RadarComment2]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment3] DEFAULT ('') FOR [RadarComment3]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment4] DEFAULT ('') FOR [RadarComment4]; GO
ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment5] DEFAULT ('') FOR [RadarComment5]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ECRIDocumentSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[ECRIDocumentSection] (
    [ECRIDocumentSectionGUID] uniqueidentifier NOT NULL,
    [ECRIDocumentGUID] uniqueidentifier NOT NULL,
    [Header] varchar(200) NOT NULL,
    [Text] nvarchar(max) NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([ECRIDocumentSectionGUID])
);
GO
ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [FK_ECRIDocumentSection_ECRIDocument] FOREIGN KEY ([ECRIDocumentGUID]) REFERENCES [dbo].[ECRIDocument] ([ECRIDocumentGUID]); GO
ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_ECRIDocumentSectionGUID] DEFAULT (newid()) FOR [ECRIDocumentSectionGUID]; GO
ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_ECRIDocumentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIDocumentGUID]; GO
ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_Text] DEFAULT ('') FOR [Text]; GO
ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_Header] DEFAULT ('') FOR [Header]; GO
ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_DisplayOrder] DEFAULT ((0)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ECRIEquipment ------------------
---------------------------------------------
CREATE TABLE [dbo].[ECRIEquipment] (
    [ECRIEquipmentGUID] uniqueidentifier NOT NULL,
    [ECRIPackageGUID] uniqueidentifier NOT NULL,
    [Name] varchar(120) NOT NULL,
    PRIMARY KEY ([ECRIEquipmentGUID])
);
GO
ALTER TABLE [dbo].[ECRIEquipment] ADD CONSTRAINT [FK_ECRIEquipmentName_ECRIPackage] FOREIGN KEY ([ECRIPackageGUID]) REFERENCES [dbo].[ECRIPackage] ([ECRIPackageGUID]); GO
ALTER TABLE [dbo].[ECRIEquipment] ADD CONSTRAINT [DF_ECRIEquipmentName_DeviceTerm] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[ECRIEquipment] ADD CONSTRAINT [DF_ECRIEquipmentName_ECRIEquipmentNameGUID] DEFAULT (newid()) FOR [ECRIEquipmentGUID]; GO
ALTER TABLE [dbo].[ECRIEquipment] ADD CONSTRAINT [DF_ECRIEquipmentName_ECRIPackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIPackageGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ECRIModel ------------------
---------------------------------------------
CREATE TABLE [dbo].[ECRIModel] (
    [ECRIModelGUID] uniqueidentifier NOT NULL,
    [ECRIPackageGUID] uniqueidentifier NOT NULL,
    [ECRIEquipmentGUID] uniqueidentifier NOT NULL,
    [ECRIVendorGUID] uniqueidentifier NOT NULL,
    [Name] varchar(300) NOT NULL,
    [ResultID] varchar(64) NOT NULL,
    PRIMARY KEY ([ECRIModelGUID])
);
GO
ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [FK_ECRIModel_ECRIPackage] FOREIGN KEY ([ECRIPackageGUID]) REFERENCES [dbo].[ECRIPackage] ([ECRIPackageGUID]); GO
ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIMODELGUID] DEFAULT (newid()) FOR [ECRIModelGUID]; GO
ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIPackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIPackageGUID]; GO
ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIEquipmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIEquipmentGUID]; GO
ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIVendorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIVendorGUID]; GO
ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIResultID] DEFAULT ('') FOR [ResultID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ECRIPackage ------------------
---------------------------------------------
CREATE TABLE [dbo].[ECRIPackage] (
    [ECRIPackageGUID] uniqueidentifier NOT NULL,
    [PlanGUID] uniqueidentifier NOT NULL,
    [SearchTerm] nvarchar(4000) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [DateCreated] datetime NOT NULL,
    PRIMARY KEY ([ECRIPackageGUID])
);
GO
ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPlanSelection_ECRIPlanSelectionGUID] DEFAULT (newid()) FOR [ECRIPackageGUID]; GO
ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPlanSelection_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO
ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPackage_Search] DEFAULT ('') FOR [SearchTerm]; GO
ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPlanSelection_ECRIEquipmentNames] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPlanSelection_ECRIVendors] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ECRIVendor ------------------
---------------------------------------------
CREATE TABLE [dbo].[ECRIVendor] (
    [ECRIVendorGUID] uniqueidentifier NOT NULL,
    [ECRIPackageGUID] uniqueidentifier NOT NULL,
    [Name] varchar(121) NOT NULL,
    PRIMARY KEY ([ECRIVendorGUID])
);
GO
ALTER TABLE [dbo].[ECRIVendor] ADD CONSTRAINT [FK_ECRIVendor_ECRIPackage] FOREIGN KEY ([ECRIPackageGUID]) REFERENCES [dbo].[ECRIPackage] ([ECRIPackageGUID]); GO
ALTER TABLE [dbo].[ECRIVendor] ADD CONSTRAINT [DF_ECRIVendor_ECRIVendorGUID] DEFAULT (newid()) FOR [ECRIVendorGUID]; GO
ALTER TABLE [dbo].[ECRIVendor] ADD CONSTRAINT [DF_ECRIVendor_ECRIPackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIPackageGUID]; GO
ALTER TABLE [dbo].[ECRIVendor] ADD CONSTRAINT [DF_ECRIVendor_Name] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFCalculatedMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFCalculatedMeasure] (
    [CalculatedMeasureGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [IsVisible] bit NOT NULL,
    [MDXName] nvarchar(450) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [DisplayFormat] nvarchar(450) NOT NULL,
    [DisplayFolder] nvarchar(450) NOT NULL,
    [NonEmptyBehavior] nvarchar(max) NOT NULL,
    [CubeStubGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CalculatedMeasureGUID])
);

CREATE NONCLUSTERED INDEX [IX_EMFCalculatedMeasure_DisplayFormat] ON [dbo].[EMFCalculatedMeasure] ([DisplayFormat]);
GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_CALCULATEDMEASUREGUID] DEFAULT (newid()) FOR [CalculatedMeasureGUID]; GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_ISVISIBLE] DEFAULT ((1)) FOR [IsVisible]; GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_MDXNAME] DEFAULT ('') FOR [MDXName]; GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_FORMATSTRING] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_DISPLAYFOLDER] DEFAULT ('') FOR [DisplayFolder]; GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_NONEMPTYBEHAVIOR] DEFAULT ('') FOR [NonEmptyBehavior]; GO
ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_CUBESTUBGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFCubeStub ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFCubeStub] (
    [CubeGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [DateProcessed] datetime NOT NULL,
    [ServerName] nvarchar(64) NOT NULL,
    [DatabaseFriendlyName] nvarchar(32) NOT NULL,
    [DatabasePrefixName] nvarchar(64) NOT NULL,
    [Status] int NOT NULL,
    [Type] int NOT NULL,
    [IsReportable] bit NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [KeyDimension] nvarchar(450) NOT NULL,
    [IsEditable] bit NOT NULL,
    [CubeType] int NOT NULL,
    [IsAutoProcessEnabled] bit NOT NULL,
    [IsAutoUpdateEnabled] bit NOT NULL,
    [MaxParallel] int NOT NULL,
    [IsUsingBatchProcessing] bit NOT NULL,
    [DateModified] datetime NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IsUsingDSCubeReportIntelliCross] bit NOT NULL,
    PRIMARY KEY ([CubeGUID])
);
GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF__EMFCubeSt__IsUsi__0A45C229] DEFAULT ((0)) FOR [IsUsingDSCubeReportIntelliCross]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF__EMFCubeSt__DateM__0B2E640C] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_CUBEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeGUID]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_DATABASEPREFIXNAME] DEFAULT ('') FOR [DatabasePrefixName]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCube_STATUS] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCube_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_ISREPORTABLE] DEFAULT ((0)) FOR [IsReportable]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_KEYDIMENSION] DEFAULT ('') FOR [KeyDimension]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_ISEDITABLE] DEFAULT ((1)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_CUBETYPE] DEFAULT ((0)) FOR [CubeType]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_IsAutoProcessEnabled] DEFAULT ((1)) FOR [IsAutoProcessEnabled]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_IsAutoUpdateEnabled] DEFAULT ((0)) FOR [IsAutoUpdateEnabled]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_MaxParallel] DEFAULT ((0)) FOR [MaxParallel]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_IsUsingBatchProcessing] DEFAULT ((0)) FOR [IsUsingBatchProcessing]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF__EMFCubeSt__Globa__5A2C0555] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_ServerName] DEFAULT ('') FOR [ServerName]; GO
ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_DatabaseFriendlyName] DEFAULT ('') FOR [DatabaseFriendlyName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFCubeStubCrosswalk ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFCubeStubCrosswalk] (
    [CUBESTUBCROSSWALKGUID] uniqueidentifier NOT NULL,
    [CubeStubGUID] uniqueidentifier NOT NULL,
    [StructureGUID] uniqueidentifier NOT NULL,
    [LinkedStructureGUID] uniqueidentifier NOT NULL,
    [LinkedDimensionGUID] uniqueidentifier NOT NULL,
    [LinkedMeasureGUID] uniqueidentifier NOT NULL,
    [JoinType] int NOT NULL,
    PRIMARY KEY ([CUBESTUBCROSSWALKGUID])
);
GO
ALTER TABLE [dbo].[EMFCubeStubCrosswalk] ADD CONSTRAINT [FK_EMFCubeStubCrosswalkLink_EMFCubeStub] FOREIGN KEY ([CubeStubGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO
ALTER TABLE [dbo].[EMFCubeStubCrosswalk] ADD CONSTRAINT [DF_EMFCubeStubCrosswalkLink_CUBESTUBCROSSWALKLINKGUID] DEFAULT (newid()) FOR [CUBESTUBCROSSWALKGUID]; GO
ALTER TABLE [dbo].[EMFCubeStubCrosswalk] ADD CONSTRAINT [DF_EMFCubeStubCrosswalk_JOINTYPE] DEFAULT ((0)) FOR [JoinType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFCubeStubCustomDimension ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFCubeStubCustomDimension] (
    [StructureGUID] uniqueidentifier NOT NULL,
    [CubeStubGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [NewDimensionGUID] uniqueidentifier NOT NULL,
    [NewName] varchar(450) NOT NULL,
    [NewSQL] varchar(max) NOT NULL,
    [NewSQLType] int NOT NULL,
    [NewSQLTableIDColName] varchar(64) NOT NULL,
    [NewSQLTableParentColName] varchar(64) NOT NULL,
    [NewSQLTableOrderColName] nvarchar(64) NOT NULL,
    [NewSQLTableValueColName] varchar(64) NOT NULL,
    [NewSQLTableOperatorColName] varchar(64) NOT NULL,
    [NewFactTableColName] nvarchar(64) NOT NULL,
    [NewSQLTableName] nvarchar(64) NOT NULL,
    [NewLevelNamingTemplate] nvarchar(50) NOT NULL,
    [NewDefaultMemberMDXName] varchar(450) NOT NULL,
    [NewAggregationType] int NOT NULL,
    [NewIsVisible] bit NOT NULL,
    [NewIsMultiLevel] bit NOT NULL,
    [NewIsQuery] bit NOT NULL,
    [IsOverridingSQLTableName] bit NOT NULL,
    [IsOverridingLevelNamingTemplate] bit NOT NULL,
    [IsOverridingDefaultMemberMDXName] bit NOT NULL,
    [IsOverridingAggregationType] bit NOT NULL,
    [IsOverridingIsVisible] bit NOT NULL,
    [IsOverridingIsMultiLevel] bit NOT NULL,
    [IsOverridingIsQuery] bit NOT NULL,
    PRIMARY KEY ([StructureGUID], [CubeStubGUID], [DimensionGUID])
);
GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [FK_EMFCubeStubCustomDimension_EMFCubeStub] FOREIGN KEY ([CubeStubGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_STRUCTUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_CUBESTUBGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubGUID]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_DIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWDIMENSIONGUID] DEFAULT (newid()) FOR [NewDimensionGUID]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWNAME] DEFAULT ('') FOR [NewName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_FILTERSQL] DEFAULT ('') FOR [NewSQL]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_FULLSQL] DEFAULT ((0)) FOR [NewSQLType]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEIDCOLNAME] DEFAULT ('') FOR [NewSQLTableIDColName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEPARENTCOLNAME] DEFAULT ('') FOR [NewSQLTableParentColName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEORDERCOLNAME] DEFAULT ('') FOR [NewSQLTableOrderColName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEVALUECOLNAME] DEFAULT ('') FOR [NewSQLTableValueColName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEOPERATORCOLNAME] DEFAULT ('') FOR [NewSQLTableOperatorColName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWFACTTABLECOLNAME] DEFAULT ('') FOR [NewFactTableColName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLENAME] DEFAULT ('') FOR [NewSQLTableName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWLEVELNAMINGTEMPLATE] DEFAULT ('') FOR [NewLevelNamingTemplate]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWDEFAULTMEMBERMDXNAME] DEFAULT ('') FOR [NewDefaultMemberMDXName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWAGGREGATIONTYPE] DEFAULT ((0)) FOR [NewAggregationType]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWISVISIBLE] DEFAULT ((0)) FOR [NewIsVisible]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWISMULTILEVEL] DEFAULT ((0)) FOR [NewIsMultiLevel]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWISQUERY] DEFAULT ((0)) FOR [NewIsQuery]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGSQLTABLENAME] DEFAULT ((0)) FOR [IsOverridingSQLTableName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGLEVELNAMINGTEMPLATE] DEFAULT ((0)) FOR [IsOverridingLevelNamingTemplate]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGDEFAULTMEMBERMDXNAME] DEFAULT ((0)) FOR [IsOverridingDefaultMemberMDXName]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGAGGREGATIONTYPE] DEFAULT ((0)) FOR [IsOverridingAggregationType]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGISVISIBLE] DEFAULT ((0)) FOR [IsOverridingIsVisible]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGISMULTILEVEL] DEFAULT ((0)) FOR [IsOverridingIsMultiLevel]; GO
ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGISQUERY] DEFAULT ((0)) FOR [IsOverridingIsQuery]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFCubeStubFormFieldLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFCubeStubFormFieldLink] (
    [CubeStubGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CubeStubGUID], [FormFieldGUID])
);
GO
ALTER TABLE [dbo].[EMFCubeStubFormFieldLink] ADD CONSTRAINT [FK_EMFCubeStubFormFieldLink_EMFCubeStub] FOREIGN KEY ([CubeStubGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO
ALTER TABLE [dbo].[EMFCubeStubFormFieldLink] ADD CONSTRAINT [FK_EMFCubeStubFormFieldLink_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFCubeStubModelDataConfigLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFCubeStubModelDataConfigLink] (
    [ModelDataConfigGUID] uniqueidentifier NOT NULL,
    [CubeGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ModelDataConfigGUID], [CubeGUID])
);
GO
ALTER TABLE [dbo].[EMFCubeStubModelDataConfigLink] ADD CONSTRAINT [FK_EMFCubeStubModelDataConfigLink_EMFCubeStub] FOREIGN KEY ([CubeGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO
ALTER TABLE [dbo].[EMFCubeStubModelDataConfigLink] ADD CONSTRAINT [FK_EMFCubeStubModelDataConfigLink_EMFModelDataConfig] FOREIGN KEY ([ModelDataConfigGUID]) REFERENCES [dbo].[EMFModelDataConfig] ([ModelDataConfigGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFCubeStubModelKeyValue ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFCubeStubModelKeyValue] (
    [CubeStubModelKeyValueGUID] uniqueidentifier NOT NULL,
    [CubeStubGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [MemberID] nvarchar(450) NOT NULL,
    PRIMARY KEY ([CubeStubModelKeyValueGUID])
);

CREATE CLUSTERED INDEX [IX_EMFCubeStubModelKeyValue] ON [dbo].[EMFCubeStubModelKeyValue] ([CubeStubGUID], [ModelGUID]);
GO
ALTER TABLE [dbo].[EMFCubeStubModelKeyValue] ADD CONSTRAINT [DF_EMFCubeStubModelKeyValue_CUBESTUBMODELKEYVALUEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubModelKeyValueGUID]; GO
ALTER TABLE [dbo].[EMFCubeStubModelKeyValue] ADD CONSTRAINT [DF_EMFCubeStubModelKeyValue_CUBESTUBGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubGUID]; GO
ALTER TABLE [dbo].[EMFCubeStubModelKeyValue] ADD CONSTRAINT [DF_EMFCubeStubModelKeyValue_MODELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[EMFCubeStubModelKeyValue] ADD CONSTRAINT [DF_Table_1_MEMBERGUID] DEFAULT ('') FOR [MemberID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFCubeStubSubtableLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFCubeStubSubtableLink] (
    [CubeStubGUID] uniqueidentifier NOT NULL,
    [SubtableGUID] uniqueidentifier NOT NULL,
    [UpdateBoolean] bit NOT NULL,
    PRIMARY KEY ([CubeStubGUID], [SubtableGUID])
);
GO
ALTER TABLE [dbo].[EMFCubeStubSubtableLink] ADD CONSTRAINT [FK_EMFCubeStubSubtableLink_EMFCubeStub] FOREIGN KEY ([CubeStubGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO
ALTER TABLE [dbo].[EMFCubeStubSubtableLink] ADD CONSTRAINT [FK_EMFCubeStubSubtableLink_EMFSubtable] FOREIGN KEY ([SubtableGUID]) REFERENCES [dbo].[EMFSubtable] ([SUBTABLEGUID]); GO
ALTER TABLE [dbo].[EMFCubeStubSubtableLink] ADD CONSTRAINT [DF_EMFCubeStubSubtableLink_UPDATEBOOLEAN] DEFAULT ((0)) FOR [UpdateBoolean]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFFillIn ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFFillIn] (
    [FillInGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [PlaceholderMemberGUID] uniqueidentifier NOT NULL,
    [FilledInMemberGUID] uniqueidentifier NOT NULL,
    [IsSetByUser] bit NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([FillInGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_EMFFillIn] ON [dbo].[EMFFillIn] ([ModelGUID], [PlaceholderMemberGUID]);
GO
ALTER TABLE [dbo].[EMFFillIn] ADD CONSTRAINT [FK_EMFFillIn_XPlan] FOREIGN KEY ([ModelGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[EMFFillIn] ADD CONSTRAINT [DF_EMFFillIn_FillInGUID] DEFAULT (newsequentialid()) FOR [FillInGUID]; GO
ALTER TABLE [dbo].[EMFFillIn] ADD CONSTRAINT [DF_EMFFillIn_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[EMFFillIn] ADD CONSTRAINT [DF_EMFFillIn_IsSetByUser] DEFAULT ((0)) FOR [IsSetByUser]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFFillInSetManyStaging ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFFillInSetManyStaging] (
    [InstanceGUID] uniqueidentifier NULL,
    [PHDimensionGUID] uniqueidentifier NULL,
    [ModelGUID] uniqueidentifier NULL,
    [ParentPHMemberGUID] uniqueidentifier NULL,
    [FillInGUID] uniqueidentifier NULL,
    [SortOrder] nvarchar(4000) NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFJoinedStructureCalculatedMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] (
    [CALCULATEDMEASUREGUID] uniqueidentifier NOT NULL,
    [StructureGUID] uniqueidentifier NOT NULL,
    [NAME] nvarchar(64) NOT NULL,
    [FORMATSTRING] nvarchar(64) NOT NULL,
    [ColumnWidth] int NOT NULL,
    PRIMARY KEY ([CALCULATEDMEASUREGUID])
);
GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_CALCULATEDMEASUREGUID] DEFAULT (newid()) FOR [CALCULATEDMEASUREGUID]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_JOINEDSTRUCTUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_NAME] DEFAULT ('') FOR [NAME]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_FORMATSTRING] DEFAULT ('#,#0;(#,#0)') FOR [FORMATSTRING]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_ColumnWidth] DEFAULT ((125)) FOR [ColumnWidth]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFJoinedStructureCalculatedMeasureVariable ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] (
    [CalculatedMeasureVariableGUID] uniqueidentifier NOT NULL,
    [CalculatedMeasureGUID] uniqueidentifier NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [StructureGUID] uniqueidentifier NOT NULL,
    [ConstantValue] float NOT NULL,
    [Operation] int NOT NULL,
    [ExecutionOrder] int NOT NULL,
    PRIMARY KEY ([CalculatedMeasureVariableGUID])
);
GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [FK_EMFJoinedStructureCalculatedMeasureVariable_EMFJoinedStructureCalculatedMeasure] FOREIGN KEY ([CalculatedMeasureGUID]) REFERENCES [dbo].[EMFJoinedStructureCalculatedMeasure] ([CALCULATEDMEASUREGUID]); GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_CALCULATEDMEASUREVARIABLEGUID] DEFAULT (newid()) FOR [CalculatedMeasureVariableGUID]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_CALCULATEDMEASUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CalculatedMeasureGUID]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_MEASUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_STRUCTUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_CONSTANTVALUE] DEFAULT ((0)) FOR [ConstantValue]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_OPERATION] DEFAULT ((2)) FOR [Operation]; GO
ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFMeasure] (
    [MEASUREGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [DataType] int NOT NULL,
    [DisplayFormat] nvarchar(255) NOT NULL,
    [IsVisible] bit NOT NULL,
    [IsModelMeasure] bit NOT NULL,
    [AggregateFunctionType] int NOT NULL,
    [IsTextOnly] bit NOT NULL,
    [MinimumValue] float NOT NULL,
    [MaximumValue] float NOT NULL,
    [BoundsType] int NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [IsPlaceholderLabel] bit NOT NULL,
    [PlaceholderDimensionGUID] uniqueidentifier NOT NULL,
    [FillInPropertyIndex] int NOT NULL,
    [IsHideRowIfUnfilled] bit NOT NULL,
    [IsHideColumnIfUnfilled] bit NOT NULL,
    PRIMARY KEY ([MEASUREGUID])
);
GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_MEASUREGUID] DEFAULT (newid()) FOR [MEASUREGUID]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_DATATYPE] DEFAULT ((0)) FOR [DataType]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_DISPLAYFORMAT] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_VISIBLE] DEFAULT ((1)) FOR [IsVisible]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_ISMODELMEASURE] DEFAULT ((1)) FOR [IsModelMeasure]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_AGGREGATEFUNCTIONTYPE] DEFAULT ((0)) FOR [AggregateFunctionType]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_ISTEXTONLY] DEFAULT ('False') FOR [IsTextOnly]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_MINIMUMVALUE] DEFAULT ((0)) FOR [MinimumValue]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_MAXIMUMVALUE] DEFAULT ((0)) FOR [MaximumValue]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_BOUNDSTYPE] DEFAULT ((0)) FOR [BoundsType]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_IsFillInLabel] DEFAULT ((0)) FOR [IsPlaceholderLabel]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_PlaceholderDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderDimensionGUID]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_FillInLabelPropertyIndex] DEFAULT ((-1)) FOR [FillInPropertyIndex]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_IsHideRowsIfUnfilled] DEFAULT ((0)) FOR [IsHideRowIfUnfilled]; GO
ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_IsHideColumnsIfUnfilled] DEFAULT ((0)) FOR [IsHideColumnIfUnfilled]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelDataConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelDataConfig] (
    [ModelDataConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [Version] timestamp NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [IsExpandable] bit NOT NULL,
    [LastProcessed] datetime NOT NULL,
    [LastProcessRequest] datetime NOT NULL,
    [ProcessInterval] int NOT NULL,
    [ShortcutName] nvarchar(16) NOT NULL,
    [FormatOverrideDimensionGUID] uniqueidentifier NOT NULL,
    [IsSetupLocked] bit NOT NULL,
    PRIMARY KEY ([ModelDataConfigGUID])
);
GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_FormatOverrideDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormatOverrideDimensionGUID]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelSetup_MODELSETUPGUID] DEFAULT (newid()) FOR [ModelDataConfigGUID]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelSetup_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_IsSetupLocked] DEFAULT ((0)) FOR [IsSetupLocked]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelStructure_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_LastProcessed] DEFAULT (getdate()) FOR [LastProcessed]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_LastProcessRequest] DEFAULT (getdate()) FOR [LastProcessRequest]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_ProcessInterval] DEFAULT ((900)) FOR [ProcessInterval]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_ShortcutName] DEFAULT ('') FOR [ShortcutName]; GO
ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_IsExpandable] DEFAULT ((0)) FOR [IsExpandable]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelDataConfigDimensionLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelDataConfigDimensionLink] (
    [ModelDataConfigGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [IsModelKey] bit NOT NULL,
    [IsFilterMember] bit NOT NULL,
    [IsUniqueIndexMember] bit NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([ModelDataConfigGUID], [DimensionGUID])
);
GO
ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [FK_MDC_MDC_Dim_Link] FOREIGN KEY ([ModelDataConfigGUID]) REFERENCES [dbo].[EMFModelDataConfig] ([ModelDataConfigGUID]); GO
ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_DimensionSet_DIMENSIONSETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelDataConfigGUID]; GO
ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_DimensionSet_NAME] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_EMFModelDataConfigDimensionLink_ISMODELKEY] DEFAULT ((0)) FOR [IsModelKey]; GO
ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_EMFModelDataConfigDimensionLink_ISFILTERMEMBER] DEFAULT ((0)) FOR [IsFilterMember]; GO
ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_EMFModelDataConfigDimensionLink_ISUNIQUEINDEXMEMBER] DEFAULT ((0)) FOR [IsUniqueIndexMember]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelDataConfigMeasureLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelDataConfigMeasureLink] (
    [ModelDataConfigGUID] uniqueidentifier NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([ModelDataConfigGUID], [MeasureGUID])
);
GO
ALTER TABLE [dbo].[EMFModelDataConfigMeasureLink] ADD CONSTRAINT [FK_MDC_MDC_Meas_Link] FOREIGN KEY ([ModelDataConfigGUID]) REFERENCES [dbo].[EMFModelDataConfig] ([ModelDataConfigGUID]); GO
ALTER TABLE [dbo].[EMFModelDataConfigMeasureLink] ADD CONSTRAINT [FK_Meas_MDC_Meas_Link] FOREIGN KEY ([MeasureGUID]) REFERENCES [dbo].[EMFMeasure] ([MEASUREGUID]); GO
ALTER TABLE [dbo].[EMFModelDataConfigMeasureLink] ADD CONSTRAINT [DF_EMFModelSetupMeasureLink_MODELSETUPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelDataConfigGUID]; GO
ALTER TABLE [dbo].[EMFModelDataConfigMeasureLink] ADD CONSTRAINT [DF_EMFModelSetupMeasureLink_MEASUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelDataLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelDataLink] (
    [ModelDataLinkGUID] uniqueidentifier NOT NULL,
    [LinkSourceGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [ParentModelGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ModelDataLinkGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_EMFMODELDATALINK] ON [dbo].[EMFModelDataLink] ([ModelGUID], [LinkSourceGUID], [ParentModelGUID]);
GO
ALTER TABLE [dbo].[EMFModelDataLink] ADD CONSTRAINT [FK_EMFModelLink_EMFModelTemplateLinkSource] FOREIGN KEY ([LinkSourceGUID]) REFERENCES [dbo].[EMFModelTemplateLinkSource] ([LinkSourceGUID]); GO
ALTER TABLE [dbo].[EMFModelDataLink] ADD CONSTRAINT [DF_EMFModelDataLink_MODELDATALINKGUID] DEFAULT (newid()) FOR [ModelDataLinkGUID]; GO
ALTER TABLE [dbo].[EMFModelDataLink] ADD CONSTRAINT [DF_EMFModelDependency_MODELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[EMFModelDataLink] ADD CONSTRAINT [DF_EMFModelDependency_PARENTMODELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentModelGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelTemplate ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelTemplate] (
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [Version] timestamp NOT NULL,
    [Type] int NOT NULL,
    [IsPublished] bit NOT NULL,
    [IsExpanded] bit NOT NULL,
    [IsSafeModeOn] bit NOT NULL,
    [DefaultFormGUID] uniqueidentifier NOT NULL,
    [IsNewLabelsOnly] bit NOT NULL,
    [IsUsingHashJoin] bit NOT NULL,
    [IsScoreFillinAdvancedMode] bit NOT NULL,
    [IsModelWorkbookCachable] bit NOT NULL,
    [HasModelDependents] bit NOT NULL,
    [IsModelRefreshOnFillinChange] bit NOT NULL,
    [IsReadUncommittedLoad] bit NOT NULL,
    [IsReadUncommittedSave] bit NOT NULL,
    [IsMemoryCachable] bit NOT NULL,
    [PublishOrder] int NOT NULL,
    [EditExpansionsMode] tinyint NOT NULL,
    [TemplateVersion] varchar(20) NOT NULL,
    [IsUsingOpenWorkbookFormat] bit NOT NULL,
    [IsHidden] bit NOT NULL,
    PRIMARY KEY ([ModelTemplateGUID])
);
GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__Templ__044BF490] DEFAULT ('') FOR [TemplateVersion]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsHidden] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__Publi__23B81C43] DEFAULT ((0)) FOR [PublishOrder]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsMem__29502EB1] DEFAULT ((0)) FOR [IsMemoryCachable]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsMod__3B6DE1CB] DEFAULT ((0)) FOR [IsModelWorkbookCachable]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_HasModelDependents] DEFAULT ((1)) FOR [HasModelDependents]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsMod__3E4A4E76] DEFAULT ((1)) FOR [IsModelRefreshOnFillinChange]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsRea__3F3E72AF] DEFAULT ((0)) FOR [IsReadUncommittedLoad]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsRea__403296E8] DEFAULT ((0)) FOR [IsReadUncommittedSave]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsUsingHashJoin] DEFAULT ((0)) FOR [IsUsingHashJoin]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsUsingOpenWorkbookFormat] DEFAULT ((0)) FOR [IsUsingOpenWorkbookFormat]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_MODELTEMPLATEGUID] DEFAULT (newid()) FOR [ModelTemplateGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_EditExpansionsMode] DEFAULT ((0)) FOR [EditExpansionsMode]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_DefaultFormGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultFormGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsNewLabelsOnly] DEFAULT ((0)) FOR [IsNewLabelsOnly]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_ISPUBLISHED] DEFAULT ((0)) FOR [IsPublished]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsSafeModeOn] DEFAULT ((0)) FOR [IsSafeModeOn]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsExpanded] DEFAULT ((1)) FOR [IsExpanded]; GO
ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsScoreFillinAdvancedMode] DEFAULT ((0)) FOR [IsScoreFillinAdvancedMode]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelTemplateExpansion ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelTemplateExpansion] (
    [ExpansionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [CellGUID] uniqueidentifier NOT NULL,
    [DimensionMemberGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([ExpansionGUID])
);
GO
ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFExpansionInfo_EXPANSIONGUID] DEFAULT (newid()) FOR [ExpansionGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFModelTemplateExpansion_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFModelTemplateExpansion_CellGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CellGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFExpansionInfo_DIMENSIONMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionMemberGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFModelTemplateExpansion_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelTemplateFormFieldMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelTemplateFormFieldMapping] (
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [CellGUID] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [dbo].[EMFModelTemplateFormFieldMapping] ADD CONSTRAINT [DF_EMFModelTemplateFormFieldMapping_FORMFIELDGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateFormFieldMapping] ADD CONSTRAINT [DF_EMFModelTemplateFormFieldMapping_CellGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CellGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelTemplateFramework ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelTemplateFramework] (
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    PRIMARY KEY ([ModelTemplateGUID], [FrameworkID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelTemplateLinkSource ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelTemplateLinkSource] (
    [LinkSourceGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [ParentSubtableGUID] uniqueidentifier NOT NULL,
    [ParentModelDataConfigGUID] uniqueidentifier NOT NULL,
    [ParentScoreCompositeTableGUID] uniqueidentifier NOT NULL,
    [IsSelf] bit NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([LinkSourceGUID])
);
GO
ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [FK_EMFModelTemplateLinkSource_EMFModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO
ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFModelTemplateLinkSource_ParentScoreCompositeTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentScoreCompositeTableGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFModelTemplateLinkSource_ISSELF] DEFAULT ((0)) FOR [IsSelf]; GO
ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFLinkSource_LINKSOURCEGUID] DEFAULT (newid()) FOR [LinkSourceGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFLinkSource_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFLinkSource_MODELTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFModelTemplateLinkSource_PARENTSUBTABLEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentSubtableGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFModelTemplateLinkSource_PARENTSTRUCTUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentModelDataConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelTemplatePlaceholderLabelMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] (
    [MappingGUID] uniqueidentifier NOT NULL,
    [PlaceholderDimensionGUID] uniqueidentifier NOT NULL,
    [PlaceholderMemberGUID] uniqueidentifier NOT NULL,
    [LabelPropertyGUID] uniqueidentifier NOT NULL,
    [IsHidingRow] bit NOT NULL,
    [IsHidingCol] bit NOT NULL,
    [CellGUID] uniqueidentifier NOT NULL,
    [RowExpanded] int NOT NULL,
    [IsUserMapped] bit NOT NULL,
    [IsClearingRow] bit NOT NULL,
    [IsClearingCol] bit NOT NULL,
    PRIMARY KEY ([MappingGUID])
);
GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_MappingGUID] DEFAULT (newid()) FOR [MappingGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_PlaceholderDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderDimensionGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_PlaceholderMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderMemberGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_Table_1_PropertyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LabelPropertyGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_Table_1_IsHidingRow] DEFAULT ((1)) FOR [IsHidingRow]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_Table_1_IsHidingCol] DEFAULT ((0)) FOR [IsHidingCol]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_CellGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CellGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_Row] DEFAULT ((0)) FOR [RowExpanded]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_IsUserMapped] DEFAULT ((1)) FOR [IsUserMapped]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_IsClearingRow] DEFAULT ((0)) FOR [IsClearingRow]; GO
ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_IsClearingCol] DEFAULT ((0)) FOR [IsClearingCol]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelTemplateWorksheet ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelTemplateWorksheet] (
    [WorksheetGUID] uniqueidentifier NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(max) NOT NULL,
    [DesignerMetaData] nvarchar(max) NOT NULL,
    [TransformStateGUID] uniqueidentifier NOT NULL,
    [IsImprov] bit NOT NULL,
    [IsHiddenOnExpand] bit NOT NULL,
    [HiddenRows] int NOT NULL,
    [HiddenColumns] int NOT NULL,
    [IsHeadingsHiddenOnExpand] bit NOT NULL,
    [ZoomLevel] int NOT NULL,
    [IsChartsEnabled] bit NOT NULL,
    [NameSourceAddress] nvarchar(50) NOT NULL,
    [DefaultCellAddress] nvarchar(50) NOT NULL,
    [FreezePanesCellAddress] nvarchar(50) NOT NULL,
    [IsDefaultSheet] bit NOT NULL,
    [CounterCellAddress] nvarchar(50) NOT NULL,
    [CloneCount] tinyint NOT NULL,
    [IsClearingByNameCell] bit NOT NULL,
    PRIMARY KEY ([WorksheetGUID])
);

CREATE NONCLUSTERED INDEX [NC_TEMPLATE] ON [dbo].[EMFModelTemplateWorksheet] ([WorksheetGUID], [ModelTemplateGUID]);
GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [FK_EMFModelTemplateWorksheet_EMFModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFMODELTEMPLATEWORKSHEET_WORKSHEETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorksheetGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFMODELTEMPLATEWORKSHEET_MODELTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFMODELTEMPLATEWORKSHEET_WORKSHEETNAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_DESIGNERMETADATAXML] DEFAULT ('') FOR [DesignerMetaData]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_TRANSFORMSTATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TransformStateGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsImprov] DEFAULT ((0)) FOR [IsImprov]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsHiddenOnExpand] DEFAULT ((0)) FOR [IsHiddenOnExpand]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_HiddenRows] DEFAULT ((0)) FOR [HiddenRows]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_HiddenColumns] DEFAULT ((0)) FOR [HiddenColumns]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsHeadingsHiddenOnExpand] DEFAULT ((0)) FOR [IsHeadingsHiddenOnExpand]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_ZoomLevel] DEFAULT ((0)) FOR [ZoomLevel]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsChartsEnabled] DEFAULT ((0)) FOR [IsChartsEnabled]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsClearingByNameCell] DEFAULT ((0)) FOR [IsClearingByNameCell]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_NameSourceAddress] DEFAULT ('') FOR [NameSourceAddress]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_DefaultCellAddress] DEFAULT ('') FOR [DefaultCellAddress]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_FreezePanesCellAddress] DEFAULT ('') FOR [FreezePanesCellAddress]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsDefaultSheet] DEFAULT ((0)) FOR [IsDefaultSheet]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_CounterCellAddress] DEFAULT ('') FOR [CounterCellAddress]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_CloneCount] DEFAULT ((0)) FOR [CloneCount]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFModelTemplateWorksheetRange ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFModelTemplateWorksheetRange] (
    [ModelTemplateRangeGUID] uniqueidentifier NOT NULL,
    [WorksheetGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [RangeName] nvarchar(128) NOT NULL,
    [IsCustomizable] bit NOT NULL,
    PRIMARY KEY ([ModelTemplateRangeGUID])
);
GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [FK_EMFModelTemplateWorksheetRange_EMFModelTemplateWorksheet] FOREIGN KEY ([WorksheetGUID]) REFERENCES [dbo].[EMFModelTemplateWorksheet] ([WorksheetGUID]); GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF__EMFModelT__Model__6C2393F0] DEFAULT (newid()) FOR [ModelTemplateRangeGUID]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF__EMFModelTe__Name__6E0BDC62] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF_EMFModelTemplateWorksheetRange_RangeName] DEFAULT ('') FOR [RangeName]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF__EMFModelT__IsCus__6F00009B] DEFAULT ((0)) FOR [IsCustomizable]; GO
ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF__EMFModelT__Works__6D17B829] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorksheetGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFScenario ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFScenario] (
    [SCENARIOGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Type] int NOT NULL,
    PRIMARY KEY ([SCENARIOGUID])
);
GO
ALTER TABLE [dbo].[EMFScenario] ADD CONSTRAINT [DF_EMFScenario_Type] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[EMFScenario] ADD CONSTRAINT [DF_EMFScenario_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[EMFScenario] ADD CONSTRAINT [DF_EMFScenario_ScenarioGUID] DEFAULT (newid()) FOR [SCENARIOGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFStrataStructureConvertedScoreCompositeLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFStrataStructureConvertedScoreCompositeLink] (
    [StructureGUID] uniqueidentifier NOT NULL,
    [ScoreCompositeGUID] uniqueidentifier NOT NULL,
    [StructureType] int NOT NULL,
    PRIMARY KEY ([StructureGUID])
);
GO
ALTER TABLE [dbo].[EMFStrataStructureConvertedScoreCompositeLink] ADD CONSTRAINT [DF__EMFStrata__Struc__420E29EA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO
ALTER TABLE [dbo].[EMFStrataStructureConvertedScoreCompositeLink] ADD CONSTRAINT [DF__EMFStrata__Score__43024E23] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreCompositeGUID]; GO
ALTER TABLE [dbo].[EMFStrataStructureConvertedScoreCompositeLink] ADD CONSTRAINT [DF__EMFStrata__Struc__43F6725C] DEFAULT ((0)) FOR [StructureType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFSubtable ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFSubtable] (
    [SUBTABLEGUID] uniqueidentifier NOT NULL,
    [MODELDATACONFIGGUID] uniqueidentifier NOT NULL,
    [PARENTSUBTABLEGUID] uniqueidentifier NOT NULL,
    [FOLDERGUID] uniqueidentifier NOT NULL,
    [NAME] nvarchar(64) NOT NULL,
    [DESCRIPTION] nvarchar(450) NOT NULL,
    [MEASUREGUID] uniqueidentifier NOT NULL,
    [AGGREGATIONFUNCTION] int NOT NULL,
    [ISALLOWINGFROZENROWS] bit NOT NULL,
    [ISALLOWINGFROZENCOLUMNS] bit NOT NULL,
    [CUSTOMMENUGUID] uniqueidentifier NOT NULL,
    [IsLoadingExistingData] bit NOT NULL,
    [IsReadOnly] bit NOT NULL,
    [IsShowingDateTimeStamp] bit NOT NULL,
    [RowHeight] int NOT NULL,
    [IsShowingModifiedUser] bit NOT NULL,
    [IsAutoRefreshingPlanCalculations] bit NOT NULL,
    PRIMARY KEY ([SUBTABLEGUID])
);
GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_SUBTABLECONFIGGUID] DEFAULT (newid()) FOR [SUBTABLEGUID]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_SUBTABLEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MODELDATACONFIGGUID]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_PARENTSUBTABLECONFIGGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PARENTSUBTABLEGUID]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FOLDERGUID]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_NAME] DEFAULT ('') FOR [NAME]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_DESCRIPTION] DEFAULT ('') FOR [DESCRIPTION]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_MEASUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MEASUREGUID]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_AGGREGATIONFUNCTION] DEFAULT ((0)) FOR [AGGREGATIONFUNCTION]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_ISALLOWINGNEWROWS] DEFAULT ((1)) FOR [ISALLOWINGFROZENROWS]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_ISALLOWINGNEWCOLUMNS] DEFAULT ((0)) FOR [ISALLOWINGFROZENCOLUMNS]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_CUSTOMMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CUSTOMMENUGUID]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsLoadingExistingData] DEFAULT ((1)) FOR [IsLoadingExistingData]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsShowingDateTimeStamp] DEFAULT ((0)) FOR [IsShowingDateTimeStamp]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_RowHeight] DEFAULT ((25)) FOR [RowHeight]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsShowingLastUserModified] DEFAULT ((0)) FOR [IsShowingModifiedUser]; GO
ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsAutoRefreshingPlanCalculations] DEFAULT ((0)) FOR [IsAutoRefreshingPlanCalculations]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFSubtableDefaultTuple ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFSubtableDefaultTuple] (
    [SUBTABLEDEFAULTTUPLEGUID] uniqueidentifier NOT NULL,
    [SUBTABLEGUID] uniqueidentifier NOT NULL,
    [ISONCOLUMN] bit NOT NULL,
    [DIMENSIONTUPLEXML] xml NOT NULL,
    PRIMARY KEY ([SUBTABLEDEFAULTTUPLEGUID])
);
GO
ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [FK_EMFSubtableDefaultTuple_EMFSubtable] FOREIGN KEY ([SUBTABLEGUID]) REFERENCES [dbo].[EMFSubtable] ([SUBTABLEGUID]); GO
ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [DF_EMFSubtableDefaultTuple_SUBTABLEDEFAULTTUPLEGUID] DEFAULT (newid()) FOR [SUBTABLEDEFAULTTUPLEGUID]; GO
ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [DF_EMFSubtableDefaultTuple_SUBTABLEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SUBTABLEGUID]; GO
ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [DF_EMFSubtableDefaultTuple_ISONCOLUMN] DEFAULT ((0)) FOR [ISONCOLUMN]; GO
ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [DF_EMFSubtableDefaultTuple_DIMENSIONTUPLEXML] DEFAULT ('') FOR [DIMENSIONTUPLEXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFSubtableDimensionLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFSubtableDimensionLink] (
    [SUBTABLEDIMENSIONLINKGUID] uniqueidentifier NOT NULL,
    [SubtableGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [FilterParentMemberGUID] uniqueidentifier NOT NULL,
    [Level] int NOT NULL,
    [IsParameter] bit NOT NULL,
    [IsAggregable] bit NOT NULL,
    [IsDisplayOnColumns] bit NOT NULL,
    [IsEditable] bit NOT NULL,
    [IsVisible] bit NOT NULL,
    [DefaultMemberGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ColumnWidth] int NOT NULL,
    [ISLOADINGCHILDMEMBERS] bit NOT NULL,
    [FRIENDLYNAME] nvarchar(64) NOT NULL,
    [AutoCompleteSearchType] int NOT NULL,
    [IsIgnoringReadSecurity] bit NOT NULL,
    PRIMARY KEY ([SUBTABLEDIMENSIONLINKGUID])
);
GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [FK_EMFSubTableDimensionLink_EMFSubTable] FOREIGN KEY ([SubtableGUID]) REFERENCES [dbo].[EMFSubtable] ([SUBTABLEGUID]); GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_IsIgnoringReadSecurity] DEFAULT ((0)) FOR [IsIgnoringReadSecurity]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubTableConfigDimensionLink_SUBTABLECONFIGDIMENSIONLINKGUID] DEFAULT (newid()) FOR [SUBTABLEDIMENSIONLINKGUID]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_SubTableConfigDimensionLink_SUBTABLECONFIGGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SubtableGUID]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_SubTableConfigDimensionLink_DIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubTableConfigDimensionLink_DIMENSIONMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FilterParentMemberGUID]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubTableConfigDimension_DIMENSIONLEVEL] DEFAULT ((0)) FOR [Level]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_SubTableConfigDimensionLink_ISPARAMETER] DEFAULT ((0)) FOR [IsParameter]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_SubTableConfigDimensionLink_ISAGGREGATABLE] DEFAULT ((0)) FOR [IsAggregable]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_ISDISPLAYONCOLUMNS] DEFAULT ((0)) FOR [IsDisplayOnColumns]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_ISALLOWINGDEFAULTMEMBERONLY] DEFAULT ((1)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_ISVISIBLE] DEFAULT ((1)) FOR [IsVisible]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_DEFAULTMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultMemberGUID]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_COLUMNWIDTH] DEFAULT ((100)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_ISLOADINGCHILDMEMBERS] DEFAULT ((0)) FOR [ISLOADINGCHILDMEMBERS]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_FRIENDLYNAME] DEFAULT ('') FOR [FRIENDLYNAME]; GO
ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_AutoCompleteSearchType] DEFAULT ((0)) FOR [AutoCompleteSearchType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFSubtableFilter ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFSubtableFilter] (
    [SubtableDimensionLinkGUID] uniqueidentifier NOT NULL,
    [DimensionMemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SubtableDimensionLinkGUID], [DimensionMemberGUID])
);
GO
ALTER TABLE [dbo].[EMFSubtableFilter] ADD CONSTRAINT [FK_EMFSubTableFilter_EMFSubTableDimensionLink] FOREIGN KEY ([SubtableDimensionLinkGUID]) REFERENCES [dbo].[EMFSubtableDimensionLink] ([SUBTABLEDIMENSIONLINKGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.EMFSubtableMeasureLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[EMFSubtableMeasureLink] (
    [SubtableMeasureLinkGUID] uniqueidentifier NOT NULL,
    [SubtableGUID] uniqueidentifier NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [AggregationFunction] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ColumnWidth] int NOT NULL,
    [IsRequired] bit NOT NULL,
    [IsReadOnly] bit NOT NULL,
    PRIMARY KEY ([SubtableMeasureLinkGUID])
);
GO
ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_SUBTABLEMEASURELINKGUID] DEFAULT (newid()) FOR [SubtableMeasureLinkGUID]; GO
ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_AGGREGATIONFUNCTION] DEFAULT ((0)) FOR [AggregationFunction]; GO
ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_COLUMNWIDTH] DEFAULT ((125)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_IsRequired] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EmailMessage ------------------
---------------------------------------------
CREATE TABLE [dbo].[EmailMessage] (
    [EmailMessageGUID] uniqueidentifier NOT NULL,
    [EmailThreadGUID] uniqueidentifier NOT NULL,
    [Subject] nvarchar(450) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [Body] nvarchar(max) NOT NULL,
    [SenderUserGUID] uniqueidentifier NOT NULL,
    [Priority] tinyint NOT NULL,
    PRIMARY KEY ([EmailMessageGUID])
);
GO
ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [FK_EmailMessage_EmailThread] FOREIGN KEY ([EmailThreadGUID]) REFERENCES [dbo].[EmailThread] ([EmailThreadGUID]); GO
ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_EmailMessageThreadGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EmailThreadGUID]; GO
ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_EmailMessageGUID] DEFAULT (newid()) FOR [EmailMessageGUID]; GO
ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_Subject] DEFAULT ('') FOR [Subject]; GO
ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_Body] DEFAULT ('') FOR [Body]; GO
ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_SenderUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SenderUserGUID]; GO
ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_Priority] DEFAULT ((0)) FOR [Priority]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EmailRecipient ------------------
---------------------------------------------
CREATE TABLE [dbo].[EmailRecipient] (
    [EmailRecipientGUID] uniqueidentifier NOT NULL,
    [EmailMessageGUID] uniqueidentifier NOT NULL,
    [IdentityGUID] uniqueidentifier NOT NULL,
    [IdentityType] tinyint NOT NULL,
    [RecipientType] tinyint NOT NULL,
    PRIMARY KEY ([EmailRecipientGUID])
);
GO
ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [FK_EmailRecipient_EmailMessage] FOREIGN KEY ([EmailMessageGUID]) REFERENCES [dbo].[EmailMessage] ([EmailMessageGUID]); GO
ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_EmailMessageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EmailMessageGUID]; GO
ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_IdentityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentityGUID]; GO
ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_EmailRecipientGUID] DEFAULT (newid()) FOR [EmailRecipientGUID]; GO
ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_IdentityType] DEFAULT ((0)) FOR [IdentityType]; GO
ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_RecipientType] DEFAULT ((0)) FOR [RecipientType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EmailThread ------------------
---------------------------------------------
CREATE TABLE [dbo].[EmailThread] (
    [EmailThreadGUID] uniqueidentifier NOT NULL,
    [Subject] nvarchar(450) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [ItemGUID] uniqueidentifier NOT NULL,
    [IsForReporting] bit NOT NULL,
    [IsPrivate] bit NOT NULL,
    PRIMARY KEY ([EmailThreadGUID])
);
GO
ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_EmailThreadGUID] DEFAULT (newid()) FOR [EmailThreadGUID]; GO
ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_Subject] DEFAULT ('') FOR [Subject]; GO
ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_ItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ItemGUID]; GO
ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_IsPrivate] DEFAULT ((0)) FOR [IsPrivate]; GO
ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_IsForReporting] DEFAULT ((0)) FOR [IsForReporting]; GO

---------------------------------------------

---------------------------------------------
-- dbo.EntityView ------------------
---------------------------------------------
CREATE TABLE [dbo].[EntityView] (
    [ENTITYVIEWGUID] uniqueidentifier NOT NULL,
    [NAME] nvarchar(64) NOT NULL,
    [DESCRIPTION] nvarchar(4000) NOT NULL,
    [DATECREATED] datetime NOT NULL,
    [FOLDERGUID] uniqueidentifier NOT NULL,
    [USERGUID] uniqueidentifier NOT NULL,
    [VIEWTYPE] int NOT NULL,
    [SearchText] nvarchar(max) NOT NULL,
    [SearchDescription] nvarchar(max) NOT NULL,
    [ProviderType] int NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [GridTemplateGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ENTITYVIEWGUID])
);
GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_View_VIEWGUID] DEFAULT (newid()) FOR [ENTITYVIEWGUID]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_View_NAME] DEFAULT ('') FOR [NAME]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_DESCRIPTION] DEFAULT ('') FOR [DESCRIPTION]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FOLDERGUID]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [USERGUID]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_VIEWTYPE] DEFAULT ((0)) FOR [VIEWTYPE]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_GridTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GridTemplateGUID]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_SearchText] DEFAULT ('') FOR [SearchText]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_SearchDescription] DEFAULT ('') FOR [SearchDescription]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_ProviderType] DEFAULT ((0)) FOR [ProviderType]; GO
ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.Event ------------------
---------------------------------------------
CREATE TABLE [dbo].[Event] (
    [EventName] varchar(64) NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([EventName])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ExtractReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[ExtractReportSetup] (
    [ExtractReportSetupID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [ColumnSetupXML] nvarchar(max) NOT NULL,
    [SetupXML] nvarchar(max) NOT NULL,
    [ReportTypeVal] tinyint NOT NULL
);
GO
ALTER TABLE [dbo].[ExtractReportSetup] ADD CONSTRAINT [DF__ExtractRep__Name__4C5C079B] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[ExtractReportSetup] ADD CONSTRAINT [DF__ExtractRe__Colum__4D502BD4] DEFAULT ('') FOR [ColumnSetupXML]; GO
ALTER TABLE [dbo].[ExtractReportSetup] ADD CONSTRAINT [DF__ExtractRe__Setup__4E44500D] DEFAULT ('') FOR [SetupXML]; GO
ALTER TABLE [dbo].[ExtractReportSetup] ADD CONSTRAINT [DF__ExtractRe__Repor__4F387446] DEFAULT ((0)) FOR [ReportTypeVal]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2AccessOverride ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2AccessOverride] (
    [AccessOverrideGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [IsWriteDeny] bit NOT NULL,
    [IsWriteAllow] bit NOT NULL,
    PRIMARY KEY ([AccessOverrideGUID])
);

CREATE NONCLUSTERED INDEX [NCNU_FormFieldGUID] ON [dbo].[FE2AccessOverride] ([FormFieldGUID]);
CREATE NONCLUSTERED INDEX [NCNU_FormFieldGUID_EntityGUID] ON [dbo].[FE2AccessOverride] ([FormFieldGUID], [EntityGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_FormFieldGUID_EntityGUID_UserGUID] ON [dbo].[FE2AccessOverride] ([FormFieldGUID], [EntityGUID], [UserGUID]);
GO
ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [FK_FE2AccessOverride_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [FK_FE2AccessOverride_XPlan] FOREIGN KEY ([EntityGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_IsReadDeny] DEFAULT ((0)) FOR [IsWriteDeny]; GO
ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_IsWriteAllow] DEFAULT ((0)) FOR [IsWriteAllow]; GO
ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_AccessOverrideGUID] DEFAULT (newid()) FOR [AccessOverrideGUID]; GO
ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO
ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2CapitalHiddenElement_TK28067 ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2CapitalHiddenElement_TK28067] (
    [FormElementGUID] uniqueidentifier NOT NULL,
    [FormGUID] uniqueidentifier NOT NULL,
    [ProjectTypeID] int NOT NULL
);
GO
ALTER TABLE [dbo].[FE2CapitalHiddenElement_TK28067] ADD CONSTRAINT [FK__FE2Capita__FormG__7AABE50F] FOREIGN KEY ([FormGUID]) REFERENCES [dbo].[FE2Form] ([FormGUID]); GO
ALTER TABLE [dbo].[FE2CapitalHiddenElement_TK28067] ADD CONSTRAINT [DF__FE2Capita__Proje__7BA00948] DEFAULT ((0)) FOR [ProjectTypeID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2Form ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2Form] (
    [FormGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Description] nvarchar(400) NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [CustomToolbarGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [IsHidden] bit NOT NULL,
    [CustomMenuGUID] uniqueidentifier NOT NULL,
    [OldFormGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FormGUID])
);
GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__OldForm__21DE87B2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OldFormGUID]; GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__PlanTyp__7691D4F5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__FormGUI__35B835D1] DEFAULT (newid()) FOR [FormGUID]; GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__Name__36AC5A0A] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__Descrip__37A07E43] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__GlobalI__3894A27C] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__CustomT__3988C6B5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomToolbarGUID]; GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__IsHidde__6A8E52C8] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__CustomM__713B5057] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomMenuGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2FormField ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2FormField] (
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [FormSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [FieldType] tinyint NOT NULL,
    [DataSourceType] tinyint NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [Row] int NOT NULL,
    [Col] int NOT NULL,
    [HelpText] nvarchar(2000) NOT NULL,
    [FormatString] nvarchar(100) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ColSpan] tinyint NOT NULL,
    [IsReadOnly] bit NOT NULL,
    [IsRequired] tinyint NOT NULL,
    [DefaultSortOrder] tinyint NOT NULL,
    [HelpTextDisplayType] tinyint NOT NULL,
    [DefaultValue] nvarchar(450) NOT NULL,
    [MinValue] decimal NOT NULL,
    [MaxValue] decimal NOT NULL,
    [MinLength] int NOT NULL,
    [MaxLength] int NOT NULL,
    [SpecialFieldClassName] nvarchar(100) NOT NULL,
    [SpecialFieldConfig] nvarchar(max) NOT NULL,
    [ComputedFieldClassName] nvarchar(100) NOT NULL,
    [ComputedFieldConfig] nvarchar(max) NOT NULL,
    [ListSourceClassName] nvarchar(100) NOT NULL,
    [ListSourceConfig] nvarchar(max) NOT NULL,
    [IsFullTextSearchable] bit NOT NULL,
    [Abbreviation] nvarchar(100) NOT NULL,
    [HasLabel] bit NOT NULL,
    [RenderType] int NOT NULL,
    [RenderThreshold] float NOT NULL,
    [RenderComparisonFieldGUID] uniqueidentifier NOT NULL,
    [RenderComparisonOperator] int NOT NULL,
    [OldFormFieldGUID] uniqueidentifier NOT NULL,
    [OldFormFieldName] nvarchar(450) NULL,
    [ShowInDirectory] bit NOT NULL,
    [IsEditableInDirectory] bit NOT NULL,
    [Height] int NOT NULL,
    [IsDeletable] bit NOT NULL,
    [IsStrataField] bit NOT NULL,
    [IsDesignerEditable] bit NOT NULL,
    [IsDesignerHidden] bit NOT NULL,
    PRIMARY KEY ([FormFieldGUID])
);
GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [FK__FE2FormFi__FormS__506C2C0D] FOREIGN KEY ([FormSectionGUID]) REFERENCES [dbo].[FE2FormSection] ([FormSectionGUID]); GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_ComputedFieldClassName] DEFAULT ('') FOR [ComputedFieldClassName]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_ComputedFieldConfig] DEFAULT ('') FOR [ComputedFieldConfig]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__HasLa__06366D3D] DEFAULT ((1)) FOR [HasLabel]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Rende__072A9176] DEFAULT ((0)) FOR [RenderType]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Rende__081EB5AF] DEFAULT ((0)) FOR [RenderThreshold]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Rende__0912D9E8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RenderComparisonFieldGUID]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__ListS__09A4A969] DEFAULT ('') FOR [ListSourceClassName]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Rende__0A06FE21] DEFAULT ((0)) FOR [RenderComparisonOperator]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__ListS__0A98CDA2] DEFAULT ('') FOR [ListSourceConfig]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_OldFormFieldName] DEFAULT ('') FOR [OldFormFieldName]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Sourc__5530E12A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__ShowI__1FF63F40] DEFAULT ((0)) FOR [ShowInDirectory]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_OldFormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OldFormFieldGUID]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__FormF__4F7807D4] DEFAULT (newid()) FOR [FormFieldGUID]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFie__Name__51605046] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Globa__5254747F] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Field__534898B8] DEFAULT ((0)) FOR [FieldType]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Sourc__543CBCF1] DEFAULT ((0)) FOR [DataSourceType]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFiel__Row__56250563] DEFAULT ((0)) FOR [Row]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFiel__Col__5719299C] DEFAULT ((0)) FOR [Col]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsDes__585960DA] DEFAULT ((0)) FOR [IsDesignerHidden]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__HelpT__59F59647] DEFAULT ('') FOR [HelpText]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Forma__5AE9BA80] DEFAULT ('') FOR [FormatString]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Heigh__5F4853FC] DEFAULT ((0)) FOR [Height]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Displ__637F0081] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__ColSp__656748F3] DEFAULT ((0)) FOR [ColSpan]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_IsRequired] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_DefaultSortOrder] DEFAULT ((0)) FOR [DefaultSortOrder]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_HelpTextDisplayType] DEFAULT ((0)) FOR [HelpTextDisplayType]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_DefaultValue] DEFAULT ('') FOR [DefaultValue]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_MinValue] DEFAULT ((0)) FOR [MinValue]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsFul__6B827701] DEFAULT ((0)) FOR [IsFullTextSearchable]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_MaxValue] DEFAULT ((0)) FOR [MaxValue]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_Abbreviation] DEFAULT ('') FOR [Abbreviation]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__MinLe__3A42832D] DEFAULT ((0)) FOR [MinLength]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__MaxLe__394E5EF4] DEFAULT ((0)) FOR [MaxLength]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsEdi__75E0D53A] DEFAULT ((0)) FOR [IsEditableInDirectory]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsDel__76DB542B] DEFAULT ((1)) FOR [IsDeletable]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Speci__796E41A0] DEFAULT ('') FOR [SpecialFieldClassName]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Speci__7A6265D9] DEFAULT ('') FOR [SpecialFieldConfig]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsStr__7D15E43D] DEFAULT ((0)) FOR [IsStrataField]; GO
ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsDes__7E0A0876] DEFAULT ((1)) FOR [IsDesignerEditable]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2FormFieldRefreshRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2FormFieldRefreshRequest] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [FormFieldGUIDCSV] nvarchar(max) NOT NULL,
    [PlanLookupSQL] nvarchar(max) NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RequestGUID])
);
GO
ALTER TABLE [dbo].[FE2FormFieldRefreshRequest] ADD CONSTRAINT [DF_FE2FormFieldRefreshRequest_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[FE2FormFieldRefreshRequest] ADD CONSTRAINT [DF_FE2FormFieldRefreshRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [dbo].[FE2FormFieldRefreshRequest] ADD CONSTRAINT [DF_FE2FormFieldRefreshRequest_FormFieldGUIDCSV] DEFAULT ('') FOR [FormFieldGUIDCSV]; GO
ALTER TABLE [dbo].[FE2FormFieldRefreshRequest] ADD CONSTRAINT [DF_FE2FormFieldRefreshRequest_PlanLookupSQL] DEFAULT ('') FOR [PlanLookupSQL]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2FormFieldSynonym ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2FormFieldSynonym] (
    [SynonymGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    PRIMARY KEY ([SynonymGUID])
);
GO
ALTER TABLE [dbo].[FE2FormFieldSynonym] ADD CONSTRAINT [FK_FE2FormFieldSynonym_FE2FormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FE2FormField] ([FormFieldGUID]); GO
ALTER TABLE [dbo].[FE2FormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_SynonymGUID] DEFAULT (newid()) FOR [SynonymGUID]; GO
ALTER TABLE [dbo].[FE2FormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_Value] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[FE2FormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2FormSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2FormSection] (
    [FormSectionGUID] uniqueidentifier NOT NULL,
    [FormTabGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ColumnCount] int NOT NULL,
    [HasSectionBreak] bit NOT NULL,
    [LabelAlign] tinyint NOT NULL,
    [LabelWidth] int NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IsPrintable] bit NOT NULL,
    [IsPageBreak] bit NOT NULL,
    PRIMARY KEY ([FormSectionGUID])
);
GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [FK__FE2FormSe__FormT__46E2C1D3] FOREIGN KEY ([FormTabGUID]) REFERENCES [dbo].[FE2FormTab] ([FormTabGUID]); GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Globa__035A0092] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__IsPag__2DB687C9] DEFAULT ((0)) FOR [IsPageBreak]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__FormS__45EE9D9A] DEFAULT (newid()) FOR [FormSectionGUID]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSec__Name__47D6E60C] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Displ__48CB0A45] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Colum__4AB352B7] DEFAULT ((0)) FOR [ColumnCount]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__IsPri__5E3FEC81] DEFAULT ((1)) FOR [IsPrintable]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__hasSe__7B568A12] DEFAULT ((1)) FOR [HasSectionBreak]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Label__7C4AAE4B] DEFAULT ((0)) FOR [LabelAlign]; GO
ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Label__7D3ED284] DEFAULT ((0)) FOR [LabelWidth]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2FormTab ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2FormTab] (
    [FormTabGUID] uniqueidentifier NOT NULL,
    [FormGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IsPrintable] bit NOT NULL,
    PRIMARY KEY ([FormTabGUID])
);
GO
ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [FK__FE2FormTa__FormG__3F41A00B] FOREIGN KEY ([FormGUID]) REFERENCES [dbo].[FE2Form] ([FormGUID]); GO
ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTa__Globa__0265DC59] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTa__FormT__3E4D7BD2] DEFAULT (newid()) FOR [FormTabGUID]; GO
ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTab__Name__4035C444] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTa__Displ__4129E87D] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTa__IsPri__54B05959] DEFAULT ((1)) FOR [IsPrintable]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2FormTextData ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2FormTextData] (
    [FormDataGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [Value] nvarchar(max) NOT NULL,
    PRIMARY KEY ([FormDataGUID])
);

CREATE NONCLUSTERED INDEX [NUNC_EntityGUID] ON [dbo].[FE2FormTextData] ([EntityGUID]);
GO
ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [FK__FE2FormDa__FormF__60A293D6] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FE2FormField] ([FormFieldGUID]); GO
ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [FK_FE2FormTextData_EntityID] FOREIGN KEY ([EntityGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [DF__FE2FormDa__Entit__6196B80F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO
ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [DF__FE2FormDa__FormD__5FAE6F9D] DEFAULT (newid()) FOR [FormDataGUID]; GO
ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [DF__FE2FormDa__Value__628ADC48] DEFAULT ('') FOR [Value]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2RuleConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2RuleConfig] (
    [RuleConfigGUID] uniqueidentifier NOT NULL,
    [FormGUID] uniqueidentifier NOT NULL,
    [FormElementGUID] uniqueidentifier NOT NULL,
    [RuleClassName] nvarchar(100) NOT NULL,
    [RuleXML] nvarchar(max) NOT NULL,
    [IsUsingOr] bit NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([RuleConfigGUID])
);
GO
ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [FK__FE2RuleCo__FormG__1E9FC64F] FOREIGN KEY ([FormGUID]) REFERENCES [dbo].[FE2Form] ([FormGUID]); GO
ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__RuleC__1DABA216] DEFAULT (newid()) FOR [RuleConfigGUID]; GO
ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__RuleC__20880EC1] DEFAULT ('') FOR [RuleClassName]; GO
ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__RuleX__217C32FA] DEFAULT ('') FOR [RuleXML]; GO
ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__IsUsi__22705733] DEFAULT ((1)) FOR [IsUsingOr]; GO
ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__Displ__41F05A65] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__FormE__1F93EA88] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormElementGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2ScriptSnippetHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2ScriptSnippetHistory] (
    [SnippetGUID] uniqueidentifier NOT NULL,
    [OldValue] nvarchar(max) NOT NULL,
    [NewValue] nvarchar(max) NOT NULL,
    [IsComplete] bit NOT NULL,
    [HistoryGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SnippetGUID])
);
GO
ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_HistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryGUID]; GO
ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_SnippetGUID] DEFAULT (newid()) FOR [SnippetGUID]; GO
ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_OldValue] DEFAULT ('') FOR [OldValue]; GO
ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_NewValue] DEFAULT ('') FOR [NewValue]; GO
ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_IsComplete] DEFAULT ((0)) FOR [IsComplete]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FE2ScriptUpgradeHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[FE2ScriptUpgradeHistory] (
    [CustomScriptGUID] uniqueidentifier NOT NULL,
    [SQLObjectName] nvarchar(100) NOT NULL,
    [OldValue] nvarchar(max) NOT NULL,
    [NewValue] nvarchar(max) NOT NULL,
    [RiskLevel] tinyint NOT NULL,
    [IsComplete] bit NOT NULL,
    [HistoryGUID] uniqueidentifier NOT NULL,
    [ErrorGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([HistoryGUID])
);
GO
ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_SQLObjectName] DEFAULT ('') FOR [SQLObjectName]; GO
ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_OldValue] DEFAULT ('') FOR [OldValue]; GO
ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_NewValue] DEFAULT ('') FOR [NewValue]; GO
ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_RiskLevel] DEFAULT ((0)) FOR [RiskLevel]; GO
ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_IsComplete] DEFAULT ((0)) FOR [IsComplete]; GO
ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_HistoryGUID] DEFAULT (newid()) FOR [HistoryGUID]; GO
ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_ErrorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorGUID]; GO
ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_CustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomScriptGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEAccessOverride ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEAccessOverride] (
    [AccessOverrideGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [IsWriteDeny] bit NOT NULL,
    [IsWriteAllow] bit NOT NULL,
    PRIMARY KEY ([AccessOverrideGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_FEAccessOverride_Unique] ON [dbo].[FEAccessOverride] ([FormFieldGUID], [EntityGUID], [UserGUID]);
GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [FK_FEAccessOverride_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [FK_FEAccessOverride_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [FK_FEAccessOverride_XPlan] FOREIGN KEY ([EntityGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_AccessOverrideGUID] DEFAULT (newid()) FOR [AccessOverrideGUID]; GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_Table_1_IdentityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_IsReadDeny] DEFAULT ((0)) FOR [IsWriteDeny]; GO
ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_IsWriteAllow] DEFAULT ((0)) FOR [IsWriteAllow]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEComment ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEComment] (
    [CommentGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [UserNameFull] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    PRIMARY KEY ([CommentGUID])
);
GO
ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [FK_FEComment_XPlan] FOREIGN KEY ([EntityGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_Table_1_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO
ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO
ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_CommentGUID] DEFAULT (newid()) FOR [CommentGUID]; GO
ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_UserNameFull] DEFAULT ('') FOR [UserNameFull]; GO
ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_Comment] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormData ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormData] (
    [FormDataGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [ValueVarChar] nvarchar(max) NOT NULL,
    [ValueSearch] nvarchar(max) NULL,
    [ValueGUID] uniqueidentifier NOT NULL,
    [ValueGUIDS] nvarchar(max) NOT NULL,
    [ValueFloat] float NOT NULL,
    [ValueDate] datetime NOT NULL,
    [ValueBit] bit NOT NULL,
    PRIMARY KEY ([FormDataGUID])
);

CREATE CLUSTERED INDEX [IX_FEFormData_FF_E_Cluster] ON [dbo].[FEFormData] ([PlanTypeGUID], [FormFieldGUID], [EntityGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_FEFormData] ON [dbo].[FEFormData] ([EntityGUID], [FormFieldGUID]);
GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [FK_FEFormData_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_FORMDATAGUID] DEFAULT (newid()) FOR [FormDataGUID]; GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEVARCHAR] DEFAULT ('') FOR [ValueVarChar]; GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ValueGUID]; GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEGUIDS] DEFAULT ('') FOR [ValueGUIDS]; GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEFLOAT] DEFAULT ((0)) FOR [ValueFloat]; GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEDATE] DEFAULT (((1)/(1))/(1980)) FOR [ValueDate]; GO
ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEBIT] DEFAULT ((0)) FOR [ValueBit]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormDataHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormDataHistory] (
    [RowID] int NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [EntityName] nvarchar(max) NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [FormFieldName] nvarchar(64) NOT NULL,
    [ValueVarChar] nvarchar(max) NOT NULL,
    [ValueGUID] uniqueidentifier NOT NULL,
    [ValueGUIDS] nvarchar(max) NOT NULL,
    [ValueFloat] float NOT NULL,
    [ValueDate] datetime NOT NULL,
    [ValueBit] bit NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_FormDataGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_EntityName] DEFAULT ('') FOR [EntityName]; GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEVARCHAR] DEFAULT ('') FOR [ValueVarChar]; GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ValueGUID]; GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEGUIDS] DEFAULT ('') FOR [ValueGUIDS]; GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEFLOAT] DEFAULT ((0)) FOR [ValueFloat]; GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEDATE] DEFAULT (((1)/(1))/(1980)) FOR [ValueDate]; GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEBIT] DEFAULT ((0)) FOR [ValueBit]; GO
ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_HistoryDateTime] DEFAULT (getdate()) FOR [DateTimeStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormDef ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormDef] (
    [FORMDEFGUID] uniqueidentifier NOT NULL,
    [RootFormSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Alias] nvarchar(64) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [ImageIndex] int NOT NULL,
    [CustomMenuGUID] uniqueidentifier NOT NULL,
    [CustomToolbarGUID] uniqueidentifier NOT NULL,
    [StyleIndex] int NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FORMDEFGUID])
);
GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_StyleIndex] DEFAULT ((0)) FOR [StyleIndex]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF__FEFormDef__PlanT__759DB0BC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF__FEFormDef__Globa__194C3D43] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_FORMDEFGUID] DEFAULT (newid()) FOR [FORMDEFGUID]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_ROOTFORMSECTIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RootFormSectionGUID]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_ALIAS] DEFAULT ('') FOR [Alias]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_IMAGEINDEX] DEFAULT ((0)) FOR [ImageIndex]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_CUSTOMMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomMenuGUID]; GO
ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_CUSTOMTOOLBARGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomToolbarGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormField ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormField] (
    [FORMFIELDGUID] uniqueidentifier NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [FieldType] int NOT NULL,
    [MaxLength] int NOT NULL,
    [MinLength] int NOT NULL,
    [DataFormat] nvarchar(256) NOT NULL,
    [DefaultValue] nvarchar(1000) NOT NULL,
    [HelpText] nvarchar(4000) NOT NULL,
    [IsReadOnly] bit NOT NULL,
    [HasNumericMaxValue] bit NOT NULL,
    [NumericMaxValue] float NOT NULL,
    [HasNumericMinValue] bit NOT NULL,
    [NumericMinValue] float NOT NULL,
    [StringMask] nvarchar(256) NOT NULL,
    [DecimalPlaces] int NOT NULL,
    [UseThousandsSeparator] bit NOT NULL,
    [UseNegParentheses] bit NOT NULL,
    [HasLabel] bit NOT NULL,
    [LabelDisplayType] int NOT NULL,
    [LabelWidth] int NOT NULL,
    [IsInDirectory] bit NOT NULL,
    [SourceType] int NOT NULL,
    [SourcePath] nvarchar(max) NOT NULL,
    [SourceGUID] uniqueidentifier NOT NULL,
    [Rows] int NOT NULL,
    [UsePicker] bit NOT NULL,
    [DefaultSortOrder] bit NOT NULL,
    [IsRequired] bit NOT NULL,
    [Mask] nvarchar(256) NOT NULL,
    [HelpTextDisplayType] int NOT NULL,
    [HasOptionHelpText] bit NOT NULL,
    [DefaultValueType] int NOT NULL,
    [Label] nvarchar(450) NOT NULL,
    [HasRowNumbers] bit NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [SpecialFieldType] int NOT NULL,
    [SourceDisplayFormat] nvarchar(450) NOT NULL,
    [ExecutionOrder] int NOT NULL,
    [DirectoryName] nvarchar(64) NOT NULL,
    [ScaleDisplayFactor] int NOT NULL,
    [DateCreated] datetime NOT NULL,
    [DateModified] datetime NOT NULL,
    [IsRecordingHistory] bit NOT NULL,
    [IsCleared] bit NOT NULL,
    [DisplayFormatOverride] nvarchar(64) NOT NULL,
    [ResizeOffset] int NOT NULL,
    [IsSetupLocked] bit NOT NULL,
    [IsCoolite] bit NOT NULL,
    [IsCopied] bit NOT NULL,
    [RenderType] int NOT NULL,
    [RenderThreshold] float NOT NULL,
    [RenderComparisonFieldGUID] uniqueidentifier NOT NULL,
    [RenderComparisonOperator] int NOT NULL,
    [RefreshMode] tinyint NOT NULL,
    [TypeConfigXML] xml NOT NULL,
    PRIMARY KEY ([FORMFIELDGUID])
);

CREATE NONCLUSTERED INDEX [IX_FEFormField_1] ON [dbo].[FEFormField] ([SourceType]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_FEFormField] ON [dbo].[FEFormField] ([Name]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_FEFormField_GlobalID] ON [dbo].[FEFormField] ([GlobalID]);
GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_DATAFORMAT] DEFAULT ('') FOR [DataFormat]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_DEFAULTVALUE] DEFAULT ('') FOR [DefaultValue]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_HELPTEXT] DEFAULT ('') FOR [HelpText]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_ISREADONLY] DEFAULT ((0)) FOR [IsReadOnly]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_HASNUMERICMAXVALUE] DEFAULT ((0)) FOR [HasNumericMaxValue]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_NUMERICMAXVALUE] DEFAULT ((0)) FOR [NumericMaxValue]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_HASNUMERICMINVALUE] DEFAULT ((0)) FOR [HasNumericMinValue]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_NUMERICMINVALUE] DEFAULT ((0)) FOR [NumericMinValue]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_STRINGMASK] DEFAULT ('') FOR [StringMask]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DECIMALPLACES] DEFAULT ((0)) FOR [DecimalPlaces]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_USETHOUSANDSSEPARATOR] DEFAULT ((1)) FOR [UseThousandsSeparator]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_USENEGPARENTHESE] DEFAULT ((0)) FOR [UseNegParentheses]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_HASLABEL] DEFAULT ((1)) FOR [HasLabel]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_LABELDISPLAYTYPE] DEFAULT ((0)) FOR [LabelDisplayType]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RefreshMode] DEFAULT ((0)) FOR [RefreshMode]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_LABELWIDTH] DEFAULT ((100)) FOR [LabelWidth]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_LABEL] DEFAULT ('') FOR [Label]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ISINDIRECTORY] DEFAULT ((0)) FOR [IsInDirectory]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SOURCETYPE] DEFAULT ((0)) FOR [SourceType]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SOURCEPATH] DEFAULT ('') FOR [SourcePath]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SOURCEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceGUID]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ROWS] DEFAULT ((0)) FOR [Rows]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_USEPICKER] DEFAULT ((0)) FOR [UsePicker]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DEFAULTSORTORDER] DEFAULT ((0)) FOR [DefaultSortOrder]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ISREQUIRED] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_MASK] DEFAULT ('') FOR [Mask]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_HELPTEXTDISPLAYTYPE] DEFAULT ((0)) FOR [HelpTextDisplayType]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_HASOPTIONHELPTEXT] DEFAULT ((0)) FOR [HasOptionHelpText]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DEFAULTVALUETYPE] DEFAULT ((0)) FOR [DefaultValueType]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_HASROWNUMBERS] DEFAULT ((1)) FOR [HasRowNumbers]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SPECIALFIELDTYPE] DEFAULT ((0)) FOR [SpecialFieldType]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SOURCEDISPLAYFORMAT] DEFAULT ('') FOR [SourceDisplayFormat]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_EXECUTIONORDER] DEFAULT ((0)) FOR [ExecutionOrder]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DirectoryName] DEFAULT ('') FOR [DirectoryName]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ScaleDisplayFactor] DEFAULT ((1)) FOR [ScaleDisplayFactor]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF__FEFormFie__IsRec__4AC6670E] DEFAULT ((0)) FOR [IsRecordingHistory]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_IsCleared] DEFAULT ((0)) FOR [IsCleared]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DisplayFormatOverride] DEFAULT ('') FOR [DisplayFormatOverride]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ResizeOffset] DEFAULT ((0)) FOR [ResizeOffset]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_IsSetupLocked] DEFAULT ((0)) FOR [IsSetupLocked]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_IsCoolite] DEFAULT ((0)) FOR [IsCoolite]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RenderType] DEFAULT ((0)) FOR [RenderType]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RenderThreshold] DEFAULT ((0)) FOR [RenderThreshold]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RenderComparisonFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RenderComparisonFieldGUID]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RenderComparisonOperator] DEFAULT ((0)) FOR [RenderComparisonOperator]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_IsCopied] DEFAULT ((1)) FOR [IsCopied]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_TypeConfigXML] DEFAULT ('') FOR [TypeConfigXML]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_FORMFIELDGUID] DEFAULT (newid()) FOR [FORMFIELDGUID]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_FIELDTYPE] DEFAULT ((0)) FOR [FieldType]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_MAXLENGTH] DEFAULT ((0)) FOR [MaxLength]; GO
ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_MINLENGTH] DEFAULT ((0)) FOR [MinLength]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormFieldCalculationTestResult ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormFieldCalculationTestResult] (
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [IsSuccess] bit NOT NULL,
    [Duration] int NOT NULL,
    [RunDate] datetime NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormFieldDefaultOverride ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormFieldDefaultOverride] (
    [DefaultOverrideGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [FormDefGUID] uniqueidentifier NOT NULL,
    [DefaultValueType] int NOT NULL,
    [DefaultValue] nvarchar(1000) NOT NULL,
    [DisplayValue] nvarchar(450) NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([DefaultOverrideGUID])
);
GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [FK_FEFormFieldDefaultOverride_FEFormDef] FOREIGN KEY ([FormDefGUID]) REFERENCES [dbo].[FEFormDef] ([FORMDEFGUID]); GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [FK_FEFormFieldDefaultOverride_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_DefaultOverrideGUID] DEFAULT (newid()) FOR [DefaultOverrideGUID]; GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_DefaultValueType] DEFAULT ((0)) FOR [DefaultValueType]; GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_DefaultValue] DEFAULT ('') FOR [DefaultValue]; GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_DisplayValue] DEFAULT ('') FOR [DisplayValue]; GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_FormDefGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormDefGUID]; GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormFieldSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormFieldSetup] (
    [FORMFIELDSETUPGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [FormDefGUID] uniqueidentifier NOT NULL,
    [FormSectionGUID] uniqueidentifier NOT NULL,
    [SetupUsePicker] bit NOT NULL,
    [SetupDecimalPlaces] int NOT NULL,
    [SetupUseThousandsSeparator] bit NOT NULL,
    [SetupUseNegParentheses] bit NOT NULL,
    [SetupHasLabel] bit NOT NULL,
    [SetupLabelDisplayType] int NOT NULL,
    [SetupRows] int NOT NULL,
    [SetupIsReadOnly] bit NOT NULL,
    [SetupLabelWidth] int NOT NULL,
    [SetupHelpTextDisplayType] int NOT NULL,
    [SetupHasOptionHelpText] bit NOT NULL,
    [SetupHasRowNumbers] bit NOT NULL,
    [SetupResizeOffset] int NOT NULL,
    PRIMARY KEY ([FORMFIELDSETUPGUID])
);

CREATE CLUSTERED INDEX [IX_FEFormFieldSetup_FormDef] ON [dbo].[FEFormFieldSetup] ([FormDefGUID]);
CREATE NONCLUSTERED INDEX [IX_FEFormFieldSetup_FormField] ON [dbo].[FEFormFieldSetup] ([FormFieldGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_FEFormFieldSetup] ON [dbo].[FEFormFieldSetup] ([FormFieldGUID], [FormDefGUID]);
GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [FK_FEFormFieldSetup_FEFormDef] FOREIGN KEY ([FormDefGUID]) REFERENCES [dbo].[FEFormDef] ([FORMDEFGUID]); GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [FK_FEFormFieldSetup_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_FORMFIELDSETUPGUID] DEFAULT (newid()) FOR [FORMFIELDSETUPGUID]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_FORMFIELDGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [FormFieldGUID]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_FORMGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [FormDefGUID]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_FormFieldSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormSectionGUID]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_USEPICKER] DEFAULT ((0)) FOR [SetupUsePicker]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_DECIMALPLACES] DEFAULT ((0)) FOR [SetupDecimalPlaces]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_USETHOUSANDSSEPARATOR] DEFAULT ((1)) FOR [SetupUseThousandsSeparator]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_USENEGPARENTHESES] DEFAULT ((0)) FOR [SetupUseNegParentheses]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_HASLABEL] DEFAULT ((1)) FOR [SetupHasLabel]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_LABELDISPLAYTYPE] DEFAULT ((0)) FOR [SetupLabelDisplayType]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_ROWS] DEFAULT ((0)) FOR [SetupRows]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_ISREADONLY] DEFAULT ((0)) FOR [SetupIsReadOnly]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SETUPLABELWIDTH] DEFAULT ((100)) FOR [SetupLabelWidth]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SETUPHELPTEXTDISPLAYTYPE] DEFAULT ((0)) FOR [SetupHelpTextDisplayType]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SETUPHASOPTIONHELPTEXT] DEFAULT ((0)) FOR [SetupHasOptionHelpText]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SETUPHASROWNUMBERS] DEFAULT ((1)) FOR [SetupHasRowNumbers]; GO
ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SetupResizeOffset] DEFAULT ((0)) FOR [SetupResizeOffset]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormFieldSynonym ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormFieldSynonym] (
    [SynonymGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    PRIMARY KEY ([SynonymGUID])
);
GO
ALTER TABLE [dbo].[FEFormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_FormFieldGUID_1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO
ALTER TABLE [dbo].[FEFormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_SynonymGUID_1] DEFAULT (newid()) FOR [SynonymGUID]; GO
ALTER TABLE [dbo].[FEFormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_Name] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormSection] (
    [FORMSECTIONGUID] uniqueidentifier NOT NULL,
    [FormDefGUID] uniqueidentifier NOT NULL,
    [ParentFormSectionGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] int NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [DisplayChildrenAsTabs] bit NOT NULL,
    [Height] int NOT NULL,
    [Width] int NOT NULL,
    [HTML] nvarchar(max) NOT NULL,
    [HTMLDesign] nvarchar(max) NOT NULL,
    [IsParentSection] bit NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [RuleGroupType] int NOT NULL,
    [IsBreakVisible] bit NOT NULL,
    [IsAjaxEnabled] bit NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [DisplayMode] int NOT NULL,
    PRIMARY KEY ([FORMSECTIONGUID])
);

CREATE CLUSTERED INDEX [IX_FEFormSection] ON [dbo].[FEFormSection] ([FormDefGUID]);
CREATE NONCLUSTERED INDEX [IX_FEFormSection_DisplayOrder] ON [dbo].[FEFormSection] ([DisplayOrder]);
GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [FK_FEFormSection_FEFormDef] FOREIGN KEY ([FormDefGUID]) REFERENCES [dbo].[FEFormDef] ([FORMDEFGUID]); GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_FORMSECTIONGUID] DEFAULT (newid()) FOR [FORMSECTIONGUID]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_DISPLAYORDER] DEFAULT ((1)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_DisplayChildrenAsTabs] DEFAULT ((0)) FOR [DisplayChildrenAsTabs]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_Height] DEFAULT ((0)) FOR [Height]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_Width] DEFAULT ((0)) FOR [Width]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_HTML] DEFAULT ('') FOR [HTML]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_HTMLDesign] DEFAULT ('') FOR [HTMLDesign]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_ISPARENTSECTION] DEFAULT ((0)) FOR [IsParentSection]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF__FEFormSec__IsAja__18260A72] DEFAULT ((0)) FOR [IsAjaxEnabled]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF__FEFormSec__Globa__1A40617C] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF__FEFormSec__Displ__1EBAFDD6] DEFAULT ((0)) FOR [DisplayMode]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_IsBreakVisible] DEFAULT ((1)) FOR [IsBreakVisible]; GO
ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_RuleGroupType] DEFAULT ((0)) FOR [RuleGroupType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormSectionRule ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormSectionRule] (
    [FormSectionRuleGUID] uniqueidentifier NOT NULL,
    [FormSectionGUID] uniqueidentifier NOT NULL,
    [RuleXML] xml NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [RuleType] int NOT NULL,
    PRIMARY KEY ([FormSectionRuleGUID])
);
GO
ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [FK_FEFormSectionRule_FEFormSection] FOREIGN KEY ([FormSectionGUID]) REFERENCES [dbo].[FEFormSection] ([FORMSECTIONGUID]); GO
ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_FormSectionRuleGUID] DEFAULT (newid()) FOR [FormSectionRuleGUID]; GO
ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_FormSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormSectionGUID]; GO
ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_RuleXML] DEFAULT ('') FOR [RuleXML]; GO
ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_RuleType] DEFAULT ((0)) FOR [RuleType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FEFormTemplateArea ------------------
---------------------------------------------
CREATE TABLE [dbo].[FEFormTemplateArea] (
    [FormTemplateAreaGUID] uniqueidentifier NOT NULL,
    [HTML] nvarchar(max) NOT NULL,
    [AreaType] int NOT NULL,
    PRIMARY KEY ([FormTemplateAreaGUID])
);
GO
ALTER TABLE [dbo].[FEFormTemplateArea] ADD CONSTRAINT [DF_FormTemplateArea_FormTemplateAreaGUID] DEFAULT (newid()) FOR [FormTemplateAreaGUID]; GO
ALTER TABLE [dbo].[FEFormTemplateArea] ADD CONSTRAINT [DF_FormTemplateArea_HTML] DEFAULT ('') FOR [HTML]; GO
ALTER TABLE [dbo].[FEFormTemplateArea] ADD CONSTRAINT [DF_FormTemplateArea_AreaType] DEFAULT ((0)) FOR [AreaType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FRDimension ------------------
---------------------------------------------
CREATE TABLE [dbo].[FRDimension] (
    [FWDimensionGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    PRIMARY KEY ([FWDimensionGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_FRDimension_Name] ON [dbo].[FRDimension] ([Name]);
GO
ALTER TABLE [dbo].[FRDimension] ADD CONSTRAINT [FK_FRDimension_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO
ALTER TABLE [dbo].[FRDimension] ADD CONSTRAINT [DF__FRDimensi__FWDim__2703FAD9] DEFAULT (newid()) FOR [FWDimensionGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FRFinancialStatement ------------------
---------------------------------------------
CREATE TABLE [dbo].[FRFinancialStatement] (
    [FinancialStatementGUID] uniqueidentifier NOT NULL,
    [FWDimensionGUID] uniqueidentifier NOT NULL,
    [Statement] nvarchar(200) NOT NULL,
    [TemplateName] nvarchar(200) NOT NULL,
    [ColumnFirstYear] nvarchar(200) NOT NULL,
    [ColumnLastYear] nvarchar(200) NOT NULL,
    [ColumnDisplayName] nvarchar(200) NOT NULL,
    [ColumnFinancialReporting] nvarchar(200) NOT NULL,
    [ColumnDataStructure] nvarchar(200) NOT NULL,
    [ColumnReportingMappingType] nvarchar(200) NOT NULL,
    [RowStartLabel] nvarchar(200) NOT NULL,
    [RowEndLabel] nvarchar(200) NOT NULL,
    [FinancialStatementSheet] nvarchar(200) NOT NULL,
    [CompositeGUID] uniqueidentifier NOT NULL,
    [ColumnAccountRollupLabel] nvarchar(200) NOT NULL,
    [SampleViewName] nvarchar(200) NOT NULL,
    [IsReportable] bit NOT NULL,
    [TemplateGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([FinancialStatementGUID])
);
GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Finan__3A16CF4D] DEFAULT (newid()) FOR [FinancialStatementGUID]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Templ__3B0AF386] DEFAULT ('') FOR [TemplateName]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3BFF17BF] DEFAULT ('') FOR [ColumnFirstYear]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3CF33BF8] DEFAULT ('') FOR [ColumnLastYear]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3DE76031] DEFAULT ('') FOR [ColumnDisplayName]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3EDB846A] DEFAULT ('') FOR [ColumnFinancialReporting]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3FCFA8A3] DEFAULT ('') FOR [ColumnDataStructure]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__40C3CCDC] DEFAULT ('') FOR [ColumnReportingMappingType]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__RowSt__41B7F115] DEFAULT ('') FOR [RowStartLabel]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__RowEn__42AC154E] DEFAULT ('') FOR [RowEndLabel]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF_FRFinancialStatement_TemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TemplateGUID]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Finan__43A03987] DEFAULT ('') FOR [FinancialStatementSheet]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Compo__467CA632] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CompositeGUID]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF_FRFinancialStatement_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__602834F3] DEFAULT ('') FOR [ColumnAccountRollupLabel]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF_FRFinancialStatement_SampleViewName] DEFAULT ('') FOR [SampleViewName]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF_FRFinancialStatement_IsReportable] DEFAULT ((1)) FOR [IsReportable]; GO
ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__SortO__77FFBE84] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FRLineItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[FRLineItem] (
    [LineItemGUID] uniqueidentifier NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [FWDimensionGUID] uniqueidentifier NOT NULL,
    [SectionGUID] uniqueidentifier NOT NULL,
    [LineName] nvarchar(200) NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [IsBold] bit NOT NULL,
    [Indent] int NOT NULL,
    [IsSpaceAbove] bit NOT NULL,
    [Type] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [Calculation] nvarchar(2000) NOT NULL,
    [Statement] nvarchar(200) NOT NULL,
    [SectionName] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [Format] int NOT NULL,
    [IsSR] bit NOT NULL,
    [IsYearOverYear] bit NOT NULL,
    [IsBalanceSheetOnly] bit NOT NULL,
    [IsRequired] bit NOT NULL,
    [IsVolume] bit NOT NULL,
    [IsEditable] bit NOT NULL,
    [IsBottomBorder] bit NOT NULL,
    [IsFTERollup] bit NOT NULL,
    [IsExpense] bit NOT NULL,
    [DecimalCount] tinyint NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IsDragAndDropAllowed] bit NOT NULL,
    [IsDeletable] bit NOT NULL,
    [IsConfigurable] bit NOT NULL,
    [ToBeDeleted] bit NOT NULL,
    PRIMARY KEY ([LineItemGUID])
);
GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsVol__0C06B731] DEFAULT ((0)) FOR [IsVolume]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsEdi__0CFADB6A] DEFAULT ((1)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsCon__1C113521] DEFAULT ((1)) FOR [IsConfigurable]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsExp__225AAF0D] DEFAULT ((0)) FOR [IsExpense]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__ToBeD__239FAA55] DEFAULT ((0)) FOR [ToBeDeleted]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsFTE__2E46C09C] DEFAULT ((0)) FOR [IsFTERollup]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__LineI__3181894C] DEFAULT (newid()) FOR [LineItemGUID]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__Secti__3275AD85] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0),0),0)) FOR [SectionGUID]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsBol__3369D1BE] DEFAULT ((0)) FOR [IsBold]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__Inden__345DF5F7] DEFAULT ((1)) FOR [Indent]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsSpa__35521A30] DEFAULT ((0)) FOR [IsSpaceAbove]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineItem__Type__36463E69] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__Calcu__373A62A2] DEFAULT ('') FOR [Calculation]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__Decim__43718A15] DEFAULT ((0)) FOR [DecimalCount]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsDra__51392A77] DEFAULT ((1)) FOR [IsDragAndDropAllowed]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsDel__522D4EB0] DEFAULT ((1)) FOR [IsDeletable]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF_FRLineItem_GlobalID] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineItem__IsSR__62107D65] DEFAULT ((0)) FOR [IsSR]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsYea__63F8C5D7] DEFAULT ((0)) FOR [IsYearOverYear]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsBal__64ECEA10] DEFAULT ((0)) FOR [IsBalanceSheetOnly]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsReq__65E10E49] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsBot__6DA22BA2] DEFAULT ((0)) FOR [IsBottomBorder]; GO
ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF_FRLineItem_Format] DEFAULT ((2)) FOR [Format]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FRSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[FRSection] (
    [SectionGUID] uniqueidentifier NOT NULL,
    [FWDimensionGUID] uniqueidentifier NOT NULL,
    [Statement] nvarchar(200) NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [IsBold] bit NOT NULL,
    [Indent] int NOT NULL,
    [IsSpaceAbove] bit NOT NULL,
    [IsVisible] bit NOT NULL,
    [IsEditable] bit NOT NULL,
    [IsRequired] bit NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IsDragAndDropAllowed] bit NOT NULL,
    [IsDeletable] bit NOT NULL,
    [IsConfigurable] bit NOT NULL,
    [ToBeDeleted] bit NOT NULL,
    PRIMARY KEY ([SectionGUID])
);
GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsEdi__0DEEFFA3] DEFAULT ((1)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsReq__0EE323DC] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsCon__1D05595A] DEFAULT ((1)) FOR [IsConfigurable]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__ToBeD__22AB861C] DEFAULT ((0)) FOR [ToBeDeleted]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__Secti__2AD48BBD] DEFAULT (newid()) FOR [SectionGUID]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsBol__2BC8AFF6] DEFAULT ((1)) FOR [IsBold]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__Inden__2CBCD42F] DEFAULT ((0)) FOR [Indent]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsSpa__2DB0F868] DEFAULT ((1)) FOR [IsSpaceAbove]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsVis__2EA51CA1] DEFAULT ((1)) FOR [IsVisible]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsDra__54159722] DEFAULT ((1)) FOR [IsDragAndDropAllowed]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsDel__5509BB5B] DEFAULT ((1)) FOR [IsDeletable]; GO
ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__Globa__576B33C5] DEFAULT ('') FOR [GlobalID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FRStatementFormula ------------------
---------------------------------------------
CREATE TABLE [dbo].[FRStatementFormula] (
    [FinancialStatementGUID] uniqueidentifier NOT NULL,
    [Column] nvarchar(5) NOT NULL,
    [StandardFormula] nvarchar(max) NOT NULL,
    [MappingFormula] nvarchar(max) NOT NULL,
    [AlternateMappingFormula] nvarchar(max) NOT NULL,
    [FormatOverride] int NOT NULL,
    [UseStandardAlways] bit NOT NULL,
    [DecimalCount] tinyint NOT NULL
);
GO
ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Colum__1EF36726] DEFAULT ('') FOR [Column]; GO
ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Stand__1FE78B5F] DEFAULT ('') FOR [StandardFormula]; GO
ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Mappi__20DBAF98] DEFAULT ('') FOR [MappingFormula]; GO
ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Alter__21CFD3D1] DEFAULT ('') FOR [AlternateMappingFormula]; GO
ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Forma__22C3F80A] DEFAULT ((-1)) FOR [FormatOverride]; GO
ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__UseSt__2B0F2548] DEFAULT ((0)) FOR [UseStandardAlways]; GO
ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Decim__7469C72B] DEFAULT ((0)) FOR [DecimalCount]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FileAttachment ------------------
---------------------------------------------
CREATE TABLE [dbo].[FileAttachment] (
    [FileAttachmentGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [EntityType] int NOT NULL,
    [FileName] nvarchar(250) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [NumBytes] float NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DateCreated] datetime NOT NULL,
    [LastSeenpath] nvarchar(4000) NOT NULL,
    [IsHome] bit NOT NULL,
    PRIMARY KEY ([FileAttachmentGUID])
);

CREATE CLUSTERED INDEX [IX_FileAttachment_ByPlanGUID] ON [dbo].[FileAttachment] ([EntityGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_FileAttachment_Unique] ON [dbo].[FileAttachment] ([EntityGUID], [FolderGUID], [FileName]);
GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_FILEATTACHMENTGUID] DEFAULT (newid()) FOR [FileAttachmentGUID]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_PLANGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_ENTITYTYPE] DEFAULT ((0)) FOR [EntityType]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_FILENAME] DEFAULT ('') FOR [FileName]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_NUMBYTES] DEFAULT ((0)) FOR [NumBytes]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_LASTSEENPATH] DEFAULT ('') FOR [LastSeenpath]; GO
ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_IsHome] DEFAULT ((0)) FOR [IsHome]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FileAttachmentPublicLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[FileAttachmentPublicLink] (
    [FileAttachmentPublicLinkGUID] uniqueidentifier NOT NULL,
    [FileAttachmentGUID] uniqueidentifier NOT NULL,
    [AuthorGuid] uniqueidentifier NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [Link] nvarchar(2000) NOT NULL,
    PRIMARY KEY ([FileAttachmentPublicLinkGUID])
);
GO
ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [FK__FileAttac__FileA__3AAA6746] FOREIGN KEY ([FileAttachmentGUID]) REFERENCES [dbo].[FileAttachment] ([FileAttachmentGUID]); GO
ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttac__FileA__39B6430D] DEFAULT (newid()) FOR [FileAttachmentPublicLinkGUID]; GO
ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttac__Autho__3B9E8B7F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGuid]; GO
ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttac__Descr__3C92AFB8] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttac__DateC__3D86D3F1] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttach__Link__69304C05] DEFAULT ('') FOR [Link]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FileAttachmentPublicRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[FileAttachmentPublicRequest] (
    [FileAttachmentPublicRequestGUID] uniqueidentifier NOT NULL,
    [FileAttachmentPublicLinkGUID] uniqueidentifier NOT NULL,
    [IPAddress] nvarchar(100) NOT NULL,
    [DateCreated] datetime NOT NULL,
    PRIMARY KEY ([FileAttachmentPublicRequestGUID])
);
GO
ALTER TABLE [dbo].[FileAttachmentPublicRequest] ADD CONSTRAINT [FK__FileAttac__FileA__415764D5] FOREIGN KEY ([FileAttachmentPublicLinkGUID]) REFERENCES [dbo].[FileAttachmentPublicLink] ([FileAttachmentPublicLinkGUID]); GO
ALTER TABLE [dbo].[FileAttachmentPublicRequest] ADD CONSTRAINT [DF__FileAttac__FileA__4063409C] DEFAULT (newid()) FOR [FileAttachmentPublicRequestGUID]; GO
ALTER TABLE [dbo].[FileAttachmentPublicRequest] ADD CONSTRAINT [DF__FileAttac__IPAdd__424B890E] DEFAULT ('') FOR [IPAddress]; GO
ALTER TABLE [dbo].[FileAttachmentPublicRequest] ADD CONSTRAINT [DF__FileAttac__DateC__433FAD47] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FileListener ------------------
---------------------------------------------
CREATE TABLE [dbo].[FileListener] (
    [FileListenerGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [FileFilter] nvarchar(450) NOT NULL,
    [ExecutionOrder] int NOT NULL,
    [ActionGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FileListenerGUID])
);
GO
ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO
ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_ActionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ActionGUID]; GO
ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_FileListenerGUID] DEFAULT (newid()) FOR [FileListenerGUID]; GO
ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_FileFilter] DEFAULT ('') FOR [FileFilter]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FillinMgmtUpdateHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[FillinMgmtUpdateHistory] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [FillinUpdateTypeID] int NOT NULL,
    [Departments] nvarchar(max) NOT NULL,
    [FillinMembers] nvarchar(max) NOT NULL,
    [Status] nvarchar(50) NOT NULL,
    [TimeStamp] datetime NOT NULL,
    [HistoryTaskGUID] uniqueidentifier NOT NULL,
    [OperationType] nvarchar(50) NOT NULL,
    [Sections] nvarchar(max) NOT NULL,
    PRIMARY KEY ([MemberGUID])
);
GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_Sections] DEFAULT ('') FOR [Sections]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF__FillinMgm__Opera__3E43BDC5] DEFAULT ('') FOR [OperationType]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_FillinUpdateTypeID] DEFAULT ((0)) FOR [FillinUpdateTypeID]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_Departments] DEFAULT ('') FOR [Departments]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_FillinMembers] DEFAULT ('') FOR [FillinMembers]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_Status] DEFAULT ('') FOR [Status]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_TimeStamp] DEFAULT (getdate()) FOR [TimeStamp]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_HistoryTaskGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryTaskGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FillinMgmtUpdateType ------------------
---------------------------------------------
CREATE TABLE [dbo].[FillinMgmtUpdateType] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [FillinUpdateTypeID] int NOT NULL,
    [FillinUpdateTypeName] nvarchar(50) NOT NULL,
    PRIMARY KEY ([MemberGUID])
);
GO
ALTER TABLE [dbo].[FillinMgmtUpdateType] ADD CONSTRAINT [DF_FillinMgmtUpdateType_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateType] ADD CONSTRAINT [DF_FillinMgmtUpdateType_FillinUpdateTypeID] DEFAULT ((0)) FOR [FillinUpdateTypeID]; GO
ALTER TABLE [dbo].[FillinMgmtUpdateType] ADD CONSTRAINT [DF_FillinMgmtUpdateType_FillinUpdateTypeName] DEFAULT ('') FOR [FillinUpdateTypeName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FillinRefreshRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[FillinRefreshRequest] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [PlaceHolderSectionGUID] uniqueidentifier NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [IssuedAt] datetime NOT NULL,
    [ErrorGUID] uniqueidentifier NOT NULL,
    [PlanGUID] uniqueidentifier NOT NULL,
    [AllowClearOnRefresh] bit NOT NULL,
    PRIMARY KEY ([RequestGUID])
);
GO
ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_PlaceHolderSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceHolderSectionGUID]; GO
ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_ModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO
ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_IssuedAt] DEFAULT (getdate()) FOR [IssuedAt]; GO
ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_AllowClearOnRefresh] DEFAULT ((1)) FOR [AllowClearOnRefresh]; GO
ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF__FillinRef__Error__29293EDB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorGUID]; GO
ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.Folder ------------------
---------------------------------------------
CREATE TABLE [dbo].[Folder] (
    [FolderGuid] uniqueidentifier NOT NULL,
    [FolderSetGUID] uniqueidentifier NOT NULL,
    [ParentFolderGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [DateModified] datetime NOT NULL,
    [OutlineLevel] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ImageType] int NOT NULL,
    [FolderType] int NOT NULL,
    [QueryRootXML] nvarchar(max) NOT NULL,
    [IsDeletedFolder] bit NOT NULL,
    [BasedOnFolderGUID] uniqueidentifier NOT NULL,
    [UpgradeHierarchyPath] nvarchar(max) NOT NULL,
    [GlobalID] nvarchar(50) NOT NULL,
    PRIMARY KEY ([FolderGuid])
);

CREATE CLUSTERED INDEX [IX_Folder_FolderSetGUID] ON [dbo].[Folder] ([FolderSetGUID]);
CREATE NONCLUSTERED INDEX [IX_Folder_ParentFolderGUID] ON [dbo].[Folder] ([ParentFolderGUID]);
GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [FK_Folder_FolderSet] FOREIGN KEY ([FolderSetGUID]) REFERENCES [dbo].[FolderSet] ([FolderSetGUID]); GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_UpgradeHierarchyPath] DEFAULT ('') FOR [UpgradeHierarchyPath]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_GlobalID] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_FolderGUID] DEFAULT (newid()) FOR [FolderGuid]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_FOLDERSETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderSetGUID]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_PARENTFOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentFolderGUID]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_DATECREATED] DEFAULT (((1)/(1))/(2000)) FOR [DateCreated]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_DATEMODIFIED] DEFAULT (((1)/(1))/(2000)) FOR [DateModified]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_OUTLINELEVEL] DEFAULT ((0)) FOR [OutlineLevel]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_IMAGEINDEX] DEFAULT ((0)) FOR [ImageType]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_FOLDERTYPE] DEFAULT ((0)) FOR [FolderType]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_QUERYROOTXML] DEFAULT ('') FOR [QueryRootXML]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_ISDELETEDFOLDER] DEFAULT ((0)) FOR [IsDeletedFolder]; GO
ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_BASEDONFOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BasedOnFolderGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.FolderSet ------------------
---------------------------------------------
CREATE TABLE [dbo].[FolderSet] (
    [FolderSetGUID] uniqueidentifier NOT NULL,
    [RootFolderGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Type] int NOT NULL,
    [OwnerGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FolderSetGUID])
);

CREATE CLUSTERED INDEX [IX_FolderSet_Type] ON [dbo].[FolderSet] ([Type]);
GO
ALTER TABLE [dbo].[FolderSet] ADD CONSTRAINT [DF_FolderSet_FolderSetGUID] DEFAULT (newid()) FOR [FolderSetGUID]; GO
ALTER TABLE [dbo].[FolderSet] ADD CONSTRAINT [DF_FolderSet_ROOTFOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RootFolderGUID]; GO
ALTER TABLE [dbo].[FolderSet] ADD CONSTRAINT [DF_FolderSet_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[FolderSet] ADD CONSTRAINT [DF_FolderSet_OWNERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OwnerGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GUIDTable ------------------
---------------------------------------------
CREATE TABLE [dbo].[GUIDTable] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [SPLongRangePlanID] int NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.GlobalAssumption ------------------
---------------------------------------------
CREATE TABLE [dbo].[GlobalAssumption] (
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [GlobalAssumptionSetGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [PlanFiltered] bit NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [DateCreated] datetime NOT NULL,
    [LastRefresh] datetime NULL,
    [Commentary] nvarchar(max) NOT NULL,
    [NumberOfBudgetsInRule] int NULL,
    PRIMARY KEY ([GlobalAssumptionGUID])
);
GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [FK_GlobalAssumption_GlobalAssumptionSet] FOREIGN KEY ([GlobalAssumptionSetGUID]) REFERENCES [dbo].[GlobalAssumptionSet] ([GlobalAssumptionSetGUID]); GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_PlanFiltered] DEFAULT ((0)) FOR [PlanFiltered]; GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF__GlobalAss__Comme__00939FA1] DEFAULT ('') FOR [Commentary]; GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_NumberOfBudgetsInRule] DEFAULT (NULL) FOR [NumberOfBudgetsInRule]; GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_GlobalAssumptionGUID] DEFAULT (newid()) FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_AssumptionSetGuid] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionSetGUID]; GO
ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GlobalAssumptionFillinKeep ------------------
---------------------------------------------
CREATE TABLE [dbo].[GlobalAssumptionFillinKeep] (
    [RowID] int NOT NULL,
    [GlobalAssumptionSetGUID] uniqueidentifier NOT NULL,
    [DepartmentalBudgetGUID] uniqueidentifier NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [FillinGUID] uniqueidentifier NOT NULL,
    [FillinID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalMonthCode] nvarchar(20) NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionSetGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_DepartmentalBudgetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DepartmentalBudgetGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_DepartmentalBudgetID] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_FillinGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_FillinID] DEFAULT ((0)) FOR [FillinID]; GO
ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_FiscalMonthCode] DEFAULT ('0') FOR [FiscalMonthCode]; GO
ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GlobalAssumptionHistoryEntry ------------------
---------------------------------------------
CREATE TABLE [dbo].[GlobalAssumptionHistoryEntry] (
    [HistoryEntryGUID] uniqueidentifier NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DateTimeStamp] datetime NULL,
    [AffectedPlansCount] int NOT NULL,
    PRIMARY KEY ([HistoryEntryGUID])
);
GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [FK_GlobalAssumptionHistory_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_HistoryEntryGUID] DEFAULT (newid()) FOR [HistoryEntryGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_DateTimeStamp] DEFAULT (NULL) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_AffectedPlansCount] DEFAULT ((0)) FOR [AffectedPlansCount]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GlobalAssumptionHistoryEntryItems ------------------
---------------------------------------------
CREATE TABLE [dbo].[GlobalAssumptionHistoryEntryItems] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [HistoryEntryGUID] uniqueidentifier NOT NULL,
    [PlanGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([HistoryItemGUID])
);
GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ADD CONSTRAINT [FK_GlobalAssumptionHistoryEntryItems_GlobalAssumptionHistoryEntry] FOREIGN KEY ([HistoryEntryGUID]) REFERENCES [dbo].[GlobalAssumptionHistoryEntry] ([HistoryEntryGUID]); GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntryItems_HistoryItemGUID] DEFAULT (newid()) FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntryItems_HistoryEntryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryEntryGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntryItems_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GlobalAssumptionPlanFilter ------------------
---------------------------------------------
CREATE TABLE [dbo].[GlobalAssumptionPlanFilter] (
    [GlobalAssumptionPlanFilterGUID] uniqueidentifier NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [Value] nvarchar(256) NOT NULL,
    PRIMARY KEY ([GlobalAssumptionPlanFilterGUID])
);
GO
ALTER TABLE [dbo].[GlobalAssumptionPlanFilter] ADD CONSTRAINT [FK_GlobalAssumptionPlanFilter_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [dbo].[GlobalAssumptionPlanFilter] ADD CONSTRAINT [DF_GlobalAssumptionPlanFilter_GlobalAssumptionPlanFilterGUID] DEFAULT (newid()) FOR [GlobalAssumptionPlanFilterGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionPlanFilter] ADD CONSTRAINT [DF_GlobalAssumptionPlanFilter_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionPlanFilter] ADD CONSTRAINT [DF_GlobalAssumptionPlanFilter_Value] DEFAULT ('') FOR [Value]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GlobalAssumptionSet ------------------
---------------------------------------------
CREATE TABLE [dbo].[GlobalAssumptionSet] (
    [GlobalAssumptionSetGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [PHSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Type] tinyint NOT NULL,
    [ModelDataTableName] nvarchar(50) NOT NULL,
    [RollupAssumptionsTableName] nvarchar(50) NOT NULL,
    [DetailAssumptionsTableName] nvarchar(50) NOT NULL,
    [Dimensionality] nvarchar(max) NOT NULL,
    [IsPercentage] bit NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([GlobalAssumptionSetGUID])
);
GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_GlobalAssumptionSetGUID] DEFAULT (newid()) FOR [GlobalAssumptionSetGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_Type] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_BaseTableName] DEFAULT ('') FOR [ModelDataTableName]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_GlobalAssumptionSetTableName] DEFAULT ('') FOR [RollupAssumptionsTableName]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_DetailAssumptionsTableName] DEFAULT ('') FOR [DetailAssumptionsTableName]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_Dimensionality] DEFAULT ('') FOR [Dimensionality]; GO
ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_IsPercentage] DEFAULT ((0)) FOR [IsPercentage]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GridColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[GridColumn] (
    [GridColumnGUID] uniqueidentifier NOT NULL,
    [GridTemplateGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [AttributeGUID] uniqueidentifier NOT NULL,
    [SpecialColumnName] nvarchar(100) NOT NULL,
    [Width] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    [IsFrozen] bit NOT NULL,
    [SortIndex] int NOT NULL,
    [SortOrder] tinyint NOT NULL,
    [TotalIndex] int NOT NULL,
    PRIMARY KEY ([GridColumnGUID])
);

CREATE NONCLUSTERED INDEX [NUNC_AttributeGUID] ON [dbo].[GridColumn] ([AttributeGUID]);
CREATE NONCLUSTERED INDEX [NUNC_UserGUID] ON [dbo].[GridColumn] ([UserGUID]);
GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [FK__GridColum__GridT__5963C6C6] FOREIGN KEY ([GridTemplateGUID]) REFERENCES [dbo].[GridTemplate] ([GRIDTEMPLATEGUID]); GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__GridC__586FA28D] DEFAULT (newid()) FOR [GridColumnGUID]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__UserG__5A57EAFF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Speci__5C403371] DEFAULT ('') FOR [SpecialColumnName]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Width__5D3457AA] DEFAULT ((150)) FOR [Width]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Displ__5E287BE3] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__IsFro__5F1CA01C] DEFAULT ((0)) FOR [IsFrozen]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__SortI__6010C455] DEFAULT ((-1)) FOR [SortIndex]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__SortO__6104E88E] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Total__699A2E8F] DEFAULT ((-1)) FOR [TotalIndex]; GO
ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Attri__5B4C0F38] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AttributeGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GridSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[GridSetting] (
    [GRIDSETTINGGUID] uniqueidentifier NOT NULL,
    [USERGUID] uniqueidentifier NOT NULL,
    [COLUMNID] nvarchar(64) NOT NULL,
    [WIDTH] float NOT NULL,
    [DISPLAYORDER] int NOT NULL,
    [ISFROZEN] bit NOT NULL,
    [ISENABLED] bit NOT NULL,
    [SORTINDEX] int NOT NULL,
    [GRIDTEMPLATEGUID] uniqueidentifier NOT NULL,
    [PLANTYPEGUID] uniqueidentifier NOT NULL,
    [SORTORDER] int NOT NULL,
    [ISAVAILABLE] bit NOT NULL,
    [WorkspaceGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([GRIDSETTINGGUID])
);

CREATE CLUSTERED INDEX [IX_GridSetting_UserType] ON [dbo].[GridSetting] ([USERGUID], [PLANTYPEGUID]);
GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_ISAVAILABLE] DEFAULT ((1)) FOR [ISAVAILABLE]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_GRIDSETTINGGUID] DEFAULT (newid()) FOR [GRIDSETTINGGUID]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [USERGUID]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_COLUMNID] DEFAULT ('') FOR [COLUMNID]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_WIDTH] DEFAULT ((100)) FOR [WIDTH]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_WorkspaceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceGUID]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_DISPLAYORDER] DEFAULT ((-1)) FOR [DISPLAYORDER]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_FROZEN] DEFAULT ((0)) FOR [ISFROZEN]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_ISENABLED] DEFAULT ((1)) FOR [ISENABLED]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_SORTINDEX] DEFAULT ((-1)) FOR [SORTINDEX]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_SORTDIRECTION] DEFAULT ((0)) FOR [SORTORDER]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_GRIDTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GRIDTEMPLATEGUID]; GO
ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_PLANTYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PLANTYPEGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GridTemplate ------------------
---------------------------------------------
CREATE TABLE [dbo].[GridTemplate] (
    [GRIDTEMPLATEGUID] uniqueidentifier NOT NULL,
    [NAME] nvarchar(64) NOT NULL,
    [DESCRIPTION] nvarchar(450) NOT NULL,
    [ISDEFAULT] bit NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([GRIDTEMPLATEGUID])
);
GO
ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF__GridTempl__PlanT__61F90CC7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF_GridTemplate_GRIDTEMPLATEGUID] DEFAULT (newid()) FOR [GRIDTEMPLATEGUID]; GO
ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF_GridTemplate_NAME] DEFAULT ('') FOR [NAME]; GO
ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF_GridTemplate_DESCRIPTION] DEFAULT ('') FOR [DESCRIPTION]; GO
ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF_GridTemplate_ISDEFAULT] DEFAULT ((0)) FOR [ISDEFAULT]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GridTemplateFormFieldLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[GridTemplateFormFieldLink] (
    [GRIDTEMPLATEFORMFIELDLINKGUID] uniqueidentifier NOT NULL,
    [GRIDTEMPLATEGUID] uniqueidentifier NOT NULL,
    [FORMFIELDGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([GRIDTEMPLATEFORMFIELDLINKGUID])
);
GO
ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [FK_GridTemplateFormFieldLink_FEFormField] FOREIGN KEY ([FORMFIELDGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO
ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [FK_GridTemplateFormFieldLink_GridTemplate] FOREIGN KEY ([GRIDTEMPLATEGUID]) REFERENCES [dbo].[GridTemplate] ([GRIDTEMPLATEGUID]); GO
ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [DF__GridTempl__Displ__322DC4FD] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [DF_GridTemplateFormFieldLink_GRIDTEMPLATEFORMFIELDLINKGUID] DEFAULT (newid()) FOR [GRIDTEMPLATEFORMFIELDLINKGUID]; GO
ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [DF_GridTemplateFormFieldLink_GRIDTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GRIDTEMPLATEGUID]; GO
ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [DF_GridTemplateFormFieldLink_FORMFIELDGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FORMFIELDGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.GridTemplateUserLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[GridTemplateUserLink] (
    [UserGUID] uniqueidentifier NOT NULL,
    [EntityViewGUID] uniqueidentifier NOT NULL,
    [GridTemplateGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([UserGUID], [EntityViewGUID])
);
GO
ALTER TABLE [dbo].[GridTemplateUserLink] ADD CONSTRAINT [FK__GridTempl__Entit__67B1E61D] FOREIGN KEY ([EntityViewGUID]) REFERENCES [dbo].[EntityView] ([ENTITYVIEWGUID]); GO
ALTER TABLE [dbo].[GridTemplateUserLink] ADD CONSTRAINT [FK__GridTempl__GridT__68A60A56] FOREIGN KEY ([GridTemplateGUID]) REFERENCES [dbo].[GridTemplate] ([GRIDTEMPLATEGUID]); GO
ALTER TABLE [dbo].[GridTemplateUserLink] ADD CONSTRAINT [FK__GridTempl__UserG__66BDC1E4] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.HangfireAuthenticationToken ------------------
---------------------------------------------
CREATE TABLE [dbo].[HangfireAuthenticationToken] (
    [TokenGuid] uniqueidentifier NOT NULL,
    [UserName] varchar(100) NOT NULL,
    PRIMARY KEY ([TokenGuid])
);
GO
ALTER TABLE [dbo].[HangfireAuthenticationToken] ADD CONSTRAINT [DF__HangfireA__Token__42F82853] DEFAULT (newid()) FOR [TokenGuid]; GO

---------------------------------------------

---------------------------------------------
-- dbo.HangfireJobQueueOverride ------------------
---------------------------------------------
CREATE TABLE [dbo].[HangfireJobQueueOverride] (
    [TypeName] varchar(250) NOT NULL,
    [MethodName] varchar(100) NOT NULL,
    [QueueName] varchar(100) NOT NULL
);

CREATE UNIQUE NONCLUSTERED INDEX [UC_HangfireJobQueueOverride_TypeName_MethodName] ON [dbo].[HangfireJobQueueOverride] ([TypeName], [MethodName]);
GO
ALTER TABLE [dbo].[HangfireJobQueueOverride] ADD CONSTRAINT [DF__HangfireJ__Queue__3F27976F] DEFAULT ('default') FOR [QueueName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.HistoryItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[HistoryItem] (
    [HISTORYITEMGUID] uniqueidentifier NOT NULL,
    [OBJECTGUID] uniqueidentifier NOT NULL,
    [OBJECTTYPE] nvarchar(256) NOT NULL,
    [DATETIMESTAMP] datetime NOT NULL,
    [MODIFIERUSERGUID] uniqueidentifier NOT NULL,
    [CATEGORY] nvarchar(64) NOT NULL,
    [DESCRIPTION] nvarchar(4000) NOT NULL,
    [USERCOMMENTS] nvarchar(256) NOT NULL,
    [METAXML] xml NOT NULL,
    [VERSION] timestamp NOT NULL,
    [MODIFIERUSERNAME] nvarchar(256) NOT NULL,
    [ITEMCOUNT] int NOT NULL,
    [ELAPSEDMS] int NOT NULL,
    [TransactionID] varchar(50) NULL,
    [DATETIMESTAMPUTC] datetime NOT NULL,
    PRIMARY KEY ([HISTORYITEMGUID])
);

CREATE NONCLUSTERED INDEX [IX_HistoryItem_DateTimeStamp] ON [dbo].[HistoryItem] ([DATETIMESTAMP], [VERSION]);
CREATE NONCLUSTERED INDEX [IDX_HistoryItem] ON [dbo].[HistoryItem] ([OBJECTGUID], [CATEGORY]);
CREATE NONCLUSTERED INDEX [IDX_HistoryItem_RunTime] ON [dbo].[HistoryItem] ([CATEGORY], [DATETIMESTAMP]) INCLUDE ([DESCRIPTION]);
GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_ITEMCOUNT] DEFAULT ((0)) FOR [ITEMCOUNT]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_HISTORYGUID] DEFAULT (newid()) FOR [HISTORYITEMGUID]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_OBJECTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OBJECTGUID]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_OBJECTTYPE] DEFAULT ('') FOR [OBJECTTYPE]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_DATETIMESTAMP] DEFAULT (getdate()) FOR [DATETIMESTAMP]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_MODIFIERUSERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MODIFIERUSERGUID]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_CATEGORY] DEFAULT ('') FOR [CATEGORY]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_DESCRIPTION] DEFAULT ('') FOR [DESCRIPTION]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF__HistoryIt__DATET__43F43DF2] DEFAULT (getutcdate()) FOR [DATETIMESTAMPUTC]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_USERCOMMENTS] DEFAULT ('') FOR [USERCOMMENTS]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_MODIFIERUSERNAME] DEFAULT ('') FOR [MODIFIERUSERNAME]; GO
ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_ELAPSEDMS] DEFAULT ((0)) FOR [ELAPSEDMS]; GO

---------------------------------------------

---------------------------------------------
-- dbo.HistoryItemBlankFactTable ------------------
---------------------------------------------
CREATE TABLE [dbo].[HistoryItemBlankFactTable] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SourceFilePath] nvarchar(256) NOT NULL,
    [ModelDataConfigGUID] uniqueidentifier NOT NULL,
    [CubeStubGUID] uniqueidentifier NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.HistoryItemLine ------------------
---------------------------------------------
CREATE TABLE [dbo].[HistoryItemLine] (
    [HistoryItemLineID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NULL,
    [DateTimeStamp] datetime NOT NULL,
    [SQLUser] nvarchar(128) NOT NULL,
    [TableName] nvarchar(64) NOT NULL,
    [RowID] int NULL,
    [BeforeValues] nvarchar(max) NULL,
    [AfterValues] nvarchar(max) NULL,
    [DateTimeStampUtc] datetime NOT NULL,
    PRIMARY KEY ([HistoryItemLineID])
);
GO
ALTER TABLE [dbo].[HistoryItemLine] ADD CONSTRAINT [DF_HistoryItemLine_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[HistoryItemLine] ADD CONSTRAINT [DF_HistoryItemLine_SQLUser] DEFAULT (suser_sname()) FOR [SQLUser]; GO
ALTER TABLE [dbo].[HistoryItemLine] ADD CONSTRAINT [DF__HistoryIt__DateT__44E8622B] DEFAULT (getutcdate()) FOR [DateTimeStampUtc]; GO

---------------------------------------------

---------------------------------------------
-- dbo.HistoryItemObject ------------------
---------------------------------------------
CREATE TABLE [dbo].[HistoryItemObject] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [ObjectGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([HistoryItemGUID], [ObjectGUID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.IPAddressWhiteList ------------------
---------------------------------------------
CREATE TABLE [dbo].[IPAddressWhiteList] (
    [IPAddressRangeGUID] uniqueidentifier NOT NULL,
    [IPAddressRangeStart] nvarchar(100) NOT NULL,
    [IPAddressRangeEnd] nvarchar(100) NOT NULL,
    PRIMARY KEY ([IPAddressRangeGUID])
);
GO
ALTER TABLE [dbo].[IPAddressWhiteList] ADD CONSTRAINT [DF__IPAddress__IPAdd__2CD47697] DEFAULT (newid()) FOR [IPAddressRangeGUID]; GO
ALTER TABLE [dbo].[IPAddressWhiteList] ADD CONSTRAINT [DF__IPAddress__IPAdd__2DC89AD0] DEFAULT ('') FOR [IPAddressRangeStart]; GO
ALTER TABLE [dbo].[IPAddressWhiteList] ADD CONSTRAINT [DF__IPAddress__IPAdd__2EBCBF09] DEFAULT ('') FOR [IPAddressRangeEnd]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IRCChat ------------------
---------------------------------------------
CREATE TABLE [dbo].[IRCChat] (
    [IRCChatGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Description] varchar(802) NOT NULL,
    [CreationTime] datetime NOT NULL,
    [SQLTableName] nvarchar(128) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [LastModifiedUserGUID] uniqueidentifier NOT NULL,
    [RowID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [IsChatDeleted] bit NOT NULL,
    PRIMARY KEY ([IRCChatGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ__IRCChat__737584F6754087D1] ON [dbo].[IRCChat] ([Name]);
CREATE UNIQUE NONCLUSTERED INDEX [UQ__IRCChat__7CE2D9A872641B26] ON [dbo].[IRCChat] ([SQLTableName]);
GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF_IRCChat_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__IRCChat__7728D043] DEFAULT (newid()) FOR [IRCChatGUID]; GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__Name__781CF47C] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__Descrip__791118B5] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__Creatio__7A053CEE] DEFAULT (getdate()) FOR [CreationTime]; GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF_IRCChat_LastModifiedUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastModifiedUserGUID]; GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__SQLTabl__7AF96127] DEFAULT ('') FOR [SQLTableName]; GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF_IRCChat_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF_IRCChat_IsDeleted] DEFAULT ((0)) FOR [IsChatDeleted]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IRCChatMembership ------------------
---------------------------------------------
CREATE TABLE [dbo].[IRCChatMembership] (
    [UserGUID] uniqueidentifier NOT NULL,
    [IRCChatGUID] uniqueidentifier NOT NULL,
    [LastCheckinTime] datetime NOT NULL
);

CREATE CLUSTERED INDEX [CLUSTERED_LASTCHECKINTIME] ON [dbo].[IRCChatMembership] ([LastCheckinTime]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_USERGUID_CHATGUID] ON [dbo].[IRCChatMembership] ([UserGUID], [IRCChatGUID]);
GO
ALTER TABLE [dbo].[IRCChatMembership] ADD CONSTRAINT [DF__IRCChatMe__UserG__7CE1A999] DEFAULT (newid()) FOR [UserGUID]; GO
ALTER TABLE [dbo].[IRCChatMembership] ADD CONSTRAINT [DF__IRCChatMe__IRCCh__7DD5CDD2] DEFAULT (newid()) FOR [IRCChatGUID]; GO
ALTER TABLE [dbo].[IRCChatMembership] ADD CONSTRAINT [DF__IRCChatMe__Check__7EC9F20B] DEFAULT (getdate()) FOR [LastCheckinTime]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IdentityCompressionLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[IdentityCompressionLog] (
    [runTime] datetime NOT NULL,
    [schemaName] nvarchar(100) NOT NULL,
    [tableName] nvarchar(100) NOT NULL,
    [status] smallint NULL,
    PRIMARY KEY ([runTime], [schemaName], [tableName])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ImportCSVConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[ImportCSVConfig] (
    [ImportCSVConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [ConfigXML] xml NOT NULL,
    [TimeoutSeconds] int NOT NULL,
    PRIMARY KEY ([ImportCSVConfigGUID])
);
GO
ALTER TABLE [dbo].[ImportCSVConfig] ADD CONSTRAINT [DF_ImportCSVConfig_ImportCSVConfig] DEFAULT (newid()) FOR [ImportCSVConfigGUID]; GO
ALTER TABLE [dbo].[ImportCSVConfig] ADD CONSTRAINT [DF_ImportCSVConfig_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[ImportCSVConfig] ADD CONSTRAINT [DF_ImportCSVConfig_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ImportCSVConfig] ADD CONSTRAINT [DF_ImportCSVConfig_TimeoutSeconds] DEFAULT ((60)) FOR [TimeoutSeconds]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntCapERPConnectorConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntCapERPConnectorConfig] (
    [ConnectorConfigGUID] uniqueidentifier NOT NULL,
    [DataType] smallint NOT NULL,
    [ServerAddress] varchar(255) NOT NULL,
    [Port] int NOT NULL,
    [UserName] nvarchar(255) NOT NULL,
    [Password] nvarchar(4000) NOT NULL,
    [IsSSL] bit NOT NULL,
    [PollFrequency] int NOT NULL,
    [EnvironmentType] tinyint NOT NULL,
    [SystemType] smallint NOT NULL,
    [AdditionalDataXML] xml NOT NULL,
    PRIMARY KEY ([ConnectorConfigGUID])
);
GO
ALTER TABLE [dbo].[IntCapERPConnectorConfig] ADD CONSTRAINT [DF_IntCapERPSystemConfig_PollFrequency] DEFAULT ((900)) FOR [PollFrequency]; GO
ALTER TABLE [dbo].[IntCapERPConnectorConfig] ADD CONSTRAINT [DF_IntCapERPSystemConfig_EnvironmentType] DEFAULT ((0)) FOR [EnvironmentType]; GO
ALTER TABLE [dbo].[IntCapERPConnectorConfig] ADD CONSTRAINT [DF_IntCapERPSystemConfig_AdditionalDataXML] DEFAULT ('') FOR [AdditionalDataXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntCapERPFieldMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntCapERPFieldMapping] (
    [FieldMappingGUID] uniqueidentifier NOT NULL,
    [ConnectorConfigGUID] uniqueidentifier NOT NULL,
    [ERPFieldName] nvarchar(4000) NOT NULL,
    [Direction] smallint NOT NULL,
    [JazzFieldGUID] uniqueidentifier NOT NULL,
    [Filter] nvarchar(4000) NOT NULL,
    [MappingType] smallint NOT NULL,
    [JazzFieldValue] nvarchar(4000) NOT NULL,
    [AttributeOverrideGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FieldMappingGUID])
);
GO
ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [FK_IntCapERPFieldMapping_IntCapERPSystemConfig] FOREIGN KEY ([ConnectorConfigGUID]) REFERENCES [dbo].[IntCapERPConnectorConfig] ([ConnectorConfigGUID]); GO
ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF_IntCapERPFieldMapping_Direction] DEFAULT ((0)) FOR [Direction]; GO
ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__JazzF__4A1138A7] DEFAULT ('') FOR [JazzFieldValue]; GO
ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__JazzF__51DC77A1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [JazzFieldGUID]; GO
ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__Filte__53C4C013] DEFAULT ('') FOR [Filter]; GO
ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__Mappi__54B8E44C] DEFAULT ((0)) FOR [MappingType]; GO
ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__Attri__5B3BC4A9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AttributeOverrideGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntCapERPFieldMappingDefaults ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntCapERPFieldMappingDefaults] (
    [FieldMappingGUID] uniqueidentifier NOT NULL,
    [ERPFieldName] nvarchar(4000) NOT NULL,
    [JazzFieldName] nvarchar(4000) NOT NULL,
    [JazzFieldValue] nvarchar(4000) NOT NULL,
    [Direction] smallint NOT NULL,
    [MappingType] smallint NOT NULL,
    [DataType] smallint NOT NULL,
    [SystemType] smallint NOT NULL,
    [SourceName] nvarchar(4000) NOT NULL,
    [IsRequired] bit NOT NULL,
    PRIMARY KEY ([FieldMappingGUID])
);
GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_ERPFieldName] DEFAULT ('') FOR [ERPFieldName]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_JazzFieldName] DEFAULT ('') FOR [JazzFieldName]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_JazzFieldValue] DEFAULT ('') FOR [JazzFieldValue]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_Direction] DEFAULT ((0)) FOR [Direction]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_MappingType] DEFAULT ((0)) FOR [MappingType]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_DataType] DEFAULT ((0)) FOR [DataType]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_SystemType] DEFAULT ((0)) FOR [SystemType]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_FieldMappingGUID] DEFAULT (newid()) FOR [FieldMappingGUID]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF__IntCapERP__Sourc__56770F8C] DEFAULT ('') FOR [SourceName]; GO
ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF__IntCapERP__IsReq__5A47A070] DEFAULT ((0)) FOR [IsRequired]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntConfig] (
    [ConfigID] uniqueidentifier NOT NULL,
    [AuthorGUID] uniqueidentifier NULL,
    [Name] nvarchar(100) NOT NULL,
    [IntegrationTypeVal] tinyint NOT NULL,
    [DropDirectoryPath] varchar(max) NOT NULL,
    [DesignerXML] varchar(max) NOT NULL,
    [DataInterfaceID] uniqueidentifier NOT NULL,
    [Summary] varchar(max) NOT NULL,
    [IsHidden] bit NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    [EmailLevelVal] tinyint NOT NULL,
    [IsCompressed] bit NOT NULL,
    [IsEncrypted] bit NOT NULL,
    [CustomEmailAddress] nvarchar(2000) NOT NULL,
    [IsRunOncePostAction] bit NOT NULL,
    [LastRunAtUtc] datetime NOT NULL,
    [CreatedAtUtc] datetime NOT NULL,
    [ModifiedAtUtc] datetime NOT NULL,
    PRIMARY KEY ([ConfigID])
);
GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__DropD__070736BF] DEFAULT ('') FOR [DropDirectoryPath]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Email__19F11CEC] DEFAULT ((0)) FOR [EmailLevelVal]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__IsRun__1A0A5602] DEFAULT ((0)) FOR [IsRunOncePostAction]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Desig__258BBDDF] DEFAULT ('') FOR [DesignerXML]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Summa__2DB6EF8C] DEFAULT ('') FOR [Summary]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF_intConfig_CustomEmails] DEFAULT ('') FOR [CustomEmailAddress]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Confi__31327AB5] DEFAULT (newid()) FOR [ConfigID]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Autho__32269EEE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Name__331AC327] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Integ__340EE760] DEFAULT ('0') FOR [IntegrationTypeVal]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__IsCom__3A9EE0C1] DEFAULT ((0)) FOR [IsCompressed]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__IsEnc__3B9304FA] DEFAULT ((0)) FOR [IsEncrypted]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__LastR__3C531C2A] DEFAULT (getutcdate()) FOR [LastRunAtUtc]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Creat__3D474063] DEFAULT (getutcdate()) FOR [CreatedAtUtc]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Modif__3E3B649C] DEFAULT (getutcdate()) FOR [ModifiedAtUtc]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__DataI__4B7C5C9D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceID]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__IsHid__5B20298E] DEFAULT ('0') FOR [IsHidden]; GO
ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF_IntConfig_FrameworkID] DEFAULT ((0)) FOR [FrameworkID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntConfigFramework ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntConfigFramework] (
    [ConfigID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    PRIMARY KEY ([ConfigID], [FrameworkID])
);
GO
ALTER TABLE [dbo].[IntConfigFramework] ADD CONSTRAINT [FK_IntConfigFramework_IntConfig] FOREIGN KEY ([ConfigID]) REFERENCES [dbo].[IntConfig] ([ConfigID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.IntConfigResponse ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntConfigResponse] (
    [ConfigResponseID] uniqueidentifier NOT NULL,
    [ConfigID] uniqueidentifier NOT NULL,
    [ProcessStateVal] int NOT NULL,
    [ResponseTypeVal] int NOT NULL,
    PRIMARY KEY ([ConfigResponseID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ__IntConfi__EC4B467370ADE14C] ON [dbo].[IntConfigResponse] ([ConfigID], [ProcessStateVal], [ResponseTypeVal]);
GO
ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [FK__IntConfig__Confi__7666BAA2] FOREIGN KEY ([ConfigID]) REFERENCES [dbo].[IntConfig] ([ConfigID]); GO
ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [DF__IntConfig__Confi__729629BE] DEFAULT (newid()) FOR [ConfigResponseID]; GO
ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [DF__IntConfig__Proce__747E7230] DEFAULT ((0)) FOR [ProcessStateVal]; GO
ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [DF__IntConfig__Respo__75729669] DEFAULT ((0)) FOR [ResponseTypeVal]; GO
ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [DF__IntConfig__Confi__738A4DF7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntConfigSchedule ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntConfigSchedule] (
    [ConfigScheduleID] uniqueidentifier NOT NULL,
    [ConfigID] uniqueidentifier NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [TaskName] nvarchar(128) NOT NULL,
    [Description] varchar(max) NOT NULL,
    [IsEnabled] bit NOT NULL,
    [IsExpiring] bit NOT NULL,
    [ExpirationDate] datetime NOT NULL,
    [StartTime] datetime NOT NULL,
    [SchedulePeriodVal] int NOT NULL,
    [RecurRate] int NOT NULL,
    [DaysOfWeekVal] int NOT NULL,
    [MonthsOfYearVal] int NOT NULL,
    [Days] nvarchar(83) NOT NULL,
    [OrderIndex] int NOT NULL,
    [DropDirectory] nvarchar(max) NOT NULL,
    [ArchiveDirectory] nvarchar(max) NOT NULL,
    [ScheduledTaskGuid] uniqueidentifier NOT NULL,
    [IsStopImport] bit NOT NULL,
    [PreviousConfigGUID] uniqueidentifier NULL,
    PRIMARY KEY ([ConfigScheduleID])
);
GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [FK__IntConfig__Confi__6388F058] FOREIGN KEY ([ConfigID]) REFERENCES [dbo].[IntConfig] ([ConfigID]); GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__DropD__23647B6C] DEFAULT ('') FOR [DropDirectory]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__IsSto__35FA2735] DEFAULT ((0)) FOR [IsStopImport]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Archi__49F69AAD] DEFAULT ('') FOR [ArchiveDirectory]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Confi__6294CC1F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Order__5E5A26E7] DEFAULT ((0)) FOR [OrderIndex]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Confi__61A0A7E6] DEFAULT (newid()) FOR [ConfigScheduleID]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfigS__Name__647D1491] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__TaskN__657138CA] DEFAULT ('') FOR [TaskName]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Descr__66655D03] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__IsEna__6759813C] DEFAULT ((0)) FOR [IsEnabled]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__IsExp__684DA575] DEFAULT ((0)) FOR [IsExpiring]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Expir__6941C9AE] DEFAULT (getdate()) FOR [ExpirationDate]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Start__6A35EDE7] DEFAULT (getdate()) FOR [StartTime]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Sched__6B2A1220] DEFAULT ((0)) FOR [SchedulePeriodVal]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Recur__6C1E3659] DEFAULT ((0)) FOR [RecurRate]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__DaysO__6D125A92] DEFAULT ((0)) FOR [DaysOfWeekVal]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Month__6E067ECB] DEFAULT ((0)) FOR [MonthsOfYearVal]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfigS__Days__6EFAA304] DEFAULT ('') FOR [Days]; GO
ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Sched__7862133C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScheduledTaskGuid]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntConfigUserGroupNotification ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntConfigUserGroupNotification] (
    [GroupNotificationGUID] uniqueidentifier NOT NULL,
    [ConfigID] uniqueidentifier NOT NULL,
    [UserGroupGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([GroupNotificationGUID])
);
GO
ALTER TABLE [dbo].[IntConfigUserGroupNotification] ADD CONSTRAINT [FK_IntConfigUserGroupNotification_UserGroupGUID] FOREIGN KEY ([UserGroupGUID]) REFERENCES [dbo].[UserGroup] ([UserGroupGUID]); GO
ALTER TABLE [dbo].[IntConfigUserGroupNotification] ADD CONSTRAINT [DF__IntConfig__Confi__2DC4D3E7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO
ALTER TABLE [dbo].[IntConfigUserGroupNotification] ADD CONSTRAINT [DF_IntConfigUserGroupNotification_GroupNotificationGUID] DEFAULT (newid()) FOR [GroupNotificationGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntDataInterface ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntDataInterface] (
    [DataInterfaceID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [DescriptionXAML] varchar(max) NOT NULL,
    [IntegrationTypeVal] tinyint NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    PRIMARY KEY ([DataInterfaceID])
);
GO
ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF_IntDataInterface_GlobalID] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataIn__DataI__29274499] DEFAULT (newid()) FOR [DataInterfaceID]; GO
ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataIn__Descr__2ADA82E1] DEFAULT ('') FOR [DescriptionXAML]; GO
ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataInt__Name__2B0F8D0B] DEFAULT ('''') FOR [Name]; GO
ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataIn__Descr__4D64A50F] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataIn__Integ__56B9051F] DEFAULT ('0') FOR [IntegrationTypeVal]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntDataInterfaceField ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntDataInterfaceField] (
    [DataInterfaceFieldID] uniqueidentifier NOT NULL,
    [DataInterfaceSectionID] uniqueidentifier NOT NULL,
    [ScoreKeyGUID] uniqueidentifier NOT NULL,
    [OrderIndex] smallint NOT NULL,
    [IsRequired] bit NOT NULL,
    [FieldName] nvarchar(100) NOT NULL,
    [ColumnTypeVal] tinyint NOT NULL,
    [MaxLength] smallint NOT NULL,
    [Precision] tinyint NOT NULL,
    [Scale] tinyint NOT NULL,
    [IsMeasure] bit NOT NULL,
    [IsKey] bit NOT NULL,
    [GivenScoreAttributeGUID] uniqueidentifier NOT NULL,
    [IsAllowingCreate] bit NOT NULL,
    [ImportName] nvarchar(200) NOT NULL,
    [IsHidden] bit NOT NULL,
    [IsForeignKey] bit NOT NULL,
    [Description] varchar(max) NOT NULL,
    [IsScoreRequired] bit NOT NULL,
    [isReplaceKey] bit NOT NULL,
    PRIMARY KEY ([DataInterfaceFieldID])
);
GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [FK__IntDataIn__DataI__38698829] FOREIGN KEY ([DataInterfaceSectionID]) REFERENCES [dbo].[IntDataInterfaceSection] ([DataInterfaceSectionID]); GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__isRep__0C811614] DEFAULT ((0)) FOR [isReplaceKey]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsHid__13F71D89] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsFor__14EB41C2] DEFAULT ((0)) FOR [IsForeignKey]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Order__3A51D09B] DEFAULT ('0') FOR [OrderIndex]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Descr__2615CDC4] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsSco__3562FE4C] DEFAULT ('0') FOR [IsScoreRequired]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__DataI__377563F0] DEFAULT (newid()) FOR [DataInterfaceFieldID]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Score__395DAC62] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreKeyGUID]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsReq__3B45F4D4] DEFAULT ('0') FOR [IsRequired]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Field__3C3A190D] DEFAULT ('''') FOR [FieldName]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Colum__3D2E3D46] DEFAULT ('0') FOR [ColumnTypeVal]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__MaxLe__3F1685B8] DEFAULT ('0') FOR [MaxLength]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Preci__400AA9F1] DEFAULT ('0') FOR [Precision]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Scale__40FECE2A] DEFAULT ('0') FOR [Scale]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsMea__42E7169C] DEFAULT ((0)) FOR [IsMeasure]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsKey__4F4CED81] DEFAULT ('0') FOR [IsKey]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Given__504111BA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GivenScoreAttributeGUID]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsAll__616B9DBC] DEFAULT ((0)) FOR [IsAllowingCreate]; GO
ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Impor__784F0314] DEFAULT ('') FOR [ImportName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntDataInterfaceMap ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntDataInterfaceMap] (
    [DataInterfaceMapID] uniqueidentifier NOT NULL,
    [SourceColumnID] uniqueidentifier NOT NULL,
    [DataInterfaceFieldID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([DataInterfaceMapID])
);
GO
ALTER TABLE [dbo].[IntDataInterfaceMap] ADD CONSTRAINT [FK__IntDataIn__DataI__4994142B] FOREIGN KEY ([DataInterfaceFieldID]) REFERENCES [dbo].[IntDataInterfaceField] ([DataInterfaceFieldID]); GO
ALTER TABLE [dbo].[IntDataInterfaceMap] ADD CONSTRAINT [FK__IntDataIn__Sourc__489FEFF2] FOREIGN KEY ([SourceColumnID]) REFERENCES [dbo].[IntSourceField] ([SourceColumnID]); GO
ALTER TABLE [dbo].[IntDataInterfaceMap] ADD CONSTRAINT [DF__IntDataIn__DataI__47ABCBB9] DEFAULT (newid()) FOR [DataInterfaceMapID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntDataInterfaceSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntDataInterfaceSection] (
    [DataInterfaceSectionID] uniqueidentifier NOT NULL,
    [DataInterfaceID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [SectionTypeVal] tinyint NOT NULL,
    [ScoreGUID] uniqueidentifier NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [SampleTypeVal] tinyint NOT NULL,
    [ScriptGUID] uniqueidentifier NOT NULL,
    [OrderIndex] tinyint NOT NULL,
    [TableName] nvarchar(200) NULL,
    [IsSummary] bit NOT NULL,
    [MergeTypeVal] tinyint NOT NULL,
    [AllowColumnPassthrough] bit NOT NULL,
    [IsDisabled] bit NOT NULL,
    PRIMARY KEY ([DataInterfaceSectionID])
);
GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [FK__IntDataIn__DataI__30C86661] FOREIGN KEY ([DataInterfaceID]) REFERENCES [dbo].[IntDataInterface] ([DataInterfaceID]); GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__IsDis__01F5D0E1] DEFAULT ((0)) FOR [IsDisabled]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Order__15DF65FB] DEFAULT ('0') FOR [OrderIndex]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Merge__2E5D3419] DEFAULT ('0') FOR [MergeTypeVal]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__DataI__2FD44228] DEFAULT (newid()) FOR [DataInterfaceSectionID]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataInt__Name__31BC8A9A] DEFAULT ('''') FOR [Name]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Secti__32B0AED3] DEFAULT ('0') FOR [SectionTypeVal]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Score__4C7080D6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreGUID]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Descr__4E58C948] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Table__50961775] DEFAULT ('') FOR [TableName]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Allow__5D240D1B] DEFAULT ((0)) FOR [AllowColumnPassthrough]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Sampl__5F83554A] DEFAULT ((1)) FOR [SampleTypeVal]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Scrip__60777983] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScriptGUID]; GO
ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__IsSum__7DF2CDD1] DEFAULT ('0') FOR [IsSummary]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntDataInterfaceSync ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntDataInterfaceSync] (
    [DataInterfaceID] uniqueidentifier NOT NULL,
    [DataInterfaceSectionID] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [dbo].[IntDataInterfaceSync] ADD CONSTRAINT [DF__IntDataIn__DataI__5F1E9A5E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceID]; GO
ALTER TABLE [dbo].[IntDataInterfaceSync] ADD CONSTRAINT [DF__IntDataIn__DataI__6012BE97] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceSectionID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntDataInterfaceSyncLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntDataInterfaceSyncLog] (
    [LogGUID] uniqueidentifier NOT NULL,
    [DataInterfaceID] uniqueidentifier NOT NULL,
    [DataInterfaceSectionID] uniqueidentifier NOT NULL,
    [Description] varchar(max) NOT NULL,
    [TimeStampUtc] datetime NOT NULL,
    PRIMARY KEY ([LogGUID])
);
GO
ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__TimeS__3F2F88D5] DEFAULT (getutcdate()) FOR [TimeStampUtc]; GO
ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__LogGU__62EF2B42] DEFAULT (newid()) FOR [LogGUID]; GO
ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__DataI__63E34F7B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceID]; GO
ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__DataI__64D773B4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceSectionID]; GO
ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__Descr__65CB97ED] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntDataSetType ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntDataSetType] (
    [DataSetTypeID] uniqueidentifier NOT NULL,
    [DataSetType] varchar(128) NOT NULL,
    [SortOrder] tinyint NOT NULL,
    PRIMARY KEY ([DataSetTypeID])
);
GO
ALTER TABLE [dbo].[IntDataSetType] ADD CONSTRAINT [DF__IntDataSe__DataS__5F3B6893] DEFAULT (newid()) FOR [DataSetTypeID]; GO
ALTER TABLE [dbo].[IntDataSetType] ADD CONSTRAINT [DF__IntDataSe__DataS__602F8CCC] DEFAULT ('') FOR [DataSetType]; GO
ALTER TABLE [dbo].[IntDataSetType] ADD CONSTRAINT [DF_IntDataSetType_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntNotification ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntNotification] (
    [NotificationID] uniqueidentifier NOT NULL,
    [DatabaseName] varchar(200) NOT NULL,
    [TransactionGUID] uniqueidentifier NOT NULL,
    [ErrorMessage] varchar(1000) NOT NULL,
    [ErrorGUID] varchar(50) NOT NULL,
    [LastPostAction] varchar(200) NOT NULL,
    PRIMARY KEY ([NotificationID])
);
GO
ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__Notif__4ECFF6A0] DEFAULT (newid()) FOR [NotificationID]; GO
ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__Datab__4FC41AD9] DEFAULT ('') FOR [DatabaseName]; GO
ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__Error__50B83F12] DEFAULT ('') FOR [ErrorMessage]; GO
ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__Error__51AC634B] DEFAULT ('') FOR [ErrorGUID]; GO
ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__LastP__52A08784] DEFAULT ('') FOR [LastPostAction]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntPostAction ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntPostAction] (
    [PostActionID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [PostActionXML] nvarchar(max) NOT NULL,
    [PostActionTypeVal] tinyint NOT NULL,
    [SeqOrder] tinyint NOT NULL,
    [ActionGUID] uniqueidentifier NOT NULL,
    [ConfigID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PostActionID])
);
GO
ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__Actio__5E8F3111] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ActionGUID]; GO
ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__Confi__60426F59] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO
ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__PostA__5A349048] DEFAULT (newid()) FOR [PostActionID]; GO
ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAct__Name__5C1CD8BA] DEFAULT ('''') FOR [Name]; GO
ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__PostA__5D10FCF3] DEFAULT ('''') FOR [PostActionXML]; GO
ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__PostA__5E05212C] DEFAULT ('0') FOR [PostActionTypeVal]; GO
ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__SeqOr__5EF94565] DEFAULT ('0') FOR [SeqOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntSourceField ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntSourceField] (
    [SourceColumnID] uniqueidentifier NOT NULL,
    [DataSourceID] uniqueidentifier NOT NULL,
    [ColumnName] nvarchar(128) NOT NULL,
    [IsKey] bit NOT NULL,
    [ColumnTypeVal] tinyint NOT NULL,
    [MaxLength] smallint NOT NULL,
    [Precision] tinyint NOT NULL,
    [Scale] tinyint NOT NULL,
    [OrderIndex] int NOT NULL,
    [IsMeasure] bit NOT NULL,
    [FixedCharacterWidth] int NOT NULL,
    [ColumnAffinityVal] tinyint NOT NULL,
    [FixedStartIndex] int NOT NULL,
    [IsTrimEnabled] bit NOT NULL,
    [SequenceCode] nvarchar(20) NOT NULL,
    [RecordNumber] nvarchar(20) NOT NULL,
    [ClientField] varchar(1000) NOT NULL,
    PRIMARY KEY ([SourceColumnID])
);
GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Sourc__014E5D69] DEFAULT (newid()) FOR [SourceColumnID]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Colum__0336A5DB] DEFAULT ('''') FOR [ColumnName]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__IsKey__042ACA14] DEFAULT ('0') FOR [IsKey]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Colum__051EEE4D] DEFAULT ('0') FOR [ColumnTypeVal]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF_IntSourceColumn_MaxLength] DEFAULT ((0)) FOR [MaxLength]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF_IntSourceColumn_Precision] DEFAULT ((0)) FOR [Precision]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF_IntSourceColumn_Scale] DEFAULT ((0)) FOR [Scale]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Recor__0B8CF1DB] DEFAULT ('') FOR [RecordNumber]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Clien__0BBC36AB] DEFAULT ('') FOR [ClientField]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Order__1DEA9C17] DEFAULT ((0)) FOR [OrderIndex]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__IsMea__3992B68C] DEFAULT ((0)) FOR [IsMeasure]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Seque__3D96ECB6] DEFAULT ('') FOR [SequenceCode]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Fixed__4A532E3A] DEFAULT ((0)) FOR [FixedStartIndex]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Fixed__525E6456] DEFAULT ((-1)) FOR [FixedCharacterWidth]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__IsTri__599571CA] DEFAULT ((0)) FOR [IsTrimEnabled]; GO
ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Colum__5D9B0CD8] DEFAULT ((0)) FOR [ColumnAffinityVal]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntSourceFile ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntSourceFile] (
    [SourceFileID] uniqueidentifier NOT NULL,
    [ConfigID] uniqueidentifier NOT NULL,
    [ExpectedFileName] nvarchar(1024) NOT NULL,
    [OrderIndex] int NOT NULL,
    [SourceFileTypeVal] tinyint NOT NULL,
    [ConfigXML] varchar(max) NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [IsRepeatable] bit NOT NULL,
    [MatchModeVal] tinyint NOT NULL,
    [PartialMatchString] varchar(800) NOT NULL,
    [AutoSkipLineCount] int NOT NULL,
    [SourceSystem] nvarchar(500) NOT NULL,
    PRIMARY KEY ([SourceFileID])
);
GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [FK__IntSource__Confi__77C4F32F] FOREIGN KEY ([ConfigID]) REFERENCES [dbo].[IntConfig] ([ConfigID]); GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSourceF__Name__1F9DDA5F] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Order__267FE218] DEFAULT ((0)) FOR [OrderIndex]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__IsRep__29E65EA8] DEFAULT ((0)) FOR [IsRepeatable]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Match__2BCEA71A] DEFAULT ((0)) FOR [MatchModeVal]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Parti__2CC2CB53] DEFAULT ('') FOR [PartialMatchString]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Sourc__516A401D] DEFAULT ((0)) FOR [SourceFileTypeVal]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Confi__5352888F] DEFAULT ('') FOR [ConfigXML]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Sourc__541F86F9] DEFAULT ('') FOR [SourceSystem]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__AutoS__5A899603] DEFAULT ((0)) FOR [AutoSkipLineCount]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Sourc__76D0CEF6] DEFAULT (newid()) FOR [SourceFileID]; GO
ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Expec__78B91768] DEFAULT ('') FOR [ExpectedFileName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntSourceFileLocation ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntSourceFileLocation] (
    [UserGUID] uniqueidentifier NOT NULL,
    [SourceFileID] uniqueidentifier NOT NULL,
    [LastFullPathSeen] varchar(800) NOT NULL,
    PRIMARY KEY ([UserGUID], [SourceFileID])
);
GO
ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [FK_IntSourceFileLocation_IntSourceFile] FOREIGN KEY ([SourceFileID]) REFERENCES [dbo].[IntSourceFile] ([SourceFileID]); GO
ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [FK_IntSourceFileLocation_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [DF__IntSource__LastF__22AF5134] DEFAULT ('') FOR [LastFullPathSeen]; GO
ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [DF__IntSource__UserG__20C708C2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [DF__IntSource__Sourc__21BB2CFB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceFileID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntSourceSystemDetail ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntSourceSystemDetail] (
    [SourceSystemDetailID] uniqueidentifier NOT NULL,
    [DataSetSource] varchar(128) NOT NULL,
    [SourceID] varchar(128) NOT NULL,
    [Notes] varchar(1000) NOT NULL,
    [DataSetTypeID] uniqueidentifier NOT NULL,
    [IsCustom] bit NOT NULL,
    PRIMARY KEY ([SourceSystemDetailID])
);
GO
ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [FK__IntSource__DataS__66DC8A5B] FOREIGN KEY ([DataSetTypeID]) REFERENCES [dbo].[IntDataSetType] ([DataSetTypeID]); GO
ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__IsCus__594D8513] DEFAULT ((0)) FOR [IsCustom]; GO
ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__Sourc__630BF977] DEFAULT (newid()) FOR [SourceSystemDetailID]; GO
ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__DataS__64001DB0] DEFAULT ('') FOR [DataSetSource]; GO
ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__Sourc__64F441E9] DEFAULT ('') FOR [SourceID]; GO
ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__Notes__65E86622] DEFAULT ('') FOR [Notes]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntTransaction ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntTransaction] (
    [TransactionGUID] uniqueidentifier NOT NULL,
    [ConfigID] uniqueidentifier NOT NULL,
    [UserID] uniqueidentifier NOT NULL,
    [IsSuccess] bit NOT NULL,
    [HasCompleted] bit NOT NULL,
    [FileCheckSum] varchar(8000) NOT NULL,
    [HasStarted] bit NOT NULL,
    [ProcessStateVal] tinyint NOT NULL,
    [LocationVal] tinyint NOT NULL,
    [Comment] nvarchar(400) NOT NULL,
    [Files] nvarchar(max) NOT NULL,
    [IsManualEntry] bit NOT NULL,
    [CanDelete] bit NOT NULL,
    [TransactionID] int NOT NULL,
    [ProcessStateFailedValue] tinyint NOT NULL,
    [PostActionDuration] int NOT NULL,
    [EndTimeUtc] datetime NOT NULL,
    [StartTimeUtc] datetime NOT NULL,
    PRIMARY KEY ([TransactionGUID])
);

CREATE NONCLUSTERED INDEX [NC_IntTransaction_ConfigIDWithCheckSum] ON [dbo].[IntTransaction] ([ConfigID]) INCLUDE ([FileCheckSum]);
GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Trans__1AEC313B] DEFAULT (newid()) FOR [TransactionGUID]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Confi__1BE05574] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__UserI__1CD479AD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserID]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__IsSuc__1DC89DE6] DEFAULT ((0)) FOR [IsSuccess]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__HasCo__1EBCC21F] DEFAULT ((0)) FOR [HasCompleted]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__FileC__1FB0E658] DEFAULT ('') FOR [FileCheckSum]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__HasSt__20A50A91] DEFAULT ((0)) FOR [HasStarted]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Proce__21992ECA] DEFAULT ((0)) FOR [ProcessStateVal]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Locat__228D5303] DEFAULT ((0)) FOR [LocationVal]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Comme__2381773C] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Files__24759B75] DEFAULT ('') FOR [Files]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__IsMan__2569BFAE] DEFAULT ((0)) FOR [IsManualEntry]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__CanDe__265DE3E7] DEFAULT ((0)) FOR [CanDelete]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Proce__27520820] DEFAULT ((0)) FOR [ProcessStateFailedValue]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__PostA__28462C59] DEFAULT ((0)) FOR [PostActionDuration]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__EndTi__293A5092] DEFAULT (getutcdate()) FOR [EndTimeUtc]; GO
ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Start__2A2E74CB] DEFAULT (getutcdate()) FOR [StartTimeUtc]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntTransactionData ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntTransactionData] (
    [TransactionDataID] uniqueidentifier NOT NULL,
    [TransactionGUID] uniqueidentifier NOT NULL,
    [DataInterfaceSectionID] uniqueidentifier NOT NULL,
    [RowsImported] int NOT NULL,
    [CanDelete] bit NOT NULL,
    [IsImportDeleted] bit NOT NULL,
    [TransactionID] int NOT NULL,
    [RowsRejected] int NOT NULL,
    [TotalRows] int NOT NULL,
    [Files] varchar(max) NOT NULL,
    [FileSize] bigint NOT NULL,
    [HasDummyFile] bit NOT NULL,
    [IsAdhocImport] bit NOT NULL,
    PRIMARY KEY ([TransactionDataID])
);

CREATE CLUSTERED INDEX [IX_TransactionGUID] ON [dbo].[IntTransactionData] ([TransactionGUID]);
GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Trans__2A1178FB] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Total__34BBEA39] DEFAULT ((0)) FOR [TotalRows]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__IsAdh__3E0987CE] DEFAULT ((0)) FOR [IsAdhocImport]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__RowsR__3ED8570E] DEFAULT ((0)) FOR [RowsRejected]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__FileS__4F50E205] DEFAULT ((0)) FOR [FileSize]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Files__526C48B1] DEFAULT ('') FOR [Files]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Trans__5FEC04BA] DEFAULT (newid()) FOR [TransactionDataID]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Trans__60E028F3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TransactionGUID]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__DataI__61D44D2C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceSectionID]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__RowsI__62C87165] DEFAULT ((0)) FOR [RowsImported]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__CanDe__63BC959E] DEFAULT ((1)) FOR [CanDelete]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__IsImp__64B0B9D7] DEFAULT ((0)) FOR [IsImportDeleted]; GO
ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__HasDu__78A03DB7] DEFAULT ((0)) FOR [HasDummyFile]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntTransformation ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntTransformation] (
    [TransformationID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [TransformXML] nvarchar(max) NULL,
    [TransformationTypeVal] tinyint NOT NULL,
    [TransformationLocationVal] tinyint NOT NULL,
    [SeqOrder] tinyint NOT NULL,
    [Description] varchar(2000) NOT NULL,
    [Level] int NOT NULL,
    [ConfigID] uniqueidentifier NOT NULL,
    [IsCopied] bit NOT NULL,
    PRIMARY KEY ([TransformationID])
);
GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF_IntTransformation_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__IsCop__272CE4F1] DEFAULT ((0)) FOR [IsCopied]; GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Trans__4721BBD4] DEFAULT (newid()) FOR [TransformationID]; GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransfo__Name__490A0446] DEFAULT ('''') FOR [Name]; GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Trans__49FE287F] DEFAULT ('0') FOR [TransformationTypeVal]; GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Level__4A883864] DEFAULT ((-1)) FOR [Level]; GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Trans__4AF24CB8] DEFAULT ('0') FOR [TransformationLocationVal]; GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__SeqOr__4BE670F1] DEFAULT ('0') FOR [SeqOrder]; GO
ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Confi__61369392] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.IntTransformationLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[IntTransformationLink] (
    [TargetDataSourceID] uniqueidentifier NOT NULL,
    [SourceDataSourceID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([TargetDataSourceID], [SourceDataSourceID])
);
GO
ALTER TABLE [dbo].[IntTransformationLink] ADD CONSTRAINT [DF__IntTransf__DataS__1AD92542] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TargetDataSourceID]; GO
ALTER TABLE [dbo].[IntTransformationLink] ADD CONSTRAINT [DF__IntTransf__Paren__1BCD497B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceDataSourceID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.LastSecurityCheck ------------------
---------------------------------------------
CREATE TABLE [dbo].[LastSecurityCheck] (
    [UserGUID] uniqueidentifier NOT NULL,
    [Checksum] int NULL,
    [EmailAddress] nvarchar(450) NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.Lock ------------------
---------------------------------------------
CREATE TABLE [dbo].[Lock] (
    [LockGUID] uniqueidentifier NOT NULL,
    [ItemGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DateLocked] datetime NOT NULL,
    [LockGroup] nvarchar(64) NOT NULL,
    [DateLastActive] datetime NOT NULL,
    [UserName] nvarchar(256) NOT NULL,
    [DateLockedUtc] datetime NOT NULL,
    [DateLastActiveUtc] datetime NOT NULL
);
GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_LOCKGUID] DEFAULT (newid()) FOR [LockGUID]; GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_ITEMGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ItemGUID]; GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_DATELOCKED] DEFAULT (getdate()) FOR [DateLocked]; GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_LOCKGROUP] DEFAULT ('') FOR [LockGroup]; GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_DATELASTACTIVE] DEFAULT (getdate()) FOR [DateLastActive]; GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF__Lock__DateLocked__3976AF7F] DEFAULT (getutcdate()) FOR [DateLockedUtc]; GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF__Lock__DateLastAc__3A6AD3B8] DEFAULT (getutcdate()) FOR [DateLastActiveUtc]; GO
ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_UserName] DEFAULT ('') FOR [UserName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.LoginHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[LoginHistory] (
    [TokenGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [LoginStamp] datetime NOT NULL,
    [LastActionStamp] datetime NULL,
    [LogoutStamp] datetime NULL,
    [UserName] nvarchar(64) NOT NULL,
    [IPAddress] nvarchar(100) NULL,
    PRIMARY KEY ([TokenGUID])
);
GO
ALTER TABLE [dbo].[LoginHistory] ADD CONSTRAINT [DF_LoginHistory_UserName] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[LoginHistory] ADD CONSTRAINT [DF_dbo.LoginHistory_TOKENGUID] DEFAULT (newid()) FOR [TokenGUID]; GO
ALTER TABLE [dbo].[LoginHistory] ADD CONSTRAINT [DF_LoginHistory_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[LoginHistory] ADD CONSTRAINT [DF_dbo.LoginHistory_LOGINSTAMP] DEFAULT (getdate()) FOR [LoginStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MECacheInvalidateLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[MECacheInvalidateLog] (
    [RowID] int NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [Source] nvarchar(100) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[MECacheInvalidateLog] ADD CONSTRAINT [DF_MECacheInvalidateLog_Source] DEFAULT ('') FOR [Source]; GO
ALTER TABLE [dbo].[MECacheInvalidateLog] ADD CONSTRAINT [DF_MECacheInvalidateLog_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[MECacheInvalidateLog] ADD CONSTRAINT [DF_MECacheInvalidateLog_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEExcelCell ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEExcelCell] (
    [ExcelCellGUID] uniqueidentifier NOT NULL,
    [ExcelSheetGUID] uniqueidentifier NOT NULL,
    [Row] int NOT NULL,
    [Row2] int NOT NULL,
    [Col] int NOT NULL,
    [MappingFormula] nvarchar(max) NOT NULL,
    [DefaultFormula] nvarchar(max) NOT NULL,
    [TestDataFormula] nvarchar(max) NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [IsReadFromDB] bit NOT NULL,
    [IsWrittenToDB] bit NOT NULL,
    [IsLocked] bit NOT NULL,
    [IsAssumptionInput] bit NOT NULL,
    [IsAssumptionOutput] bit NOT NULL,
    [IsWrittenIfZero] bit NOT NULL,
    [IsAssumptionDriver] bit NOT NULL,
    PRIMARY KEY ([ExcelCellGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_ModelLoad] ON [dbo].[MEExcelCell] ([IsReadFromDB], [ExcelSheetGUID], [ExcelCellGUID], [Col], [IsLocked], [IsAssumptionInput], [IsAssumptionOutput]) INCLUDE ([DefaultFormula]);
CREATE NONCLUSTERED INDEX [IX_IsWrittenToDB] ON [dbo].[MEExcelCell] ([IsWrittenToDB]) INCLUDE ([ExcelCellGUID], [ExcelSheetGUID], [Col]);
CREATE NONCLUSTERED INDEX [IDX_MEExcelCell] ON [dbo].[MEExcelCell] ([ExcelSheetGUID]);
GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [FK_MEExcelCell_EMFModelTemplateWorksheet] FOREIGN KEY ([ExcelSheetGUID]) REFERENCES [dbo].[EMFModelTemplateWorksheet] ([WorksheetGUID]); GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_TestDataFormula] DEFAULT ('') FOR [TestDataFormula]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_CompositeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsReadFromDB] DEFAULT ((0)) FOR [IsReadFromDB]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsWrittenToDB] DEFAULT ((0)) FOR [IsWrittenToDB]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsAssumptionInput] DEFAULT ((0)) FOR [IsAssumptionInput]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsAssumptionOutput] DEFAULT ((0)) FOR [IsAssumptionOutput]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsWrittenIfZero] DEFAULT ((0)) FOR [IsWrittenIfZero]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MFExcelCell_ExcelCellGUID] DEFAULT (newid()) FOR [ExcelCellGUID]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_Row2] DEFAULT ((0)) FOR [Row2]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_MappingFormula] DEFAULT ('') FOR [MappingFormula]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_DefaultFormula] DEFAULT ('') FOR [DefaultFormula]; GO
ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsAssumptionDriver] DEFAULT ((0)) FOR [IsAssumptionDriver]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEFillinTemplate ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEFillinTemplate] (
    [FillinTemplateGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(400) NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [IsDefault] bit NOT NULL,
    PRIMARY KEY ([FillinTemplateGUID])
);
GO
ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [FK_MEFillinTemplate_EMFModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO
ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [DF__FillinTem__Filli__36CAF0B7] DEFAULT (newid()) FOR [FillinTemplateGUID]; GO
ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [DF__FillinTemp__Name__37BF14F0] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [DF__FillinTem__Model__38B33929] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO
ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [DF_MEFillinTemplate_IsDefault] DEFAULT ((0)) FOR [IsDefault]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEImprovData ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEImprovData] (
    [ImprovDataGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [WorksheetGUID] uniqueidentifier NOT NULL,
    [Row] int NOT NULL,
    [Col] int NOT NULL,
    [Formula] nvarchar(4000) NOT NULL,
    [CellValue] nvarchar(4000) NOT NULL,
    [OriginalComment] nvarchar(4000) NOT NULL,
    PRIMARY KEY ([ImprovDataGUID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_MEImprovData] ON [dbo].[MEImprovData] ([ModelGUID], [WorksheetGUID], [Row], [Col]);
GO
ALTER TABLE [dbo].[MEImprovData] ADD CONSTRAINT [FK_MEImprovData_MEImprovData] FOREIGN KEY ([ImprovDataGUID]) REFERENCES [dbo].[MEImprovData] ([ImprovDataGUID]); GO
ALTER TABLE [dbo].[MEImprovData] ADD CONSTRAINT [DF_MEImprovData_OriginalStyleName] DEFAULT ('') FOR [OriginalComment]; GO
ALTER TABLE [dbo].[MEImprovData] ADD CONSTRAINT [DF_MEImprovData_RowGUID] DEFAULT (newsequentialid()) FOR [ImprovDataGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEModelRefreshQueue ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEModelRefreshQueue] (
    [ModelGUID] uniqueidentifier NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [ErrorLogGUID] uniqueidentifier NOT NULL,
    [UserName] nvarchar(64) NOT NULL,
    [Source] nvarchar(100) NOT NULL,
    [CompositeGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ModelGUID])
);
GO
ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_Source] DEFAULT ('') FOR [Source]; GO
ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF__MEModelRe__UserN__5C2FE8E2] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_ErrorLogGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorLogGUID]; GO
ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_CompositeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CompositeGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEPHSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEPHSection] (
    [PHSectionGUID] uniqueidentifier NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [PHSectionDimensionGUID] uniqueidentifier NOT NULL,
    [PHSectionMemberGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(100) NOT NULL,
    [SortType] int NOT NULL,
    [IsConstantIndex] bit NOT NULL,
    [RootHierarchyPath] nvarchar(max) NOT NULL,
    [DefaultHierarchyPath] nvarchar(max) NOT NULL,
    [IsAppend] bit NOT NULL,
    [IsHidden] bit NOT NULL,
    [IsReadOnly] bit NOT NULL,
    [IsExclusive] bit NOT NULL,
    [RuleType] smallint NOT NULL,
    [IsOneTime] bit NOT NULL,
    [IsClearOnRefresh] bit NOT NULL,
    [ExclusivityGroup] nvarchar(100) NOT NULL,
    [IsOrderByName] bit NOT NULL,
    [IsOrderByNameSkippingCode] bit NOT NULL,
    PRIMARY KEY ([PHSectionGUID])
);
GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [FK_MEPHSectionConfig_EMFModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_IsExclusive] DEFAULT ((0)) FOR [IsExclusive]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF__MEPHSecti__Exclu__0282DC58] DEFAULT ('') FOR [ExclusivityGroup]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_RuleType] DEFAULT ((0)) FOR [RuleType]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_IsOrderByNameSkippingCode] DEFAULT ((0)) FOR [IsOrderByNameSkippingCode]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_IsOrderByName] DEFAULT ((0)) FOR [IsOrderByName]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF__MEPHSecti__IsCle__3CD0AC98] DEFAULT ((0)) FOR [IsClearOnRefresh]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF__MEPHSecti__IsOne__77E6856E] DEFAULT ((0)) FOR [IsOneTime]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_PHSectionConfigGUID] DEFAULT (newid()) FOR [PHSectionGUID]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_IsAutoSort] DEFAULT ((0)) FOR [SortType]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_IsConstantIndex] DEFAULT ((0)) FOR [IsConstantIndex]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_RootHierarchyPath] DEFAULT ('') FOR [RootHierarchyPath]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_DefaultHierarchyPath] DEFAULT ('') FOR [DefaultHierarchyPath]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_IsAppend] DEFAULT ((0)) FOR [IsAppend]; GO
ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_IsHidden] DEFAULT ((0)) FOR [IsHidden]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEPHSectionDataTableLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEPHSectionDataTableLink] (
    [PHSectionConfigGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PHSectionConfigGUID], [DataTableGUID])
);
GO
ALTER TABLE [dbo].[MEPHSectionDataTableLink] ADD CONSTRAINT [FK_MEPHSectionDataTableLink_MEPHSectionConfig] FOREIGN KEY ([PHSectionConfigGUID]) REFERENCES [dbo].[MEPHSection] ([PHSectionGUID]); GO
ALTER TABLE [dbo].[MEPHSectionDataTableLink] ADD CONSTRAINT [FK_MEPHSectionDataTableLink_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.MEPHSectionRuleValue ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEPHSectionRuleValue] (
    [PHSectionRuleValueGUID] uniqueidentifier NOT NULL,
    [PHSectionGUID] uniqueidentifier NOT NULL,
    [RuleValueKey] nvarchar(50) NOT NULL,
    [RuleValue] nvarchar(max) NOT NULL,
    [SortOrder] int NULL,
    [FillinTemplateGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PHSectionRuleValueGUID])
);
GO
ALTER TABLE [dbo].[MEPHSectionRuleValue] ADD CONSTRAINT [FK_MEPHSectionRuleValue_MEPHSection] FOREIGN KEY ([PHSectionGUID]) REFERENCES [dbo].[MEPHSection] ([PHSectionGUID]); GO
ALTER TABLE [dbo].[MEPHSectionRuleValue] ADD CONSTRAINT [DF__dbo_MEPHSectionRuleValue_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[MEPHSectionRuleValue] ADD CONSTRAINT [DF__MEPHSecti__Filli__3A9B819B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinTemplateGUID]; GO
ALTER TABLE [dbo].[MEPHSectionRuleValue] ADD CONSTRAINT [DF_MEPHSectionRuleValue_PHSectionRuleGUID] DEFAULT (newid()) FOR [PHSectionRuleValueGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEReportLinkTemplateMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEReportLinkTemplateMapping] (
    [ReportLinkTemplateMappingGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [CellGUID] uniqueidentifier NOT NULL,
    [RowExpanded] int NOT NULL,
    [ReportParams] nvarchar(max) NOT NULL,
    PRIMARY KEY ([ReportLinkTemplateMappingGUID])
);
GO
ALTER TABLE [dbo].[MEReportLinkTemplateMapping] ADD CONSTRAINT [FK_MEReportLinkTemplateMapping_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[MEReportLinkTemplateMapping] ADD CONSTRAINT [DF_MEReportLinkTemplateMapping_ReportLinkTemplateMappingGUID] DEFAULT (newid()) FOR [ReportLinkTemplateMappingGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MESaveErrorLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[MESaveErrorLog] (
    [LogGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [ErrorLogGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([LogGUID])
);
GO
ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_Table_1_HistoryGUID] DEFAULT (newid()) FOR [LogGUID]; GO
ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_MESaveErrorLog_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_MESaveErrorLog_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_MESaveErrorLog_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_MESaveErrorLog_ErrorLogGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorLogGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEScoreExpansion ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEScoreExpansion] (
    [ExcelCellGUID] uniqueidentifier NOT NULL,
    [ExpansionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [IndexName] nvarchar(64) NOT NULL,
    [Count] int NOT NULL,
    [ExecutionOrder] int NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ExpansionGUID])
);
GO
ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_ExpansionGUID] DEFAULT (newid()) FOR [ExpansionGUID]; GO
ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_IndexName] DEFAULT ('') FOR [IndexName]; GO
ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_Count] DEFAULT ((0)) FOR [Count]; GO
ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO
ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_MEScoreExpansion_GlobalID] DEFAULT ('') FOR [GlobalID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEScoreExpansionOverride ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEScoreExpansionOverride] (
    [OverrideGUID] uniqueidentifier NOT NULL,
    [ExpansionProfileGUID] uniqueidentifier NOT NULL,
    [ExpansionGlobalID] nvarchar(100) NOT NULL,
    [CountOverride] int NOT NULL,
    PRIMARY KEY ([OverrideGUID])
);
GO
ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [FK_MEScoreExpansionOverride_MEScoreExpansionProfile] FOREIGN KEY ([ExpansionProfileGUID]) REFERENCES [dbo].[MEScoreExpansionProfile] ([ExpansionProfileGUID]); GO
ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [DF_MEScoreExpansionOverride_OverrideGUID] DEFAULT (newid()) FOR [OverrideGUID]; GO
ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [DF_MEScoreExpansionOverride_ExpansionGlobalID] DEFAULT ('') FOR [ExpansionGlobalID]; GO
ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [DF_MEScoreExpansionOverride_ExpansionProfileGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ExpansionProfileGUID]; GO
ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [DF_MEScoreExpansionOverride_Count] DEFAULT ((0)) FOR [CountOverride]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEScoreExpansionProfile ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEScoreExpansionProfile] (
    [ExpansionProfileGUID] uniqueidentifier NOT NULL,
    [ParentModelTemplateGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [ChildModelTemplateGUID] uniqueidentifier NOT NULL,
    [UsageOrder] tinyint NOT NULL,
    [IsOutlier] bit NOT NULL,
    PRIMARY KEY ([ExpansionProfileGUID])
);
GO
ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [FK_MEScoreExpansionProfile_EMFModelTemplate] FOREIGN KEY ([ParentModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO
ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_ModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentModelTemplateGUID]; GO
ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_IsOutlier] DEFAULT ((0)) FOR [IsOutlier]; GO
ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_ChildModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChildModelTemplateGUID]; GO
ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_ExpansionProfileGUID] DEFAULT (newid()) FOR [ExpansionProfileGUID]; GO
ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_UsageOrder] DEFAULT ((0)) FOR [UsageOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEScoreExpansionRecommendedMaxCount ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEScoreExpansionRecommendedMaxCount] (
    [RecommendedMaxCountID] int NOT NULL,
    [SectionName] nvarchar(100) NOT NULL,
    [RecommendedMaxCount] int NOT NULL,
    PRIMARY KEY ([RecommendedMaxCountID])
);
GO
ALTER TABLE [dbo].[MEScoreExpansionRecommendedMaxCount] ADD CONSTRAINT [DF_MEScoreExpansionRecommendedMaxCount_SectionName] DEFAULT ('') FOR [SectionName]; GO
ALTER TABLE [dbo].[MEScoreExpansionRecommendedMaxCount] ADD CONSTRAINT [DF_MEScoreExpansionRecommendedMaxCount_RecommendedMaxCount] DEFAULT ((0)) FOR [RecommendedMaxCount]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MEScorePlaceholderLabel ------------------
---------------------------------------------
CREATE TABLE [dbo].[MEScorePlaceholderLabel] (
    [CellGUID] uniqueidentifier NOT NULL,
    [RowExpanded] int NOT NULL,
    [SectionMemberGUID] uniqueidentifier NOT NULL,
    [PHIndex] int NOT NULL,
    [FillinDimensionGUID] uniqueidentifier NOT NULL,
    [FillinAttributeGUID] uniqueidentifier NOT NULL,
    [IsHidingRow] bit NOT NULL,
    [IsHidingColumn] bit NOT NULL,
    [IsUserMapped] bit NOT NULL,
    [IsExpanded] bit NOT NULL,
    [IsClearingRow] bit NOT NULL,
    [IsClearingColumn] bit NOT NULL,
    [PlaceholderLabelID] bigint NOT NULL,
    PRIMARY KEY ([PlaceholderLabelID])
);

CREATE UNIQUE NONCLUSTERED INDEX [idx_uniquelabel] ON [dbo].[MEScorePlaceholderLabel] ([CellGUID], [RowExpanded]);
GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [FK_MEScorePlaceholderLabel_MEExcelCell] FOREIGN KEY ([CellGUID]) REFERENCES [dbo].[MEExcelCell] ([ExcelCellGUID]); GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [FK_MEScorePlaceholderLabel_ScoreAttribute] FOREIGN KEY ([FillinAttributeGUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [FK_MEScorePlaceholderLabel_ScoreDimension] FOREIGN KEY ([FillinDimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsHidingRow] DEFAULT ((0)) FOR [IsHidingRow]; GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsHidingColumn] DEFAULT ((0)) FOR [IsHidingColumn]; GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsUserMapped] DEFAULT ((0)) FOR [IsUserMapped]; GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsExpanded] DEFAULT ((1)) FOR [IsExpanded]; GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsClearingRow] DEFAULT ((0)) FOR [IsClearingRow]; GO
ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsClearingColumn] DEFAULT ((0)) FOR [IsClearingColumn]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MSchange_tracking_history ------------------
---------------------------------------------
CREATE TABLE [dbo].[MSchange_tracking_history] (
    [internal_table_name] nvarchar(128) NOT NULL,
    [table_name] nvarchar(128) NOT NULL,
    [start_time] datetime NOT NULL,
    [end_time] datetime NOT NULL,
    [rows_cleaned_up] bigint NOT NULL,
    [cleanup_version] bigint NOT NULL,
    [comments] nvarchar(max) NOT NULL
);

CREATE NONCLUSTERED INDEX [IX_MSchange_tracking_history_start_time] ON [dbo].[MSchange_tracking_history] ([start_time]);
GO

---------------------------------------------

---------------------------------------------
-- dbo.MenuItemSecurity ------------------
---------------------------------------------
CREATE TABLE [dbo].[MenuItemSecurity] (
    [MenuItemSecurityGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(400) NOT NULL,
    PRIMARY KEY ([MenuItemSecurityGUID])
);
GO
ALTER TABLE [dbo].[MenuItemSecurity] ADD CONSTRAINT [DF__MenuItemS__MenuI__539C6B59] DEFAULT (newid()) FOR [MenuItemSecurityGUID]; GO
ALTER TABLE [dbo].[MenuItemSecurity] ADD CONSTRAINT [DF__MenuItemSe__Name__54908F92] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MergedRoleRoles ------------------
---------------------------------------------
CREATE TABLE [dbo].[MergedRoleRoles] (
    [MergedRoleRolesGUID] uniqueidentifier NOT NULL,
    [MergedRoleGUID] uniqueidentifier NOT NULL,
    [UserRoleGuid] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MergedRoleGUID], [UserRoleGuid])
);
GO
ALTER TABLE [dbo].[MergedRoleRoles] ADD CONSTRAINT [DF__MergedRol__Merge__36F3DACF] DEFAULT (newid()) FOR [MergedRoleRolesGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MergedRoles ------------------
---------------------------------------------
CREATE TABLE [dbo].[MergedRoles] (
    [MergedRoleGUID] uniqueidentifier NOT NULL,
    [Name] varchar(100) NOT NULL,
    PRIMARY KEY ([MergedRoleGUID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.MobileDashboardFilterCache ------------------
---------------------------------------------
CREATE TABLE [dbo].[MobileDashboardFilterCache] (
    [MobileDashboardFilterCacheGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DashboardGUID] uniqueidentifier NOT NULL,
    [ParameterGUID] uniqueidentifier NOT NULL,
    [Filter] nvarchar(max) NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    PRIMARY KEY ([MobileDashboardFilterCacheGUID])
);
GO
ALTER TABLE [dbo].[MobileDashboardFilterCache] ADD CONSTRAINT [DF_dbo_MobileDashboardFilterCache_DateCreatedUTC] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [dbo].[MobileDashboardFilterCache] ADD CONSTRAINT [DF__MobileDas__Mobil__6FFCDD62] DEFAULT (newid()) FOR [MobileDashboardFilterCacheGUID]; GO
ALTER TABLE [dbo].[MobileDashboardFilterCache] ADD CONSTRAINT [DF__MobileDas__Filte__70F1019B] DEFAULT ('') FOR [Filter]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MobileDashboardWidgetCache ------------------
---------------------------------------------
CREATE TABLE [dbo].[MobileDashboardWidgetCache] (
    [MobileDashboardWidgetCacheGUID] uniqueidentifier NOT NULL,
    [DashboardWidgetGUID] uniqueidentifier NOT NULL,
    [DesktopTemplateGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [Data] nvarchar(max) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [IsCube] bit NOT NULL,
    PRIMARY KEY ([MobileDashboardWidgetCacheGUID])
);
GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [FK__MobileDas__Dashb__7714BA9C] FOREIGN KEY ([DashboardWidgetGUID]) REFERENCES [dbo].[DashboardWidget] ([DashboardWidgetGUID]); GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__Mobil__6F7398D4] DEFAULT (newid()) FOR [MobileDashboardWidgetCacheGUID]; GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__Dashb__7067BD0D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DashboardWidgetGUID]; GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__Deskt__715BE146] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DesktopTemplateGUID]; GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__UserG__7250057F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDash__Data__734429B8] DEFAULT ('') FOR [Data]; GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__DateC__74384DF1] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__DateC__752C722A] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__IsCub__76209663] DEFAULT ((0)) FOR [IsCube]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MobileSecurity ------------------
---------------------------------------------
CREATE TABLE [dbo].[MobileSecurity] (
    [UserGUID] uniqueidentifier NOT NULL,
    [MobileSecurityGUID] uniqueidentifier NOT NULL,
    [DashboardGUID] uniqueidentifier NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    PRIMARY KEY ([MobileSecurityGUID])
);
GO
ALTER TABLE [dbo].[MobileSecurity] ADD CONSTRAINT [DF_dbo_MobileSecurity_DateCreatedUTC] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [dbo].[MobileSecurity] ADD CONSTRAINT [DF__MobileSec__Dashb__2AB38EDC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DashboardGUID]; GO
ALTER TABLE [dbo].[MobileSecurity] ADD CONSTRAINT [DF__MobileSec__Mobil__6C2C4C7E] DEFAULT (newid()) FOR [MobileSecurityGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ModelCacheLookup ------------------
---------------------------------------------
CREATE TABLE [dbo].[ModelCacheLookup] (
    [ModelCacheLookupID] uniqueidentifier NOT NULL,
    [ModelGuid] uniqueidentifier NULL,
    [ModelCacheServer] nvarchar(400) NOT NULL,
    [DateCached] datetime NOT NULL,
    PRIMARY KEY ([ModelCacheLookupID])
);

CREATE NONCLUSTERED INDEX [NUNC_ModelGuid] ON [dbo].[ModelCacheLookup] ([ModelGuid]);
GO
ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [FK_ModelCacheLookup_XPlan] FOREIGN KEY ([ModelGuid]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [DF__ModelCach__Model__33558E7C] DEFAULT (newid()) FOR [ModelCacheLookupID]; GO
ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [DF__ModelCach__Model__3449B2B5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGuid]; GO
ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [DF__ModelCach__Model__353DD6EE] DEFAULT ('') FOR [ModelCacheServer]; GO
ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [DF__ModelCach__DateC__6A7BA634] DEFAULT (getdate()) FOR [DateCached]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ModelImportExportLock ------------------
---------------------------------------------
CREATE TABLE [dbo].[ModelImportExportLock] (
    [ModelImportExportLockGuid] uniqueidentifier NOT NULL,
    [PlanGuid] uniqueidentifier NOT NULL,
    [UserGuid] uniqueidentifier NOT NULL,
    [UserName] nvarchar(max) NOT NULL,
    [DateExportedUtc] datetime NOT NULL,
    [DateImportedUtc] datetime NOT NULL,
    [IsImported] bit NOT NULL,
    PRIMARY KEY ([ModelImportExportLockGuid])
);
GO
ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [FK__ModelImpo__PlanG__44D4EA40] FOREIGN KEY ([PlanGuid]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__Model__43E0C607] DEFAULT (newid()) FOR [ModelImportExportLockGuid]; GO
ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__UserG__45C90E79] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGuid]; GO
ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__UserN__46BD32B2] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__DateE__47B156EB] DEFAULT (getutcdate()) FOR [DateExportedUtc]; GO
ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__DateI__48A57B24] DEFAULT (getutcdate()) FOR [DateImportedUtc]; GO
ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__IsImp__49999F5D] DEFAULT ((0)) FOR [IsImported]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ModelSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[ModelSection] (
    [ModelSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(400) NOT NULL,
    [Range] nvarchar(400) NOT NULL,
    [Address] nvarchar(400) NOT NULL,
    [SheetGUID] uniqueidentifier NOT NULL,
    [ParentGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [IsInherit] bit NOT NULL,
    [IsHidden] bit NOT NULL,
    PRIMARY KEY ([ModelSectionGUID])
);

CREATE NONCLUSTERED INDEX [IX_ModelSection_SheetGUID] ON [dbo].[ModelSection] ([SheetGUID]);
GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Model__46535457] DEFAULT (newid()) FOR [ModelSectionGUID]; GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSecti__Name__47477890] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Range__483B9CC9] DEFAULT ('') FOR [Range]; GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Addre__492FC102] DEFAULT ('') FOR [Address]; GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Sheet__4A23E53B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SheetGUID]; GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Paren__4B180974] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentGUID]; GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__SortO__4C0C2DAD] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__IsInh__4D0051E6] DEFAULT ((1)) FOR [IsInherit]; GO
ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__IsHid__4DF4761F] DEFAULT ((0)) FOR [IsHidden]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgAttachment ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgAttachment] (
    [AttachmentGUID] uniqueidentifier NOT NULL,
    [MessageGUID] uniqueidentifier NOT NULL,
    [Filename] nvarchar(64) NOT NULL,
    [FileSize] int NOT NULL,
    [FileDirectory] nvarchar(450) NOT NULL,
    PRIMARY KEY ([AttachmentGUID])
);
GO
ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [FK_MsgAttachment_MsgMessage] FOREIGN KEY ([MessageGUID]) REFERENCES [dbo].[MsgMessage] ([MessageGUID]); GO
ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_ATTACHMENTGUID] DEFAULT (newid()) FOR [AttachmentGUID]; GO
ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_MESSAGEGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [MessageGUID]; GO
ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_FILENAME] DEFAULT ('') FOR [Filename]; GO
ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_FILESIZE] DEFAULT ((0)) FOR [FileSize]; GO
ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_FILEDIRECTORY] DEFAULT ('') FOR [FileDirectory]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgBookmark ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgBookmark] (
    [BookmarkGUID] uniqueidentifier NOT NULL,
    [ForumGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([BookmarkGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [ak_bookmarkforumuser] ON [dbo].[MsgBookmark] ([ForumGUID], [UserGUID]);
GO
ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [FK_MsgBookmark_MsgForum] FOREIGN KEY ([ForumGUID]) REFERENCES [dbo].[MsgForum] ([ForumGUID]); GO
ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [FK_MsgBookmark_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [DF_MsgBookmark_BOOKMARKGUID] DEFAULT (newid()) FOR [BookmarkGUID]; GO
ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [DF_MsgBookmark_FORUMGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [ForumGUID]; GO
ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [DF_MsgBookmark_USERGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [UserGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgEmailActivity ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgEmailActivity] (
    [EmailActivityID] bigint NOT NULL,
    [EmailSummaryID] int NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [EmailAddress] nvarchar(450) NOT NULL,
    [MessageGUID] uniqueidentifier NOT NULL,
    [Timestamp] datetime NOT NULL,
    [IsSuccess] bit NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [ErrorLogGUID] uniqueidentifier NOT NULL,
    [DateCreated] datetime NOT NULL,
    PRIMARY KEY ([EmailActivityID])
);

CREATE NONCLUSTERED INDEX [NCNU_Timestamp_Index] ON [dbo].[MsgEmailActivity] ([Timestamp]);
GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [FK_MsgEmailActivity_MsgEmailSummary] FOREIGN KEY ([EmailSummaryID]) REFERENCES [dbo].[MsgEmailSummary] ([EmailSummaryID]); GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__Messa__4F1A1392] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MessageGUID]; GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF_MsgEmailActivity_LogGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorLogGUID]; GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF_MsgEmailActivity_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__Email__4C3DA6E7] DEFAULT ((0)) FOR [EmailSummaryID]; GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__Email__4E25EF59] DEFAULT ('') FOR [EmailAddress]; GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__Times__500E37CB] DEFAULT (getdate()) FOR [Timestamp]; GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__IsSuc__51025C04] DEFAULT ((0)) FOR [IsSuccess]; GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF_MsgEmailActivity_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__UserG__4D31CB20] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgEmailSummary ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgEmailSummary] (
    [EmailSummaryID] int NOT NULL,
    [Timestamp] datetime NOT NULL,
    [IsSuccess] bit NOT NULL,
    PRIMARY KEY ([EmailSummaryID])
);

CREATE NONCLUSTERED INDEX [NCNU_Timestamp_Index] ON [dbo].[MsgEmailSummary] ([Timestamp]);
GO
ALTER TABLE [dbo].[MsgEmailSummary] ADD CONSTRAINT [DF__MsgEmailS__Times__52EAA476] DEFAULT (getdate()) FOR [Timestamp]; GO
ALTER TABLE [dbo].[MsgEmailSummary] ADD CONSTRAINT [DF__MsgEmailS__IsSuc__53DEC8AF] DEFAULT ((0)) FOR [IsSuccess]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgForum ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgForum] (
    [ForumGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [ForumType] int NOT NULL,
    PRIMARY KEY ([ForumGUID])
);
GO
ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_FORUMGUID] DEFAULT (newid()) FOR [ForumGUID]; GO
ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_ENTITYGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [EntityGUID]; GO
ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_FORUMTYPE] DEFAULT ((0)) FOR [ForumType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgForumRead ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgForumRead] (
    [ForumReadGUID] uniqueidentifier NOT NULL,
    [ForumGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DateViewed] datetime NOT NULL
);

CREATE UNIQUE NONCLUSTERED INDEX [ak_forumreadforumuser] ON [dbo].[MsgForumRead] ([ForumGUID], [UserGUID]);
GO
ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [FK_MsgForumRead_MsgForum] FOREIGN KEY ([ForumGUID]) REFERENCES [dbo].[MsgForum] ([ForumGUID]); GO
ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [FK_MsgForumRead_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [DF_MsgForumRead_FORUMREADGUID] DEFAULT (newid()) FOR [ForumReadGUID]; GO
ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [DF_MsgForumRead_FORUMGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [ForumGUID]; GO
ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [DF_MsgForumRead_USERGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [UserGUID]; GO
ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [DF_MsgForumRead_DATEVIEWED] DEFAULT (getdate()) FOR [DateViewed]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgForumViewed ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgForumViewed] (
    [UserGUID] uniqueidentifier NOT NULL,
    [ForumGUID] uniqueidentifier NOT NULL,
    [LastViewDate] datetime NOT NULL,
    PRIMARY KEY ([UserGUID], [ForumGUID])
);
GO
ALTER TABLE [dbo].[MsgForumViewed] ADD CONSTRAINT [DF_MsgForumViewed_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[MsgForumViewed] ADD CONSTRAINT [DF_MsgForumViewed_FORUMGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ForumGUID]; GO
ALTER TABLE [dbo].[MsgForumViewed] ADD CONSTRAINT [DF_MsgForumViewed_LASTVIEWDATE] DEFAULT (((1)-(1))-(2000)) FOR [LastViewDate]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgMessage ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgMessage] (
    [MessageGUID] uniqueidentifier NOT NULL,
    [TopicGUID] uniqueidentifier NOT NULL,
    [MessageTypeGUID] uniqueidentifier NOT NULL,
    [ReplyToMsgGUID] uniqueidentifier NOT NULL,
    [Subject] nvarchar(450) NOT NULL,
    [Body] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [DateCreated] datetime NOT NULL,
    [DateSent] datetime NOT NULL,
    [HasAttachments] bit NOT NULL,
    [IsSent] bit NOT NULL,
    PRIMARY KEY ([MessageGUID])
);

CREATE NONCLUSTERED INDEX [NCNU_TopicGUID] ON [dbo].[MsgMessage] ([TopicGUID]);
GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [FK_MsgMessage_MsgTopic] FOREIGN KEY ([TopicGUID]) REFERENCES [dbo].[MsgTopic] ([TopicGUID]); GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_MESSAGEGUID] DEFAULT (newid()) FOR [MessageGUID]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_TOPICGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [TopicGUID]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_MESSAGETYPEGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [MessageTypeGUID]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_REPLYTOMSGGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [ReplyToMsgGUID]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_SUBJECT] DEFAULT ('') FOR [Subject]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_BODY] DEFAULT ('') FOR [Body]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_AUTHORGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_HASATTACHMENTS] DEFAULT ((0)) FOR [HasAttachments]; GO
ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_ISSENT] DEFAULT ((0)) FOR [IsSent]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgMessagePlanLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgMessagePlanLink] (
    [MessageGUID] uniqueidentifier NOT NULL,
    [PlanGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MessageGUID], [PlanGUID])
);
GO
ALTER TABLE [dbo].[MsgMessagePlanLink] ADD CONSTRAINT [FK_MsgMessagePlanLink_MsgMessage] FOREIGN KEY ([MessageGUID]) REFERENCES [dbo].[MsgMessage] ([MessageGUID]); GO
ALTER TABLE [dbo].[MsgMessagePlanLink] ADD CONSTRAINT [DF_MsgMessagePlanLink_MESSAGEGUID] DEFAULT (newid()) FOR [MessageGUID]; GO
ALTER TABLE [dbo].[MsgMessagePlanLink] ADD CONSTRAINT [DF_MsgMessagePlanLink_PLANGUID] DEFAULT (newid()) FOR [PlanGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgMessageRead ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgMessageRead] (
    [UserGUID] uniqueidentifier NOT NULL,
    [MessageGUID] uniqueidentifier NOT NULL,
    [IsRead] bit NOT NULL,
    [DateRead] datetime NOT NULL,
    PRIMARY KEY ([UserGUID], [MessageGUID])
);
GO
ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [FK_MsgMessageRead_MsgMessage] FOREIGN KEY ([MessageGUID]) REFERENCES [dbo].[MsgMessage] ([MessageGUID]); GO
ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [FK_MsgMessageRead_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [DF_MsgMessageRead_USERGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [UserGUID]; GO
ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [DF_MsgMessageRead_MESSAGEGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [MessageGUID]; GO
ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [DF_MsgMessageRead_ISUNREAD] DEFAULT ((1)) FOR [IsRead]; GO
ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [DF_MsgMessageRead_DATEREAD] DEFAULT (((1)-(1))-(2000)) FOR [DateRead]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgMessageType ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgMessageType] (
    [MessageTypeGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [ImageType] int NOT NULL,
    [LinkType] int NOT NULL,
    [Type] int NOT NULL,
    [SubjectPrefix] nvarchar(64) NOT NULL,
    [Header] nvarchar(max) NOT NULL,
    [Footer] nvarchar(max) NOT NULL,
    [BuiltInType] int NOT NULL,
    [IsAllowingReplyViaEmail] bit NOT NULL,
    [IsMarkingReadForNewMessages] bit NOT NULL,
    [IsVisible] bit NOT NULL,
    PRIMARY KEY ([MessageTypeGUID])
);
GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_MESSAGETYPEGUID] DEFAULT (newid()) FOR [MessageTypeGUID]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_ICONNAME] DEFAULT ((0)) FOR [ImageType]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_LINKTYPE] DEFAULT ((0)) FOR [LinkType]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_SUBJECTPREFIX] DEFAULT ('') FOR [SubjectPrefix]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_HEADER] DEFAULT ('') FOR [Header]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_FOOTER] DEFAULT ('') FOR [Footer]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_BuiltInType] DEFAULT ((0)) FOR [BuiltInType]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_IsVisible] DEFAULT ((1)) FOR [IsVisible]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_IsMarkingReadForNewMessages] DEFAULT ((0)) FOR [IsMarkingReadForNewMessages]; GO
ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_IsAllowingReplyViaEmail] DEFAULT ((0)) FOR [IsAllowingReplyViaEmail]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgTopic ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgTopic] (
    [TopicGUID] uniqueidentifier NOT NULL,
    [ForumGUID] uniqueidentifier NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [TopicType] int NOT NULL,
    [DateCreated] datetime NOT NULL,
    [Tag] nvarchar(450) NOT NULL,
    PRIMARY KEY ([TopicGUID])
);
GO
ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_TOPICGUID] DEFAULT (newid()) FOR [TopicGUID]; GO
ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_FORUMGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [ForumGUID]; GO
ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_AUTHORGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_TOPICTYPE] DEFAULT ((0)) FOR [TopicType]; GO
ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_Tag] DEFAULT ('') FOR [Tag]; GO

---------------------------------------------

---------------------------------------------
-- dbo.MsgTopicArchive ------------------
---------------------------------------------
CREATE TABLE [dbo].[MsgTopicArchive] (
    [UserGUID] uniqueidentifier NOT NULL,
    [TopicGUID] uniqueidentifier NOT NULL,
    [DateArchived] datetime NOT NULL,
    PRIMARY KEY ([UserGUID], [TopicGUID])
);

CREATE NONCLUSTERED INDEX [NCNU_TopicGUID_UserGUID] ON [dbo].[MsgTopicArchive] ([TopicGUID], [UserGUID]);
GO
ALTER TABLE [dbo].[MsgTopicArchive] ADD CONSTRAINT [FK_MsgTopicArchive_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[MsgTopicArchive] ADD CONSTRAINT [DF_MsgTopicArchive_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[MsgTopicArchive] ADD CONSTRAINT [DF_MsgTopicArchive_TopicGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TopicGUID]; GO
ALTER TABLE [dbo].[MsgTopicArchive] ADD CONSTRAINT [DF_MsgTopicArchive_DateArchived] DEFAULT ('1/1/1900') FOR [DateArchived]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZCriterion ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZCriterion] (
    [CriterionGUID] uniqueidentifier NOT NULL,
    [ProviderSettingsGUID] uniqueidentifier NOT NULL,
    [DimensionMemberGUID] uniqueidentifier NOT NULL,
    [CriterionType] int NOT NULL,
    [WeightingType] int NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [dbo].[OMZCriterion] ADD CONSTRAINT [DF_OMZCriterion_PROVIDERSETTINGSGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderSettingsGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZEvaluatorStatus ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZEvaluatorStatus] (
    [EvaluatorStatusGUID] uniqueidentifier NOT NULL,
    [PoolGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [Type] int NOT NULL,
    [Status] int NOT NULL,
    PRIMARY KEY ([EvaluatorStatusGUID])
);
GO
ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [FK_OMZEvaluatorStatus_OMZPool] FOREIGN KEY ([PoolGUID]) REFERENCES [dbo].[OMZPool] ([PoolGUID]); GO
ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_Table_1_POOLEVALUATORSTATUSGUID] DEFAULT (newid()) FOR [EvaluatorStatusGUID]; GO
ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_OMZEvaluatorStatus_POOLGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PoolGUID]; GO
ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_OMZEvaluatorStatus_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_OMZEvaluatorStatus_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_OMZEvaluatorStatus_STATUS] DEFAULT ((0)) FOR [Status]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZMapping] (
    [MappingGUID] uniqueidentifier NOT NULL,
    [Category] nvarchar(64) NOT NULL,
    [ParentGUID] uniqueidentifier NOT NULL,
    [SourceGUID] uniqueidentifier NOT NULL,
    [TargetGUID] uniqueidentifier NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZPool ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZPool] (
    [PoolGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [ProviderSettingsGUID] uniqueidentifier NOT NULL,
    [PoolDimensionMemberGUID] uniqueidentifier NOT NULL,
    [Metadata] xml NOT NULL,
    [ApprovedFormFieldGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [IsUsingFinancialReturn] bit NOT NULL,
    [ScoringReportGUID] uniqueidentifier NOT NULL,
    [LastDistributeDate] datetime NOT NULL,
    [IsScoringLocked] bit NOT NULL,
    [ProjectTypeID] tinyint NOT NULL,
    PRIMARY KEY ([PoolGUID])
);
GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_OPTIMIZATIONPOOLGUID] DEFAULT (newid()) FOR [PoolGUID]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_INPUTDATACONFIGGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderSettingsGUID]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_POOLDIMENSIONMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PoolDimensionMemberGUID]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_METADATA] DEFAULT ('') FOR [Metadata]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_APPROVEDFORMFIELDGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ApprovedFormFieldGUID]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_ProjectTypeID] DEFAULT ((1)) FOR [ProjectTypeID]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_IsUsingFinancialReturn] DEFAULT ((1)) FOR [IsUsingFinancialReturn]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_LastDistributeDate] DEFAULT ('2000-01-01 00:00:00.000') FOR [LastDistributeDate]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_IsScoringLocked] DEFAULT ((0)) FOR [IsScoringLocked]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_ScoringReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoringReportGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZProviderSettings ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZProviderSettings] (
    [ProviderSettingsGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [AssemblyQualifiedName] nvarchar(450) NOT NULL,
    [Metadata] xml NOT NULL,
    [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL,
    [PoolDimensionGUID] uniqueidentifier NOT NULL,
    [DefaultEvaluatorRoleGUID] uniqueidentifier NOT NULL,
    [DefaultGridTemplateGUID] uniqueidentifier NOT NULL,
    [DefaultApprovedFieldGUID] uniqueidentifier NOT NULL,
    [DefaultScoringReportGUID] uniqueidentifier NOT NULL,
    [DefaultPlanTypeGUID] uniqueidentifier NOT NULL,
    [IsActive] bit NOT NULL,
    PRIMARY KEY ([ProviderSettingsGUID])
);
GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_METADATA] DEFAULT ('') FOR [Metadata]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_PROVIDERASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [ProviderAssemblyQualifiedName]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_POOLDIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PoolDimensionGUID]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultScoringReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultScoringReportGUID]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultPlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultPlanTypeGUID]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_IsActive] DEFAULT ((1)) FOR [IsActive]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultEvaluatorRoleGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultEvaluatorRoleGUID]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultGridTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultGridTemplateGUID]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultApprovedFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultApprovedFieldGUID]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_PROVIDERSETTINGSGUID] DEFAULT (newid()) FOR [ProviderSettingsGUID]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZScenario ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZScenario] (
    [ScenarioGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [PoolGUID] uniqueidentifier NOT NULL,
    [Metadata] xml NOT NULL,
    PRIMARY KEY ([ScenarioGUID])
);
GO
ALTER TABLE [dbo].[OMZScenario] ADD CONSTRAINT [DF_OMZScenario_Description] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZWorkspaceColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZWorkspaceColumn] (
    [WorkspaceColumnGUID] uniqueidentifier NOT NULL,
    [WorkspaceTabGUID] uniqueidentifier NOT NULL,
    [ColumnID] nvarchar(64) NOT NULL,
    [ColumnIndex] int NOT NULL,
    [Width] int NOT NULL,
    [IsVisible] bit NOT NULL,
    [IsTotal] bit NOT NULL,
    PRIMARY KEY ([WorkspaceColumnGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_OMZWorkspaceColumn] ON [dbo].[OMZWorkspaceColumn] ([WorkspaceTabGUID], [ColumnID]);
GO
ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [FK_OMZWorkspaceColumn_OMZWorkspaceTab] FOREIGN KEY ([WorkspaceTabGUID]) REFERENCES [dbo].[OMZWorkspaceTab] ([WorkspaceTabGUID]); GO
ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_Table_1_WORKSPACETABCOLUMNGUID] DEFAULT (newid()) FOR [WorkspaceColumnGUID]; GO
ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_WORKSPACETABGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceTabGUID]; GO
ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_COLUMNID] DEFAULT ('') FOR [ColumnID]; GO
ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_INDEX] DEFAULT ((-1)) FOR [ColumnIndex]; GO
ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_WIDTH] DEFAULT ((-1)) FOR [Width]; GO
ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_ISVISIBLE] DEFAULT ((0)) FOR [IsVisible]; GO
ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_ISTOTAL] DEFAULT ((0)) FOR [IsTotal]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZWorkspaceLayout ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZWorkspaceLayout] (
    [WorkspaceLayoutGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL,
    [LayoutXML] nvarchar(max) NOT NULL,
    [IsFlyoutCollapsed] bit NOT NULL,
    PRIMARY KEY ([WorkspaceLayoutGUID])
);
GO
ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_IsFlyoutCollapsed] DEFAULT ((0)) FOR [IsFlyoutCollapsed]; GO
ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_WORKSPACELAYOUTGUID] DEFAULT (newid()) FOR [WorkspaceLayoutGUID]; GO
ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_PROVIDERASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [ProviderAssemblyQualifiedName]; GO
ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_LAYOUTXML] DEFAULT ('') FOR [LayoutXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZWorkspacePanel ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZWorkspacePanel] (
    [WorkspacePanelGUID] uniqueidentifier NOT NULL,
    [WorkspaceLayoutGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    PRIMARY KEY ([WorkspacePanelGUID])
);
GO
ALTER TABLE [dbo].[OMZWorkspacePanel] ADD CONSTRAINT [FK_OMZWorkspacePanel_OMZWorkspaceLayout] FOREIGN KEY ([WorkspaceLayoutGUID]) REFERENCES [dbo].[OMZWorkspaceLayout] ([WorkspaceLayoutGUID]); GO
ALTER TABLE [dbo].[OMZWorkspacePanel] ADD CONSTRAINT [DF_OMZWorkspacePanel_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[OMZWorkspacePanel] ADD CONSTRAINT [DF_OMZWorkspacePanel_WORKSPACEPANELGUID] DEFAULT (newid()) FOR [WorkspacePanelGUID]; GO
ALTER TABLE [dbo].[OMZWorkspacePanel] ADD CONSTRAINT [DF_OMZWorkspacePanel_WORKSPACELAYOUTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceLayoutGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.OMZWorkspaceTab ------------------
---------------------------------------------
CREATE TABLE [dbo].[OMZWorkspaceTab] (
    [WorkspaceTabGUID] uniqueidentifier NOT NULL,
    [WorkspacePanelGUID] uniqueidentifier NOT NULL,
    [ViewID] nvarchar(64) NOT NULL,
    [NumFrozenColumns] int NOT NULL,
    [PrimarySortColumnID] nvarchar(450) NOT NULL,
    [SecondarySortColumnID] nvarchar(450) NOT NULL,
    [PrimarySortDirection] int NOT NULL,
    [SecondarySortDirection] int NOT NULL,
    PRIMARY KEY ([WorkspaceTabGUID])
);
GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [FK_OMZWorkspaceTab_OMZWorkspacePanel] FOREIGN KEY ([WorkspacePanelGUID]) REFERENCES [dbo].[OMZWorkspacePanel] ([WorkspacePanelGUID]); GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_WORKSPACETABGUID] DEFAULT (newid()) FOR [WorkspaceTabGUID]; GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_WORKSPACEPANELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspacePanelGUID]; GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_VIEWID] DEFAULT ('') FOR [ViewID]; GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_NUMFROZENCOLUMNS] DEFAULT ((0)) FOR [NumFrozenColumns]; GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_SORTCOLUMNID] DEFAULT ('') FOR [PrimarySortColumnID]; GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_SECONDARYSORTCOLUMNID] DEFAULT ('') FOR [SecondarySortColumnID]; GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_PRIMARYSORTDIRECTION] DEFAULT ((0)) FOR [PrimarySortDirection]; GO
ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_SECONDARYSORTDIRECTION] DEFAULT ((0)) FOR [SecondarySortDirection]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PHILogExtractHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[PHILogExtractHistory] (
    [ExtractID] int NOT NULL,
    [UserName] nvarchar(128) NOT NULL,
    [DateTimeStampUtc] datetime NOT NULL,
    [StartDate] datetime NOT NULL,
    [EndDate] datetime NOT NULL,
    [ExtractReason] nvarchar(255) NOT NULL,
    [Status] tinyint NOT NULL,
    PRIMARY KEY ([ExtractID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.PartitionInfo ------------------
---------------------------------------------
CREATE TABLE [dbo].[PartitionInfo] (
    [DatabaseID] varchar(200) NOT NULL,
    [CubeID] varchar(200) NOT NULL,
    [MeasureGroupID] varchar(400) NOT NULL,
    [PartitionID] varchar(400) NOT NULL,
    [PartitionName] varchar(400) NOT NULL,
    [QueryDefinition] varchar(4000) NOT NULL,
    [Filter] varchar(2000) NULL,
    [Dirty] bit NULL,
    [Version] varchar(200) NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.PasswordHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[PasswordHistory] (
    [HistoryID] bigint NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [HashedPassword] nvarchar(64) NOT NULL,
    [Iteration] tinyint NOT NULL,
    PRIMARY KEY ([HistoryID])
);
GO
ALTER TABLE [dbo].[PasswordHistory] ADD CONSTRAINT [DF_PasswordHistory_HashedPassword] DEFAULT ('') FOR [HashedPassword]; GO
ALTER TABLE [dbo].[PasswordHistory] ADD CONSTRAINT [DF_PasswordHistory_Iteration] DEFAULT ((0)) FOR [Iteration]; GO
ALTER TABLE [dbo].[PasswordHistory] ADD CONSTRAINT [DF_PasswordHistory_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanPrint ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanPrint] (
    [PlanPrintGuid] uniqueidentifier NOT NULL,
    [FileName] nvarchar(200) NOT NULL,
    [FilePath] nvarchar(400) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [UserGuid] uniqueidentifier NOT NULL,
    [FileSize] int NOT NULL,
    [PlanNames] nvarchar(max) NOT NULL,
    PRIMARY KEY ([PlanPrintGuid])
);
GO
ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__PlanP__5D1B8228] DEFAULT (newid()) FOR [PlanPrintGuid]; GO
ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__FileN__5E0FA661] DEFAULT ('') FOR [FileName]; GO
ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__FileP__5F03CA9A] DEFAULT ('') FOR [FilePath]; GO
ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__DateC__5FF7EED3] DEFAULT ('') FOR [DateCreated]; GO
ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__UserG__60EC130C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGuid]; GO
ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__FileS__61E03745] DEFAULT ((0)) FOR [FileSize]; GO
ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__PlanN__62D45B7E] DEFAULT ('') FOR [PlanNames]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanType ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanType] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(256) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [ModelDataConfigGUID] uniqueidentifier NOT NULL,
    [GridTemplateGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] int NOT NULL,
    [IsPermissionCopyEnabled] bit NOT NULL,
    [NameFormFieldGUID] uniqueidentifier NOT NULL,
    [WorkflowGridTemplateGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [OnSaveCustomScriptGUID] uniqueidentifier NOT NULL,
    [OnSaveCustomScript2GUID] uniqueidentifier NOT NULL,
    [OnTemplateChangeCustomScriptGUID] uniqueidentifier NOT NULL,
    [ScoreDefaultFillInTemplateName] nvarchar(100) NOT NULL,
    [DefaultMessageSubject] nvarchar(450) NOT NULL,
    [FriendlyName] nvarchar(256) NOT NULL,
    [OnAfterModelRefreshCustomScriptGUID] uniqueidentifier NOT NULL,
    [LootIDSQLExpression] nvarchar(450) NOT NULL,
    [OnCopyCustomScriptGUID] uniqueidentifier NOT NULL,
    [IsSimpleRoutingSlip] bit NOT NULL,
    [AssumptionInputNameFormat] nvarchar(450) NOT NULL,
    [AssumptionOutputNameFormat] nvarchar(450) NOT NULL,
    [OpenPlanUrl] nvarchar(100) NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IsSavingNewWay] bit NOT NULL,
    [FinancialsAlias] nvarchar(100) NOT NULL,
    [AllowPublicAttachment] bit NOT NULL,
    [OnModelSaveCustomScriptGUID] uniqueidentifier NOT NULL,
    [DefaultModelTemplateGUID] uniqueidentifier NOT NULL,
    [HelpID] nvarchar(400) NOT NULL,
    [FormHelpID] nvarchar(50) NOT NULL,
    [IsSystemSetFillinEditable] bit NOT NULL,
    [IsModelRefreshEnabled] bit NOT NULL,
    [IsBulkDeleteAllowed] bit NOT NULL,
    PRIMARY KEY ([PlanTypeGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_PlanType] ON [dbo].[PlanType] ([Name]);
CREATE NONCLUSTERED INDEX [NCNU_PlanTypeGUID] ON [dbo].[PlanType] ([PlanTypeGUID]);
GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [FK_PlanType_Folder] FOREIGN KEY ([FolderGUID]) REFERENCES [dbo].[Folder] ([FolderGuid]); GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_LootIDSQLExpression] DEFAULT ('') FOR [LootIDSQLExpression]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__IsMode__14442DAF] DEFAULT ((1)) FOR [IsModelRefreshEnabled]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_dbo_PlanType_IsSystemSetFillinEditable] DEFAULT ((0)) FOR [IsSystemSetFillinEditable]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_AssumptionInputNameFormat] DEFAULT ('') FOR [AssumptionInputNameFormat]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_AssumptionOutputNameFormat] DEFAULT ('') FOR [AssumptionOutputNameFormat]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__Defaul__26D57D31] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultModelTemplateGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_DefaultMessageSubject] DEFAULT ('New Message') FOR [DefaultMessageSubject]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__AllowP__366FC20E] DEFAULT ((0)) FOR [AllowPublicAttachment]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__OnAfte__7E0E0558] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnAfterModelRefreshCustomScriptGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnModelSaveCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnModelSaveCustomScriptGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__IsBulk__509A0BF9] DEFAULT ((1)) FOR [IsBulkDeleteAllowed]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnSaveCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnSaveCustomScriptGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnSaveCustomScriptGUID1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnSaveCustomScript2GUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__OpenPl__53862DD5] DEFAULT ('') FOR [OpenPlanUrl]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__Global__556E7647] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__Financ__55E212AF] DEFAULT ('') FOR [FinancialsAlias]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_IsSimpleRoutingSlip] DEFAULT ((0)) FOR [IsSimpleRoutingSlip]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_PlanTypeGUID] DEFAULT (newid()) FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__FormHe__6F7BF1FD] DEFAULT ('') FOR [FormHelpID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_MODELDATACONFIGGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelDataConfigGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_GRIDTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GridTemplateGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_DISPLAYORDER] DEFAULT ((-1)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnCopyCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnCopyCustomScriptGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_ISPERMISSIONCOPYENABLED] DEFAULT ((1)) FOR [IsPermissionCopyEnabled]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__HelpID__74BEFEB0] DEFAULT ('') FOR [HelpID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__IsSavi__74C42A7D] DEFAULT ((0)) FOR [IsSavingNewWay]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_NAMEFORMFIELDGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [NameFormFieldGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_WorkflowGridTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowGridTemplateGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_ScoreDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_ScoreDefaultFillInTemplateName] DEFAULT ('') FOR [ScoreDefaultFillInTemplateName]; GO
ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnTemplateChangeCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnTemplateChangeCustomScriptGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanTypeCalculatedFieldLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanTypeCalculatedFieldLink] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PlanTypeGUID], [FormFieldGUID])
);
GO
ALTER TABLE [dbo].[PlanTypeCalculatedFieldLink] ADD CONSTRAINT [FK_PlanTypeCalculatedFieldLink_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO
ALTER TABLE [dbo].[PlanTypeCalculatedFieldLink] ADD CONSTRAINT [FK_PlanTypeCalculatedFieldLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO
ALTER TABLE [dbo].[PlanTypeCalculatedFieldLink] ADD CONSTRAINT [DF_PlanTypeCalculatedFieldLink_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[PlanTypeCalculatedFieldLink] ADD CONSTRAINT [DF_PlanTypeCalculatedFieldLink_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanTypeFormDefLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanTypeFormDefLink] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [FormDefGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PlanTypeGUID], [FormDefGUID])
);
GO
ALTER TABLE [dbo].[PlanTypeFormDefLink] ADD CONSTRAINT [FK_PlanTypeFormDefLink_PlanType1] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanTypeGridFieldLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanTypeGridFieldLink] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [FormFieldGUID] uniqueidentifier NOT NULL,
    [IsFullTextSearchField] bit NOT NULL,
    PRIMARY KEY ([PlanTypeGUID], [FormFieldGUID])
);
GO
ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [FK_PlanTypeGridFieldLink_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO
ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [FK_PlanTypeGridFieldLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO
ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [DF_PlanTypeGridFieldLink_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [DF_PlanTypeGridFieldLink_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO
ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [DF_PlanTypeGridFieldLink_IsFullTextSearchField] DEFAULT ((0)) FOR [IsFullTextSearchField]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanTypeModelDataConfigLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanTypeModelDataConfigLink] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [ModelDataConfigGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PlanTypeGUID], [ModelDataConfigGUID])
);
GO
ALTER TABLE [dbo].[PlanTypeModelDataConfigLink] ADD CONSTRAINT [FK_PlanTypeModelDataConfigLink_EMFModelDataConfig] FOREIGN KEY ([ModelDataConfigGUID]) REFERENCES [dbo].[EMFModelDataConfig] ([ModelDataConfigGUID]); GO
ALTER TABLE [dbo].[PlanTypeModelDataConfigLink] ADD CONSTRAINT [FK_PlanTypeModelDataConfigLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO
ALTER TABLE [dbo].[PlanTypeModelDataConfigLink] ADD CONSTRAINT [DF_PlanTypeModelDataConfigLink_PlanTypeGUID] DEFAULT (newid()) FOR [PlanTypeGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanTypeModelTemplateLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanTypeModelTemplateLink] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PlanTypeGUID], [ModelTemplateGUID])
);
GO
ALTER TABLE [dbo].[PlanTypeModelTemplateLink] ADD CONSTRAINT [FK_PlanTypeModelTemplateLink_ModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO
ALTER TABLE [dbo].[PlanTypeModelTemplateLink] ADD CONSTRAINT [FK_PlanTypeModelTemplateLink_PlanTypeGUID] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanTypePHSectionLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanTypePHSectionLink] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PlanTypeGUID], [PlaceholderSectionMemberGUID])
);
GO
ALTER TABLE [dbo].[PlanTypePHSectionLink] ADD CONSTRAINT [FK_PlanTypePHSectionLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO
ALTER TABLE [dbo].[PlanTypePHSectionLink] ADD CONSTRAINT [DF_PlanTypePHSectionLink_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[PlanTypePHSectionLink] ADD CONSTRAINT [DF_PlanTypePHSectionLink_PlaceholderSectionMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderSectionMemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanTypeReportLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanTypeReportLink] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PlanTypeGUID], [ReportGUID])
);
GO
ALTER TABLE [dbo].[PlanTypeReportLink] ADD CONSTRAINT [FK_PlanTypeReportLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO
ALTER TABLE [dbo].[PlanTypeReportLink] ADD CONSTRAINT [FK_PlanTypeReportLink_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[PlanTypeReportLink] ADD CONSTRAINT [DF_PlanTypeReportLink_PLANTYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[PlanTypeReportLink] ADD CONSTRAINT [DF_PlanTypeReportLink_REPORTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.PlanTypeWorkflowMapLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[PlanTypeWorkflowMapLink] (
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [IsRequiredWorkflow] bit NOT NULL,
    PRIMARY KEY ([PlanTypeGUID], [WorkflowMapGUID])
);
GO
ALTER TABLE [dbo].[PlanTypeWorkflowMapLink] ADD CONSTRAINT [FK_PlanTypeWorkflowMapLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO
ALTER TABLE [dbo].[PlanTypeWorkflowMapLink] ADD CONSTRAINT [FK_PlanTypeWorkflowMapLink_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO
ALTER TABLE [dbo].[PlanTypeWorkflowMapLink] ADD CONSTRAINT [DF_PlanTypeWorkflowMapLink_ISREQUIREDWORKFLOW] DEFAULT ((0)) FOR [IsRequiredWorkflow]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RECachedReport ------------------
---------------------------------------------
CREATE TABLE [dbo].[RECachedReport] (
    [CachedReportGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [Identifier] nvarchar(4000) NOT NULL,
    [CachedDataType] int NOT NULL,
    [LastRefreshDate] datetime NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [ReportMetaData] nvarchar(max) NOT NULL,
    PRIMARY KEY ([CachedReportGUID])
);
GO
ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [FK_RECachedReport_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_CachedReport_CachedReportGUID] DEFAULT (newid()) FOR [CachedReportGUID]; GO
ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_Parameters] DEFAULT ('') FOR [Identifier]; GO
ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_CACHEDDATATYPE] DEFAULT ((0)) FOR [CachedDataType]; GO
ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_LastRefreshDate] DEFAULT (getdate()) FOR [LastRefreshDate]; GO
ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_ReportMetaData] DEFAULT ('') FOR [ReportMetaData]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportCalculation ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportCalculation] (
    [ClientReportCalculationGUID] uniqueidentifier NOT NULL,
    [ClientReportSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(1000) NULL,
    [DisplayOrder] int NOT NULL,
    [CalculationAssemblyQualifiedName] nvarchar(400) NOT NULL,
    [CalculationXML] nvarchar(max) NOT NULL,
    [DetailReportGUID] uniqueidentifier NOT NULL,
    [DisplayFormat] nvarchar(max) NOT NULL,
    [ColumnWidth] int NOT NULL,
    [IsAttributeMember] bit NOT NULL,
    [CSSClass] nvarchar(100) NOT NULL,
    [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL,
    [IsColumnCalculationTakePrecedent] bit NOT NULL,
    PRIMARY KEY ([ClientReportCalculationGUID])
);
GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [FK__REClientR__Clien__590B61E5] FOREIGN KEY ([ClientReportSectionGUID]) REFERENCES [dbo].[REClientReportSection] ([ClientReportSectionGUID]); GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Displ__17C7AE6D] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Colum__18BBD2A6] DEFAULT ((0)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__CSSCl__34C4AB25] DEFAULT ('') FOR [CSSClass]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Detai__3C66CA0E] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Clien__58173DAC] DEFAULT (newid()) FOR [ClientReportCalculationGUID]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientRe__Name__59FF861E] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Detai__5ABEA02D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Displ__5AF3AA57] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Calcu__5BE7CE90] DEFAULT ('') FOR [CalculationAssemblyQualifiedName]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__IsAtt__5C71DE75] DEFAULT ((0)) FOR [IsAttributeMember]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Calcu__5CDBF2C9] DEFAULT ('') FOR [CalculationXML]; GO
ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__IsCol__641F1C20] DEFAULT ((0)) FOR [IsColumnCalculationTakePrecedent]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportConditionalFormat ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportConditionalFormat] (
    [ClientReportConditionalFormatGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [ColumnTupleInfoXML] nvarchar(max) NOT NULL,
    [OperatorValue] int NOT NULL,
    [ValueToCompareAsString] nvarchar(1000) NOT NULL,
    [CSSClass] nvarchar(100) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [Comment] nvarchar(4000) NOT NULL,
    PRIMARY KEY ([ClientReportConditionalFormatGUID])
);
GO
ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [FK__REClientR__Repor__1E74ABFC] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Clien__1D8087C3] DEFAULT (newid()) FOR [ClientReportConditionalFormatGUID]; GO
ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Colum__1F68D035] DEFAULT ('') FOR [ColumnTupleInfoXML]; GO
ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Opera__205CF46E] DEFAULT ((0)) FOR [OperatorValue]; GO
ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Value__215118A7] DEFAULT ('') FOR [ValueToCompareAsString]; GO
ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__CSSCl__22453CE0] DEFAULT ('') FOR [CSSClass]; GO
ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Displ__23396119] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Comme__2521A98B] DEFAULT ('') FOR [Comment]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportDataSourceLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportDataSourceLink] (
    [ReportGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL,
    [IsDefault] bit NOT NULL,
    PRIMARY KEY ([ReportGUID], [DataSourceGUID])
);
GO
ALTER TABLE [dbo].[REClientReportDataSourceLink] ADD CONSTRAINT [FK__REClientR__Repor__0E9CA038] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REClientReportDataSourceLink] ADD CONSTRAINT [DF__REClientR__Provi__1084E8AA] DEFAULT ('') FOR [ProviderAssemblyQualifiedName]; GO
ALTER TABLE [dbo].[REClientReportDataSourceLink] ADD CONSTRAINT [DF__REClientR__DataS__0F90C471] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO
ALTER TABLE [dbo].[REClientReportDataSourceLink] ADD CONSTRAINT [DF__REClientR__IsDef__775ADEDB] DEFAULT ((0)) FOR [IsDefault]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportParameter] (
    [ClientReportParameterGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [ClientReportSectionItemGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [ColumnName] nvarchar(150) NOT NULL,
    [SourceTypeValue] int NOT NULL,
    [IsUserEditable] bit NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ParameterXML] nvarchar(max) NOT NULL,
    [DimensionID] nvarchar(100) NOT NULL,
    [AttributeID] nvarchar(100) NOT NULL,
    [MeasureID] nvarchar(100) NOT NULL,
    [ParameterValueAQN] nvarchar(400) NOT NULL,
    [ClientReportParameterGroupGUID] uniqueidentifier NOT NULL,
    [IsExpandingColumns] bit NOT NULL,
    [HierarchyID] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ClientReportParameterGUID])
);
GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [FK__REClientR__Repor__49C91E55] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Dimen__02CC9187] DEFAULT ('') FOR [DimensionID]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Attri__111AB0DE] DEFAULT ('') FOR [AttributeID]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Measu__120ED517] DEFAULT ('') FOR [MeasureID]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF_REClientReportParameter_HierarchyID] DEFAULT ('') FOR [HierarchyID]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Clien__48D4FA1C] DEFAULT (newid()) FOR [ClientReportParameterGUID]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientRe__Name__4BB166C7] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Sourc__4CA58B00] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Sourc__4D99AF39] DEFAULT ((0)) FOR [SourceTypeValue]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__IsUse__4E8DD372] DEFAULT ((0)) FOR [IsUserEditable]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Displ__4F81F7AB] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF_REClientReportParameter_IsExpandingColumns] DEFAULT ((0)) FOR [IsExpandingColumns]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Param__50761BE4] DEFAULT ('') FOR [ParameterXML]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Param__53EEAB7B] DEFAULT ('') FOR [ParameterValueAQN]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Clien__678D2682] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportParameterGroupGUID]; GO
ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Clien__4ABD428E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportSectionItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportParameterGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportParameterGroup] (
    [ClientReportParameterGroupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [IsMerged] bit NOT NULL,
    PRIMARY KEY ([ClientReportParameterGroupGUID])
);
GO
ALTER TABLE [dbo].[REClientReportParameterGroup] ADD CONSTRAINT [FK__REClientR__Repor__14FEEB77] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REClientReportParameterGroup] ADD CONSTRAINT [DF__REClientR__Clien__140AC73E] DEFAULT (newid()) FOR [ClientReportParameterGroupGUID]; GO
ALTER TABLE [dbo].[REClientReportParameterGroup] ADD CONSTRAINT [DF__REClientRe__Name__15F30FB0] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REClientReportParameterGroup] ADD CONSTRAINT [DF__REClientR__IsMer__16E733E9] DEFAULT ((0)) FOR [IsMerged]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportSection] (
    [ClientReportSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [DisplayLabel] nvarchar(100) NOT NULL,
    [IsTemplate] bit NOT NULL,
    [ShowSectionLabel] bit NOT NULL,
    [ShowGrandTotal] bit NOT NULL,
    [IsAutoNameFilter] bit NOT NULL,
    [IsMergingRepeatHeader] bit NOT NULL,
    [IsHidden] bit NOT NULL,
    [ShowMargin] bit NOT NULL,
    [IsTimeRelative] bit NOT NULL,
    PRIMARY KEY ([ClientReportSectionGUID])
);
GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF_REClientReportSection_ShowSectionLabel] DEFAULT ((0)) FOR [ShowSectionLabel]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF_REClientReportSection_ShowGrandTotal] DEFAULT ((0)) FOR [ShowGrandTotal]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsHid__113187EF] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__Clien__2C38BB6E] DEFAULT (newid()) FOR [ClientReportSectionGUID]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientRe__Name__2D2CDFA7] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__Displ__2E2103E0] DEFAULT ('') FOR [DisplayLabel]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsTem__30094C52] DEFAULT ((0)) FOR [IsTemplate]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsTim__3FF3035A] DEFAULT ((0)) FOR [IsTimeRelative]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__ShowM__4AEABEE6] DEFAULT ((1)) FOR [ShowMargin]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsAut__5D6602AE] DEFAULT ((0)) FOR [IsAutoNameFilter]; GO
ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsMer__6C51DB9F] DEFAULT ((1)) FOR [IsMergingRepeatHeader]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportSectionAttribute ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportSectionAttribute] (
    [ClientReportSectionAttributeGUID] uniqueidentifier NOT NULL,
    [ClientReportSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [ColumnName] nvarchar(200) NOT NULL,
    [AttributeID] nvarchar(200) NOT NULL,
    [DimensionID] nvarchar(200) NOT NULL,
    [HierarchyID] nvarchar(200) NOT NULL,
    [HierarchyNameCached] nvarchar(100) NOT NULL,
    [DrilldownStatusValue] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    [VisibilityStatusValue] int NOT NULL,
    [ColumnWidth] int NOT NULL,
    [DetailReportGUID] uniqueidentifier NOT NULL,
    [FilterMemberCSV] nvarchar(max) NOT NULL,
    [SortOrderValue] int NOT NULL,
    [ShowSubtotal] bit NOT NULL,
    [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL,
    PRIMARY KEY ([ClientReportSectionAttributeGUID])
);
GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [FK__REClientR__Clien__74B37C5A] FOREIGN KEY ([ClientReportSectionGUID]) REFERENCES [dbo].[REClientReportSection] ([ClientReportSectionGUID]); GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Visib__227A470A] DEFAULT ((0)) FOR [VisibilityStatusValue]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Colum__236E6B43] DEFAULT ((0)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Detai__3A7E819C] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Detai__58D657BB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Filte__5CA6E89F] DEFAULT ('') FOR [FilterMemberCSV]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__SortO__6353E62E] DEFAULT ((-1)) FOR [SortOrderValue]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__ShowS__6D45FFD8] DEFAULT ((0)) FOR [ShowSubtotal]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Clien__73BF5821] DEFAULT (newid()) FOR [ClientReportSectionAttributeGUID]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientRe__Name__75A7A093] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Colum__769BC4CC] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Attri__778FE905] DEFAULT ('') FOR [AttributeID]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Dimen__78840D3E] DEFAULT ('') FOR [DimensionID]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Hiera__79783177] DEFAULT ('') FOR [HierarchyID]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Hiera__7A6C55B0] DEFAULT ('') FOR [HierarchyNameCached]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Drill__7B6079E9] DEFAULT ((0)) FOR [DrilldownStatusValue]; GO
ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Displ__7D48C25B] DEFAULT ((0)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportSectionLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportSectionLink] (
    [ClientReportSectionLinkGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [ClientReportSectionGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] int NOT NULL,
    [IsOnColumn] bit NOT NULL,
    PRIMARY KEY ([ClientReportSectionLinkGUID])
);
GO
ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [FK__REClientR__Clien__36B649E1] FOREIGN KEY ([ClientReportSectionGUID]) REFERENCES [dbo].[REClientReportSection] ([ClientReportSectionGUID]); GO
ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [FK__REClientR__Repor__35C225A8] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [DF__REClientR__Clien__34CE016F] DEFAULT (newid()) FOR [ClientReportSectionLinkGUID]; GO
ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [DF__REClientR__Displ__37AA6E1A] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [DF__REClientR__IsOnC__389E9253] DEFAULT ((0)) FOR [IsOnColumn]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportSectionMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportSectionMeasure] (
    [ClientReportSectionMeasureGUID] uniqueidentifier NOT NULL,
    [ClientReportSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [MeasureID] nvarchar(100) NOT NULL,
    [DisplayFormatCached] nvarchar(100) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ColumnWidth] int NOT NULL,
    [DetailReportGUID] uniqueidentifier NOT NULL,
    [LinkedSectionGUIDsCSV] nvarchar(max) NOT NULL,
    [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL,
    [AggregationType] tinyint NOT NULL,
    PRIMARY KEY ([ClientReportSectionMeasureGUID])
);
GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [FK__REClientR__Clien__03019BB1] FOREIGN KEY ([ClientReportSectionGUID]) REFERENCES [dbo].[REClientReportSection] ([ClientReportSectionGUID]); GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Clien__020D7778] DEFAULT (newid()) FOR [ClientReportSectionMeasureGUID]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientRe__Name__03F5BFEA] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Measu__04E9E423] DEFAULT ('') FOR [MeasureID]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Displ__05DE085C] DEFAULT ('') FOR [DisplayFormatCached]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Displ__06D22C95] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Linke__16D38A34] DEFAULT ('') FOR [LinkedSectionGUIDsCSV]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Colum__24628F7C] DEFAULT ((0)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Detai__3B72A5D5] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Aggre__3D0580C9] DEFAULT ((0)) FOR [AggregationType]; GO
ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Detai__59CA7BF4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REClientReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[REClientReportSetup] (
    [ClientReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [LaunchMode] int NOT NULL,
    [IsDrilldownIndented] bit NOT NULL,
    [Style] nvarchar(100) NOT NULL,
    [IsAutoRefresh] bit NOT NULL,
    [SortArgsXML] nvarchar(max) NOT NULL,
    [IsTitleVisible] bit NOT NULL,
    [HideEmptyData] bit NOT NULL,
    [HasPHIData] bit NOT NULL,
    [IsPaneFrozen] bit NOT NULL,
    [IsExcelOnly] bit NOT NULL,
    [IsAutoHidingRows] bit NOT NULL,
    [ChartConfigJSON] nvarchar(max) NOT NULL,
    [ChartConfigAQN] nvarchar(max) NOT NULL,
    PRIMARY KEY ([ClientReportSetupGUID])
);
GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [FK__REClientR__Repor__0BC0338D] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Clien__0ACC0F54] DEFAULT (newid()) FOR [ClientReportSetupGUID]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Launc__0CB457C6] DEFAULT ((0)) FOR [LaunchMode]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF_REClientReportSetup_IsAutoHidingRows] DEFAULT ((0)) FOR [IsAutoHidingRows]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__IsAut__0F32686C] DEFAULT ((0)) FOR [IsAutoRefresh]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__SortA__1302F950] DEFAULT ('') FOR [SortArgsXML]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Chart__162C7621] DEFAULT ('') FOR [ChartConfigJSON]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Chart__17209A5A] DEFAULT ('') FOR [ChartConfigAQN]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__IsDri__2091FE98] DEFAULT ((0)) FOR [IsDrilldownIndented]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Style__218622D1] DEFAULT ('') FOR [Style]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF_REClientReportSetup_IsTitleVisible] DEFAULT ((0)) FOR [IsTitleVisible]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__HideE__2866C5A6] DEFAULT ((0)) FOR [HideEmptyData]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__IsExc__4133A25B] DEFAULT ((0)) FOR [IsExcelOnly]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__HasPH__5E542FC3] DEFAULT ((0)) FOR [HasPHIData]; GO
ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__IsPan__7FF153C7] DEFAULT ((0)) FOR [IsPaneFrozen]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RECubeReportDimension ------------------
---------------------------------------------
CREATE TABLE [dbo].[RECubeReportDimension] (
    [CubeReportDimensionGUID] uniqueidentifier NOT NULL,
    [CubeReportSetupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [HierarchyID] nvarchar(400) NOT NULL,
    [DimensionType] int NOT NULL,
    [IsConsolidatable] bit NOT NULL,
    [IsOnColumn] bit NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([CubeReportDimensionGUID])
);
GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [FK_CubeReportDimension_CubeReportSetup] FOREIGN KEY ([CubeReportSetupGUID]) REFERENCES [dbo].[RECubeReportSetup] ([CubeReportSetupGUID]); GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_CubeReportDimensionGUID] DEFAULT (newid()) FOR [CubeReportDimensionGUID]; GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_CubeReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeReportSetupGUID]; GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_HierarchyID] DEFAULT ('') FOR [HierarchyID]; GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_DimensionType] DEFAULT ((0)) FOR [DimensionType]; GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_IsConsolidatable] DEFAULT ((0)) FOR [IsConsolidatable]; GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_IsOnColumn] DEFAULT ((0)) FOR [IsOnColumn]; GO
ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RECubeReportLevel ------------------
---------------------------------------------
CREATE TABLE [dbo].[RECubeReportLevel] (
    [CubeReportLevelGUID] uniqueidentifier NOT NULL,
    [CubeReportDimensionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [LevelID] nvarchar(400) NOT NULL,
    [LevelIndex] int NOT NULL,
    [IsConsolidated] bit NOT NULL,
    [MDXName] nvarchar(400) NOT NULL,
    PRIMARY KEY ([CubeReportLevelGUID])
);
GO
ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [FK_CubeReportLevel_CubeReportDimension] FOREIGN KEY ([CubeReportDimensionGUID]) REFERENCES [dbo].[RECubeReportDimension] ([CubeReportDimensionGUID]); GO
ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_CubeReportLevelGUID] DEFAULT (newid()) FOR [CubeReportLevelGUID]; GO
ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_CubeReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeReportDimensionGUID]; GO
ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_LevelID] DEFAULT ('') FOR [LevelID]; GO
ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_LevelIndex] DEFAULT ((-1)) FOR [LevelIndex]; GO
ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_IsConsolidated] DEFAULT ((0)) FOR [IsConsolidated]; GO
ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_MDXName] DEFAULT ('') FOR [MDXName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RECubeReportMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[RECubeReportMeasure] (
    [CubeReportMeasureGUID] uniqueidentifier NOT NULL,
    [CubeReportSetupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [MeasureID] nvarchar(400) NOT NULL,
    [MDXName] nvarchar(400) NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([CubeReportMeasureGUID])
);
GO
ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [FK_CubeReportMeasure_CubeReportSetup] FOREIGN KEY ([CubeReportSetupGUID]) REFERENCES [dbo].[RECubeReportSetup] ([CubeReportSetupGUID]); GO
ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_CubeReportMeasureGUID] DEFAULT (newid()) FOR [CubeReportMeasureGUID]; GO
ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_CubeReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeReportSetupGUID]; GO
ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_MeasureID] DEFAULT ('') FOR [MeasureID]; GO
ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_MDXName] DEFAULT ('') FOR [MDXName]; GO
ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RECubeReportParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[RECubeReportParameter] (
    [CubeReportParameterGUID] uniqueidentifier NOT NULL,
    [CubeReportSetupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [HierarchyID] nvarchar(400) NOT NULL,
    [IsEditable] bit NOT NULL,
    [MemberIDs] nvarchar(max) NOT NULL,
    [MemberNames] nvarchar(max) NOT NULL,
    PRIMARY KEY ([CubeReportParameterGUID])
);
GO
ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [FK_CubeReportParameter_CubeReportSetup] FOREIGN KEY ([CubeReportSetupGUID]) REFERENCES [dbo].[RECubeReportSetup] ([CubeReportSetupGUID]); GO
ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_CubeReportParameterGUID] DEFAULT (newid()) FOR [CubeReportParameterGUID]; GO
ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeReportSetupGUID]; GO
ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_HierarchyID] DEFAULT ('') FOR [HierarchyID]; GO
ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_IsEditable] DEFAULT ((1)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_MemberIDs] DEFAULT ('') FOR [MemberIDs]; GO
ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_MemberNames] DEFAULT ('') FOR [MemberNames]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RECubeReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[RECubeReportSetup] (
    [CubeReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [CubeName] nvarchar(64) NOT NULL,
    [IsNonEmptyColumns] bit NOT NULL,
    [IsNonEmptyRows] bit NOT NULL,
    [IsShowingTotal] bit NOT NULL,
    [IsUsingMDXOverride] bit NOT NULL,
    [MDXOverride] nvarchar(max) NOT NULL,
    PRIMARY KEY ([CubeReportSetupGUID])
);
GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [FK_RECubeReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_CubeReportSetupGUID] DEFAULT (newid()) FOR [CubeReportSetupGUID]; GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_CubeName] DEFAULT ('') FOR [CubeName]; GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_IsNonEmptyColumns] DEFAULT ((0)) FOR [IsNonEmptyColumns]; GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_IsNonEmptyRows] DEFAULT ((0)) FOR [IsNonEmptyRows]; GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_IsShowingTotal] DEFAULT ((1)) FOR [IsShowingTotal]; GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_RECubeReportSetup_IsUsingMDXOverride] DEFAULT ((0)) FOR [IsUsingMDXOverride]; GO
ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_RECubeReportSetup_MDXOverride] DEFAULT ('') FOR [MDXOverride]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportCalculation ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportCalculation] (
    [DSCubeReportCalculationGUID] uniqueidentifier NOT NULL,
    [DSCubeReportSectionGUID] uniqueidentifier NULL,
    [Name] nvarchar(1000) NULL,
    [DisplayOrder] int NOT NULL,
    [CalculationAssemblyQualifiedName] nvarchar(400) NOT NULL,
    [CalculationXML] nvarchar(max) NOT NULL,
    [DetailReportGUID] uniqueidentifier NOT NULL,
    [DisplayFormat] nvarchar(max) NOT NULL,
    [ColumnWidth] int NOT NULL,
    [IsAttributeMember] bit NOT NULL,
    [CSSClass] nvarchar(100) NOT NULL,
    [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL,
    [IsColumnCalculationTakePrecedent] bit NOT NULL,
    PRIMARY KEY ([DSCubeReportCalculationGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [FK__REDSCubeR__DSCub__1789E357] FOREIGN KEY ([DSCubeReportSectionGUID]) REFERENCES [dbo].[REDSCubeReportSection] ([DSCubeReportSectionGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__DSCub__15A19AE5] DEFAULT (newid()) FOR [DSCubeReportCalculationGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__DSCub__1695BF1E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeRe__Name__187E0790] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Displ__19722BC9] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Calcu__1A665002] DEFAULT ('') FOR [CalculationAssemblyQualifiedName]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Calcu__1B5A743B] DEFAULT ('') FOR [CalculationXML]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Detai__1C4E9874] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Displ__1D42BCAD] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Colum__1E36E0E6] DEFAULT ((0)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__IsAtt__1F2B051F] DEFAULT ((0)) FOR [IsAttributeMember]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__CSSCl__201F2958] DEFAULT ('') FOR [CSSClass]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Detai__21134D91] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO
ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__IsCol__220771CA] DEFAULT ((0)) FOR [IsColumnCalculationTakePrecedent]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportConditionalFormat ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportConditionalFormat] (
    [DSCubeReportConditionalFormatGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [ColumnTupleInfoXML] nvarchar(max) NOT NULL,
    [OperatorValue] int NOT NULL,
    [ValueToCompareAsString] nvarchar(1000) NOT NULL,
    [CSSClass] nvarchar(100) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [Comment] nvarchar(4000) NOT NULL,
    PRIMARY KEY ([DSCubeReportConditionalFormatGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [FK__REDSCubeR__Repor__4EDA1841] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__DSCub__4CF1CFCF] DEFAULT (newid()) FOR [DSCubeReportConditionalFormatGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Repor__4DE5F408] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Colum__4FCE3C7A] DEFAULT ('') FOR [ColumnTupleInfoXML]; GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Opera__50C260B3] DEFAULT ((0)) FOR [OperatorValue]; GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Value__51B684EC] DEFAULT ('') FOR [ValueToCompareAsString]; GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__CSSCl__52AAA925] DEFAULT ('') FOR [CSSClass]; GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Displ__539ECD5E] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Comme__5492F197] DEFAULT ('') FOR [Comment]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportDataSourceLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportDataSourceLink] (
    [ReportGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL,
    [IsDefault] bit NOT NULL,
    PRIMARY KEY ([ReportGUID], [DataSourceGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [FK__REDSCubeR__Repor__5863827B] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [DF__REDSCubeR__Repor__576F5E42] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [DF__REDSCubeR__DataS__5957A6B4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [DF__REDSCubeR__Provi__5A4BCAED] DEFAULT ('') FOR [ProviderAssemblyQualifiedName]; GO
ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [DF__REDSCubeR__IsDef__5B3FEF26] DEFAULT ((0)) FOR [IsDefault]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportParameter] (
    [DSCubeReportParameterGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [DSCubeReportSectionItemGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [ColumnName] nvarchar(150) NOT NULL,
    [SourceTypeValue] int NOT NULL,
    [IsUserEditable] bit NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ParameterXML] nvarchar(max) NOT NULL,
    [DimensionID] nvarchar(100) NOT NULL,
    [AttributeID] nvarchar(100) NOT NULL,
    [MeasureID] nvarchar(100) NOT NULL,
    [ParameterValueAQN] nvarchar(400) NOT NULL,
    [DSCubeReportParameterGroupGUID] uniqueidentifier NOT NULL,
    [IsExpandingColumns] bit NOT NULL,
    [HierarchyID] nvarchar(100) NOT NULL,
    PRIMARY KEY ([DSCubeReportParameterGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [FK__REDSCubeR__Repor__6004A443] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__DSCub__5E1C5BD1] DEFAULT (newid()) FOR [DSCubeReportParameterGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Repor__5F10800A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__DSCub__60F8C87C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionItemGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeRe__Name__61ECECB5] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Colum__62E110EE] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Sourc__63D53527] DEFAULT ((0)) FOR [SourceTypeValue]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__IsUse__64C95960] DEFAULT ((0)) FOR [IsUserEditable]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Displ__65BD7D99] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Param__66B1A1D2] DEFAULT ('') FOR [ParameterXML]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Dimen__67A5C60B] DEFAULT ('') FOR [DimensionID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Attri__6899EA44] DEFAULT ('') FOR [AttributeID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Measu__698E0E7D] DEFAULT ('') FOR [MeasureID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Param__6A8232B6] DEFAULT ('') FOR [ParameterValueAQN]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__DSCub__6B7656EF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportParameterGroupGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__IsExp__6C6A7B28] DEFAULT ((0)) FOR [IsExpandingColumns]; GO
ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Hiera__6D5E9F61] DEFAULT ('') FOR [HierarchyID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportParameterGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportParameterGroup] (
    [DSCubeReportParameterGroupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [IsMerged] bit NOT NULL,
    PRIMARY KEY ([DSCubeReportParameterGroupGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [FK__REDSCubeR__Repor__7223547E] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [DF__REDSCubeR__DSCub__703B0C0C] DEFAULT (newid()) FOR [DSCubeReportParameterGroupGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [DF__REDSCubeR__Repor__712F3045] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [DF__REDSCubeRe__Name__731778B7] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [DF__REDSCubeR__IsMer__740B9CF0] DEFAULT ((0)) FOR [IsMerged]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportSection] (
    [DSCubeReportSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [DisplayLabel] nvarchar(100) NOT NULL,
    [IsTemplate] bit NOT NULL,
    [ShowSectionLabel] bit NOT NULL,
    [ShowGrandTotal] bit NOT NULL,
    [IsAutoNameFilter] bit NOT NULL,
    [IsMergingRepeatHeader] bit NOT NULL,
    [IsHidden] bit NOT NULL,
    [ShowMargin] bit NOT NULL,
    [IsTimeRelative] bit NOT NULL,
    PRIMARY KEY ([DSCubeReportSectionGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__DSCub__093BC400] DEFAULT (newid()) FOR [DSCubeReportSectionGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeRe__Name__0A2FE839] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__Displ__0B240C72] DEFAULT ('') FOR [DisplayLabel]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsTem__0C1830AB] DEFAULT ((0)) FOR [IsTemplate]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__ShowS__0D0C54E4] DEFAULT ((0)) FOR [ShowSectionLabel]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__ShowG__0E00791D] DEFAULT ((0)) FOR [ShowGrandTotal]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsAut__0EF49D56] DEFAULT ((0)) FOR [IsAutoNameFilter]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsMer__0FE8C18F] DEFAULT ((1)) FOR [IsMergingRepeatHeader]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsHid__10DCE5C8] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__ShowM__11D10A01] DEFAULT ((1)) FOR [ShowMargin]; GO
ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsTim__12C52E3A] DEFAULT ((0)) FOR [IsTimeRelative]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportSectionAttribute ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportSectionAttribute] (
    [DSCubeReportSectionAttributeGUID] uniqueidentifier NOT NULL,
    [DSCubeReportSectionGUID] uniqueidentifier NULL,
    [Name] nvarchar(100) NOT NULL,
    [ColumnName] nvarchar(200) NOT NULL,
    [AttributeID] nvarchar(200) NOT NULL,
    [DimensionID] nvarchar(200) NOT NULL,
    [HierarchyID] nvarchar(200) NOT NULL,
    [HierarchyNameCached] nvarchar(100) NOT NULL,
    [DrilldownStatusValue] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    [VisibilityStatusValue] int NOT NULL,
    [ColumnWidth] int NOT NULL,
    [DetailReportGUID] uniqueidentifier NOT NULL,
    [FilterMemberCSV] nvarchar(max) NOT NULL,
    [SortOrderValue] int NOT NULL,
    [ShowSubtotal] bit NOT NULL,
    [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL,
    PRIMARY KEY ([DSCubeReportSectionAttributeGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [FK__REDSCubeR__DSCub__26CC26E7] FOREIGN KEY ([DSCubeReportSectionGUID]) REFERENCES [dbo].[REDSCubeReportSection] ([DSCubeReportSectionGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__DSCub__24E3DE75] DEFAULT (newid()) FOR [DSCubeReportSectionAttributeGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__DSCub__25D802AE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeRe__Name__27C04B20] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Colum__28B46F59] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Attri__29A89392] DEFAULT ('') FOR [AttributeID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Dimen__2A9CB7CB] DEFAULT ('') FOR [DimensionID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Hiera__2B90DC04] DEFAULT ('') FOR [HierarchyID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Hiera__2C85003D] DEFAULT ('') FOR [HierarchyNameCached]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Drill__2D792476] DEFAULT ((0)) FOR [DrilldownStatusValue]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Displ__2E6D48AF] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Visib__2F616CE8] DEFAULT ((0)) FOR [VisibilityStatusValue]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Colum__30559121] DEFAULT ((0)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Detai__3149B55A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Filte__323DD993] DEFAULT ('') FOR [FilterMemberCSV]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__SortO__3331FDCC] DEFAULT ((-1)) FOR [SortOrderValue]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__ShowS__34262205] DEFAULT ((0)) FOR [ShowSubtotal]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Detai__351A463E] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportSectionLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportSectionLink] (
    [DSCubeReportSectionLinkGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [DSCubeReportSectionGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] int NOT NULL,
    [IsOnColumn] bit NOT NULL,
    PRIMARY KEY ([DSCubeReportSectionLinkGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [FK__REDSCubeR__DSCub__7AB89A7F] FOREIGN KEY ([DSCubeReportSectionGUID]) REFERENCES [dbo].[REDSCubeReportSection] ([DSCubeReportSectionGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [FK__REDSCubeR__Repor__78D0520D] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__DSCub__76E8099B] DEFAULT (newid()) FOR [DSCubeReportSectionLinkGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__Repor__77DC2DD4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__DSCub__79C47646] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__Displ__7BACBEB8] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__IsOnC__7CA0E2F1] DEFAULT ((0)) FOR [IsOnColumn]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportSectionMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportSectionMeasure] (
    [DSCubeReportSectionMeasureGUID] uniqueidentifier NOT NULL,
    [DSCubeReportSectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [MeasureID] nvarchar(100) NOT NULL,
    [DisplayFormatCached] nvarchar(100) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ColumnWidth] int NOT NULL,
    [DetailReportGUID] uniqueidentifier NOT NULL,
    [LinkedSectionGUIDsCSV] nvarchar(max) NOT NULL,
    [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL,
    [AggregationType] tinyint NOT NULL,
    PRIMARY KEY ([DSCubeReportSectionMeasureGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [FK__REDSCubeR__DSCub__41801D23] FOREIGN KEY ([DSCubeReportSectionGUID]) REFERENCES [dbo].[REDSCubeReportSection] ([DSCubeReportSectionGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__DSCub__3F97D4B1] DEFAULT (newid()) FOR [DSCubeReportSectionMeasureGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__DSCub__408BF8EA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeRe__Name__4274415C] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Measu__43686595] DEFAULT ('') FOR [MeasureID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Displ__445C89CE] DEFAULT ('') FOR [DisplayFormatCached]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Displ__4550AE07] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Colum__4644D240] DEFAULT ((0)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Detai__4738F679] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Linke__482D1AB2] DEFAULT ('') FOR [LinkedSectionGUIDsCSV]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Detai__49213EEB] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO
ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Aggre__4A156324] DEFAULT ((0)) FOR [AggregationType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDSCubeReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDSCubeReportSetup] (
    [DSCubeReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [LaunchMode] int NOT NULL,
    [IsDrilldownIndented] bit NOT NULL,
    [Style] nvarchar(100) NOT NULL,
    [IsAutoRefresh] bit NOT NULL,
    [SortArgsXML] nvarchar(max) NOT NULL,
    [IsTitleVisible] bit NOT NULL,
    [HideEmptyData] bit NOT NULL,
    [HasPHIData] bit NOT NULL,
    [IsPaneFrozen] bit NOT NULL,
    [IsExcelOnly] bit NOT NULL,
    [ChartConfigJSON] nvarchar(max) NOT NULL,
    [ChartConfigAQN] nvarchar(max) NOT NULL,
    PRIMARY KEY ([DSCubeReportSetupGUID])
);
GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [FK__REDSCubeR__Repor__7CD5ED1B] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsAut__00A67DFF] DEFAULT ((0)) FOR [IsAutoRefresh]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__SortA__019AA238] DEFAULT ('') FOR [SortArgsXML]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsTit__028EC671] DEFAULT ((0)) FOR [IsTitleVisible]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__HideE__0382EAAA] DEFAULT ((0)) FOR [HideEmptyData]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__HasPH__04770EE3] DEFAULT ((0)) FOR [HasPHIData]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsPan__056B331C] DEFAULT ((0)) FOR [IsPaneFrozen]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsExc__065F5755] DEFAULT ((0)) FOR [IsExcelOnly]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Chart__6FC6D617] DEFAULT ('') FOR [ChartConfigJSON]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Chart__72A342C2] DEFAULT ('') FOR [ChartConfigAQN]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__DSCub__7AEDA4A9] DEFAULT (newid()) FOR [DSCubeReportSetupGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Repor__7BE1C8E2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Launc__7DCA1154] DEFAULT ((0)) FOR [LaunchMode]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsDri__7EBE358D] DEFAULT ((0)) FOR [IsDrilldownIndented]; GO
ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Style__7FB259C6] DEFAULT ('') FOR [Style]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REDataSource ------------------
---------------------------------------------
CREATE TABLE [dbo].[REDataSource] (
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [SourceGUID] uniqueidentifier NOT NULL,
    [SourceType] int NOT NULL,
    [Name] nvarchar(max) NOT NULL,
    [SkipBlanks] bit NOT NULL,
    [SimpleNames] bit NOT NULL,
    PRIMARY KEY ([DataSourceGUID])
);

CREATE NONCLUSTERED INDEX [IDX_REDataSource] ON [dbo].[REDataSource] ([ReportGUID]);
GO
ALTER TABLE [dbo].[REDataSource] ADD CONSTRAINT [FK_REDataSource_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.REERHelpText ------------------
---------------------------------------------
CREATE TABLE [dbo].[REERHelpText] (
    [ERHelpID] smallint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Text] nvarchar(max) NOT NULL,
    [Grouping] nvarchar(20) NOT NULL,
    [ImagePath] nvarchar(50) NOT NULL,
    PRIMARY KEY ([ERHelpID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.REExConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[REExConfig] (
    [ExConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(max) NOT NULL,
    [SheetGUID] uniqueidentifier NOT NULL,
    [ParentGUID] uniqueidentifier NOT NULL,
    [ConfigType] int NOT NULL,
    [DataSource] nvarchar(max) NOT NULL,
    [Dimension] nvarchar(max) NOT NULL,
    [UseParentContext] bit NOT NULL,
    [RangeAddress] nvarchar(max) NOT NULL,
    [Descending] bit NOT NULL,
    [IsWebDrillDownable] bit NOT NULL,
    [HiddenPIndex] int NOT NULL,
    [DDIconAlignment] bit NOT NULL,
    [DrillDownDimension] nvarchar(max) NOT NULL,
    [ClickCellAddress] nchar(10) NOT NULL,
    [FilterDimensionMember] nvarchar(max) NOT NULL,
    [HideConsolidatedMembers] bit NOT NULL,
    PRIMARY KEY ([ExConfigGUID])
);
GO
ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [FK_REExConfig_REExConfig] FOREIGN KEY ([SheetGUID]) REFERENCES [dbo].[RESheetConfig] ([SheetGUID]); GO
ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_IsWebDrillDownable] DEFAULT ((0)) FOR [IsWebDrillDownable]; GO
ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_HiddenPIndex] DEFAULT ((0)) FOR [HiddenPIndex]; GO
ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_ClickPIndex] DEFAULT ((0)) FOR [DDIconAlignment]; GO
ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_DrillDownDimension] DEFAULT ('') FOR [DrillDownDimension]; GO
ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_ClickCellAddress] DEFAULT ('0') FOR [ClickCellAddress]; GO
ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_FilterDimensionMember] DEFAULT ('') FOR [FilterDimensionMember]; GO
ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_HideConsolidatedMembers] DEFAULT ((0)) FOR [HideConsolidatedMembers]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REExConfigFilterMembers ------------------
---------------------------------------------
CREATE TABLE [dbo].[REExConfigFilterMembers] (
    [ExConfigGUID] uniqueidentifier NOT NULL,
    [FilterMember] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ExConfigGUID], [FilterMember])
);
GO
ALTER TABLE [dbo].[REExConfigFilterMembers] ADD CONSTRAINT [FK_REEXCONFIG_EXCONFIGGUID] FOREIGN KEY ([ExConfigGUID]) REFERENCES [dbo].[REExConfig] ([ExConfigGUID]); GO
ALTER TABLE [dbo].[REExConfigFilterMembers] ADD CONSTRAINT [DF_REExConfigFilterMembers_FilterMember] DEFAULT ('') FOR [FilterMember]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REExReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[REExReportSetup] (
    [ExReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [ExReportTemplateGUID] uniqueidentifier NOT NULL,
    [OutputType] nvarchar(64) NOT NULL,
    [ParametersXML] nvarchar(max) NOT NULL,
    PRIMARY KEY ([ExReportSetupGUID])
);
GO
ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [FK_REExReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_ExReportSetupGUID] DEFAULT (newid()) FOR [ExReportSetupGUID]; GO
ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_ExReportTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ExReportTemplateGUID]; GO
ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_OutputType] DEFAULT ('') FOR [OutputType]; GO
ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_ParametersXML] DEFAULT ('') FOR [ParametersXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REExtractReportOutputColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[REExtractReportOutputColumn] (
    [ExtractReportOutputFormatColumnGUID] uniqueidentifier NOT NULL,
    [ClientReportSetupGUID] uniqueidentifier NULL,
    [ClientReportSectionIdentifierGUID] uniqueidentifier NULL,
    [DisplayOrder] int NOT NULL,
    [IsTrimLeadingZeroes] bit NOT NULL,
    [FormatString] nvarchar(100) NOT NULL,
    [NullHandler] smallint NOT NULL,
    PRIMARY KEY ([ExtractReportOutputFormatColumnGUID])
);
GO
ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [FK__REExtract__Clien__494731A0] FOREIGN KEY ([ClientReportSetupGUID]) REFERENCES [dbo].[REClientReportSetup] ([ClientReportSetupGUID]); GO
ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__NullH__004E191E] DEFAULT ((0)) FOR [NullHandler]; GO
ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Extra__475EE92E] DEFAULT (newid()) FOR [ExtractReportOutputFormatColumnGUID]; GO
ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Clien__48530D67] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportSetupGUID]; GO
ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Clien__4A3B55D9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportSectionIdentifierGUID]; GO
ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Displ__4B2F7A12] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__IsTri__4C239E4B] DEFAULT ((0)) FOR [IsTrimLeadingZeroes]; GO
ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Forma__4D17C284] DEFAULT ('') FOR [FormatString]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REExtractReportOutputFormat ------------------
---------------------------------------------
CREATE TABLE [dbo].[REExtractReportOutputFormat] (
    [ExtractReportOutputFormatGUID] uniqueidentifier NOT NULL,
    [ClientReportSetupGUID] uniqueidentifier NULL,
    [FilenameExtension] nvarchar(10) NOT NULL,
    [SourceFileTypeVal] smallint NOT NULL,
    [ConfigXML] nvarchar(max) NOT NULL,
    [IsCompressed] bit NOT NULL,
    [IsDatetimeIncluded] bit NOT NULL,
    [IsCleaningCarriageReturn] bit NOT NULL,
    [IsCleaningSpecialCharacters] bit NOT NULL,
    PRIMARY KEY ([ExtractReportOutputFormatGUID])
);
GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [FK__REExtract__Clien__3EC9A32D] FOREIGN KEY ([ClientReportSetupGUID]) REFERENCES [dbo].[REClientReportSetup] ([ClientReportSetupGUID]); GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__IsDat__1660B4F4] DEFAULT ((0)) FOR [IsDatetimeIncluded]; GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__IsCle__1754D92D] DEFAULT ((0)) FOR [IsCleaningCarriageReturn]; GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__IsCle__1848FD66] DEFAULT ((0)) FOR [IsCleaningSpecialCharacters]; GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Extra__3CE15ABB] DEFAULT (newid()) FOR [ExtractReportOutputFormatGUID]; GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Clien__3DD57EF4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportSetupGUID]; GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Filen__3FBDC766] DEFAULT ('') FOR [FilenameExtension]; GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Sourc__40B1EB9F] DEFAULT ((0)) FOR [SourceFileTypeVal]; GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Confi__41A60FD8] DEFAULT ('') FOR [ConfigXML]; GO
ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__IsCom__668E471B] DEFAULT ((0)) FOR [IsCompressed]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REFileReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[REFileReportSetup] (
    [FileReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [Extension] nvarchar(64) NOT NULL,
    [ImageName] nvarchar(64) NOT NULL,
    [OriginalFileName] nvarchar(400) NOT NULL,
    [ContentLengthInByte] int NOT NULL,
    PRIMARY KEY ([FileReportSetupGUID])
);
GO
ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [FK_REFileReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_FileReportSetupGUID] DEFAULT (newid()) FOR [FileReportSetupGUID]; GO
ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_Extension] DEFAULT ('') FOR [Extension]; GO
ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_ImageName] DEFAULT ('') FOR [ImageName]; GO
ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_OriginalFileName] DEFAULT ('') FOR [OriginalFileName]; GO
ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_ContentLengthInByte] DEFAULT ((0)) FOR [ContentLengthInByte]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REFormReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[REFormReportSetup] (
    [FormReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [FormGUID] uniqueidentifier NOT NULL,
    [PlanGUIDs] nvarchar(max) NOT NULL,
    [PlanNames] nvarchar(max) NOT NULL,
    PRIMARY KEY ([FormReportSetupGUID])
);
GO
ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_FormReportSetupGUID] DEFAULT (newid()) FOR [FormReportSetupGUID]; GO
ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_FormGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormGUID]; GO
ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_PlanGUIDs] DEFAULT ('') FOR [PlanGUIDs]; GO
ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_PlanNames] DEFAULT ('') FOR [PlanNames]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REGroupingParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[REGroupingParameter] (
    [GroupingParameterGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [ParameterValueXML] nvarchar(max) NOT NULL,
    [IsEditable] bit NOT NULL,
    [DefaultLinkedParameterGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [IsMultiSelect] bit NOT NULL,
    [IsExpandable] bit NOT NULL,
    PRIMARY KEY ([GroupingParameterGUID])
);
GO
ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [FK_REGroupingParameter_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_DefaultLinkedParameterGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultLinkedParameterGUID]; GO
ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter2_GroupingParameterGUID] DEFAULT (newid()) FOR [GroupingParameterGUID]; GO
ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_IsEditable] DEFAULT ((1)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_Order] DEFAULT ((-1)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_IsMultiSelect] DEFAULT ((1)) FOR [IsMultiSelect]; GO
ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF__REGroupin__IsExp__65114617] DEFAULT ((1)) FOR [IsExpandable]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REGroupingParameterLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[REGroupingParameterLink] (
    [GroupingParameterLinkGUID] uniqueidentifier NOT NULL,
    [GroupingParameterGUID] uniqueidentifier NOT NULL,
    [LinkedSourceGUID] uniqueidentifier NOT NULL,
    [LinkedParameterGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([GroupingParameterLinkGUID])
);
GO
ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [FK_REGroupingParameterLink_REGroupingParameter] FOREIGN KEY ([GroupingParameterGUID]) REFERENCES [dbo].[REGroupingParameter] ([GroupingParameterGUID]); GO
ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [DF_REGroupingParameterParameterLink_GroupingParameterParameterLinkGUID] DEFAULT (newid()) FOR [GroupingParameterLinkGUID]; GO
ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [DF_REGroupingParameterParameterLink_GroupingParameterGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingParameterGUID]; GO
ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [DF_REGroupingParameterParameterLink_LinkedSourceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LinkedSourceGUID]; GO
ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [DF_REGroupingParameterParameterLink_LinkedParameterGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LinkedParameterGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RELootType ------------------
---------------------------------------------
CREATE TABLE [dbo].[RELootType] (
    [ID] uniqueidentifier NOT NULL,
    [LootType] int NOT NULL,
    [LootTypeName] nvarchar(64) NOT NULL,
    [VERSION] timestamp NOT NULL,
    PRIMARY KEY ([ID])
);
GO
ALTER TABLE [dbo].[RELootType] ADD CONSTRAINT [DF_RELootType_ID] DEFAULT (newid()) FOR [ID]; GO
ALTER TABLE [dbo].[RELootType] ADD CONSTRAINT [DF_RELootType_LootType] DEFAULT ((0)) FOR [LootType]; GO
ALTER TABLE [dbo].[RELootType] ADD CONSTRAINT [DF_RELootType_LootTypeName] DEFAULT ('') FOR [LootTypeName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REModelDataReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[REModelDataReportSetup] (
    [ModelDataReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [Ranges] nvarchar(max) NOT NULL,
    [EntityViewGUID] uniqueidentifier NOT NULL,
    [PlanGUIDs] nvarchar(max) NOT NULL,
    [PrintArea] nvarchar(64) NOT NULL,
    [PrintTitleRows] nvarchar(64) NOT NULL,
    [PrintTitleColumns] nvarchar(64) NOT NULL,
    PRIMARY KEY ([ModelDataReportSetupGUID])
);
GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_PrintArea] DEFAULT ('') FOR [PrintArea]; GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_PrintTitleRows] DEFAULT ('') FOR [PrintTitleRows]; GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_PrintTitleColumns] DEFAULT ('') FOR [PrintTitleColumns]; GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_ModelDataReportSetupGUID] DEFAULT (newid()) FOR [ModelDataReportSetupGUID]; GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_ModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_Ranges] DEFAULT ('') FOR [Ranges]; GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_EntityViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityViewGUID]; GO
ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_PlanGUIDs] DEFAULT ('') FOR [PlanGUIDs]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RENumberingParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[RENumberingParameter] (
    [ParameterGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [StartValue] int NOT NULL,
    [StopValue] int NOT NULL,
    [StepValue] int NOT NULL,
    PRIMARY KEY ([ParameterGUID])
);
GO
ALTER TABLE [dbo].[RENumberingParameter] ADD CONSTRAINT [FK_RENumberingParameter_REDataSource1] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.REParameterCache ------------------
---------------------------------------------
CREATE TABLE [dbo].[REParameterCache] (
    [ReportGUID] uniqueidentifier NOT NULL,
    [ParameterCacheGUID] uniqueidentifier NOT NULL,
    [Parameters] nvarchar(max) NOT NULL,
    [CreatedAt] datetime NOT NULL,
    PRIMARY KEY ([ParameterCacheGUID])
);
GO
ALTER TABLE [dbo].[REParameterCache] ADD CONSTRAINT [FK__REParamet__Repor__2D7196A4] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REParameterCache] ADD CONSTRAINT [DF__REParamet__Param__2E65BADD] DEFAULT (newid()) FOR [ParameterCacheGUID]; GO
ALTER TABLE [dbo].[REParameterCache] ADD CONSTRAINT [DF__REParamet__Param__2F59DF16] DEFAULT ('') FOR [Parameters]; GO
ALTER TABLE [dbo].[REParameterCache] ADD CONSTRAINT [DF__REParamet__Creat__304E034F] DEFAULT (getdate()) FOR [CreatedAt]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REParameterCrosswalk ------------------
---------------------------------------------
CREATE TABLE [dbo].[REParameterCrosswalk] (
    [ParameterCrosswalkGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [StructureGUID] uniqueidentifier NOT NULL,
    [IsExpanding] bit NOT NULL,
    [IsScore] bit NOT NULL,
    PRIMARY KEY ([ParameterCrosswalkGUID])
);
GO
ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_IsExpanding] DEFAULT ((0)) FOR [IsExpanding]; GO
ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_ParameterCrosswalkGUID] DEFAULT (newid()) FOR [ParameterCrosswalkGUID]; GO
ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_StructureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO
ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_IsScore] DEFAULT ((0)) FOR [IsScore]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REParameterSet ------------------
---------------------------------------------
CREATE TABLE [dbo].[REParameterSet] (
    [ParameterSetGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [IsEditable] bit NOT NULL,
    [IsRecombiningAfterExpand] bit NOT NULL,
    [IsSchedulable] bit NOT NULL,
    PRIMARY KEY ([ParameterSetGUID])
);
GO
ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_IsPermanent] DEFAULT ((0)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_IsExpanding] DEFAULT ((0)) FOR [IsRecombiningAfterExpand]; GO
ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_IsScheduleable] DEFAULT ((0)) FOR [IsSchedulable]; GO
ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REParameterSetParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[REParameterSetParameter] (
    [ParameterSetParameterGUID] uniqueidentifier NOT NULL,
    [ParameterSetGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [ParameterValueXML] nvarchar(max) NOT NULL,
    [SourceID] nvarchar(100) NOT NULL,
    [ParameterValueAQN] nvarchar(400) NOT NULL,
    PRIMARY KEY ([ParameterSetParameterGUID])
);
GO
ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [FK_REParameterSetParameter_REParameterSet] FOREIGN KEY ([ParameterSetGUID]) REFERENCES [dbo].[REParameterSet] ([ParameterSetGUID]); GO
ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF__REParamet__Sourc__18CF7C5B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceID]; GO
ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF__REParamet__Param__3CA2C87D] DEFAULT ('') FOR [ParameterValueAQN]; GO
ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_ParameterSetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParameterSetGUID]; GO
ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_DimensionGUID_1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_ParameterSetParameterGUID] DEFAULT (newid()) FOR [ParameterSetParameterGUID]; GO
ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_DimensionGUID] DEFAULT ('') FOR [ParameterValueXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REParameterValue ------------------
---------------------------------------------
CREATE TABLE [dbo].[REParameterValue] (
    [ParameterValueGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ParameterValueXML] nvarchar(max) NOT NULL,
    [AssemblyQualifiedName] nvarchar(450) NOT NULL,
    PRIMARY KEY ([ParameterValueGUID])
);
GO
ALTER TABLE [dbo].[REParameterValue] ADD CONSTRAINT [FK_REParameterValue_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.REPatientPopulationLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[REPatientPopulationLink] (
    [ReportGUID] uniqueidentifier NOT NULL,
    [PatientPopulationID] int NOT NULL
);

CREATE UNIQUE NONCLUSTERED INDEX [UC_ReportPatientPopulation] ON [dbo].[REPatientPopulationLink] ([ReportGUID], [PatientPopulationID]);
GO
ALTER TABLE [dbo].[REPatientPopulationLink] ADD CONSTRAINT [FK__REPatient__Patie__1E01D6BC] FOREIGN KEY ([PatientPopulationID]) REFERENCES [dss].[DimClinicalIndicator] ([ClinicalIndicatorID]); GO
ALTER TABLE [dbo].[REPatientPopulationLink] ADD CONSTRAINT [FK__REPatient__Repor__1C198E4A] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[REPatientPopulationLink] ADD CONSTRAINT [DF__REPatient__Repor__1B256A11] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REPatientPopulationLink] ADD CONSTRAINT [DF__REPatient__Patie__1D0DB283] DEFAULT ((0)) FOR [PatientPopulationID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REPlanHackParameterValue ------------------
---------------------------------------------
CREATE TABLE [dbo].[REPlanHackParameterValue] (
    [ParameterValueGUID] uniqueidentifier NOT NULL,
    [ParameterGUID] uniqueidentifier NOT NULL,
    [PlanGUIDs] nvarchar(max) NOT NULL,
    [EntityViewGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ParameterValueGUID])
);
GO
ALTER TABLE [dbo].[REPlanHackParameterValue] ADD CONSTRAINT [DF_REPlanHackParameterValue_ParameterValueGUID] DEFAULT (newid()) FOR [ParameterValueGUID]; GO
ALTER TABLE [dbo].[REPlanHackParameterValue] ADD CONSTRAINT [DF_REPlanHackParameterValue_ParameterGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParameterGUID]; GO
ALTER TABLE [dbo].[REPlanHackParameterValue] ADD CONSTRAINT [DF_REPlanHackParameterValue_PlanGUIDs] DEFAULT ('') FOR [PlanGUIDs]; GO
ALTER TABLE [dbo].[REPlanHackParameterValue] ADD CONSTRAINT [DF_REPlanHackParameterValue_EntityViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityViewGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REQueryParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[REQueryParameter] (
    [ParameterGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [QueryString] nvarchar(max) NOT NULL,
    PRIMARY KEY ([ParameterGUID])
);
GO
ALTER TABLE [dbo].[REQueryParameter] ADD CONSTRAINT [FK_REQueryParameter_REDataSource] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.REReport ------------------
---------------------------------------------
CREATE TABLE [dbo].[REReport] (
    [ReportGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [AssemblyQualifiedName] nvarchar(450) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [IsBuiltIn] bit NOT NULL,
    [IsScheduleable] bit NOT NULL,
    [IsDesktopEmbeddable] bit NOT NULL,
    [IsPlanEmbeddable] bit NOT NULL,
    [IsExecReportEmbeddable] bit NOT NULL,
    [IsDirectoryReportable] bit NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [ReportXML] nvarchar(max) NOT NULL,
    [IsUserDeletable] bit NOT NULL,
    [ImageName] nvarchar(450) NOT NULL,
    [DateLastModified] datetime NOT NULL,
    [IsCacheable] bit NOT NULL,
    [IsCachedPerUser] bit NOT NULL,
    [IsBatchReport] bit NOT NULL,
    [ReportDetailsXML] nvarchar(max) NOT NULL,
    [IsBatchProcessable] bit NOT NULL,
    [IsUsingDefaultTime] bit NOT NULL,
    [AuthorUserGUID] uniqueidentifier NOT NULL,
    [ConsolidatedItemsCSV] nvarchar(max) NOT NULL,
    [ExpandedParametersCSV] nvarchar(max) NOT NULL,
    [IsUsingZeroViewer] bit NOT NULL,
    [IsRecombiningAfterExpand] bit NOT NULL,
    [IsDataSource] bit NOT NULL,
    [IsUsingPlanAttributes] bit NOT NULL,
    [GlobalID] nvarchar(50) NOT NULL,
    [IsERMacroEnabled] bit NOT NULL,
    [IsAutoSizeRows] bit NOT NULL,
    [DateAccessed] datetime NOT NULL,
    [ScheduledTaskGUID] uniqueidentifier NOT NULL,
    [LastRunDuration] int NOT NULL,
    [LastRunRowCount] int NOT NULL,
    [SourceReportGuid] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(256) NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    [IsPublished] bit NOT NULL,
    [StrataSphereReportGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ReportGUID])
);
GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REREPORTTEMP_REPORTGUID] DEFAULT (newid()) FOR [ReportGUID]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REREPORTTEMP_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REREPORTTEMP_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISBUILTIN] DEFAULT ((0)) FOR [IsBuiltIn]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISSCHEDULEABLE] DEFAULT ((0)) FOR [IsScheduleable]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISDESKTOPEMBEDDABLE] DEFAULT ((0)) FOR [IsDesktopEmbeddable]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__Author__0A7E933C] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISPLANEMBEDDABLE] DEFAULT ((0)) FOR [IsPlanEmbeddable]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISEXECREPORTEMBEDDABLE] DEFAULT ((0)) FOR [IsExecReportEmbeddable]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISDIRECTORYREPORTABLE] DEFAULT ((0)) FOR [IsDirectoryReportable]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REREPORTTEMP_REPORTXML] DEFAULT ('') FOR [ReportXML]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_ISUSERDELETABLE] DEFAULT ((1)) FOR [IsUserDeletable]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IMAGENAME] DEFAULT ('') FOR [ImageName]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_DateLastModified] DEFAULT (getdate()) FOR [DateLastModified]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsCacheable] DEFAULT ((0)) FOR [IsCacheable]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsCachedPerUser] DEFAULT ((1)) FOR [IsCachedPerUser]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsBatchReport] DEFAULT ((0)) FOR [IsBatchReport]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsUsingZeroViewer] DEFAULT ((0)) FOR [IsUsingZeroViewer]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsRecombiningAfterExpand] DEFAULT ((0)) FOR [IsRecombiningAfterExpand]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__Module__1CD64654] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__LastRu__269488EE] DEFAULT ((0)) FOR [LastRunDuration]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__LastRu__2788AD27] DEFAULT ((0)) FOR [LastRunRowCount]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__IsPubl__2ABA5157] DEFAULT ((0)) FOR [IsPublished]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__DateAc__3120CB42] DEFAULT (getdate()) FOR [DateAccessed]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsBatchProcessable] DEFAULT ((0)) FOR [IsBatchProcessable]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsUsingDefaultTime] DEFAULT ((0)) FOR [IsUsingDefaultTime]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsDataSource] DEFAULT ((0)) FOR [IsDataSource]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsUsingPlanAttributes] DEFAULT ((0)) FOR [IsUsingPlanAttributes]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__Schedu__429A3411] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScheduledTaskGUID]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_AuthorUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorUserGUID]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_ConsolidatedItems] DEFAULT ('') FOR [ConsolidatedItemsCSV]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_ExpandedParameters] DEFAULT ('') FOR [ExpandedParametersCSV]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__IsERMa__5937E11C] DEFAULT ((0)) FOR [IsERMacroEnabled]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_GlobalID] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_StrataSphereReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StrataSphereReportGUID]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_ReportDetailsXML] DEFAULT ('') FOR [ReportDetailsXML]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__Source__76114D24] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceReportGuid]; GO
ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__IsAuto__7B71C199] DEFAULT ((0)) FOR [IsAutoSizeRows]; GO

---------------------------------------------

---------------------------------------------
-- dbo.REReportCustomActionLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[REReportCustomActionLink] (
    [REReportCustomActionLink] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [ActionGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([REReportCustomActionLink])
);
GO
ALTER TABLE [dbo].[REReportCustomActionLink] ADD CONSTRAINT [FK_REReportCustomActionLink_CustomAction] FOREIGN KEY ([ActionGUID]) REFERENCES [dbo].[CustomAction] ([ActionGUID]); GO
ALTER TABLE [dbo].[REReportCustomActionLink] ADD CONSTRAINT [FK_REReportCustomActionLink_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.RESQLReportDisplayColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESQLReportDisplayColumn] (
    [DisplayColumnGUID] uniqueidentifier NOT NULL,
    [SQLReportSetupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [DrillDownParentColumnGUID] uniqueidentifier NOT NULL,
    [IsDrillDown] bit NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ColumnWidth] int NOT NULL,
    [AggregateFunction] int NOT NULL,
    [FormatString] nvarchar(64) NOT NULL,
    [ColumnName] nvarchar(64) NOT NULL,
    [IsConsolidatable] bit NOT NULL,
    [IsConsolidated] bit NOT NULL,
    [SimpleDataType] int NOT NULL,
    [LayoutType] int NOT NULL,
    [SortOrder] int NOT NULL,
    [IsAutoWidth] bit NOT NULL,
    PRIMARY KEY ([DisplayColumnGUID])
);
GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [FK_RESQLReportDisplayColumn_RESQLReportSetup] FOREIGN KEY ([SQLReportSetupGUID]) REFERENCES [dbo].[RESQLReportSetup] ([SQLReportSetupGUID]); GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_SortOrder] DEFAULT ((-1)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_DisplayColumnGUID] DEFAULT (newid()) FOR [DisplayColumnGUID]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_IsAutoWidth] DEFAULT ((0)) FOR [IsAutoWidth]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_SQLReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SQLReportSetupGUID]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_DrillDownParentColumnGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DrillDownParentColumnGUID]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_IsDrillDown] DEFAULT ((0)) FOR [IsDrillDown]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_ColumnWidth] DEFAULT ((150)) FOR [ColumnWidth]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_AggregateFunction] DEFAULT ((0)) FOR [AggregateFunction]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_FormatString] DEFAULT ('') FOR [FormatString]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_ColumnName] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_IsConsolidtable] DEFAULT ((0)) FOR [IsConsolidatable]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_IsConsolidated] DEFAULT ((0)) FOR [IsConsolidated]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_SimpleDataType] DEFAULT ((0)) FOR [SimpleDataType]; GO
ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_LayoutType] DEFAULT ((0)) FOR [LayoutType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RESQLReportFilterColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESQLReportFilterColumn] (
    [FilterColumnGUID] uniqueidentifier NOT NULL,
    [SQLReportSetupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [ColumnName] nvarchar(64) NOT NULL,
    [ColumnSourceGUID] uniqueidentifier NOT NULL,
    [DataViewColumnType] int NOT NULL,
    [IsUserEditable] bit NOT NULL,
    [SimpleDataType] int NOT NULL,
    [ParameterXML] nvarchar(max) NOT NULL,
    [IsSQLOperatorEditable] bit NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([FilterColumnGUID])
);
GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [FK_RESQLReportFilterColumn_RESQLReportSetup] FOREIGN KEY ([SQLReportSetupGUID]) REFERENCES [dbo].[RESQLReportSetup] ([SQLReportSetupGUID]); GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_FilterColumnGUID] DEFAULT (newid()) FOR [FilterColumnGUID]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_SQLReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SQLReportSetupGUID]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_ColumnName] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_ColumnSourceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ColumnSourceGUID]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_DataViewColumnType] DEFAULT ((0)) FOR [DataViewColumnType]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_IsUserEditable] DEFAULT ((0)) FOR [IsUserEditable]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_SimpleDataType] DEFAULT ((0)) FOR [SimpleDataType]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_ParameterXML] DEFAULT ('') FOR [ParameterXML]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_IsSQLOperatorEditable] DEFAULT ((1)) FOR [IsSQLOperatorEditable]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RESQLReportPivotColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESQLReportPivotColumn] (
    [PivotColumnGUID] uniqueidentifier NOT NULL,
    [SQLReportSetupGUID] uniqueidentifier NOT NULL,
    [ValueColumnName] nvarchar(64) NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([PivotColumnGUID])
);
GO
ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [FK_RESQLReportPivotColumn_RESQLReportSetup] FOREIGN KEY ([SQLReportSetupGUID]) REFERENCES [dbo].[RESQLReportSetup] ([SQLReportSetupGUID]); GO
ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [DF_RESQLReportPivotColumn_PivotColumnGUID] DEFAULT (newid()) FOR [PivotColumnGUID]; GO
ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [DF_RESQLReportPivotColumn_ValueColumnName] DEFAULT ('') FOR [ValueColumnName]; GO
ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [DF_RESQLReportPivotColumn_DisplayOrder] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [DF_RESQLReportPivotColumn_SQLReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SQLReportSetupGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RESQLReportPivotColumnFilter ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESQLReportPivotColumnFilter] (
    [PivotColumnFilterGUID] uniqueidentifier NOT NULL,
    [PivotColumnGUID] uniqueidentifier NOT NULL,
    [ColumnName] nvarchar(64) NOT NULL,
    [ColumnValue] nvarchar(400) NOT NULL,
    [SimpleDataType] int NOT NULL,
    PRIMARY KEY ([PivotColumnFilterGUID])
);
GO
ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [FK_RESQLReportPivotColumnFilter_RESQLReportPivotColumn] FOREIGN KEY ([PivotColumnGUID]) REFERENCES [dbo].[RESQLReportPivotColumn] ([PivotColumnGUID]); GO
ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_PivotColumnFilterGUID] DEFAULT (newid()) FOR [PivotColumnFilterGUID]; GO
ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_ColumnName] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_Value] DEFAULT ('') FOR [ColumnValue]; GO
ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_SimpleDataType] DEFAULT ((0)) FOR [SimpleDataType]; GO
ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_PivotColumnGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PivotColumnGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RESQLReportRegisteredAttribute ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESQLReportRegisteredAttribute] (
    [RegisteredAttributeGUID] uniqueidentifier NOT NULL,
    [RegisteredDimensionGUID] uniqueidentifier NOT NULL,
    [AttributeGUID] uniqueidentifier NOT NULL,
    [ColumnAlias] nvarchar(100) NOT NULL,
    PRIMARY KEY ([RegisteredAttributeGUID])
);
GO
ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [FK_RESQLReportRegisteredAttribute_RESQLReportRegisteredDimension] FOREIGN KEY ([RegisteredDimensionGUID]) REFERENCES [dbo].[RESQLReportRegisteredDimension] ([RegisteredDimensionGUID]); GO
ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [DF_RESQLReportRegisteredDimensionAttribute_SQLReportRegisteredDimensionAttributeGUID] DEFAULT (newid()) FOR [RegisteredAttributeGUID]; GO
ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [DF_RESQLReportRegisteredAttribute_AliasedColumnName] DEFAULT ('') FOR [ColumnAlias]; GO
ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [DF_RESQLReportRegisteredDimensionAttribute_SQLReportRegisteredDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RegisteredDimensionGUID]; GO
ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [DF_RESQLReportRegisteredDimensionAttribute_AttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AttributeGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RESQLReportRegisteredDimension ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESQLReportRegisteredDimension] (
    [RegisteredDimensionGUID] uniqueidentifier NOT NULL,
    [DataViewGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [HierarchyGUID] uniqueidentifier NOT NULL,
    [SQLColumnNames] nvarchar(max) NOT NULL,
    [KeyColumnName] nvarchar(64) NOT NULL,
    [KeyGUID] uniqueidentifier NOT NULL,
    [IsKeyColumnVisible] bit NOT NULL,
    [KeyJoinType] int NOT NULL,
    [IsSecured] bit NOT NULL,
    PRIMARY KEY ([RegisteredDimensionGUID])
);
GO
ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [FK_RESQLReportRegisteredDimension_DataView] FOREIGN KEY ([DataViewGUID]) REFERENCES [dbo].[DataView] ([DataViewGUID]); GO
ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_IsKeyColumnVisible] DEFAULT ((1)) FOR [IsKeyColumnVisible]; GO
ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_KeyJoinType] DEFAULT ((0)) FOR [KeyJoinType]; GO
ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_IsSecured] DEFAULT ((0)) FOR [IsSecured]; GO
ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_HierarchyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HierarchyGUID]; GO
ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_RegisteredDimensionGUID] DEFAULT (newid()) FOR [RegisteredDimensionGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RESQLReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESQLReportSetup] (
    [SQLReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [DataViewGUID] uniqueidentifier NOT NULL,
    [IsAutoRefresh] bit NOT NULL,
    [IsAutoPivotColumn] bit NOT NULL,
    [TableStyleName] nvarchar(64) NOT NULL,
    [IsAutoColumnWidth] bit NOT NULL,
    [LaunchOption] int NOT NULL,
    [IsShowingTotals] bit NOT NULL,
    [TopRowCount] int NOT NULL,
    [IsGroupBy] bit NOT NULL,
    [IsSecurityHashJoin] bit NOT NULL,
    PRIMARY KEY ([SQLReportSetupGUID])
);
GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [FK_RESQLReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsSecurityHashJoin] DEFAULT ((0)) FOR [IsSecurityHashJoin]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsGroupBy] DEFAULT ((1)) FOR [IsGroupBy]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLTableReportSetup_SQLReportSetupGUID] DEFAULT (newid()) FOR [SQLReportSetupGUID]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLTableReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLTableReportSetup_DataViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataViewGUID]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsAutoRefresh] DEFAULT ((0)) FOR [IsAutoRefresh]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsAutoPivotColumn] DEFAULT ((1)) FOR [IsAutoPivotColumn]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_TableStyle] DEFAULT ('Blue') FOR [TableStyleName]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsAutoColumnWidth] DEFAULT ((1)) FOR [IsAutoColumnWidth]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_LaunchOption] DEFAULT ((0)) FOR [LaunchOption]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsShowingTotals] DEFAULT ((0)) FOR [IsShowingTotals]; GO
ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_TopRowCount] DEFAULT ((100)) FOR [TopRowCount]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RESRReportFile ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESRReportFile] (
    [SRReportFileGUID] uniqueidentifier NOT NULL,
    [SRReportSetupGUID] uniqueidentifier NOT NULL,
    [FileContent] nvarchar(max) NOT NULL,
    PRIMARY KEY ([SRReportFileGUID])
);
GO
ALTER TABLE [dbo].[RESRReportFile] ADD CONSTRAINT [FK_RESRReportFile_RESRReportSetup] FOREIGN KEY ([SRReportSetupGUID]) REFERENCES [dbo].[RESRReportSetup] ([SRReportSetupGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.RESRReportSetup ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESRReportSetup] (
    [SRReportSetupGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SRReportSetupGUID])
);
GO
ALTER TABLE [dbo].[RESRReportSetup] ADD CONSTRAINT [FK_RESRReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.RESelector ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESelector] (
    [ID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Value] int NOT NULL,
    [Type] nvarchar(64) NOT NULL,
    [VERSION] timestamp NOT NULL
);
GO
ALTER TABLE [dbo].[RESelector] ADD CONSTRAINT [DF_REBooleanSelector_ID] DEFAULT (newid()) FOR [ID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RESheetConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESheetConfig] (
    [SheetGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SheetGUID])
);
GO
ALTER TABLE [dbo].[RESheetConfig] ADD CONSTRAINT [FK_RESheetConfig_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.RESortingParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[RESortingParameter] (
    [ParameterGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ColumnName] nvarchar(450) NOT NULL,
    [Direction] bit NOT NULL,
    [SortOrder] int NOT NULL,
    PRIMARY KEY ([ParameterGUID])
);
GO
ALTER TABLE [dbo].[RESortingParameter] ADD CONSTRAINT [FK_RESortingParameter_REDataSource1] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.RETemplateColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[RETemplateColumn] (
    [RETemplateColumnGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ColumnName] varchar(512) NOT NULL,
    [ColumnType] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([RETemplateColumnGUID])
);
GO
ALTER TABLE [dbo].[RETemplateColumn] ADD CONSTRAINT [FK__RETemplat__DataS__1B6C8B71] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO
ALTER TABLE [dbo].[RETemplateColumn] ADD CONSTRAINT [DF__RETemplat__Colum__198442FF] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[RETemplateColumn] ADD CONSTRAINT [DF__RETemplat__Colum__1A786738] DEFAULT ((0)) FOR [ColumnType]; GO
ALTER TABLE [dbo].[RETemplateColumn] ADD CONSTRAINT [DF__RETemplat__Displ__1B6C8B71] DEFAULT ((0)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RETemplateMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[RETemplateMeasure] (
    [RETemplateMeasureGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [ColumnName] varchar(512) NOT NULL,
    [ColumnType] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([RETemplateMeasureGUID])
);
GO
ALTER TABLE [dbo].[RETemplateMeasure] ADD CONSTRAINT [FK__RETemplat__DataS__230DAD39] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO
ALTER TABLE [dbo].[RETemplateMeasure] ADD CONSTRAINT [DF__RETemplat__Colum__212564C7] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[RETemplateMeasure] ADD CONSTRAINT [DF__RETemplat__Colum__22198900] DEFAULT ((0)) FOR [ColumnType]; GO
ALTER TABLE [dbo].[RETemplateMeasure] ADD CONSTRAINT [DF__RETemplat__Displ__230DAD39] DEFAULT ((0)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ReasonableURL ------------------
---------------------------------------------
CREATE TABLE [dbo].[ReasonableURL] (
    [ReasonableURLGUID] uniqueidentifier NOT NULL,
    [URL] nvarchar(max) NOT NULL,
    [CreatedDate] datetime NOT NULL,
    [LastUsedDate] datetime NOT NULL,
    [UseCount] int NOT NULL,
    PRIMARY KEY ([ReasonableURLGUID])
);
GO
ALTER TABLE [dbo].[ReasonableURL] ADD CONSTRAINT [DF_ReasonableURL_ReasonableURLGUID] DEFAULT (newsequentialid()) FOR [ReasonableURLGUID]; GO
ALTER TABLE [dbo].[ReasonableURL] ADD CONSTRAINT [DF_ReasonableURL_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate]; GO
ALTER TABLE [dbo].[ReasonableURL] ADD CONSTRAINT [DF_ReasonableURL_LastUsedDate] DEFAULT (getdate()) FOR [LastUsedDate]; GO
ALTER TABLE [dbo].[ReasonableURL] ADD CONSTRAINT [DF_ReasonableURL_UseCount] DEFAULT ((0)) FOR [UseCount]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RefreshViewsLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[RefreshViewsLog] (
    [RowID] int NOT NULL,
    [BrokenViewName] nvarchar(450) NOT NULL,
    [BrokenViewDropSQL] nvarchar(450) NOT NULL,
    [BrokenViewSelectSQL] nvarchar(450) NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[RefreshViewsLog] ADD CONSTRAINT [DF_RefreshViewsLog_BrokenViewName] DEFAULT ('') FOR [BrokenViewName]; GO
ALTER TABLE [dbo].[RefreshViewsLog] ADD CONSTRAINT [DF_RefreshViewsLog_BrokenViewDropSQL] DEFAULT ('') FOR [BrokenViewDropSQL]; GO
ALTER TABLE [dbo].[RefreshViewsLog] ADD CONSTRAINT [DF_RefreshViewsLog_BrokenViewSelectSQL] DEFAULT ('') FOR [BrokenViewSelectSQL]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ReplicationTable ------------------
---------------------------------------------
CREATE TABLE [dbo].[ReplicationTable] (
    [TableName] nvarchar(200) NOT NULL,
    [LastRefreshDateTimeUtc] datetime NULL,
    [LastRefreshChangeTrackingVersion] bigint NULL,
    [ReplicationFrequencyCron] varchar(100) NOT NULL,
    [IsDisabled] bit NOT NULL,
    [SelectFromQuery] nvarchar(200) NOT NULL,
    [LastChangeDateTimeUtc] datetime NULL,
    [HangfireQueue] nvarchar(200) NOT NULL,
    [BeginChangeTrackingVersion] bigint NOT NULL,
    [NumParallelBatches] int NOT NULL,
    [ColumnDataJSON] nvarchar(max) NOT NULL,
    PRIMARY KEY ([TableName])
);
GO
ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Repli__0582D584] DEFAULT ('*/5 * * * *') FOR [ReplicationFrequencyCron]; GO
ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__IsDis__0676F9BD] DEFAULT ((0)) FOR [IsDisabled]; GO
ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Begin__0F02E974] DEFAULT ((0)) FOR [BeginChangeTrackingVersion]; GO
ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__NumPa__0FF70DAD] DEFAULT ((1)) FOR [NumParallelBatches]; GO
ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Selec__16AD6186] DEFAULT ('') FOR [SelectFromQuery]; GO
ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Hangf__4104595C] DEFAULT ('default') FOR [HangfireQueue]; GO
ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Colum__65634C11] DEFAULT ('[]') FOR [ColumnDataJSON]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ReplicationTableHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[ReplicationTableHistory] (
    [RowID] bigint NOT NULL,
    [ReplicationTableName] nvarchar(200) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [Description] nvarchar(1000) NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[ReplicationTableHistory] ADD CONSTRAINT [DF__Replicati__DateT__5DAAB9AB] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[ReplicationTableHistory] ADD CONSTRAINT [DF__Replicati__Descr__5E9EDDE4] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ReplicationTableTrackingTable ------------------
---------------------------------------------
CREATE TABLE [dbo].[ReplicationTableTrackingTable] (
    [BaseTableName] nvarchar(200) NOT NULL,
    [TableName] nvarchar(200) NOT NULL,
    [LastRefreshChangeTrackingVersion] bigint NULL,
    PRIMARY KEY ([BaseTableName], [TableName])
);
GO
ALTER TABLE [dbo].[ReplicationTableTrackingTable] ADD CONSTRAINT [FK__Replicati__BaseT__00540C13] FOREIGN KEY ([BaseTableName]) REFERENCES [dbo].[ReplicationTable] ([TableName]); GO

---------------------------------------------

---------------------------------------------
-- dbo.ReportArchiveEntry ------------------
---------------------------------------------
CREATE TABLE [dbo].[ReportArchiveEntry] (
    [ReportArchiveEntryGUID] uniqueidentifier NOT NULL,
    [ReportArchivePath] nvarchar(1000) NOT NULL,
    [ReportArchiveType] int NOT NULL,
    [ReportArchiveDate] datetime NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [UserName] nvarchar(128) NOT NULL,
    [DateArchivedUtc] datetime NOT NULL,
    [NotificationMessageGUID] uniqueidentifier NOT NULL,
    [IsS3] bit NOT NULL,
    PRIMARY KEY ([ReportArchiveEntryGUID])
);
GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Repor__030D1E07] DEFAULT (getdate()) FOR [ReportArchiveDate]; GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArch__IsS3__0D9B5A9D] DEFAULT ((0)) FOR [IsS3]; GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__DateA__369A42D4] DEFAULT (getutcdate()) FOR [DateArchivedUtc]; GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Notif__42C34FF3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [NotificationMessageGUID]; GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__UserG__4FE27FBC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__UserN__50D6A3F5] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Repor__779B6B5B] DEFAULT (newid()) FOR [ReportArchiveEntryGUID]; GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Repor__788F8F94] DEFAULT ('') FOR [ReportArchivePath]; GO
ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Repor__7983B3CD] DEFAULT ((0)) FOR [ReportArchiveType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ReportArchiveEntryDetail ------------------
---------------------------------------------
CREATE TABLE [dbo].[ReportArchiveEntryDetail] (
    [ReportArchiveEntryDetailGUID] uniqueidentifier NOT NULL,
    [ReportArchiveEntryGUID] uniqueidentifier NOT NULL,
    [ReportArchiveDetailAQN] nvarchar(400) NOT NULL,
    [ReportArchiveDetailXML] xml NOT NULL,
    PRIMARY KEY ([ReportArchiveEntryDetailGUID])
);
GO
ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [FK__ReportArc__Repor__7F3C8D23] FOREIGN KEY ([ReportArchiveEntryGUID]) REFERENCES [dbo].[ReportArchiveEntry] ([ReportArchiveEntryGUID]); GO
ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [DF__ReportArc__Repor__0030B15C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportArchiveEntryGUID]; GO
ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [DF__ReportArc__Repor__0124D595] DEFAULT ('') FOR [ReportArchiveDetailAQN]; GO
ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [DF__ReportArc__Repor__0218F9CE] DEFAULT ('') FOR [ReportArchiveDetailXML]; GO
ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [DF__ReportArc__Repor__7E4868EA] DEFAULT (newid()) FOR [ReportArchiveEntryDetailGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RoleAssignmentAutomationHistoryLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[RoleAssignmentAutomationHistoryLog] (
    [RoleAssignmentAutomationHistoryLogGuid] uniqueidentifier NOT NULL,
    [ImportDate] datetime NOT NULL,
    [Status] varchar(7) NOT NULL,
    [ImportedRowCount] int NOT NULL,
    [NewAssignments] int NOT NULL,
    [RemovedAssignments] int NOT NULL,
    [InvalidAssignments] int NOT NULL,
    PRIMARY KEY ([RoleAssignmentAutomationHistoryLogGuid])
);
GO
ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__RoleA__23E03B04] DEFAULT (newid()) FOR [RoleAssignmentAutomationHistoryLogGuid]; GO
ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__Impor__24D45F3D] DEFAULT ((0)) FOR [ImportedRowCount]; GO
ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__NewAs__25C88376] DEFAULT ((0)) FOR [NewAssignments]; GO
ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__Remov__26BCA7AF] DEFAULT ((0)) FOR [RemovedAssignments]; GO
ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__Inval__27B0CBE8] DEFAULT ((0)) FOR [InvalidAssignments]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RoleVisibilityRule ------------------
---------------------------------------------
CREATE TABLE [dbo].[RoleVisibilityRule] (
    [RoleVisibilityRuleGUID] uniqueidentifier NOT NULL,
    [PermissionSetID] tinyint NOT NULL,
    [RoleID] smallint NOT NULL,
    [UserGroupGUID] uniqueidentifier NOT NULL,
    [IsVisible] bit NOT NULL,
    PRIMARY KEY ([RoleVisibilityRuleGUID])
);
GO
ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__RoleV__2567FB65] DEFAULT (newid()) FOR [RoleVisibilityRuleGUID]; GO
ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__Permi__265C1F9E] DEFAULT ((0)) FOR [PermissionSetID]; GO
ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__RoleI__275043D7] DEFAULT ((0)) FOR [RoleID]; GO
ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__IsVis__29388C49] DEFAULT ((1)) FOR [IsVisible]; GO
ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__UserG__28446810] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGroupGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RuleAction ------------------
---------------------------------------------
CREATE TABLE [dbo].[RuleAction] (
    [RuleActionGUID] uniqueidentifier NOT NULL,
    [RuleSetGUID] uniqueidentifier NOT NULL,
    [ExecutionOrder] int NOT NULL,
    [RuleActionTypeAQN] nvarchar(450) NOT NULL,
    [RuleActionTypeConfigXML] xml NOT NULL,
    PRIMARY KEY ([RuleActionGUID])
);

CREATE XML INDEX [es19833_RuleActionTypeConfigXML] ON [dbo].[RuleAction] ([RuleActionTypeConfigXML]);
GO
ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [FK_RuleAction_RuleSet] FOREIGN KEY ([RuleSetGUID]) REFERENCES [dbo].[RuleSet] ([RuleSetGUID]); GO
ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_RuleActionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleActionGUID]; GO
ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_RuleSetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleSetGUID]; GO
ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO
ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_RuleActionTypeAQN] DEFAULT ('') FOR [RuleActionTypeAQN]; GO
ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_RuleActionTypeConfigXML] DEFAULT ('') FOR [RuleActionTypeConfigXML]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RuleGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[RuleGroup] (
    [RuleGroupGUID] uniqueidentifier NOT NULL,
    [RuleSetGUID] uniqueidentifier NOT NULL,
    [GroupType] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    [ParentRuleGroupGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RuleGroupGUID])
);
GO
ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [FK_RuleGroup_RuleSet] FOREIGN KEY ([RuleSetGUID]) REFERENCES [dbo].[RuleSet] ([RuleSetGUID]); GO
ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_RuleGroup_RuleGroupGUID] DEFAULT (newid()) FOR [RuleGroupGUID]; GO
ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_Table_1_Type] DEFAULT ((0)) FOR [GroupType]; GO
ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_RuleGroup_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_RuleGroup_RuleSetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleSetGUID]; GO
ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_RuleGroup_ParentRuleGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentRuleGroupGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RuleItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[RuleItem] (
    [RuleGUID] uniqueidentifier NOT NULL,
    [RuleGroupGUID] uniqueidentifier NOT NULL,
    [RuleTypeAQN] nvarchar(450) NOT NULL,
    [RuleTypeConfigXML] xml NOT NULL,
    [DisplayOrder] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    PRIMARY KEY ([RuleGUID])
);

CREATE NONCLUSTERED INDEX [NC_RuleItem_RuleGroupGUID] ON [dbo].[RuleItem] ([RuleGroupGUID]) INCLUDE ([RuleTypeConfigXML]);
GO
ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [FK_Rule_RuleGroup] FOREIGN KEY ([RuleGroupGUID]) REFERENCES [dbo].[RuleGroup] ([RuleGroupGUID]); GO
ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_RuleGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleGUID]; GO
ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_RuleTypeAQN] DEFAULT ('') FOR [RuleTypeAQN]; GO
ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_RuleTypeConfigXML] DEFAULT ('') FOR [RuleTypeConfigXML]; GO
ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_RuleGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleGroupGUID]; GO
ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF__RuleItem__Name__54D0BCAD] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.RuleSet ------------------
---------------------------------------------
CREATE TABLE [dbo].[RuleSet] (
    [RuleSetGUID] uniqueidentifier NOT NULL,
    [Category] nvarchar(100) NOT NULL,
    [ExecutionOrder] int NOT NULL,
    [RootRuleGroupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Description] nvarchar(800) NOT NULL,
    [RuleSetID] int NOT NULL,
    [Tag] nvarchar(100) NOT NULL,
    [MetadataXML] nvarchar(max) NOT NULL,
    [MetadataAssemblyQualifiedName] nvarchar(400) NOT NULL,
    PRIMARY KEY ([RuleSetGUID])
);

CREATE NONCLUSTERED INDEX [NC_RuleSet_Category] ON [dbo].[RuleSet] ([Category]);
CREATE NONCLUSTERED INDEX [NC_RS_RuleSetID_Category] ON [dbo].[RuleSet] ([RuleSetID]) INCLUDE ([Category]);
GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF_RuleSet_RuleSetGUID] DEFAULT (newid()) FOR [RuleSetGUID]; GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF_RuleSet_Category] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF_RuleSet_ExecutionOrder] DEFAULT ((-1)) FOR [ExecutionOrder]; GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Name__3ABA800B] DEFAULT ('Term') FOR [Name]; GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Discrip__3BAEA444] DEFAULT ('New Term') FOR [Description]; GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF_RuleSet_RootRuleGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RootRuleGroupGUID]; GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Tag__787A1D67] DEFAULT ('') FOR [Tag]; GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Metadat__7E32F6BD] DEFAULT ('') FOR [MetadataXML]; GO
ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Metadat__7F271AF6] DEFAULT ('') FOR [MetadataAssemblyQualifiedName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.S3AutomationNotification ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3AutomationNotification] (
    [SecurityAutomationNotificationGUID] uniqueidentifier NOT NULL,
    [RecipientGuid] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SecurityAutomationNotificationGUID])
);
GO
ALTER TABLE [dbo].[S3AutomationNotification] ADD CONSTRAINT [DF__SecurityA__Secur__378675A7] DEFAULT (newid()) FOR [SecurityAutomationNotificationGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.S3AutomationRole ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3AutomationRole] (
    [SecurityAutomationRoleGUID] uniqueidentifier NOT NULL,
    [UserRoleGUID] uniqueidentifier NOT NULL,
    [ColumnName] nvarchar(100) NOT NULL,
    PRIMARY KEY ([SecurityAutomationRoleGUID])
);
GO
ALTER TABLE [dbo].[S3AutomationRole] ADD CONSTRAINT [FK_SecurityAutomationRole_UserRoleGUID] FOREIGN KEY ([UserRoleGUID]) REFERENCES [dbo].[UserRole] ([UserRoleGUID]); GO
ALTER TABLE [dbo].[S3AutomationRole] ADD CONSTRAINT [DF__SecurityA__Secur__3A62E252] DEFAULT (newid()) FOR [SecurityAutomationRoleGUID]; GO
ALTER TABLE [dbo].[S3AutomationRole] ADD CONSTRAINT [DF__SecurityA__Colum__3B57068B] DEFAULT ('') FOR [ColumnName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.S3IdentityLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3IdentityLink] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [Fullpath] varchar(800) NOT NULL,
    [Distance] int NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([MemberGUID], [GroupingGUID], [Fullpath])
);

CREATE NONCLUSTERED INDEX [IX_S3IdentityLink] ON [dbo].[S3IdentityLink] ([GroupingGUID], [MemberGUID]);
GO

---------------------------------------------

---------------------------------------------
-- dbo.S3Loot ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3Loot] (
    [LootID] nvarchar(128) NOT NULL,
    [PermissionSetID] smallint NOT NULL,
    [LootGroupPrefix] nvarchar(128) NULL,
    PRIMARY KEY ([LootID])
);
GO
ALTER TABLE [dbo].[S3Loot] ADD CONSTRAINT [DF_S3Loot_LootGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LootID]; GO
ALTER TABLE [dbo].[S3Loot] ADD CONSTRAINT [DF_S3Loot_PermissionSetID] DEFAULT ((0)) FOR [PermissionSetID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.S3LootGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3LootGroup] (
    [LootID] nvarchar(128) NOT NULL,
    [LootGroupID] nvarchar(128) NOT NULL,
    PRIMARY KEY ([LootID], [LootGroupID])
);

CREATE NONCLUSTERED INDEX [IX_S3LootGroup] ON [dbo].[S3LootGroup] ([LootGroupID], [LootID]);
GO

---------------------------------------------

---------------------------------------------
-- dbo.S3LootRefreshLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3LootRefreshLog] (
    [RowID] bigint NOT NULL,
    [PlanGUID] uniqueidentifier NOT NULL,
    [OldCachedLootID] nvarchar(128) NOT NULL,
    [NewCachedLootID] nvarchar(128) NOT NULL,
    [DateRefreshed] datetime NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[S3LootRefreshLog] ADD CONSTRAINT [DF_S3LootRefreshLog_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO
ALTER TABLE [dbo].[S3LootRefreshLog] ADD CONSTRAINT [DF_S3LootRefreshLog_OldCachedLootID] DEFAULT ('') FOR [OldCachedLootID]; GO
ALTER TABLE [dbo].[S3LootRefreshLog] ADD CONSTRAINT [DF_S3LootRefreshLog_NewCachedLootID] DEFAULT ('') FOR [NewCachedLootID]; GO
ALTER TABLE [dbo].[S3LootRefreshLog] ADD CONSTRAINT [DF_S3LootRefreshLog_DateRefreshed] DEFAULT (getdate()) FOR [DateRefreshed]; GO

---------------------------------------------

---------------------------------------------
-- dbo.S3Permission ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3Permission] (
    [PermissionSetID] smallint NOT NULL,
    [RoleID] smallint NOT NULL,
    [Weight] tinyint NOT NULL,
    [ReadValue] bit NULL,
    [WriteValue] bit NULL,
    [SecureValue] bit NULL,
    [CreateValue] bit NULL,
    [DeleteValue] bit NULL,
    [ReadAllowPts] decimal NOT NULL,
    [ReadDenyPts] decimal NOT NULL,
    [WriteAllowPts] decimal NOT NULL,
    [WriteDenyPts] decimal NOT NULL,
    [SecureAllowPts] decimal NOT NULL,
    [SecureDenyPts] decimal NOT NULL,
    [CreateAllowPts] decimal NOT NULL,
    [CreateDenyPts] decimal NOT NULL,
    [DeleteAllowPts] decimal NOT NULL,
    [DeleteDenyPts] decimal NOT NULL,
    PRIMARY KEY ([PermissionSetID], [RoleID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.S3PermissionSet ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3PermissionSet] (
    [PermissionSetID] smallint NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] varchar(max) NOT NULL,
    [MetaForUpgrade] varchar(max) NULL,
    [IsLocked] bit NOT NULL,
    PRIMARY KEY ([PermissionSetID])
);
GO
ALTER TABLE [dbo].[S3PermissionSet] ADD CONSTRAINT [DF_S3PermissionSet_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[S3PermissionSet] ADD CONSTRAINT [DF_S3PermissionSet_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO

---------------------------------------------

---------------------------------------------
-- dbo.S3RoleAssignment ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3RoleAssignment] (
    [RowID] int NOT NULL,
    [IdentityGUID] uniqueidentifier NOT NULL,
    [RoleID] smallint NOT NULL,
    [LootGroupID] nvarchar(128) NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [IsMarkedDeleted] bit NOT NULL,
    [LootGroupPrefix] nvarchar(128) NULL,
    PRIMARY KEY ([IdentityGUID], [RoleID], [LootGroupID])
);

CREATE NONCLUSTERED INDEX [IX_S3RoleAssignment] ON [dbo].[S3RoleAssignment] ([LootGroupID], [RoleID], [IdentityGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [UX_S3RoleAssignment] ON [dbo].[S3RoleAssignment] ([RowID]);
GO
ALTER TABLE [dbo].[S3RoleAssignment] ADD CONSTRAINT [DF_S3RoleAssignment_IsDeleted] DEFAULT ((0)) FOR [IsMarkedDeleted]; GO
ALTER TABLE [dbo].[S3RoleAssignment] ADD CONSTRAINT [DF_S3RoleAssignment_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.S3SimplePermission ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3SimplePermission] (
    [PermissionGUID] uniqueidentifier NOT NULL,
    [LootID] uniqueidentifier NOT NULL,
    [IdentityGUID] uniqueidentifier NOT NULL,
    [ReadValue] bit NOT NULL,
    [WriteValue] bit NOT NULL,
    [SecureValue] bit NOT NULL,
    PRIMARY KEY ([PermissionGUID])
);

CREATE NONCLUSTERED INDEX [IX_S3SimplePermission_ByLootIdentity] ON [dbo].[S3SimplePermission] ([LootID], [IdentityGUID]) INCLUDE ([PermissionGUID], [ReadValue], [WriteValue], [SecureValue]);
CREATE NONCLUSTERED INDEX [IX_S3SimplePermission_ByIdentityLoot] ON [dbo].[S3SimplePermission] ([IdentityGUID], [LootID]) INCLUDE ([ReadValue], [WriteValue]);
GO
ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_PermissionGUID] DEFAULT (newid()) FOR [PermissionGUID]; GO
ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_LootID] DEFAULT (newid()) FOR [LootID]; GO
ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_IdentityGUID] DEFAULT (newid()) FOR [IdentityGUID]; GO
ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_ReadValue] DEFAULT ('0') FOR [ReadValue]; GO
ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_WriteValue] DEFAULT ('0') FOR [WriteValue]; GO
ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_SecureValue] DEFAULT ('0') FOR [SecureValue]; GO

---------------------------------------------

---------------------------------------------
-- dbo.S3SimplePermissionDefault ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3SimplePermissionDefault] (
    [EntityType] int NOT NULL,
    [IdentityGUID] uniqueidentifier NOT NULL,
    [ReadValue] bit NOT NULL,
    [WriteValue] bit NOT NULL,
    [SecureValue] bit NOT NULL,
    PRIMARY KEY ([EntityType], [IdentityGUID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.S3UserACLRegenRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[S3UserACLRegenRequest] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [IssuedAt] datetime NOT NULL,
    PRIMARY KEY ([RequestGUID])
);
GO
ALTER TABLE [dbo].[S3UserACLRegenRequest] ADD CONSTRAINT [DF__S3UserACL__Reque__4734CBFC] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [dbo].[S3UserACLRegenRequest] ADD CONSTRAINT [DF__S3UserACL__Issue__4828F035] DEFAULT (getdate()) FOR [IssuedAt]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SAScenarioShockLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[SAScenarioShockLink] (
    [LinkGUID] uniqueidentifier NOT NULL,
    [ScenarioGUID] uniqueidentifier NOT NULL,
    [ShockGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([LinkGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IU_ScenarioGUID_ShockGUID] ON [dbo].[SAScenarioShockLink] ([ScenarioGUID], [ShockGUID]);
GO
ALTER TABLE [dbo].[SAScenarioShockLink] ADD CONSTRAINT [DF_SAScenarioShockLink_LinkGUID] DEFAULT (newid()) FOR [LinkGUID]; GO
ALTER TABLE [dbo].[SAScenarioShockLink] ADD CONSTRAINT [DF_SAScenarioShockLink_ScenarioGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScenarioGUID]; GO
ALTER TABLE [dbo].[SAScenarioShockLink] ADD CONSTRAINT [DF_SAScenarioShockLink_ShockGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ShockGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SAShock ------------------
---------------------------------------------
CREATE TABLE [dbo].[SAShock] (
    [ShockGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [PlanFilter] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [DateCreated] datetime NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [ValueType] smallint NOT NULL,
    [IsDeleted] bit NOT NULL,
    [ShockAssumptionTypeGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ShockGUID])
);
GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF__SAShock__ShockAs__06F35711] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ShockAssumptionTypeGUID]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_ShockGUID] DEFAULT (newid()) FOR [ShockGUID]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_PlanFilter] DEFAULT ('') FOR [PlanFilter]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_Comment] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_ValueType] DEFAULT ((0)) FOR [ValueType]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF__FactAccShock__IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SAShockAssumptionColumnConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[SAShockAssumptionColumnConfig] (
    [ShockAssumptionColumnConfigID] int NOT NULL,
    [ShockAssumptionTypeGUID] uniqueidentifier NOT NULL,
    [DataIndexName] nvarchar(50) NOT NULL,
    [DisplayName] nvarchar(50) NOT NULL,
    [IsHiddenColumn] bit NOT NULL,
    [DimensionGuid] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ShockAssumptionColumnConfigID])
);
GO
ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF__ShockAssu__Shock__022EA1F4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ShockAssumptionTypeGUID]; GO
ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF_ShockAssumptionColumnConfig_DataIndexName] DEFAULT ('') FOR [DataIndexName]; GO
ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF_ShockAssumptionColumnConfig_DisplayName] DEFAULT ('') FOR [DisplayName]; GO
ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF_ShockAssumptionColumnConfig_IsHiddenColumn] DEFAULT ((0)) FOR [IsHiddenColumn]; GO
ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF__SAShockAs__Dimen__5A75B655] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGuid]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SAShockAssumptionType ------------------
---------------------------------------------
CREATE TABLE [dbo].[SAShockAssumptionType] (
    [ShockAssumptionTypeGUID] uniqueidentifier NOT NULL,
    [AssumptionGroupID] smallint NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [BaseTableName] nvarchar(50) NOT NULL,
    [ShockTableName] nvarchar(50) NOT NULL,
    [WhereClauseXML] xml NOT NULL,
    [DisplayFormat] nvarchar(50) NOT NULL,
    [IsPercentage] bit NOT NULL,
    [FormulaColumnName] nvarchar(max) NOT NULL,
    [CommentColumnName] nvarchar(max) NOT NULL,
    PRIMARY KEY ([ShockAssumptionTypeGUID])
);
GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.SAShockAssumptionType_FormulaColumnName] DEFAULT ('') FOR [FormulaColumnName]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.SAShockAssumptionType_CommentColumnName] DEFAULT ('') FOR [CommentColumnName]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF__ShockAssu__Shock__77B11381] DEFAULT (newid()) FOR [ShockAssumptionTypeGUID]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_AssumptionGroupID] DEFAULT ((0)) FOR [AssumptionGroupID]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF__ShockAssu__PlanT__79995BF3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_BaseTableName] DEFAULT ('') FOR [BaseTableName]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_ShockTableName] DEFAULT ('') FOR [ShockTableName]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_WhereClauseXML] DEFAULT ('<WhereClauseItems></WhereClauseItems>') FOR [WhereClauseXML]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_DisplayFormat] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_IsPercentage] DEFAULT ((0)) FOR [IsPercentage]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SAShockViewByOptions ------------------
---------------------------------------------
CREATE TABLE [dbo].[SAShockViewByOptions] (
    [RowID] bigint NOT NULL,
    [ShockGUID] uniqueidentifier NOT NULL,
    [ChkPatientClass] bit NOT NULL,
    [ChkServiceLineRollup] bit NOT NULL,
    [ChkServiceLine] bit NOT NULL,
    [ChkMedicalSurgical] bit NOT NULL,
    [ChkAgeCohort] bit NOT NULL,
    [ChkPayorOrPayorGroup] bit NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [FK_SAShockViewByOptions_SAShock] FOREIGN KEY ([ShockGUID]) REFERENCES [dbo].[SAShock] ([ShockGUID]); GO
ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ShockGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ShockGUID]; GO
ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkPatientClass] DEFAULT ((0)) FOR [ChkPatientClass]; GO
ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkServiceLineRollup] DEFAULT ((0)) FOR [ChkServiceLineRollup]; GO
ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkServiceLine] DEFAULT ((0)) FOR [ChkServiceLine]; GO
ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkMedicalSurgical] DEFAULT ((0)) FOR [ChkMedicalSurgical]; GO
ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkAgeCohort] DEFAULT ((0)) FOR [ChkAgeCohort]; GO
ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkPayorOrPayorGroup] DEFAULT ((0)) FOR [ChkPayorOrPayorGroup]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SBKeyColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[SBKeyColumn] (
    [SBKeyColumnGUID] uniqueidentifier NOT NULL,
    [SBTargetGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(400) NOT NULL,
    [VERSION] timestamp NOT NULL,
    PRIMARY KEY ([SBKeyColumnGUID])
);
GO
ALTER TABLE [dbo].[SBKeyColumn] ADD CONSTRAINT [DF_SBKeyColumn_SBKeyColumnGUID] DEFAULT (newid()) FOR [SBKeyColumnGUID]; GO
ALTER TABLE [dbo].[SBKeyColumn] ADD CONSTRAINT [DF_SBKeyColumn_SBTargetGUID] DEFAULT (newid()) FOR [SBTargetGUID]; GO
ALTER TABLE [dbo].[SBKeyColumn] ADD CONSTRAINT [DF_SBKeyColumn_Name] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SBProject ------------------
---------------------------------------------
CREATE TABLE [dbo].[SBProject] (
    [SBProjectGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(400) NOT NULL,
    [TemplateFilePath] nvarchar(400) NOT NULL,
    [Context] nvarchar(2000) NOT NULL,
    [VERSION] timestamp NOT NULL,
    PRIMARY KEY ([SBProjectGUID])
);
GO
ALTER TABLE [dbo].[SBProject] ADD CONSTRAINT [DF_SBProject_SBProjectGUID] DEFAULT (newid()) FOR [SBProjectGUID]; GO
ALTER TABLE [dbo].[SBProject] ADD CONSTRAINT [DF_SBProject_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SBProject] ADD CONSTRAINT [DF_SBProject_TemplateFilePath] DEFAULT ('') FOR [TemplateFilePath]; GO
ALTER TABLE [dbo].[SBProject] ADD CONSTRAINT [DF_SBProject_Context] DEFAULT ('') FOR [Context]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SBSource ------------------
---------------------------------------------
CREATE TABLE [dbo].[SBSource] (
    [SBSourceGUID] uniqueidentifier NOT NULL,
    [SQLQuery] nvarchar(max) NOT NULL,
    [SBProjectGUID] uniqueidentifier NOT NULL,
    [VERSION] timestamp NOT NULL,
    PRIMARY KEY ([SBSourceGUID])
);
GO
ALTER TABLE [dbo].[SBSource] ADD CONSTRAINT [DF_SBSource_SBSource] DEFAULT (newid()) FOR [SBSourceGUID]; GO
ALTER TABLE [dbo].[SBSource] ADD CONSTRAINT [DF_SBSource_SQLQuery] DEFAULT ('') FOR [SQLQuery]; GO
ALTER TABLE [dbo].[SBSource] ADD CONSTRAINT [DF_SBSource_SBProjectGUID] DEFAULT (newid()) FOR [SBProjectGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SBTarget ------------------
---------------------------------------------
CREATE TABLE [dbo].[SBTarget] (
    [SBTargetGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(400) NOT NULL,
    [TableName] nvarchar(400) NOT NULL,
    [SBProjectGUID] uniqueidentifier NOT NULL,
    [VERSION] timestamp NOT NULL,
    PRIMARY KEY ([SBTargetGUID])
);
GO
ALTER TABLE [dbo].[SBTarget] ADD CONSTRAINT [DF_SBTarget_SBTargetGUID] DEFAULT (newid()) FOR [SBTargetGUID]; GO
ALTER TABLE [dbo].[SBTarget] ADD CONSTRAINT [DF_SBTarget_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SBTarget] ADD CONSTRAINT [DF_SBTarget_TableName] DEFAULT ('') FOR [TableName]; GO
ALTER TABLE [dbo].[SBTarget] ADD CONSTRAINT [DF_SBTarget_SBProjectGUID] DEFAULT (newid()) FOR [SBProjectGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SBValueColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[SBValueColumn] (
    [SBValueColumnGUID] uniqueidentifier NOT NULL,
    [SBTargetGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(400) NOT NULL,
    [AggregateFunction] nvarchar(400) NOT NULL,
    [VERSION] timestamp NOT NULL,
    PRIMARY KEY ([SBValueColumnGUID])
);
GO
ALTER TABLE [dbo].[SBValueColumn] ADD CONSTRAINT [DF_SBValueColumn_SBValueColumnGUID] DEFAULT (newid()) FOR [SBValueColumnGUID]; GO
ALTER TABLE [dbo].[SBValueColumn] ADD CONSTRAINT [DF_SBValueColumn_SBTargetGUID] DEFAULT (newid()) FOR [SBTargetGUID]; GO
ALTER TABLE [dbo].[SBValueColumn] ADD CONSTRAINT [DF_SBValueColumn_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SBValueColumn] ADD CONSTRAINT [DF_SBValueColumn_AggregateFunction] DEFAULT ('') FOR [AggregateFunction]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SEScript ------------------
---------------------------------------------
CREATE TABLE [dbo].[SEScript] (
    [ScriptGUID] uniqueidentifier NOT NULL,
    [Name] varchar(20) NOT NULL,
    [Description] varchar(64) NOT NULL,
    [Engine] varchar(3) NOT NULL,
    [ScriptCode] varchar(max) NOT NULL,
    PRIMARY KEY ([ScriptGUID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2CorrelationGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2CorrelationGroup] (
    [CorrelationGroupGUID] uniqueidentifier NOT NULL,
    [TableEditorConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    PRIMARY KEY ([CorrelationGroupGUID])
);
GO
ALTER TABLE [dbo].[SR2CorrelationGroup] ADD CONSTRAINT [FK_SR2CorrelationGroup_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO
ALTER TABLE [dbo].[SR2CorrelationGroup] ADD CONSTRAINT [DF_SR2CorrelationGroup_CorrelationGroupGUID] DEFAULT (newid()) FOR [CorrelationGroupGUID]; GO
ALTER TABLE [dbo].[SR2CorrelationGroup] ADD CONSTRAINT [DF_SR2CorrelationGroup_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SR2CorrelationGroup] ADD CONSTRAINT [DF_SR2CorrelationGroup_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2CorrelationGroupMember ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2CorrelationGroupMember] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [CorrelationGroupGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [RowID] int NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MemberGUID])
);
GO
ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [FK_SR2CorrelationGroupMember_SR2CorrelationGroup] FOREIGN KEY ([CorrelationGroupGUID]) REFERENCES [dbo].[SR2CorrelationGroup] ([CorrelationGroupGUID]); GO
ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_RowID] DEFAULT ((0)) FOR [RowID]; GO
ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_CorrelationGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CorrelationGroupGUID]; GO
ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2Project ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2Project] (
    [ProjectGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [InputNameFormat] nvarchar(450) NOT NULL,
    [OutputNameFormat] nvarchar(450) NOT NULL,
    [SensitivityConfigGUID] uniqueidentifier NOT NULL,
    [RiskConfigGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ProjectGUID])
);
GO
ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SR2Project_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO
ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SR2Project_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO
ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SNRProject_PackageGUID] DEFAULT (newid()) FOR [ProjectGUID]; GO
ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SR2Project_InputNameFormat] DEFAULT ('') FOR [InputNameFormat]; GO
ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SR2Project_OutputNameFormat] DEFAULT ('') FOR [OutputNameFormat]; GO
ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SNRProject_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SNRProject_Description] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2ProjectModelLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2ProjectModelLink] (
    [LinkGUID] uniqueidentifier NOT NULL,
    [ProjectGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [ProcessLevel] int NOT NULL,
    PRIMARY KEY ([LinkGUID])
);
GO
ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [FK_SNRProjectModelLink_SNRProject] FOREIGN KEY ([ProjectGUID]) REFERENCES [dbo].[SR2Project] ([ProjectGUID]); GO
ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [FK_SNRProjectModelLink_XPlan] FOREIGN KEY ([ModelGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [DF_SR2ProjectModelLink_ProcessLevel] DEFAULT ((-1)) FOR [ProcessLevel]; GO
ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [DF_SNRProjectModelLink_LinkGUID] DEFAULT (newid()) FOR [LinkGUID]; GO
ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [DF_SNRProjectModelLink_ProjectGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProjectGUID]; GO
ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [DF_SNRProjectModelLink_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2ProjectViewLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2ProjectViewLink] (
    [LinkGUID] uniqueidentifier NOT NULL,
    [ProjectGUID] uniqueidentifier NOT NULL,
    [TableEditorConfigGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([LinkGUID])
);
GO
ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [FK_SNRProjectViewLink_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO
ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [FK_SNRProjectViewLink_SNRProject] FOREIGN KEY ([ProjectGUID]) REFERENCES [dbo].[SR2Project] ([ProjectGUID]); GO
ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [DF_SNRProjectViewLink_LinkGUID] DEFAULT (newid()) FOR [LinkGUID]; GO
ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [DF_SNRProjectViewLink_ProjectGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProjectGUID]; GO
ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [DF_SNRProjectViewLink_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2RiskConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2RiskConfig] (
    [RiskConfigGUID] uniqueidentifier NOT NULL,
    [ProjectGUID] uniqueidentifier NOT NULL,
    [BinCount] int NOT NULL,
    [TrialCount] int NOT NULL,
    [DistributionType] smallint NOT NULL,
    [CachedSummary] nvarchar(4000) NOT NULL,
    [TaskState] int NOT NULL,
    [TaskNumModelsComplete] int NOT NULL,
    [TaskErrorGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RiskConfigGUID])
);
GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [FK_SR2RiskConfig_SR2Project] FOREIGN KEY ([ProjectGUID]) REFERENCES [dbo].[SR2Project] ([ProjectGUID]); GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_ExecutionState] DEFAULT ((0)) FOR [TaskState]; GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_ExecutionPercentComplete] DEFAULT ((0)) FOR [TaskNumModelsComplete]; GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_TaskErrorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TaskErrorGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_RiskConfigGUID] DEFAULT (newid()) FOR [RiskConfigGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_BinCount] DEFAULT ((0)) FOR [BinCount]; GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_TrialCount] DEFAULT ((0)) FOR [TrialCount]; GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_DistributionType] DEFAULT ((0)) FOR [DistributionType]; GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_CachedSummary] DEFAULT ('') FOR [CachedSummary]; GO
ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_ProjectGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProjectGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2RiskConfigInput ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2RiskConfigInput] (
    [InputGUID] uniqueidentifier NOT NULL,
    [RiskConfigGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [RowID] int NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [CachedName] nvarchar(450) NOT NULL,
    [GroupName] nvarchar(450) NOT NULL,
    [GroupID] int NOT NULL,
    PRIMARY KEY ([InputGUID])
);
GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [FK_SR2RiskConfigInput_SR2RiskConfig] FOREIGN KEY ([RiskConfigGUID]) REFERENCES [dbo].[SR2RiskConfig] ([RiskConfigGUID]); GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_CachedName] DEFAULT ('') FOR [CachedName]; GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF__SR2RiskCo__Group__39C65BD2] DEFAULT ('') FOR [GroupName]; GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_GroupID] DEFAULT ((0)) FOR [GroupID]; GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_InputGUID] DEFAULT (newid()) FOR [InputGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_RowID] DEFAULT ((0)) FOR [RowID]; GO
ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2RiskConfigOutput ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2RiskConfigOutput] (
    [OutputGUID] uniqueidentifier NOT NULL,
    [RiskConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [DisplayFormat] nvarchar(100) NOT NULL,
    PRIMARY KEY ([OutputGUID])
);
GO
ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [FK_SR2RiskConfigOutput_SR2RiskConfig] FOREIGN KEY ([RiskConfigGUID]) REFERENCES [dbo].[SR2RiskConfig] ([RiskConfigGUID]); GO
ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [DF_SR2RiskConfigOutput_DisplayFormat] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [DF_SR2RiskConfigOutput_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [DF_SR2RiskConfigOutput_OutputGUID] DEFAULT (newid()) FOR [OutputGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [DF_SR2RiskConfigOutput_Name] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2RiskConfigOutputMember ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2RiskConfigOutputMember] (
    [OutputMemberGUID] uniqueidentifier NOT NULL,
    [OutputGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [RowID] int NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [CachedName] nvarchar(450) NOT NULL,
    PRIMARY KEY ([OutputMemberGUID])
);
GO
ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [FK_SR2RiskConfigOutputMember_SR2RiskConfigOutput] FOREIGN KEY ([OutputGUID]) REFERENCES [dbo].[SR2RiskConfigOutput] ([OutputGUID]); GO
ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_OutputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OutputGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_CachedName] DEFAULT ('') FOR [CachedName]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_OutputMemberGUID] DEFAULT (newid()) FOR [OutputMemberGUID]; GO
ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_RowID] DEFAULT ((0)) FOR [RowID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2RiskResult ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2RiskResult] (
    [RiskResultGUID] uniqueidentifier NOT NULL,
    [RiskConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [BinCount] int NOT NULL,
    PRIMARY KEY ([RiskResultGUID])
);
GO
ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [FK_SR2RiskResult_SR2RiskConfig] FOREIGN KEY ([RiskConfigGUID]) REFERENCES [dbo].[SR2RiskConfig] ([RiskConfigGUID]); GO
ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO
ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_BinCount] DEFAULT ((0)) FOR [BinCount]; GO
ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_RiskResultGUID] DEFAULT (newid()) FOR [RiskResultGUID]; GO
ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2RiskResultDetail ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2RiskResultDetail] (
    [RowID] int NOT NULL,
    [RiskResultGUID] uniqueidentifier NOT NULL,
    [TrialNumber] int NOT NULL,
    [OutputGUID] uniqueidentifier NOT NULL,
    [BinNumber] int NOT NULL,
    [Value] decimal NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [IsDeleted] bit NOT NULL,
    [DetailGUID] uniqueidentifier NOT NULL,
    [OutputUniqueID] nvarchar(80) NOT NULL,
    [CachedOutputName] nvarchar(450) NOT NULL,
    [CachedOutputDisplayFormat] nvarchar(450) NOT NULL,
    PRIMARY KEY ([DetailGUID])
);

CREATE NONCLUSTERED INDEX [idx_SR2RiskReport] ON [dbo].[SR2RiskResultDetail] ([RiskResultGUID], [OutputGUID]) INCLUDE ([RowID], [TrialNumber], [BinNumber], [Value], [HistoryItemGUID], [IsDeleted], [DetailGUID], [OutputUniqueID]);
GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [FK_SR2RiskResultDetail_SR2RiskResult] FOREIGN KEY ([RiskResultGUID]) REFERENCES [dbo].[SR2RiskResult] ([RiskResultGUID]); GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_BinNumber] DEFAULT ((0)) FOR [BinNumber]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_Value] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_CachedOutputName] DEFAULT ('') FOR [CachedOutputName]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_DetailGUID] DEFAULT (newid()) FOR [DetailGUID]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_CachedOutputDisplayFormat] DEFAULT ('') FOR [CachedOutputDisplayFormat]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_OutputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OutputGUID]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_RiskResultGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskResultGUID]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_TrialNumber] DEFAULT ((0)) FOR [TrialNumber]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2RiskTrial ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2RiskTrial] (
    [RiskTrialGUID] uniqueidentifier NOT NULL,
    [RiskConfigGUID] uniqueidentifier NOT NULL,
    [TrialNumber] int NOT NULL,
    PRIMARY KEY ([RiskTrialGUID])
);
GO
ALTER TABLE [dbo].[SR2RiskTrial] ADD CONSTRAINT [DF_SR2RiskTrial_TrialNumber] DEFAULT ((0)) FOR [TrialNumber]; GO
ALTER TABLE [dbo].[SR2RiskTrial] ADD CONSTRAINT [DF_SR2RiskTrial_RiskTrialGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskTrialGUID]; GO
ALTER TABLE [dbo].[SR2RiskTrial] ADD CONSTRAINT [DF_SR2RiskTrial_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2RiskTrialInput ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2RiskTrialInput] (
    [RiskTrialInputGUID] uniqueidentifier NOT NULL,
    [RiskTrialGUID] uniqueidentifier NOT NULL,
    [InputGUID] uniqueidentifier NOT NULL,
    [DistributionPoint] int NOT NULL,
    PRIMARY KEY ([RiskTrialInputGUID])
);
GO
ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [FK_SR2RiskTrialInput_SR2RiskTrial] FOREIGN KEY ([RiskTrialGUID]) REFERENCES [dbo].[SR2RiskTrial] ([RiskTrialGUID]); GO
ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [DF_SR2RiskTrialInput_RiskTrialGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskTrialGUID]; GO
ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [DF_SR2RiskTrialInput_DistributionPoint] DEFAULT ((0)) FOR [DistributionPoint]; GO
ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [DF_SR2RiskTrialInput_InputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [InputGUID]; GO
ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [DF_SR2RiskTrialInput_RiskTrialInputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskTrialInputGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2SensitivityConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2SensitivityConfig] (
    [SensitivityConfigGUID] uniqueidentifier NOT NULL,
    [ProjectGUID] uniqueidentifier NOT NULL,
    [CachedSummary] nvarchar(4000) NOT NULL,
    [TaskState] int NOT NULL,
    [TaskNumModelsComplete] int NOT NULL,
    [TaskErrorGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SensitivityConfigGUID])
);
GO
ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [FK_SR2SensitivityConfig_SR2Project] FOREIGN KEY ([ProjectGUID]) REFERENCES [dbo].[SR2Project] ([ProjectGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_ExecutionState] DEFAULT ((0)) FOR [TaskState]; GO
ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_ExecutionPercentComplete] DEFAULT ((0)) FOR [TaskNumModelsComplete]; GO
ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_SensitivityConfigGUID] DEFAULT (newid()) FOR [SensitivityConfigGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_CachedSummary] DEFAULT ('') FOR [CachedSummary]; GO
ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_TaskErrorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TaskErrorGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_ProjectGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProjectGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2SensitivityConfigAutoGroupLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] (
    [AutoGroupGUID] uniqueidentifier NOT NULL,
    [SensitivityConfigGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([AutoGroupGUID])
);
GO
ALTER TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ADD CONSTRAINT [FK_SR2SensitivityConfigAutoGroupLink_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigAutoGroupLink_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigAutoGroupLink_AutoGroupGUID] DEFAULT (newid()) FOR [AutoGroupGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigAutoGroupLink_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2SensitivityConfigCorrelationGroupLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] (
    [LinkGUID] uniqueidentifier NOT NULL,
    [SensitivityConfigGUID] uniqueidentifier NOT NULL,
    [CorrelationGroupGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([LinkGUID])
);
GO
ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [FK_SR2SensitivityConfigCorrelationGroupLink_SR2CorrelationGroup] FOREIGN KEY ([CorrelationGroupGUID]) REFERENCES [dbo].[SR2CorrelationGroup] ([CorrelationGroupGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [FK_SR2SensitivityConfigCorrelationGroupLink_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigCorrelationGroupLink_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigCorrelationGroupLink_CorrelationGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CorrelationGroupGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigCorrelationGroupLink_LinkGUID] DEFAULT (newid()) FOR [LinkGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2SensitivityConfigInput ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2SensitivityConfigInput] (
    [InputGUID] uniqueidentifier NOT NULL,
    [SensitivityConfigGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [RowID] int NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [CachedName] nvarchar(450) NOT NULL,
    [GroupName] nvarchar(450) NOT NULL,
    [GroupID] int NOT NULL,
    PRIMARY KEY ([InputGUID])
);
GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [FK_SR2SensitivityConfigInput_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_InputGUID] DEFAULT (newid()) FOR [InputGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_RowID] DEFAULT ((0)) FOR [RowID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_CachedName] DEFAULT ('') FOR [CachedName]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF__SR2Sensit__Group__38D23799] DEFAULT ('') FOR [GroupName]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_GroupID] DEFAULT ((0)) FOR [GroupID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2SensitivityConfigOutput ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2SensitivityConfigOutput] (
    [OutputGUID] uniqueidentifier NOT NULL,
    [SensitivityConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [DisplayFormat] nvarchar(100) NOT NULL,
    PRIMARY KEY ([OutputGUID])
);
GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [FK_SR2SensitivityConfigOutput_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [DF_SR2SensitivityConfigOutput_DisplayFormat] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [DF_SR2SensitivityConfigOutput_OutputGUID] DEFAULT (newid()) FOR [OutputGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [DF_SR2SensitivityConfigOutput_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [DF_SR2SensitivityConfigOutput_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2SensitivityConfigOutputMember ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2SensitivityConfigOutputMember] (
    [OutputMemberGUID] uniqueidentifier NOT NULL,
    [OutputGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [RowID] int NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [CachedName] nvarchar(450) NOT NULL,
    PRIMARY KEY ([OutputMemberGUID])
);
GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [FK_SR2SensitivityConfigOutputMember_SR2SensitivityConfigOutput] FOREIGN KEY ([OutputGUID]) REFERENCES [dbo].[SR2SensitivityConfigOutput] ([OutputGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_OutputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OutputGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_CachedName] DEFAULT ('') FOR [CachedName]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_OutputMemberGUID] DEFAULT (newid()) FOR [OutputMemberGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_RowID] DEFAULT ((0)) FOR [RowID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2SensitivityResult ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2SensitivityResult] (
    [SensitivityResultGUID] uniqueidentifier NOT NULL,
    [SensitivityConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [DateCreated] datetime NOT NULL,
    PRIMARY KEY ([SensitivityResultGUID])
);
GO
ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [FK_SR2SensitivityResult_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [DF_SR2SensitivityResult_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [DF_SR2SensitivityResult_SensitivityResultGUID] DEFAULT (newid()) FOR [SensitivityResultGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [DF_SR2SensitivityResult_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [DF_SR2SensitivityResult_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SR2SensitivityResultDetail ------------------
---------------------------------------------
CREATE TABLE [dbo].[SR2SensitivityResultDetail] (
    [RowID] int NOT NULL,
    [SensitivityResultGUID] uniqueidentifier NOT NULL,
    [OutputGUID] uniqueidentifier NOT NULL,
    [ValueLow] decimal NOT NULL,
    [ValueHigh] decimal NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [IsDeleted] bit NOT NULL,
    [DetailGUID] uniqueidentifier NOT NULL,
    [InputGUID] uniqueidentifier NOT NULL,
    [ValueBaseline] decimal NOT NULL,
    [OutputUniqueID] nvarchar(80) NOT NULL,
    [CachedInputName] nvarchar(450) NOT NULL,
    [CachedGroupName] nvarchar(450) NOT NULL,
    [CachedOutputName] nvarchar(450) NOT NULL,
    [CachedOutputDisplayFormat] nvarchar(450) NOT NULL,
    PRIMARY KEY ([DetailGUID])
);

CREATE NONCLUSTERED INDEX [idx_SR2SensReport] ON [dbo].[SR2SensitivityResultDetail] ([SensitivityResultGUID], [OutputGUID], [InputGUID]) INCLUDE ([RowID], [ValueLow], [ValueHigh], [HistoryItemGUID], [IsDeleted], [DetailGUID], [ValueBaseline], [OutputUniqueID]);
GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [FK_SR2SensitivityResultDetail_SR2SensitivityResult] FOREIGN KEY ([SensitivityResultGUID]) REFERENCES [dbo].[SR2SensitivityResult] ([SensitivityResultGUID]); GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_CachedInputName] DEFAULT ('') FOR [CachedInputName]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_CachedGroupName] DEFAULT ('') FOR [CachedGroupName]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_CachedOutputName] DEFAULT ('') FOR [CachedOutputName]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_ValueBaseline] DEFAULT ((0)) FOR [ValueBaseline]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_SensitivityResultGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityResultGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_DetailGUID] DEFAULT (newid()) FOR [DetailGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_CachedOutputDisplayFormat] DEFAULT ('') FOR [CachedOutputDisplayFormat]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_InputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [InputGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_OutputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OutputGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_ValueLow] DEFAULT ((0)) FOR [ValueLow]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_ValueHigh] DEFAULT ((0)) FOR [ValueHigh]; GO
ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRAssumption ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRAssumption] (
    [AssumptionID] int NOT NULL,
    [AssumptionSetID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    PRIMARY KEY ([AssumptionID])
);
GO
ALTER TABLE [dbo].[SRAssumption] ADD CONSTRAINT [FK_SRAssumptionSetMember_SRAssumptionSet] FOREIGN KEY ([AssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO
ALTER TABLE [dbo].[SRAssumption] ADD CONSTRAINT [DF_AMAssumptionSetMember_AssumptionSetID] DEFAULT ((0)) FOR [AssumptionSetID]; GO
ALTER TABLE [dbo].[SRAssumption] ADD CONSTRAINT [DF_AMAssumptionSetMember_Name] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRAssumptionLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRAssumptionLink] (
    [AssumptionID] int NOT NULL,
    [ParentAssumptionID] int NOT NULL,
    [ScenarioID] int NOT NULL,
    [ParentScenarioID] int NOT NULL,
    PRIMARY KEY ([ParentAssumptionID], [AssumptionID])
);
GO
ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [FK_SRAssumptionSetMemberLink_SRAssumptionSetMember] FOREIGN KEY ([ParentAssumptionID]) REFERENCES [dbo].[SRAssumption] ([AssumptionID]); GO
ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [FK_SRAssumptionSetMemberLink_SRAssumptionSetMember2] FOREIGN KEY ([AssumptionID]) REFERENCES [dbo].[SRAssumption] ([AssumptionID]); GO
ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [FK_SRAssumptionSetMemberLink_SRScenario] FOREIGN KEY ([ScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO
ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [FK_SRAssumptionSetMemberLink_SRScenario1] FOREIGN KEY ([ParentScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO
ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [DF_SRCorrelation_AssumptionSetMemberID] DEFAULT ((0)) FOR [AssumptionID]; GO
ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [DF_SRCorrelation_ParentAssumptionSetMemberID] DEFAULT ((0)) FOR [ParentAssumptionID]; GO
ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [DF_SRAssumptionSetMemberLink_ScenarioID] DEFAULT ((0)) FOR [ScenarioID]; GO
ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [DF_SRAssumptionSetMemberLink_ParentScenarioID] DEFAULT ((0)) FOR [ParentScenarioID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRAssumptionSet ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRAssumptionSet] (
    [AssumptionSetID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [IsInputSet] bit NOT NULL,
    [IsOutputSet] bit NOT NULL,
    [IsGroupingTime] bit NOT NULL,
    [IsGroupingPlans] bit NOT NULL,
    PRIMARY KEY ([AssumptionSetID])
);
GO
ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_AMAssumptionSet_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_AMAssumptionSet_IsInputSet] DEFAULT ((0)) FOR [IsInputSet]; GO
ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_AMAssumptionSet_IsOutputSet] DEFAULT ((0)) FOR [IsOutputSet]; GO
ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_SRAssumptionSet_IsGroupingTime] DEFAULT ((0)) FOR [IsGroupingTime]; GO
ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_SRAssumptionSet_IsGroupingPlans] DEFAULT ((0)) FOR [IsGroupingPlans]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRAssumptionTuple ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRAssumptionTuple] (
    [AssumptionID] int NOT NULL,
    [DimensionMemberGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([AssumptionID], [DimensionMemberGUID])
);
GO
ALTER TABLE [dbo].[SRAssumptionTuple] ADD CONSTRAINT [FK_SRAssumptionSetMemberTuple_SRAssumptionSetMember] FOREIGN KEY ([AssumptionID]) REFERENCES [dbo].[SRAssumption] ([AssumptionID]); GO
ALTER TABLE [dbo].[SRAssumptionTuple] ADD CONSTRAINT [DF_AMAssumptionSetMemberTuple_AssumptionSetMemberID] DEFAULT ((0)) FOR [AssumptionID]; GO
ALTER TABLE [dbo].[SRAssumptionTuple] ADD CONSTRAINT [DF_AMAssumptionSetMemberTuple_DimensionMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionMemberGUID]; GO
ALTER TABLE [dbo].[SRAssumptionTuple] ADD CONSTRAINT [DF_AMAssumptionSetMemberTuple_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRPackage ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRPackage] (
    [PackageGUID] uniqueidentifier NOT NULL,
    [ProjectID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PackageGUID])
);
GO
ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [FK_SRPackage_Folder] FOREIGN KEY ([FolderGUID]) REFERENCES [dbo].[Folder] ([FolderGuid]); GO
ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [FK_SRPackage_SRProject] FOREIGN KEY ([ProjectID]) REFERENCES [dbo].[SRProject] ([ProjectID]); GO
ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [DF_SRPackage_PackageGUID] DEFAULT (newid()) FOR [PackageGUID]; GO
ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [DF_SRPackage_ProjectID] DEFAULT ((0)) FOR [ProjectID]; GO
ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [DF_SRPackage_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [DF_SRPackage_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRPackageConfigLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRPackageConfigLink] (
    [PackageConfigLinkGUID] uniqueidentifier NOT NULL,
    [PackageGUID] uniqueidentifier NOT NULL,
    [TableEditorConfigGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PackageConfigLinkGUID])
);
GO
ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [FK_SRPackageConfigLink_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO
ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [FK_SRPackageConfigLink_SRPackageConfigLink] FOREIGN KEY ([PackageGUID]) REFERENCES [dbo].[SRPackage] ([PackageGUID]); GO
ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [DF_SRPackageConfigLink_PackageConfigLinkGUID] DEFAULT (newid()) FOR [PackageConfigLinkGUID]; GO
ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [DF_SRPackageConfigLink_PackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PackageGUID]; GO
ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [DF_SRPackageConfigLink_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRProject ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRProject] (
    [ProjectID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [SensitivityConfigID] int NOT NULL,
    [RiskConfigID] int NOT NULL,
    PRIMARY KEY ([ProjectID])
);
GO
ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [FK_SRProject_SRRiskConfig] FOREIGN KEY ([RiskConfigID]) REFERENCES [dbo].[SRRiskConfig] ([RiskConfigID]); GO
ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [FK_SRProject_SRSensitivityConfig] FOREIGN KEY ([SensitivityConfigID]) REFERENCES [dbo].[SRSensitivityConfig] ([SensitivityConfigID]); GO
ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [DF_SRProject_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [DF_SRProject_SensitivityConfigID] DEFAULT ((0)) FOR [SensitivityConfigID]; GO
ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [DF_SRProject_RiskConfigID] DEFAULT ((0)) FOR [RiskConfigID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRProjectModelLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRProjectModelLink] (
    [ProjectID] int NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [IsPrimary] bit NOT NULL,
    PRIMARY KEY ([ProjectID], [ModelGUID])
);
GO
ALTER TABLE [dbo].[SRProjectModelLink] ADD CONSTRAINT [FK_SRProjectModelLink_SRProject] FOREIGN KEY ([ProjectID]) REFERENCES [dbo].[SRProject] ([ProjectID]); GO
ALTER TABLE [dbo].[SRProjectModelLink] ADD CONSTRAINT [FK_SRProjectModelLink_XPlan] FOREIGN KEY ([ModelGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[SRProjectModelLink] ADD CONSTRAINT [DF_SRProjectModelLink_IsPrimaryModel] DEFAULT ((0)) FOR [IsPrimary]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRRiskConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRRiskConfig] (
    [RiskConfigID] int NOT NULL,
    [InputAssumptionSetID] int NOT NULL,
    [OutputAssumptionSetID] int NOT NULL,
    [Trials] int NOT NULL,
    [Bins] int NOT NULL,
    [LowScenarioID] int NOT NULL,
    [HighScenarioID] int NOT NULL,
    PRIMARY KEY ([RiskConfigID])
);
GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [FK_SRRiskConfig_SRAssumptionSet] FOREIGN KEY ([InputAssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [FK_SRRiskConfig_SRAssumptionSet1] FOREIGN KEY ([OutputAssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [FK_SRRiskConfig_SRScenario] FOREIGN KEY ([LowScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [FK_SRRiskConfig_SRScenario1] FOREIGN KEY ([HighScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_InputAssumptionSetID] DEFAULT ((0)) FOR [InputAssumptionSetID]; GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_OutputAssumptionSetID] DEFAULT ((0)) FOR [OutputAssumptionSetID]; GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_Trials] DEFAULT ((0)) FOR [Trials]; GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_Bins] DEFAULT ((0)) FOR [Bins]; GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_LowScenarioID] DEFAULT ((0)) FOR [LowScenarioID]; GO
ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_HighScenarioID] DEFAULT ((0)) FOR [HighScenarioID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRScenario ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRScenario] (
    [ScenarioID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [IsCustom] bit NOT NULL,
    PRIMARY KEY ([ScenarioID])
);
GO
ALTER TABLE [dbo].[SRScenario] ADD CONSTRAINT [DF_ScoreScenario_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SRScenario] ADD CONSTRAINT [DF_ScoreScenario_IsSystem] DEFAULT ((0)) FOR [IsCustom]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SRSensitivityConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[SRSensitivityConfig] (
    [SensitivityConfigID] int NOT NULL,
    [InputAssumptionSetID] int NOT NULL,
    [OutputAssumptionSetID] int NOT NULL,
    [LowScenarioID] int NOT NULL,
    [HighScenarioID] int NOT NULL,
    PRIMARY KEY ([SensitivityConfigID])
);
GO
ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [FK_SRSensitivityConfig_SRAssumptionSet] FOREIGN KEY ([InputAssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO
ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [FK_SRSensitivityConfig_SRAssumptionSet1] FOREIGN KEY ([OutputAssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO
ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [FK_SRSensitivityConfig_SRScenario] FOREIGN KEY ([LowScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO
ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [FK_SRSensitivityConfig_SRScenario1] FOREIGN KEY ([HighScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO
ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [DF_SRSensitivityConfig_InputAssumptionSetID] DEFAULT ((0)) FOR [InputAssumptionSetID]; GO
ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [DF_SRSensitivityConfig_OutputAssumptionSetID] DEFAULT ((0)) FOR [OutputAssumptionSetID]; GO
ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [DF_SRSensitivityConfig_LowScenarioID] DEFAULT ((0)) FOR [LowScenarioID]; GO
ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [DF_SRSensitivityConfig_HighScenarioID] DEFAULT ((0)) FOR [HighScenarioID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreAttribute ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreAttribute] (
    [AttributeGUID] uniqueidentifier NOT NULL,
    [DimensionGroupGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(200) NULL,
    [IsWrittenToDB] bit NOT NULL,
    [IsKey] bit NOT NULL,
    [IsSecuredLootID] bit NOT NULL,
    [IsSecuredLootConfigID] bit NOT NULL,
    [IsSecuredLootGroupID] bit NOT NULL,
    [SecuredLootGroupPrefix] nvarchar(128) NOT NULL,
    [SQLColumnName] nvarchar(64) NOT NULL,
    [DefaultSortAttributeGUID] uniqueidentifier NOT NULL,
    [ForeignKeyGUID] uniqueidentifier NOT NULL,
    [IsRequired] bit NOT NULL,
    [SpecialAttributeIndex] tinyint NOT NULL,
    [IsCopiedWithPlan] bit NOT NULL,
    [DisplayOrder] smallint NOT NULL,
    [IsHidden] bit NOT NULL,
    [DateModified] datetime NOT NULL,
    [AttributeType] tinyint NOT NULL,
    [MetaXML] varchar(max) NOT NULL,
    [InferredSourceGUID] uniqueidentifier NOT NULL,
    [InferredColumnName] nvarchar(128) NOT NULL,
    [InferredAttributeGUID] uniqueidentifier NOT NULL,
    [HelpText] nvarchar(800) NOT NULL,
    [ColumnType] tinyint NOT NULL,
    [ComputedValueDefinition] nvarchar(max) NOT NULL,
    [IsComputed] bit NOT NULL,
    [IsIdentity] bit NOT NULL,
    [IdentityIncrement] int NOT NULL,
    [IdentitySeed] int NOT NULL,
    [IsNullable] bit NOT NULL,
    [DefaultValueDefinition] nvarchar(max) NOT NULL,
    [Precision] tinyint NOT NULL,
    [Scale] tinyint NOT NULL,
    [MaxLength] smallint NOT NULL,
    [IsColumnExist] bit NOT NULL,
    [IsForeignKeyed] bit NOT NULL,
    [ForeignKeySchema] nvarchar(128) NOT NULL,
    [ForeignKeyTable] nvarchar(128) NOT NULL,
    [ForeignKeyColumn] nvarchar(128) NOT NULL,
    [ForeignKeyOnDelete] nvarchar(100) NOT NULL,
    [CachedInferredSQLColumnType] tinyint NOT NULL,
    [IsFKAutoFilter] bit NOT NULL,
    [JoinTypeVal] int NOT NULL,
    [IsCustomNumberFormat] bit NOT NULL,
    [CustomNumberFormat] varchar(128) NOT NULL,
    [IsLocked] bit NOT NULL,
    [ForeignKeyHierarchyGUID] uniqueidentifier NOT NULL,
    [PHIDisclaimer] nvarchar(2000) NOT NULL,
    [CopyrightDisclaimer] nvarchar(2000) NOT NULL,
    [IsFormField] bit NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    [IsModelDriver] bit NOT NULL,
    [Description] nvarchar(1000) NOT NULL,
    [DSSIsUsed] bit NOT NULL,
    PRIMARY KEY ([AttributeGUID])
);

CREATE CLUSTERED INDEX [ix_ScoreAttribute] ON [dbo].[ScoreAttribute] ([DimensionGroupGUID]);
GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [FK_ScoreAttribute_ScoreDimensionGroup] FOREIGN KEY ([DimensionGroupGUID]) REFERENCES [dbo].[ScoreDimensionGroup] ([DimensionGroupGUID]); GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsCus__1A0E52E4] DEFAULT ((0)) FOR [IsCustomNumberFormat]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Custo__1B02771D] DEFAULT ('') FOR [CustomNumberFormat]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_DimensionGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGroupGUID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsLoc__2185577A] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Descr__235CED9A] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__PHIDi__23998596] DEFAULT ('') FOR [PHIDisclaimer]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Copyr__248DA9CF] DEFAULT ('') FOR [CopyrightDisclaimer]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_AttributeType] DEFAULT ((0)) FOR [AttributeType]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_MetaXML] DEFAULT ('') FOR [MetaXML]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__DSSIs__2867F491] DEFAULT ((1)) FOR [DSSIsUsed]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_InferredColumnName] DEFAULT ('') FOR [InferredColumnName]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_HelpText] DEFAULT ('') FOR [HelpText]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Colum__3DA96780] DEFAULT ((0)) FOR [ColumnType]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Compu__3E9D8BB9] DEFAULT ('') FOR [ComputedValueDefinition]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsCom__3F91AFF2] DEFAULT ((0)) FOR [IsComputed]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsIde__4085D42B] DEFAULT ((0)) FOR [IsIdentity]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Ident__4179F864] DEFAULT ((0)) FOR [IdentityIncrement]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Ident__426E1C9D] DEFAULT ((0)) FOR [IdentitySeed]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsNul__436240D6] DEFAULT ((0)) FOR [IsNullable]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Defau__4456650F] DEFAULT ('') FOR [DefaultValueDefinition]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Preci__454A8948] DEFAULT ((0)) FOR [Precision]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Scale__463EAD81] DEFAULT ((0)) FOR [Scale]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__MaxLe__4732D1BA] DEFAULT ((0)) FOR [MaxLength]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsCol__4826F5F3] DEFAULT ((0)) FOR [IsColumnExist]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsFor__491B1A2C] DEFAULT ((0)) FOR [IsForeignKeyed]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__4A0F3E65] DEFAULT ('') FOR [ForeignKeySchema]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__4B03629E] DEFAULT ('') FOR [ForeignKeyTable]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__4BF786D7] DEFAULT ('') FOR [ForeignKeyColumn]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__4CEBAB10] DEFAULT ('') FOR [ForeignKeyOnDelete]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Cache__4DDFCF49] DEFAULT ((0)) FOR [CachedInferredSQLColumnType]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsFKAutoFilter] DEFAULT ((1)) FOR [IsFKAutoFilter]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_InferredAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [InferredSourceGUID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__5284BA9F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ForeignKeyHierarchyGUID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsModelDriver] DEFAULT ((0)) FOR [IsModelDriver]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_AttributeGUID] DEFAULT (newid()) FOR [AttributeGUID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Frame__66D53282] DEFAULT ((0)) FOR [FrameworkID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_JoinType] DEFAULT ((0)) FOR [JoinTypeVal]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_Name] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsWrittenToDB] DEFAULT ((0)) FOR [IsWrittenToDB]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsKey] DEFAULT ((0)) FOR [IsKey]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsSecuredLootID] DEFAULT ((0)) FOR [IsSecuredLootID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsSecuredConfigID] DEFAULT ((0)) FOR [IsSecuredLootConfigID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsSecuredLootGroupID] DEFAULT ((0)) FOR [IsSecuredLootGroupID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_InferredAttributeGUID_1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [InferredAttributeGUID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_SecuredLootGroupPrefix] DEFAULT ('') FOR [SecuredLootGroupPrefix]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_SQLColumnName_1] DEFAULT ('') FOR [SQLColumnName]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_DefaultSortAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultSortAttributeGUID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_ForeignKeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ForeignKeyGUID]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsRequired] DEFAULT ((1)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_SpecialAttributeIndex] DEFAULT ((0)) FOR [SpecialAttributeIndex]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsCopiedWithPlan] DEFAULT ((1)) FOR [IsCopiedWithPlan]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsSys__74A98C83] DEFAULT ((0)) FOR [IsFormField]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_DisplayOrder] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsHidden] DEFAULT ((0)) FOR [IsHidden]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreAttributeSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreAttributeSetting] (
    [ScoreAttributeSettingGuid] uniqueidentifier NOT NULL,
    [AttributeGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [IsCustom] bit NOT NULL,
    [IsMarkedForDeletion] bit NOT NULL,
    [IsUsed] bit NOT NULL,
    [CAPIsUsed] bit NOT NULL,
    [DSSIsUsed] bit NOT NULL,
    [MRIsUsed] bit NOT NULL,
    [OBIsUsed] bit NOT NULL,
    [PRIsUsed] bit NOT NULL,
    [SPIsUsed] bit NOT NULL,
    PRIMARY KEY ([ScoreAttributeSettingGuid])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ_SCOREATTRIBUTESETTING_ATTRIBUTEGUID] ON [dbo].[ScoreAttributeSetting] ([AttributeGUID]);
GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_CAPIsUsed] DEFAULT ((0)) FOR [CAPIsUsed]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_DSSIsUsed] DEFAULT ((0)) FOR [DSSIsUsed]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_MRIsUsed] DEFAULT ((0)) FOR [MRIsUsed]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_OBIsUsed] DEFAULT ((0)) FOR [OBIsUsed]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_PRIsUsed] DEFAULT ((0)) FOR [PRIsUsed]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_SPIsUsed] DEFAULT ((0)) FOR [SPIsUsed]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF__ScoreAttr__IsMar__3DA3D3F0] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_IsUsed] DEFAULT ((0)) FOR [IsUsed]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF__ScoreAttr__Score__5E8C9913] DEFAULT (newid()) FOR [ScoreAttributeSettingGuid]; GO
ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF__ScoreAttr__IsCus__616905BE] DEFAULT ((0)) FOR [IsCustom]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreAttributeType ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreAttributeType] (
    [ScoreAttributeTypeID] tinyint NOT NULL,
    [Name] nvarchar(50) NOT NULL,
    PRIMARY KEY ([ScoreAttributeTypeID])
);
GO
ALTER TABLE [dbo].[ScoreAttributeType] ADD CONSTRAINT [DF_Table_1_name] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreComposite ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreComposite] (
    [CompositeGUID] uniqueidentifier NOT NULL,
    [DataTableGUID1] uniqueidentifier NOT NULL,
    [DataTableGUID2] uniqueidentifier NOT NULL,
    [IsWrittenToDB] bit NOT NULL,
    [FriendlyName] nvarchar(64) NOT NULL,
    [Description] varchar(2000) NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    [ModifiedAt] datetime NOT NULL,
    [TableEditorConfigGUID] uniqueidentifier NOT NULL,
    [isSubtable] bit NOT NULL,
    [BoundsDataTableGUID] uniqueidentifier NOT NULL,
    [ModelQueryHint] nvarchar(450) NOT NULL,
    [IsUsingHashJoin] bit NOT NULL,
    PRIMARY KEY ([CompositeGUID])
);
GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [FK_ScoreComposite_ScoreDataTable] FOREIGN KEY ([DataTableGUID1]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [FK_ScoreComposite_ScoreDataTable1] FOREIGN KEY ([DataTableGUID2]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_ModelQueryHint] DEFAULT ('OPTION(RECOMPILE)') FOR [ModelQueryHint]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF__ScoreComp__isSub__1BD46F8A] DEFAULT ((0)) FOR [isSubtable]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_FrameworkID] DEFAULT ((0)) FOR [FrameworkID]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_BoundsDataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BoundsDataTableGUID]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF__ScoreComp__Modif__7E73876C] DEFAULT (getdate()) FOR [ModifiedAt]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF__ScoreComp__IsUsi__78DC0A5C] DEFAULT ((0)) FOR [IsUsingHashJoin]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_CompositeGUID] DEFAULT (newid()) FOR [CompositeGUID]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_IsWrittenToDB] DEFAULT ((1)) FOR [IsWrittenToDB]; GO
ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_FriendlyNam] DEFAULT ('') FOR [FriendlyName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreCompositeLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreCompositeLink] (
    [CompositeLinkGUID] uniqueidentifier NOT NULL,
    [CompositeGUID] uniqueidentifier NOT NULL,
    [Type] smallint NOT NULL,
    [Key1GUID] uniqueidentifier NOT NULL,
    [Key2GUID] uniqueidentifier NOT NULL,
    [Key1AttributeGUID] uniqueidentifier NOT NULL,
    [Key2AttributeGUID] uniqueidentifier NOT NULL,
    [SQLCustomLinkExpression] nvarchar(4000) NOT NULL,
    [PlaceholderIndexMeasureGUID] uniqueidentifier NOT NULL,
    [IsPlaceholder] bit NOT NULL,
    [IsFixedIndex] bit NOT NULL,
    [CompositeLinkID] int NOT NULL,
    [ModifiedAt] datetime NOT NULL,
    PRIMARY KEY ([CompositeLinkGUID])
);
GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [FK_ScoreCompositeLink_ScoreAttribute] FOREIGN KEY ([Key1GUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [FK_ScoreCompositeLink_ScoreAttribute1] FOREIGN KEY ([Key2GUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [FK_ScoreCompositeLink_ScoreComposite] FOREIGN KEY ([CompositeGUID]) REFERENCES [dbo].[ScoreComposite] ([CompositeGUID]); GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_PlaceholderIndexMeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderIndexMeasureGUID]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_IsPlaceholder] DEFAULT ((0)) FOR [IsPlaceholder]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_IsFixedIndex] DEFAULT ((0)) FOR [IsFixedIndex]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF__ScoreComp__Modif__005BCFDE] DEFAULT (getdate()) FOR [ModifiedAt]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_Table_1_DimensionKeyMappingGUID] DEFAULT (newid()) FOR [CompositeLinkGUID]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_CompositeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CompositeGUID]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Type] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Key1GUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Key1GUID]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Key2GUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Key2GUID]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Key1AttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Key1AttributeGUID]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Key2AttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Key2AttributeGUID]; GO
ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_SQLCustomLinkExpression] DEFAULT ('') FOR [SQLCustomLinkExpression]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDataHistoryLine ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDataHistoryLine] (
    [DataHistoryLineID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [TableName] nvarchar(64) NOT NULL,
    [RowID] int NOT NULL,
    [BeforeValues] nvarchar(max) NOT NULL,
    [AfterValues] nvarchar(max) NOT NULL,
    PRIMARY KEY ([DataHistoryLineID])
);
GO
ALTER TABLE [dbo].[ScoreDataHistoryLine] ADD CONSTRAINT [DF_ScoreDataHistoryLine_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDataTable ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDataTable] (
    [DataTableGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(64) NOT NULL,
    [Description] varchar(2000) NOT NULL,
    [SQLSchemaName] nvarchar(128) NOT NULL,
    [SQLObjectName] nvarchar(128) NOT NULL,
    [SQLTableAlias] nvarchar(50) NOT NULL,
    [IsWrittenToDB] bit NOT NULL,
    [DisplayFormatAttributeGUID] uniqueidentifier NOT NULL,
    [DataTableID] int NOT NULL,
    [SQLTableAliasUnique] nvarchar(72) NULL,
    [IsCompositeMappingTable] bit NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    [ModifiedAt] datetime NOT NULL,
    [IsWrittenIfZero] bit NOT NULL,
    [GlobalID] nvarchar(128) NULL,
    [IsCompositeBoundsTable] bit NOT NULL,
    [DisplayFormatAttributeDimensionGUID] uniqueidentifier NOT NULL,
    [IsClientFriendly] bit NOT NULL,
    [OverrideLoadBySQLSchemaName] nvarchar(200) NOT NULL,
    [OverrideLoadBySQLObjectName] nvarchar(200) NOT NULL,
    [IsGeneratingSelectIntoTempTable] bit NOT NULL,
    [ModelQueryHint] nvarchar(900) NOT NULL,
    [DIDeleteQueryHint] nvarchar(900) NOT NULL,
    PRIMARY KEY ([DataTableGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_ScoreDataTable_SQLTableAlias] ON [dbo].[ScoreDataTable] ([SQLTableAliasUnique]);
GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__DIDel__0AC084A0] DEFAULT ('') FOR [DIDeleteQueryHint]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_ScoreDataTableGUID] DEFAULT (newid()) FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_SQLSchemaName] DEFAULT ('') FOR [SQLSchemaName]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_SQLObjectName] DEFAULT ('') FOR [SQLObjectName]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_SQLTableAlias] DEFAULT ('') FOR [SQLTableAlias]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_IsWrittenToDB] DEFAULT ((1)) FOR [IsWrittenToDB]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_DisplayFormatAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DisplayFormatAttributeGUID]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_IsCompositeMappingTable] DEFAULT ((0)) FOR [IsCompositeMappingTable]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_FrameworkID] DEFAULT ((0)) FOR [FrameworkID]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__Overr__235C540D] DEFAULT ('') FOR [OverrideLoadBySQLSchemaName]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_IsWrittenIfZero] DEFAULT ((0)) FOR [IsWrittenIfZero]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__Overr__24507846] DEFAULT ('') FOR [OverrideLoadBySQLObjectName]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__IsCli__302CA709] DEFAULT ((0)) FOR [IsClientFriendly]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_DisplayFormatAttributeDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DisplayFormatAttributeDimensionGUID]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__IsGen__426291E9] DEFAULT ((0)) FOR [IsGeneratingSelectIntoTempTable]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_GlobalID] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_IsCompositeBoundsTable] DEFAULT ((0)) FOR [IsCompositeBoundsTable]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__Modif__02441850] DEFAULT (getdate()) FOR [ModifiedAt]; GO
ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__Model__7F575CE7] DEFAULT ('OPTION(RECOMPILE)') FOR [ModelQueryHint]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDataTableKeyLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDataTableKeyLink] (
    [DataTableKeyLinkGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [KeyGUID] uniqueidentifier NOT NULL,
    [ObjectID] int NOT NULL,
    [ColumnID] int NOT NULL,
    [SchemaName] nvarchar(128) NOT NULL,
    [ObjectName] nvarchar(128) NOT NULL,
    [ColumnName] nvarchar(128) NOT NULL,
    [ObjectType] int NOT NULL,
    [MaxLength] smallint NOT NULL,
    [IsComputed] bit NOT NULL,
    [IsNullable] bit NOT NULL,
    [Scale] tinyint NOT NULL,
    [Precision] tinyint NOT NULL,
    [IsIdentity] bit NOT NULL,
    [ColumnTypeValue] tinyint NOT NULL,
    [IdentityIncrement] int NOT NULL,
    [IdentitySeed] int NOT NULL,
    [DefaultValueDefinition] nvarchar(max) NOT NULL,
    [IsPartOfUniqueIndex] bit NOT NULL,
    [IsUniqueIndex] bit NOT NULL,
    [IsPartOfPrimaryKey] bit NOT NULL,
    [IsPrimaryKey] bit NOT NULL,
    [ComputedValueDefinition] nvarchar(max) NOT NULL,
    [IsForeignKeyed] bit NOT NULL,
    [ForeignKeySchema] nvarchar(128) NOT NULL,
    [ForeignKeyTable] nvarchar(128) NOT NULL,
    [ForeignKeyColumn] nvarchar(128) NOT NULL,
    [ForeignKeyOnDelete] nvarchar(128) NOT NULL,
    [ModifiedAt] datetime NOT NULL,
    [IsRequired] bit NOT NULL,
    [Description] nvarchar(1000) NOT NULL,
    PRIMARY KEY ([DataTableKeyLinkGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_ScoreDataTableKeyLink_UniqueKey] ON [dbo].[ScoreDataTableKeyLink] ([DataTableGUID], [KeyGUID]);
GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [FK_ScoreDataTableKeyLink_ScoreAttribute] FOREIGN KEY ([KeyGUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [FK_ScoreDataTableKeyLink_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsIde__36ECEAB9] DEFAULT ((0)) FOR [IsIdentity]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Colum__37E10EF2] DEFAULT ((0)) FOR [ColumnTypeValue]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Ident__38D5332B] DEFAULT ((0)) FOR [IdentityIncrement]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Ident__39C95764] DEFAULT ((0)) FOR [IdentitySeed]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Defau__3ABD7B9D] DEFAULT ('') FOR [DefaultValueDefinition]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsPar__3BB19FD6] DEFAULT ((0)) FOR [IsPartOfUniqueIndex]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsUni__3CA5C40F] DEFAULT ((0)) FOR [IsUniqueIndex]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF_ScoreDataTableKeyLink_DataTableKeyLinkGUID] DEFAULT (newid()) FOR [DataTableKeyLinkGUID]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsPar__3D99E848] DEFAULT ((0)) FOR [IsPartOfPrimaryKey]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF_ScoreDataTableKeyLink_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsPri__3E8E0C81] DEFAULT ((0)) FOR [IsPrimaryKey]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF_ScoreDataTableKeyLink_KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyGUID]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Compu__3F8230BA] DEFAULT ('') FOR [ComputedValueDefinition]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsFor__407654F3] DEFAULT ((0)) FOR [IsForeignKeyed]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Forei__416A792C] DEFAULT ('') FOR [ForeignKeySchema]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Forei__425E9D65] DEFAULT ('') FOR [ForeignKeyTable]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Forei__4352C19E] DEFAULT ('') FOR [ForeignKeyColumn]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Forei__4446E5D7] DEFAULT ('') FOR [ForeignKeyOnDelete]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Modif__0614A934] DEFAULT (getdate()) FOR [ModifiedAt]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Descr__1854B5B5] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsReq__749BD5C3] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Objec__2C6F5C46] DEFAULT ((0)) FOR [ObjectID]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Colum__2D63807F] DEFAULT ((0)) FOR [ColumnID]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Schem__2E57A4B8] DEFAULT ('') FOR [SchemaName]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Objec__2F4BC8F1] DEFAULT ('') FOR [ObjectName]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Colum__303FED2A] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Objec__31341163] DEFAULT ((0)) FOR [ObjectType]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__MaxLe__3228359C] DEFAULT ((0)) FOR [MaxLength]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsCom__331C59D5] DEFAULT ((0)) FOR [IsComputed]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsNul__34107E0E] DEFAULT ((0)) FOR [IsNullable]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Scale__3504A247] DEFAULT ((0)) FOR [Scale]; GO
ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Preci__35F8C680] DEFAULT ((0)) FOR [Precision]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDataTableLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDataTableLink] (
    [DataTableLinkGUID] uniqueidentifier NOT NULL,
    [DataTable1GUID] uniqueidentifier NOT NULL,
    [DataTable1KeyGUID] uniqueidentifier NOT NULL,
    [DataTable2GUID] uniqueidentifier NOT NULL,
    [DataTable2KeyGUID] uniqueidentifier NOT NULL,
    [IsReportingOnly] bit NOT NULL,
    [IsReceivingParentTableColumns] bit NOT NULL,
    [IsChildDataCached] bit NOT NULL,
    PRIMARY KEY ([DataTableLinkGUID])
);
GO
ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTable1GUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTable1GUID]; GO
ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTable1KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTable1KeyGUID]; GO
ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTable2GUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTable2GUID]; GO
ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [df_IsChildDataCached] DEFAULT ((0)) FOR [IsChildDataCached]; GO
ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTableLinkGUID] DEFAULT (newid()) FOR [DataTableLinkGUID]; GO
ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTable2KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTable2KeyGUID]; GO
ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF__ScoreData__IsRep__6B365FCD] DEFAULT ((0)) FOR [IsReportingOnly]; GO
ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF__ScoreData__IsRec__6E738A82] DEFAULT ((0)) FOR [IsReceivingParentTableColumns]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDataTableMeasureGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDataTableMeasureGroup] (
    [ScoreDataTableMeasureGroupGUID] uniqueidentifier NOT NULL,
    [MeasureGroupName] nvarchar(200) NOT NULL,
    [CubeViewName] nvarchar(200) NOT NULL,
    [ScoreDataTableGUID] uniqueidentifier NOT NULL,
    [IsPrimary] bit NOT NULL,
    [DatasourceViewName] nvarchar(200) NOT NULL,
    PRIMARY KEY ([ScoreDataTableMeasureGroupGUID])
);
GO
ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__IsPri__0B96ABB9] DEFAULT ((0)) FOR [IsPrimary]; GO
ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__Datas__152015F3] DEFAULT ('') FOR [DatasourceViewName]; GO
ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__Score__161E5BCD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreDataTableGUID]; GO
ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__Score__5E778A7A] DEFAULT (newid()) FOR [ScoreDataTableMeasureGroupGUID]; GO
ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__Measu__6153F725] DEFAULT ('') FOR [MeasureGroupName]; GO
ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__CubeV__62481B5E] DEFAULT ('') FOR [CubeViewName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDatatableSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDatatableSetting] (
    [DataTableGUID] uniqueidentifier NOT NULL,
    [IsUsed] bit NOT NULL,
    [IsRequired] bit NOT NULL,
    PRIMARY KEY ([DataTableGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ_SCOREDATATABLESETTING_DATATABLEGUID] ON [dbo].[ScoreDatatableSetting] ([DataTableGUID]);
GO
ALTER TABLE [dbo].[ScoreDatatableSetting] ADD CONSTRAINT [DF__ScoreData__DataT__4D620D11] DEFAULT (newid()) FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[ScoreDatatableSetting] ADD CONSTRAINT [DF__ScoreData__IsUse__4E56314A] DEFAULT ((0)) FOR [IsUsed]; GO
ALTER TABLE [dbo].[ScoreDatatableSetting] ADD CONSTRAINT [DF__ScoreData__IsReq__5EAC94A4] DEFAULT ((0)) FOR [IsRequired]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDimension ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDimension] (
    [DimensionGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(128) NOT NULL,
    [Description] varchar(2000) NOT NULL,
    [SQLTableAlias] nvarchar(50) NOT NULL,
    [DefaultKeyGUID] uniqueidentifier NOT NULL,
    [DefaultHierarchyGUID] uniqueidentifier NOT NULL,
    [DefaultLookupKeyGUID] uniqueidentifier NOT NULL,
    [IsSecured] bit NOT NULL,
    [PermissionSetID] smallint NOT NULL,
    [SQLSchemaName] nvarchar(128) NOT NULL,
    [SQLObjectName] nvarchar(max) NOT NULL,
    [DefaultMemberGUID] uniqueidentifier NOT NULL,
    [IsSysAdminOnly] bit NOT NULL,
    [IsAllowMemberDelete] bit NOT NULL,
    [IsAllowMemberAdd] bit NOT NULL,
    [PrimaryGroupGUID] uniqueidentifier NOT NULL,
    [SQLTableAliasUnique] nvarchar(72) NULL,
    [DimensionID] int NOT NULL,
    [IsStock] bit NOT NULL,
    [DateModified] datetime NOT NULL,
    [PickerType] int NOT NULL,
    [IsSharingSecurity] bit NOT NULL,
    [DimensionVersion] int NOT NULL,
    [IsGeneratingWrapperView] bit NOT NULL,
    [GlobalID] nvarchar(50) NOT NULL,
    [DimensionEditorMode] int NOT NULL,
    [IsSensitivityRiskHidden] bit NOT NULL,
    [PHIDisclaimer] nvarchar(2000) NOT NULL,
    [CopyrightDisclaimer] nvarchar(2000) NOT NULL,
    [IsSecurityReadOnly] bit NOT NULL,
    [IsSecuredSetupOnly] bit NOT NULL,
    [IsClientFriendly] bit NOT NULL,
    [IsSecurityTriggersEnabled] bit NOT NULL,
    [HelpTextAttributeGUID] uniqueidentifier NOT NULL,
    [IsEditable] bit NOT NULL,
    [IsCustomAttributeAllowed] bit NOT NULL,
    [IsCustom] bit NOT NULL,
    [ParentDimensionGUID] uniqueidentifier NOT NULL,
    [StandardCodesLastUpdated] smalldatetime NOT NULL,
    [StandardCodesVersion] smalldatetime NOT NULL,
    [IsStandard] bit NOT NULL,
    [IsDisablingHistoryTriggers] bit NOT NULL,
    PRIMARY KEY ([DimensionGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_FriendlyName] ON [dbo].[ScoreDimension] ([FriendlyName]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ScoreDimension_SQLTableAlias] ON [dbo].[ScoreDimension] ([SQLTableAliasUnique]);
GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_SQLTableAlias] DEFAULT ('') FOR [SQLTableAlias]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSecuredSetupOnly] DEFAULT ((0)) FOR [IsSecuredSetupOnly]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DefaultKeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultKeyGUID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DefaultHeirarchyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultHierarchyGUID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DefaultLookupKeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultLookupKeyGUID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSecured] DEFAULT ((0)) FOR [IsSecured]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_PermissionSetID] DEFAULT ((0)) FOR [PermissionSetID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_SQLSchema] DEFAULT ('') FOR [SQLSchemaName]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_SQLObjectName] DEFAULT ('') FOR [SQLObjectName]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DefaultMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultMemberGUID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSysAdminOnly] DEFAULT ((0)) FOR [IsSysAdminOnly]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsAllowMemberDelete] DEFAULT ((1)) FOR [IsAllowMemberDelete]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsAllowMemberAdd] DEFAULT ((1)) FOR [IsAllowMemberAdd]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__Stand__0D222ED4] DEFAULT ('1900-01-01 00:00:00') FOR [StandardCodesLastUpdated]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsStock] DEFAULT ((0)) FOR [IsStock]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__Stand__0E16530D] DEFAULT ('1900-01-01 00:00:00') FOR [StandardCodesVersion]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsSta__0F0A7746] DEFAULT ((0)) FOR [IsStandard]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_PickerType] DEFAULT ((0)) FOR [PickerType]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DimensionVersion] DEFAULT ((2)) FOR [DimensionVersion]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsGeneratingWrapperView] DEFAULT ((0)) FOR [IsGeneratingWrapperView]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__PHIDi__21B13D24] DEFAULT ('') FOR [PHIDisclaimer]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__Copyr__22A5615D] DEFAULT ('') FOR [CopyrightDisclaimer]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsDis__26F8A61E] DEFAULT ((0)) FOR [IsDisablingHistoryTriggers]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsCli__2F3882D0] DEFAULT ((0)) FOR [IsClientFriendly]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSecurityTriggersEnabled] DEFAULT ((1)) FOR [IsSecurityTriggersEnabled]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsCus__3AC439E9] DEFAULT ((0)) FOR [IsCustom]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsCus__40E72793] DEFAULT ((1)) FOR [IsCustomAttributeAllowed]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__HelpT__4B0195F7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HelpTextAttributeGUID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DimensionEditorMode] DEFAULT ((0)) FOR [DimensionEditorMode]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_GlobalID] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSharingSecurity] DEFAULT ((0)) FOR [IsSharingSecurity]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__Paren__60F66677] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentDimensionGUID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsSen__65A4DE10] DEFAULT ((0)) FOR [IsSensitivityRiskHidden]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsEdi__664DB66C] DEFAULT ((1)) FOR [IsEditable]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_PrimaryGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PrimaryGroupGUID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSecurityReadOnly] DEFAULT ((0)) FOR [IsSecurityReadOnly]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DimensionGUID] DEFAULT (newid()) FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDimensionFramework ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDimensionFramework] (
    [DimensionGUID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    PRIMARY KEY ([DimensionGUID], [FrameworkID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDimensionGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDimensionGroup] (
    [DimensionGroupGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [Description] varchar(2000) NOT NULL,
    [SchemaName] nvarchar(128) NOT NULL,
    [ObjectName] nvarchar(128) NOT NULL,
    [IsStock] bit NOT NULL,
    [DateModified] datetime NOT NULL,
    PRIMARY KEY ([DimensionGroupGUID])
);
GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [FK_ScoreDimensionGroup_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Dimen__758215A1] DEFAULT (newid()) FOR [DimensionGroupGUID]; GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDimen__Name__776A5E13] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Descr__785E824C] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Schem__7952A685] DEFAULT ('') FOR [SchemaName]; GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Objec__7A46CABE] DEFAULT ('') FOR [ObjectName]; GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__IsSto__7B3AEEF7] DEFAULT ((0)) FOR [IsStock]; GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF_ScoreDimensionGroup_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Dimen__767639DA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDimensionGroupViewHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDimensionGroupViewHistory] (
    [ScoreDimensionGroupViewHistoryID] int NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [DimensionGroupGUID] uniqueidentifier NOT NULL,
    [ViewBefore] nvarchar(max) NOT NULL,
    [ViewAfter] nvarchar(max) NOT NULL,
    [DateModified] datetime NOT NULL,
    PRIMARY KEY ([ScoreDimensionGroupViewHistoryID])
);
GO
ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__Dimen__5ECBC4DE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__Dimen__5FBFE917] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGroupGUID]; GO
ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__ViewB__60B40D50] DEFAULT ('') FOR [ViewBefore]; GO
ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__ViewA__61A83189] DEFAULT ('') FOR [ViewAfter]; GO
ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__DateM__629C55C2] DEFAULT (getdate()) FOR [DateModified]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDimensionHistoryLine ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDimensionHistoryLine] (
    [DimensionHistoryLineID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [TableName] nvarchar(64) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [BeforeValues] nvarchar(max) NOT NULL,
    [AfterValues] nvarchar(max) NOT NULL,
    PRIMARY KEY ([DimensionHistoryLineID])
);

CREATE NONCLUSTERED INDEX [NC_HISTORYITEMGUID_DATETIMESTAMP] ON [dbo].[ScoreDimensionHistoryLine] ([HistoryItemGUID], [DateTimeStamp]);
CREATE NONCLUSTERED INDEX [NC_MEMBERGUID_DATETIMESTAMP] ON [dbo].[ScoreDimensionHistoryLine] ([MemberGUID], [DateTimeStamp]);
GO
ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_TableName] DEFAULT ('') FOR [TableName]; GO
ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_BeforeValues] DEFAULT ('') FOR [BeforeValues]; GO
ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_AfterValues] DEFAULT ('') FOR [AfterValues]; GO
ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_MemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreDimensionRegenRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreDimensionRegenRequest] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IssuedAt] datetime NOT NULL,
    [ErrorMessage] nvarchar(max) NOT NULL,
    [Recommendation] nvarchar(max) NOT NULL,
    [Author] nvarchar(100) NOT NULL,
    [MigrationName] nvarchar(400) NOT NULL,
    [LastProcessAttempt] datetime NOT NULL,
    PRIMARY KEY ([RequestGUID])
);
GO
ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_LastProcessAttempt] DEFAULT ('1/1/1900 12:00:00 AM') FOR [LastProcessAttempt]; GO
ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_MigrationName] DEFAULT ('') FOR [MigrationName]; GO
ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_ErrorMessage] DEFAULT ('') FOR [ErrorMessage]; GO
ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_Recommendation] DEFAULT ('') FOR [Recommendation]; GO
ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_Author] DEFAULT ('') FOR [Author]; GO
ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_GlobalID] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_IssuedAt] DEFAULT (getdate()) FOR [IssuedAt]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreFillInTemplateItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreFillInTemplateItem] (
    [FillInTemplateName] nvarchar(100) NOT NULL,
    [FillInTemplateItemID] int NOT NULL,
    [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL,
    [PlaceholderSectionIndex] int NULL,
    [IsQuery] bit NOT NULL,
    [Query] nvarchar(max) NULL,
    [IsCurrentModelGUID] bit NOT NULL,
    [IsConstantMemberGUID] bit NOT NULL,
    [ConstantMemberGUID] uniqueidentifier NULL,
    PRIMARY KEY ([FillInTemplateItemID])
);
GO
ALTER TABLE [dbo].[ScoreFillInTemplateItem] ADD CONSTRAINT [DF_ScoreFillInTemplateItem_FillInTemplateName] DEFAULT ('') FOR [FillInTemplateName]; GO
ALTER TABLE [dbo].[ScoreFillInTemplateItem] ADD CONSTRAINT [DF_ScoreFillInTemplate_IsQuery] DEFAULT ((0)) FOR [IsQuery]; GO
ALTER TABLE [dbo].[ScoreFillInTemplateItem] ADD CONSTRAINT [DF_ScoreFillInTemplate_IsCurrentModelGUID] DEFAULT ((0)) FOR [IsCurrentModelGUID]; GO
ALTER TABLE [dbo].[ScoreFillInTemplateItem] ADD CONSTRAINT [DF_ScoreFillInTemplateItem_IsConstantMemberGUID] DEFAULT ((0)) FOR [IsConstantMemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreFillin ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreFillin] (
    [FillinGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL,
    [PlaceholderIndex] int NOT NULL,
    [FillinMemberGUID] uniqueidentifier NOT NULL,
    [FillinMemberName] nvarchar(max) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [RowID] int NOT NULL,
    [IsSystemSet] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ScoreFillin_Cluster] ON [dbo].[ScoreFillin] ([ModelGUID], [PlaceholderSectionMemberGUID]);
CREATE NONCLUSTERED INDEX [idx_isdeleted] ON [dbo].[ScoreFillin] ([IsDeleted]) INCLUDE ([FillinGUID]);
CREATE NONCLUSTERED INDEX [IDX_ScoreFillin] ON [dbo].[ScoreFillin] ([ModelGUID], [PlaceholderSectionMemberGUID], [FillinMemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [IDX_ScoreFillin_Unique] ON [dbo].[ScoreFillin] ([ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [IsDeleted]);
CREATE NONCLUSTERED INDEX [IDX_ScoreFillin_FillinMemberGUID] ON [dbo].[ScoreFillin] ([FillinMemberGUID]);
GO
ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [FK_ScoreFillin_XPlan] FOREIGN KEY ([ModelGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO
ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_PlaceholderIndex] DEFAULT ((0)) FOR [PlaceholderIndex]; GO
ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_ScoreFillinGUID] DEFAULT (newid()) FOR [FillinGUID]; GO
ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_FillInMemberName] DEFAULT (N'default') FOR [FillinMemberName]; GO
ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF__ScoreFill__IsSys__7440DD13] DEFAULT ((0)) FOR [IsSystemSet]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreFillinExclusivityLogItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreFillinExclusivityLogItem] (
    [ScoreFillinExclusivityLogItemGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [FillinGUID] uniqueidentifier NOT NULL,
    [FillinMemberGUID] uniqueidentifier NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [Message] nvarchar(max) NOT NULL,
    [TaskGUID] uniqueidentifier NOT NULL,
    [IsError] bit NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [FillinDimensionGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ScoreFillinExclusivityLogItemGUID])
);
GO
ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_dbo_ScoreFillinExclusivityLogItem_FillinDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinDimensionGUID]; GO
ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_dbo_ScoreFillinExclusivityLogItem_IsError] DEFAULT ((0)) FOR [IsError]; GO
ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_dbo_ScoreFillinExclusivityLogItem_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_ScoreFillinExclusivityLogItem_ScoreFillinExclusivityLogItemGUID] DEFAULT (newid()) FOR [ScoreFillinExclusivityLogItemGUID]; GO
ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_ScoreFillinExclusivityLogItem_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreFillinRefreshLogItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreFillinRefreshLogItem] (
    [ScoreFillinRefreshLogItemGUID] uniqueidentifier NOT NULL,
    [FillinGUID] uniqueidentifier NOT NULL,
    [FillinMemberGUID] uniqueidentifier NOT NULL,
    [Action] smallint NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [TaskGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [IsSystemSet] bit NOT NULL,
    [FillinMemberName] nvarchar(max) NOT NULL,
    [SectionName] nvarchar(100) NOT NULL,
    PRIMARY KEY ([ScoreFillinRefreshLogItemGUID])
);

CREATE NONCLUSTERED INDEX [IX_ScoreFillinRefreshLogItem_FillinMemberGUID] ON [dbo].[ScoreFillinRefreshLogItem] ([FillinMemberGUID]) INCLUDE ([ModelGUID], [FillinMemberName]);
CREATE NONCLUSTERED INDEX [IX_ScoreFillinRefreshLogItem_ModelGUID] ON [dbo].[ScoreFillinRefreshLogItem] ([ModelGUID]);
CREATE NONCLUSTERED INDEX [NCNU_HistoryItemGUID] ON [dbo].[ScoreFillinRefreshLogItem] ([HistoryItemGUID]);
GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__IsSys__08325F64] DEFAULT ((0)) FOR [IsSystemSet]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__Filli__0926839D] DEFAULT ('') FOR [FillinMemberName]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__Histo__073E3B2B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_ScoreFillinRefreshLogItemGUID] DEFAULT (newid()) FOR [ScoreFillinRefreshLogItemGUID]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_FillinGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinGUID]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_FillinMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinMemberGUID]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_Action] DEFAULT ((-1)) FOR [Action]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__Secti__2A1D6314] DEFAULT ('') FOR [SectionName]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_TaskGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TaskGUID]; GO
ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__Model__7AB868B5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreFillinSetManyStaging ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreFillinSetManyStaging] (
    [InstanceGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [FillinMemberGUID] uniqueidentifier NOT NULL,
    [FillinMemberName] nvarchar(50) NOT NULL,
    [MakeUnique] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [dbo].[ScoreFillinSetManyStaging] ADD CONSTRAINT [DF_ScoreFillinSetManyStaging_MakeUnique] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MakeUnique]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreFillin_old ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreFillin_old] (
    [FillinGUID] uniqueidentifier NOT NULL,
    [ModelGUID] uniqueidentifier NOT NULL,
    [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL,
    [PlaceholderIndex] int NOT NULL,
    [FillinMemberGUID] uniqueidentifier NOT NULL,
    [FillinMemberName] nvarchar(max) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [RowID] int NOT NULL,
    [IsSystemSet] bit NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreHierarchy ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreHierarchy] (
    [HierarchyGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(128) NOT NULL,
    [PathAlias] nvarchar(12) NOT NULL,
    [DateModified] datetime NOT NULL,
    [HierarchyID] int NOT NULL,
    [GlobalID] nvarchar(128) NOT NULL,
    [IsMR] bit NOT NULL,
    PRIMARY KEY ([HierarchyGUID])
);
GO
ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [FK_ScoreHierarchy_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO
ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF__ScoreHiera__IsMR__09519DF0] DEFAULT ((0)) FOR [IsMR]; GO
ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF_ScoreHierarchy_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF__ScoreHier__Globa__177240EF] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF_ScoreHierarchy_PathAlias] DEFAULT ('') FOR [PathAlias]; GO
ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF_ScoreHeirarchy_HeirarchyGUID] DEFAULT (newid()) FOR [HierarchyGUID]; GO
ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF_ScoreHeirarchy_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreHierarchyAttributeLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreHierarchyAttributeLink] (
    [HierarchyAttributeLinkGUID] uniqueidentifier NOT NULL,
    [HierarchyGUID] uniqueidentifier NOT NULL,
    [AttributeGUID] uniqueidentifier NOT NULL,
    [DisplayAttributeGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [IsDependentOnChild] bit NOT NULL,
    [DateModified] datetime NOT NULL,
    [IsAttributeFiltered] bit NOT NULL,
    [FilterAttributeGUID] uniqueidentifier NOT NULL,
    [FilterString] nvarchar(250) NOT NULL,
    PRIMARY KEY ([HierarchyAttributeLinkGUID])
);
GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [FK_ScoreHeirarchyAttributeLink_ScoreAttribute] FOREIGN KEY ([AttributeGUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [FK_ScoreHeirarchyAttributeLink_ScoreHeirarchy] FOREIGN KEY ([HierarchyGUID]) REFERENCES [dbo].[ScoreHierarchy] ([HierarchyGUID]); GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_FilterAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FilterAttributeGUID]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_IsAttributeFiltered] DEFAULT ((0)) FOR [IsAttributeFiltered]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_FilterString] DEFAULT ('') FOR [FilterString]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHeirarchyAttributeLink_ScoreHeirarchyAttributeLinkGUID] DEFAULT (newid()) FOR [HierarchyAttributeLinkGUID]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHeirarchyAttributeLink_HeirarchyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HierarchyGUID]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_AttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AttributeGUID]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_DisplayAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DisplayAttributeGUID]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHeirarchyAttributeLink_SortOrder] DEFAULT ((1)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_IsDependentOnChild] DEFAULT ((0)) FOR [IsDependentOnChild]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreKeyLinkSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreKeyLinkSetting] (
    [ScoreKeyLinkSettingGuid] uniqueidentifier NOT NULL,
    [KeyGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [IsUsed] bit NOT NULL,
    [IsCustom] bit NOT NULL,
    [IsMarkedForDeletion] bit NOT NULL,
    PRIMARY KEY ([ScoreKeyLinkSettingGuid])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ_SCOREKEYLINKSETTING_DATATABLEGUIDKEYGUID] ON [dbo].[ScoreKeyLinkSetting] ([DataTableGUID], [KeyGUID]);
GO
ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [FK__ScoreKeyL__DataT__5226C22E] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDatatableSetting] ([DataTableGUID]); GO
ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [DF__ScoreKeyL__IsMar__3BBB8B7E] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO
ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [DF__ScoreKeyL__Score__51329DF5] DEFAULT (newid()) FOR [ScoreKeyLinkSettingGuid]; GO
ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [DF__ScoreKeyL__IsUse__531AE667] DEFAULT ((0)) FOR [IsUsed]; GO
ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [DF__ScoreKeyL__IsCus__55032ED9] DEFAULT ((0)) FOR [IsCustom]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreMeasure ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreMeasure] (
    [MeasureGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(64) NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [IsReadFromDB] bit NOT NULL,
    [IsWrittenToDB] bit NOT NULL,
    [SQLColumnName] nvarchar(64) NOT NULL,
    [DisplayFormat] nvarchar(64) NOT NULL,
    [HasMin] bit NOT NULL,
    [Min] decimal NOT NULL,
    [HasMax] bit NOT NULL,
    [Max] decimal NOT NULL,
    [HasMinLength] bit NOT NULL,
    [MinLength] int NOT NULL,
    [DefaultValue] nvarchar(64) NOT NULL,
    [AggType] int NOT NULL,
    [SpecialMeasureIndex] tinyint NOT NULL,
    [SpecialFormulaSQLColumnName] nvarchar(64) NOT NULL,
    [SpecialCommentSQLColumnName] nvarchar(64) NOT NULL,
    [HasRestrictedValues] bit NOT NULL,
    [RestrictedValues] nvarchar(max) NOT NULL,
    [ObjectID] int NOT NULL,
    [ColumnID] int NOT NULL,
    [SchemaName] nvarchar(128) NOT NULL,
    [ObjectName] nvarchar(128) NOT NULL,
    [ColumnName] nvarchar(128) NOT NULL,
    [ObjectType] int NOT NULL,
    [MaxLength] smallint NOT NULL,
    [IsComputed] bit NOT NULL,
    [IsNullable] bit NOT NULL,
    [Scale] tinyint NOT NULL,
    [Precision] tinyint NOT NULL,
    [IsIdentity] bit NOT NULL,
    [ColumnTypeValue] tinyint NOT NULL,
    [IdentityIncrement] int NOT NULL,
    [IdentitySeed] int NOT NULL,
    [DefaultValueDefinition] nvarchar(max) NOT NULL,
    [IsPartOfUniqueIndex] bit NOT NULL,
    [IsUniqueIndex] bit NOT NULL,
    [IsPartOfPrimaryKey] bit NOT NULL,
    [IsPrimaryKey] bit NOT NULL,
    [ComputedValueDefinition] nvarchar(max) NOT NULL,
    [IsForeignKeyed] bit NOT NULL,
    [ForeignKeySchema] nvarchar(128) NOT NULL,
    [ForeignKeyTable] nvarchar(128) NOT NULL,
    [ForeignKeyColumn] nvarchar(128) NOT NULL,
    [ForeignKeyOnDelete] nvarchar(128) NOT NULL,
    [ModifiedAt] datetime NOT NULL,
    [IsHidden] bit NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IsRequired] bit NOT NULL,
    [Description] nvarchar(1000) NOT NULL,
    [DisplayFolder] nvarchar(50) NOT NULL,
    PRIMARY KEY ([MeasureGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_ScoreMeasure_UniqueColumn] ON [dbo].[ScoreMeasure] ([DataTableGUID], [SQLColumnName]);
CREATE NONCLUSTERED INDEX [IX_MemberGUID] ON [dbo].[ScoreMeasure] ([MeasureGUID]) INCLUDE ([SQLColumnName]);
GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [FK_ScoreMeasure_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Objec__13A3AE7C] DEFAULT ((0)) FOR [ObjectID]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Colum__1497D2B5] DEFAULT ((0)) FOR [ColumnID]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Schem__158BF6EE] DEFAULT ('') FOR [SchemaName]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Objec__16801B27] DEFAULT ('') FOR [ObjectName]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Colum__17743F60] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Objec__18686399] DEFAULT ((0)) FOR [ObjectType]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__MaxLe__195C87D2] DEFAULT ((0)) FOR [MaxLength]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsCom__1A50AC0B] DEFAULT ((0)) FOR [IsComputed]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsNul__1B44D044] DEFAULT ((0)) FOR [IsNullable]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Scale__1C38F47D] DEFAULT ((0)) FOR [Scale]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Preci__1D2D18B6] DEFAULT ((0)) FOR [Precision]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Descr__1948D9EE] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsIde__1E213CEF] DEFAULT ((0)) FOR [IsIdentity]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Colum__1F156128] DEFAULT ((0)) FOR [ColumnTypeValue]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Displ__1BD9C8F2] DEFAULT ('') FOR [DisplayFolder]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Ident__20098561] DEFAULT ((0)) FOR [IdentityIncrement]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Ident__20FDA99A] DEFAULT ((0)) FOR [IdentitySeed]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Defau__21F1CDD3] DEFAULT ('') FOR [DefaultValueDefinition]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsPar__22E5F20C] DEFAULT ((0)) FOR [IsPartOfUniqueIndex]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsUni__23DA1645] DEFAULT ((0)) FOR [IsUniqueIndex]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsPar__24CE3A7E] DEFAULT ((0)) FOR [IsPartOfPrimaryKey]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsPri__25C25EB7] DEFAULT ((0)) FOR [IsPrimaryKey]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Compu__26B682F0] DEFAULT ('') FOR [ComputedValueDefinition]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsFor__27AAA729] DEFAULT ((0)) FOR [IsForeignKeyed]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Forei__289ECB62] DEFAULT ('') FOR [ForeignKeySchema]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Forei__2992EF9B] DEFAULT ('') FOR [ForeignKeyTable]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Forei__2A8713D4] DEFAULT ('') FOR [ForeignKeyColumn]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Forei__2B7B380D] DEFAULT ('') FOR [ForeignKeyOnDelete]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Modif__042C60C2] DEFAULT (getdate()) FOR [ModifiedAt]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsHid__30F380B4] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_SpecialMeasureIndex] DEFAULT ((0)) FOR [SpecialMeasureIndex]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_HasRestrictedValues] DEFAULT ((0)) FOR [HasRestrictedValues]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_SpecialFormulaSQLColumnName] DEFAULT ('') FOR [SpecialFormulaSQLColumnName]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_RestrictedValues] DEFAULT ('') FOR [RestrictedValues]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_SpecialCommentSQLColumnName] DEFAULT ('') FOR [SpecialCommentSQLColumnName]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_AggType] DEFAULT ((1)) FOR [AggType]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_MeasureGUID] DEFAULT (newid()) FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_IsReadFromDB] DEFAULT ((1)) FOR [IsReadFromDB]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_IsWrittenToDB] DEFAULT ((1)) FOR [IsWrittenToDB]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsReq__5DB8706B] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_SQLColumnName] DEFAULT ('') FOR [SQLColumnName]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_Min] DEFAULT ((0)) FOR [Min]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_DisplayFormat] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_Max] DEFAULT ((0)) FOR [Max]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_HasMin] DEFAULT ((0)) FOR [HasMin]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_HasMax] DEFAULT ((0)) FOR [HasMax]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_HasMinLength] DEFAULT ((0)) FOR [HasMinLength]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_MinLength] DEFAULT ((0)) FOR [MinLength]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_DefaultValue] DEFAULT ('') FOR [DefaultValue]; GO
ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Globa__73B5684A] DEFAULT ('') FOR [GlobalID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreMeasureLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreMeasureLink] (
    [MeasureLinkID] int NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [ParentMeasureGUID] uniqueidentifier NOT NULL,
    [MeasureLinkType] int NOT NULL,
    PRIMARY KEY ([MeasureLinkID])
);
GO
ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [FK_ScoreMeasureLink_ScoreMeasure] FOREIGN KEY ([MeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO
ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [FK_ScoreMeasureLink_ScoreMeasure1] FOREIGN KEY ([ParentMeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO
ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [DF_ScoreMeasureLink_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [DF_ScoreMeasureLink_MeasureLinkType] DEFAULT ((0)) FOR [MeasureLinkType]; GO
ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [DF_ScoreMeasureLink_ParentMeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentMeasureGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreMeasureLinkParameter ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreMeasureLinkParameter] (
    [MeasureLinkID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Value] nvarchar(max) NOT NULL,
    PRIMARY KEY ([MeasureLinkID], [Name])
);
GO
ALTER TABLE [dbo].[ScoreMeasureLinkParameter] ADD CONSTRAINT [FK_ScoreMeasureLinkParameter_ScoreMeasureLink] FOREIGN KEY ([MeasureLinkID]) REFERENCES [dbo].[ScoreMeasureLink] ([MeasureLinkID]); GO
ALTER TABLE [dbo].[ScoreMeasureLinkParameter] ADD CONSTRAINT [DF_ScoreMeasureLinkParameter_MeasureLinkID] DEFAULT ((0)) FOR [MeasureLinkID]; GO
ALTER TABLE [dbo].[ScoreMeasureLinkParameter] ADD CONSTRAINT [DF_ScoreMeasureLinkParameter_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[ScoreMeasureLinkParameter] ADD CONSTRAINT [DF_ScoreMeasureLinkParameter_Value] DEFAULT ('') FOR [Value]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreMeasureSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreMeasureSetting] (
    [ScoreMeasureSettingGuid] uniqueidentifier NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [IsUsed] bit NOT NULL,
    [IsCustom] bit NOT NULL,
    [IsMarkedForDeletion] bit NOT NULL,
    PRIMARY KEY ([ScoreMeasureSettingGuid])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ_SCOREMEASURESETTING_MEASUREGUID] ON [dbo].[ScoreMeasureSetting] ([MeasureGUID]);
GO
ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [FK__ScoreMeas__DataT__58D3BFBD] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDatatableSetting] ([DataTableGUID]); GO
ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [DF__ScoreMeas__IsMar__3CAFAFB7] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO
ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [DF__ScoreMeas__Score__57DF9B84] DEFAULT (newid()) FOR [ScoreMeasureSettingGuid]; GO
ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [DF__ScoreMeas__IsUse__59C7E3F6] DEFAULT ((0)) FOR [IsUsed]; GO
ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [DF__ScoreMeas__IsCus__5BB02C68] DEFAULT ((0)) FOR [IsCustom]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreModelLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreModelLink] (
    [ModelLinkID] int NOT NULL,
    [SourceModelGUID] uniqueidentifier NOT NULL,
    [TargetModelGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ModelLinkID])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreTableEditorColumn ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreTableEditorColumn] (
    [TableEditorColumnGUID] uniqueidentifier NOT NULL,
    [TableEditorConfigGUID] uniqueidentifier NOT NULL,
    [KeyGUID] uniqueidentifier NOT NULL,
    [Type] int NOT NULL,
    [PixelWidth] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    [MetaData] xml NOT NULL,
    [DisplayName] nvarchar(450) NOT NULL,
    [DefaultMemberType] int NOT NULL,
    [IsTextWrap] bit NOT NULL,
    [IsSortedByDefault] bit NOT NULL,
    [DefaultSortDirectionValue] int NOT NULL,
    [DefaultSortIndex] int NOT NULL,
    [TableEditorColumnGroupGUID] uniqueidentifier NOT NULL,
    [IsRequired] bit NOT NULL,
    [IsLocked] bit NOT NULL,
    [IsNonFilterable] bit NOT NULL,
    PRIMARY KEY ([TableEditorColumnGUID])
);
GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [FK_ScoreTableEditorColumn_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF__ScoreTabl__Table__7586401E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorColumnGroupGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_IsTextWrap] DEFAULT ((0)) FOR [IsTextWrap]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF__ScoreTabl__IsReq__2B67F1EC] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_IsDefaultSorted] DEFAULT ((0)) FOR [IsSortedByDefault]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF__ScoreTabl__IsLoc__2D503A5E] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DefaultSortDirectionValue] DEFAULT ((0)) FOR [DefaultSortDirectionValue]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DefaultSortIndex] DEFAULT ((0)) FOR [DefaultSortIndex]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF__ScoreTabl__IsNon__330913B4] DEFAULT ((0)) FOR [IsNonFilterable]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DisplayName] DEFAULT ('') FOR [DisplayName]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DefaultMemberType] DEFAULT ((0)) FOR [DefaultMemberType]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_TableEditorColumnGUID] DEFAULT (newid()) FOR [TableEditorColumnGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_IsMeasure] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_PixelWidth] DEFAULT ((150)) FOR [PixelWidth]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_MetaData] DEFAULT ('') FOR [MetaData]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreTableEditorColumnGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreTableEditorColumnGroup] (
    [TableEditorColumnGroupGUID] uniqueidentifier NOT NULL,
    [TableEditorConfigGUID] uniqueidentifier NOT NULL,
    [DisplayColumnGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [GroupType] int NOT NULL,
    [IsActive] bit NOT NULL,
    PRIMARY KEY ([TableEditorColumnGroupGUID])
);
GO
ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [FK__ScoreTabl__Table__4DCD547F] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO
ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTabl__Table__4CD93046] DEFAULT (newid()) FOR [TableEditorColumnGroupGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTabl__Displ__4EC178B8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DisplayColumnGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTable__Name__4FB59CF1] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTabl__Group__50A9C12A] DEFAULT ((0)) FOR [GroupType]; GO
ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTabl__IsAct__519DE563] DEFAULT ((0)) FOR [IsActive]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreTableEditorConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreTableEditorConfig] (
    [TableEditorConfigGUID] uniqueidentifier NOT NULL,
    [DataSourceGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(64) NOT NULL,
    [MaxRecords] int NOT NULL,
    [DefaultSortColumnGUID] uniqueidentifier NOT NULL,
    [DefaultSortDirection] bit NOT NULL,
    [IsShowingExpanded] bit NOT NULL,
    [IsMeasureEditOnly] bit NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [IsTemplateBased] bit NOT NULL,
    [FixedRowHeight] int NOT NULL,
    [IsDeleteAllowed] bit NOT NULL,
    [RowNumberColumnGUID] uniqueidentifier NOT NULL,
    [CreatedDate] datetime NOT NULL,
    [CreatedBy] uniqueidentifier NOT NULL,
    [LastUsedDate] datetime NOT NULL,
    [IsPromptForFilter] bit NOT NULL,
    [IsAutoAddRow] bit NOT NULL,
    [IsPlanFKFilterEnabled] bit NOT NULL,
    [IsForModel] bit NOT NULL,
    [IsSaveCommentsRequired] bit NOT NULL,
    [VarianceMode] int NOT NULL,
    [IsSensitivityRiskEnabled] bit NOT NULL,
    [IsReadOnly] bit NOT NULL,
    [IsBaselineLocked] bit NOT NULL,
    [IsAddAllowed] bit NOT NULL,
    [IsScoreFillinAdvancedMode] bit NOT NULL,
    [OnSaveCustomScriptGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([TableEditorConfigGUID])
);
GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsScoreFillinAdvancedMode] DEFAULT ((0)) FOR [IsScoreFillinAdvancedMode]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_CreatedBy] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CreatedBy]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsSensitivityRiskEnabled] DEFAULT ((0)) FOR [IsSensitivityRiskEnabled]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_TableEditorConfigGUID] DEFAULT (newid()) FOR [TableEditorConfigGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_DataSourceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_Name] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_MaxRecords] DEFAULT ((500)) FOR [MaxRecords]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_DefaultSortKeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultSortColumnGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_DefaultSortDirection] DEFAULT ((0)) FOR [DefaultSortDirection]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsShowingExpanded] DEFAULT ((0)) FOR [IsShowingExpanded]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsMeasureEditOnly] DEFAULT ((0)) FOR [IsMeasureEditOnly]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsTemplateBased] DEFAULT ((0)) FOR [IsTemplateBased]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_FixedRowHeight] DEFAULT ((50)) FOR [FixedRowHeight]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsDeleteAllowed] DEFAULT ((1)) FOR [IsDeleteAllowed]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF__ScoreTabl__Varia__231800A4] DEFAULT ((0)) FOR [VarianceMode]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsAutoAddRow] DEFAULT ((0)) FOR [IsAutoAddRow]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_OnSaveCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnSaveCustomScriptGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsForModel] DEFAULT ((0)) FOR [IsForModel]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_LastUsedDate] DEFAULT (getdate()) FOR [LastUsedDate]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsPromptForFilter] DEFAULT ((0)) FOR [IsPromptForFilter]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF__ScoreTabl__IsBas__66990249] DEFAULT ((0)) FOR [IsBaselineLocked]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF__ScoreTabl__IsSav__686AA574] DEFAULT ((0)) FOR [IsSaveCommentsRequired]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsAddAllowed] DEFAULT ((1)) FOR [IsAddAllowed]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_RowNumberColumnGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RowNumberColumnGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsPlanFKFilterEnabled] DEFAULT ((1)) FOR [IsPlanFKFilterEnabled]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreTableEditorFilter ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreTableEditorFilter] (
    [TableEditorFilterGUID] uniqueidentifier NOT NULL,
    [TableEditorConfigGUID] uniqueidentifier NOT NULL,
    [KeyGUID] uniqueidentifier NOT NULL,
    [HierarchyPath] nvarchar(4000) NOT NULL,
    [FriendlyName] nvarchar(450) NOT NULL,
    [FilterType] int NOT NULL,
    [MetaData] nvarchar(max) NOT NULL,
    PRIMARY KEY ([TableEditorFilterGUID])
);
GO
ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [FK_ScoreTableEditorFilter_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO
ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_TableEditorFilterGUID] DEFAULT (newid()) FOR [TableEditorFilterGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyGUID]; GO
ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_HierarchyPath] DEFAULT ('') FOR [HierarchyPath]; GO
ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_FilterType] DEFAULT ((0)) FOR [FilterType]; GO
ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_MetaData] DEFAULT ('') FOR [MetaData]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ScoreTupleDataHistoryChangeItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[ScoreTupleDataHistoryChangeItem] (
    [RowID] int NOT NULL,
    [ChangedRowID] bigint NOT NULL,
    [DataTableGUID] uniqueidentifier NOT NULL,
    [WorksheetName] nvarchar(max) NOT NULL,
    [CellAddress] nvarchar(100) NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [TupleString] nvarchar(max) NOT NULL,
    [BeforeValueString] nvarchar(max) NOT NULL,
    [BeforeFormula] nvarchar(max) NOT NULL,
    [BeforeValueIsNumeric] bit NOT NULL,
    [AfterValueString] nvarchar(max) NOT NULL,
    [AfterFormula] nvarchar(max) NOT NULL,
    [AfterValueIsNumeric] bit NOT NULL,
    [IsUserSet] bit NOT NULL,
    [IdentityGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ScoreTupleDataHistoryChangeItem] ON [dbo].[ScoreTupleDataHistoryChangeItem] ([HistoryItemGUID]);
GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_IdentityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentityGUID]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_WorksheetName] DEFAULT ('') FOR [WorksheetName]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_CellAddress] DEFAULT ('') FOR [CellAddress]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_TupleString] DEFAULT ('') FOR [TupleString]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_BeforeValueString] DEFAULT ('') FOR [BeforeValueString]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_BeforeFormula] DEFAULT ('') FOR [BeforeFormula]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_BeforeValueIsNumeric] DEFAULT ((0)) FOR [BeforeValueIsNumeric]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_AfterValueString] DEFAULT ('') FOR [AfterValueString]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_AfterFormula] DEFAULT ('') FOR [AfterFormula]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_AfterValueIsNumeric] DEFAULT ((0)) FOR [AfterValueIsNumeric]; GO
ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_IsUserSet] DEFAULT ((0)) FOR [IsUserSet]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SecureList ------------------
---------------------------------------------
CREATE TABLE [dbo].[SecureList] (
    [ListGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [DefaultListMemberGUID] uniqueidentifier NOT NULL,
    [DisplayOrder] int NOT NULL,
    [AggregationType] int NOT NULL,
    [OriginalGUID] uniqueidentifier NOT NULL,
    [ListType] int NOT NULL,
    [DimensionType] int NOT NULL,
    [Version] timestamp NOT NULL,
    [DefaultListMemberID] nvarchar(450) NOT NULL,
    [IsSecured] bit NOT NULL,
    [UnknownMemberBehavior] int NOT NULL,
    [IsPlaceholder] bit NOT NULL,
    [FillInDimensionGUID] uniqueidentifier NOT NULL,
    [PermissionSetID] smallint NOT NULL,
    [IsSetupLocked] bit NOT NULL,
    [IsSecurityHackEnabled] bit NOT NULL,
    [IsEditLocked] bit NOT NULL,
    [SyncedScoreDimensionGUID] uniqueidentifier NULL,
    [SyncedScoreNameAttributeGUID] uniqueidentifier NULL,
    [ConvertedScoreDimensionGUID] uniqueidentifier NULL,
    [SyncedScoreOrderByAttributeGUID] uniqueidentifier NULL,
    PRIMARY KEY ([ListGUID])
);
GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_PermissionSetID] DEFAULT ((0)) FOR [PermissionSetID]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsSetupLocked] DEFAULT ((0)) FOR [IsSetupLocked]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_ConvertedScoreDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConvertedScoreDimensionGUID]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_ListGUID] DEFAULT (newid()) FOR [ListGUID]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_DEFAULTLISTITEMGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultListMemberGUID]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_DISPLAYORDER_1] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsAggregatable] DEFAULT ((1)) FOR [AggregationType]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_ORIGINALGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OriginalGUID]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_LISTOWNERTYPE] DEFAULT ((0)) FOR [ListType]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_LISTTYPE] DEFAULT ((0)) FOR [DimensionType]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_DEFAULTLISTMEMBERID] DEFAULT ('') FOR [DefaultListMemberID]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsSecured] DEFAULT ((0)) FOR [IsSecured]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_UNKNOWNMEMBERBEHAVIOR] DEFAULT ((0)) FOR [UnknownMemberBehavior]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsPlaceholder] DEFAULT ((0)) FOR [IsPlaceholder]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_FillInDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillInDimensionGUID]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsEditLocked] DEFAULT ((0)) FOR [IsEditLocked]; GO
ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsSecurityHackEnabled] DEFAULT ((0)) FOR [IsSecurityHackEnabled]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SecureListInsertionPoint ------------------
---------------------------------------------
CREATE TABLE [dbo].[SecureListInsertionPoint] (
    [ListInsertionPointGUID] uniqueidentifier NOT NULL,
    [ListGUID] uniqueidentifier NOT NULL,
    [ParentListMemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    PRIMARY KEY ([ListInsertionPointGUID])
);
GO
ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [FK_SecureListInsertionPoint_SecureList] FOREIGN KEY ([ListGUID]) REFERENCES [dbo].[SecureList] ([ListGUID]); GO
ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_LISTINSERTIONPOINTGUID] DEFAULT (newid()) FOR [ListInsertionPointGUID]; GO
ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_LISTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ListGUID]; GO
ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_PARENTLISTMEMBERGUID_1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentListMemberGUID]; GO
ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_DESCRIPTION] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SecureListLevel ------------------
---------------------------------------------
CREATE TABLE [dbo].[SecureListLevel] (
    [ListLevelGUID] uniqueidentifier NOT NULL,
    [ListGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [LevelIndex] int NOT NULL,
    [LevelType] int NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([ListLevelGUID])
);

CREATE CLUSTERED INDEX [IX_SecureListLevel] ON [dbo].[SecureListLevel] ([ListGUID], [LevelIndex]);
GO
ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [FK_SecureListLevel_SecureList] FOREIGN KEY ([ListGUID]) REFERENCES [dbo].[SecureList] ([ListGUID]); GO
ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_Table_1_SECURELISTLEVEL] DEFAULT (newid()) FOR [ListLevelGUID]; GO
ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_SecureListLevel_SECURELISTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ListGUID]; GO
ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_SecureListLevel_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_SecureListLevel_INDEX] DEFAULT ((0)) FOR [LevelIndex]; GO
ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_SecureListLevel_LEVELTYPE] DEFAULT ((0)) FOR [LevelType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SecureListMember ------------------
---------------------------------------------
CREATE TABLE [dbo].[SecureListMember] (
    [ListMemberGUID] uniqueidentifier NOT NULL,
    [ListGUID] uniqueidentifier NOT NULL,
    [ParentListMemberGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [FullPath] nvarchar(4000) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [OutlineLevel] int NOT NULL,
    [OperatorType] int NOT NULL,
    [Version] timestamp NOT NULL,
    [IsIDLocked] bit NOT NULL,
    [IsNameLocked] bit NOT NULL,
    [IsDeleteLocked] bit NOT NULL,
    [IsNewChildLocked] bit NOT NULL,
    [IsParentAssociationLocked] bit NOT NULL,
    [IsEditAttributeLocked] bit NOT NULL,
    [ListMemberID] nvarchar(400) NOT NULL,
    [SortOrderFullPath] nvarchar(4000) NOT NULL,
    [FillInConfigGUID] uniqueidentifier NOT NULL,
    [FillInDimensionGUID] uniqueidentifier NULL,
    [DateCreated] datetime NOT NULL,
    [DateModified] datetime NOT NULL,
    [LootIDOverride] nvarchar(128) NULL,
    [LootID] nvarchar(128) NULL,
    PRIMARY KEY ([ListMemberGUID])
);

CREATE CLUSTERED INDEX [IX_ListMember_ListGUID] ON [dbo].[SecureListMember] ([ListGUID]);
CREATE NONCLUSTERED INDEX [IX_ListMember_ParentGUID] ON [dbo].[SecureListMember] ([ParentListMemberGUID]);
CREATE NONCLUSTERED INDEX [IX_ListMember_DisplayOrder] ON [dbo].[SecureListMember] ([DisplayOrder]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ListMember_UniqueDK] ON [dbo].[SecureListMember] ([ListGUID], [ListMemberID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ListMember_Unique] ON [dbo].[SecureListMember] ([ListGUID], [ParentListMemberGUID], [Name]);
GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_PARENTLISTITEMGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentListMemberGUID]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_LISTITEMGUID] DEFAULT (newid()) FOR [ListMemberGUID]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_LISTGUID] DEFAULT (newid()) FOR [ListGUID]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_FULLPATH] DEFAULT ('') FOR [FullPath]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_OUTLINELEVEL] DEFAULT ((0)) FOR [OutlineLevel]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_OPERATORTYPE] DEFAULT ((0)) FOR [OperatorType]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISIDLOCKED] DEFAULT ((0)) FOR [IsIDLocked]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISNAMELOCKED] DEFAULT ((0)) FOR [IsNameLocked]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISDELETELOCKED] DEFAULT ((0)) FOR [IsDeleteLocked]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISNEWCHILDLOCKED] DEFAULT ((0)) FOR [IsNewChildLocked]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISPARENTLOCKED] DEFAULT ((0)) FOR [IsParentAssociationLocked]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISEDITATTRIBUTELOCKED] DEFAULT ((0)) FOR [IsEditAttributeLocked]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_LISTMEMBERID] DEFAULT ('') FOR [ListMemberID]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_DISPLAYORDERFULLPATH] DEFAULT ('') FOR [SortOrderFullPath]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_FillInDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillInConfigGUID]; GO
ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SecureListMemberValue ------------------
---------------------------------------------
CREATE TABLE [dbo].[SecureListMemberValue] (
    [ListMemberValueGUID] uniqueidentifier NOT NULL,
    [ListMemberGUID] uniqueidentifier NOT NULL,
    [ListGUID] uniqueidentifier NOT NULL,
    [Type] int NOT NULL,
    [ValueFloat] float NOT NULL,
    [ValueText] nvarchar(1000) NOT NULL,
    [ValueIndex] int NOT NULL,
    [DateCreated] datetime NOT NULL,
    [DateModified] datetime NOT NULL,
    [Version] timestamp NOT NULL
);

CREATE CLUSTERED INDEX [IX_ListMemberValue_ListGUID] ON [dbo].[SecureListMemberValue] ([ListGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [PK_ListMemberValue] ON [dbo].[SecureListMemberValue] ([ListMemberValueGUID]);
CREATE NONCLUSTERED INDEX [IX_ListMemberValue_ListMemberGUID] ON [dbo].[SecureListMemberValue] ([ListMemberGUID]);
CREATE NONCLUSTERED INDEX [IX_ListMemberValue_ValueIndex] ON [dbo].[SecureListMemberValue] ([ValueIndex]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_SecureListMemberValue] ON [dbo].[SecureListMemberValue] ([ListMemberGUID], [ValueIndex]);
GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [FK_SecureListMemberValue_SecureListMember] FOREIGN KEY ([ListMemberGUID]) REFERENCES [dbo].[SecureListMember] ([ListMemberGUID]); GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_VALUEFLOAT] DEFAULT ((0)) FOR [ValueFloat]; GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SecureListMemberValue_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SecureListMemberValue_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SecureListMemberValue_INDEX] DEFAULT ((0)) FOR [ValueIndex]; GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_VALUETEXT] DEFAULT ('') FOR [ValueText]; GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_LISTITEMVALUEGUID] DEFAULT (newid()) FOR [ListMemberValueGUID]; GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_LISTITEMGUID] DEFAULT (newid()) FOR [ListMemberGUID]; GO
ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_LISTGUID] DEFAULT (newid()) FOR [ListGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SecureListProperty ------------------
---------------------------------------------
CREATE TABLE [dbo].[SecureListProperty] (
    [ListPropertyGUID] uniqueidentifier NOT NULL,
    [ListGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [PropertyIndex] int NOT NULL,
    [PropertyType] int NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([ListPropertyGUID])
);
GO
ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [FK_SecureListProperty_SecureList] FOREIGN KEY ([ListGUID]) REFERENCES [dbo].[SecureList] ([ListGUID]); GO
ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_SECURELISTPROPERTYGUID] DEFAULT (newid()) FOR [ListPropertyGUID]; GO
ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_SECURELISTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ListGUID]; GO
ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_INDEX] DEFAULT ((0)) FOR [PropertyIndex]; GO
ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_PROPERTYTYPE] DEFAULT ((0)) FOR [PropertyType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SecurityHistoryItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[SecurityHistoryItem] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [UserName] nvarchar(64) NOT NULL,
    [Type] nvarchar(64) NOT NULL,
    [Change] nvarchar(64) NOT NULL,
    [Field1] nvarchar(64) NOT NULL,
    [Field2] nvarchar(64) NOT NULL,
    [BeforeValue] nvarchar(1024) NOT NULL,
    [AfterValue] nvarchar(1024) NOT NULL,
    [TimeStampUtc] datetime NOT NULL,
    PRIMARY KEY ([HistoryItemGUID])
);
GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__After__00A05511] DEFAULT ('') FOR [AfterValue]; GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__TimeS__52425D49] DEFAULT (getutcdate()) FOR [TimeStampUtc]; GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Histo__78FF3349] DEFAULT (newid()) FOR [HistoryItemGUID]; GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__UserN__7AE77BBB] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityHi__Type__7BDB9FF4] DEFAULT ('') FOR [Type]; GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Chang__7CCFC42D] DEFAULT ('') FOR [Change]; GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Field__7DC3E866] DEFAULT ('') FOR [Field1]; GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Field__7EB80C9F] DEFAULT ('') FOR [Field2]; GO
ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Befor__7FAC30D8] DEFAULT ('') FOR [BeforeValue]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SisenseDataMart ------------------
---------------------------------------------
CREATE TABLE [dbo].[SisenseDataMart] (
    [SisenseDataMartGUID] uniqueidentifier NOT NULL,
    [DataMartName] nvarchar(200) NOT NULL,
    [StrataId] nvarchar(5) NOT NULL,
    [FactTableName] nvarchar(100) NOT NULL,
    [DataTableGuid] uniqueidentifier NOT NULL,
    [QueryTag] nvarchar(50) NOT NULL,
    [FactTablePrefix] nvarchar(100) NOT NULL,
    [SisenseFactTable] nvarchar(200) NOT NULL,
    [IsUsingDepartmentSecurity] bit NOT NULL,
    [IsAppendedOnly] bit NOT NULL,
    [WarehouseSize] nvarchar(200) NOT NULL,
    [IsUsingReportingSchema] bit NOT NULL,
    PRIMARY KEY ([SisenseDataMartGUID])
);
GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [FK__SisenseDa__DataT__14C51914] FOREIGN KEY ([DataTableGuid]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Sisen__0518C130] DEFAULT ('') FOR [SisenseFactTable]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Sisen__0F0C3FBE] DEFAULT (newid()) FOR [SisenseDataMartGUID]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__DataM__100063F7] DEFAULT ('') FOR [DataMartName]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Strat__10F48830] DEFAULT ('') FOR [StrataId]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__FactT__11E8AC69] DEFAULT ('') FOR [FactTableName]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Query__12DCD0A2] DEFAULT ('') FOR [QueryTag]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__FactT__13D0F4DB] DEFAULT ('') FOR [FactTablePrefix]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Wareh__261A8D9F] DEFAULT ('REPORT_XS_WH') FOR [WarehouseSize]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__IsApp__286CEA65] DEFAULT ((0)) FOR [IsAppendedOnly]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__IsUsi__40103523] DEFAULT ((0)) FOR [IsUsingReportingSchema]; GO
ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__IsUsi__6EDF674E] DEFAULT ((0)) FOR [IsUsingDepartmentSecurity]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SnapinActionConfig ------------------
---------------------------------------------
CREATE TABLE [dbo].[SnapinActionConfig] (
    [SnapinActionConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(50) NOT NULL,
    PRIMARY KEY ([SnapinActionConfigGUID])
);
GO
ALTER TABLE [dbo].[SnapinActionConfig] ADD CONSTRAINT [DF_SnapinActionConfig_SnapinActionGUID] DEFAULT (newid()) FOR [SnapinActionConfigGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SnapinActionItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[SnapinActionItem] (
    [SnapinActionItemGUID] uniqueidentifier NOT NULL,
    [SnapinActionConfigGUID] uniqueidentifier NOT NULL,
    [SnapinGUID] uniqueidentifier NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [DisplayOrder] smallint NOT NULL,
    [Mode] tinyint NOT NULL,
    PRIMARY KEY ([SnapinActionItemGUID])
);
GO
ALTER TABLE [dbo].[SnapinActionItem] ADD CONSTRAINT [FK_SnapinActionItem_SnapinActionConfig] FOREIGN KEY ([SnapinActionConfigGUID]) REFERENCES [dbo].[SnapinActionConfig] ([SnapinActionConfigGUID]); GO
ALTER TABLE [dbo].[SnapinActionItem] ADD CONSTRAINT [DF_Table_1_SnapinActionStripItemGUID] DEFAULT (newid()) FOR [SnapinActionItemGUID]; GO
ALTER TABLE [dbo].[SnapinActionItem] ADD CONSTRAINT [DF_SnapinActionItem_Description] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[SnapinActionItem] ADD CONSTRAINT [DF_SnapinActionItem_Mode] DEFAULT ((0)) FOR [Mode]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SnapinActionItemFramework ------------------
---------------------------------------------
CREATE TABLE [dbo].[SnapinActionItemFramework] (
    [SnapinActionItemGUID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL
);
GO
ALTER TABLE [dbo].[SnapinActionItemFramework] ADD CONSTRAINT [FK_SnapinActionItemFramework_SnapinActionItem] FOREIGN KEY ([SnapinActionItemGUID]) REFERENCES [dbo].[SnapinActionItem] ([SnapinActionItemGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.SnapinActionItemTag ------------------
---------------------------------------------
CREATE TABLE [dbo].[SnapinActionItemTag] (
    [SnapinActionItemGUID] uniqueidentifier NOT NULL,
    [TagGUID] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [dbo].[SnapinActionItemTag] ADD CONSTRAINT [FK_SnapinActionItemTag_SnapinActionItem] FOREIGN KEY ([SnapinActionItemGUID]) REFERENCES [dbo].[SnapinActionItem] ([SnapinActionItemGUID]); GO

---------------------------------------------

---------------------------------------------
-- dbo.StandardCodesDimensionUpgradeRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[StandardCodesDimensionUpgradeRequest] (
    [StandardCodesDimensionUpgradeRequestGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [StandardCodesDimensionName] nvarchar(400) NOT NULL,
    PRIMARY KEY ([StandardCodesDimensionUpgradeRequestGUID])
);
GO
ALTER TABLE [dbo].[StandardCodesDimensionUpgradeRequest] ADD CONSTRAINT [DF__StandardC__Dimen__1523434F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[StandardCodesDimensionUpgradeRequest] ADD CONSTRAINT [DF__StandardC__Stand__142F1F16] DEFAULT (newid()) FOR [StandardCodesDimensionUpgradeRequestGUID]; GO
ALTER TABLE [dbo].[StandardCodesDimensionUpgradeRequest] ADD CONSTRAINT [DF__StandardC__Stand__16176788] DEFAULT ('') FOR [StandardCodesDimensionName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.StandardCodesUpdateRulesRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[StandardCodesUpdateRulesRequest] (
    [StandardCodesDimensionUpgradeRequestGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([StandardCodesDimensionUpgradeRequestGUID])
);
GO
ALTER TABLE [dbo].[StandardCodesUpdateRulesRequest] ADD CONSTRAINT [DF__StandardC__Dimen__76A9DAF1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO
ALTER TABLE [dbo].[StandardCodesUpdateRulesRequest] ADD CONSTRAINT [DF__StandardC__Stand__75B5B6B8] DEFAULT (newid()) FOR [StandardCodesDimensionUpgradeRequestGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.StandardDefinitionMapping ------------------
---------------------------------------------
CREATE TABLE [dbo].[StandardDefinitionMapping] (
    [MappingId] int NOT NULL,
    [StandardDefinitionGUID] uniqueidentifier NOT NULL,
    [StandardDefinitionType] nvarchar(200) NOT NULL,
    [MappingMemberValue] nvarchar(max) NULL,
    PRIMARY KEY ([MappingId])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.Survey ------------------
---------------------------------------------
CREATE TABLE [dbo].[Survey] (
    [SurveyGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(128) NOT NULL,
    [Description] varchar(400) NOT NULL,
    PRIMARY KEY ([SurveyGUID])
);
GO
ALTER TABLE [dbo].[Survey] ADD CONSTRAINT [DF_Survey_SurveyGUID] DEFAULT (newid()) FOR [SurveyGUID]; GO
ALTER TABLE [dbo].[Survey] ADD CONSTRAINT [DF_Survey_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SurveyItem ------------------
---------------------------------------------
CREATE TABLE [dbo].[SurveyItem] (
    [SurveyItemGUID] uniqueidentifier NOT NULL,
    [SurveyGUID] uniqueidentifier NOT NULL,
    [FriendlyName] nvarchar(128) NOT NULL,
    [SurveyItemType] smallint NOT NULL,
    [ContextXML] varchar(max) NOT NULL,
    [SurveyText] nvarchar(400) NOT NULL,
    [Footer] nvarchar(400) NOT NULL,
    [DisplayOrder] smallint NOT NULL,
    [IsRequired] bit NOT NULL,
    PRIMARY KEY ([SurveyItemGUID])
);
GO
ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyItem_Isrequired] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_SurveyQuestionGUID] DEFAULT (newid()) FOR [SurveyItemGUID]; GO
ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyItem_SurveyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SurveyGUID]; GO
ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_SurveyQuestionType] DEFAULT ((0)) FOR [SurveyItemType]; GO
ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_ContextXML] DEFAULT ('') FOR [ContextXML]; GO
ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_QuestionText] DEFAULT ('') FOR [SurveyText]; GO
ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyItem_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SurveyResults ------------------
---------------------------------------------
CREATE TABLE [dbo].[SurveyResults] (
    [DatabaseGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [UserName] varchar(100) NOT NULL,
    [DepartmentID] int NOT NULL,
    [FiscalYear] int NOT NULL,
    [ResultSelection] smallint NOT NULL,
    [ResultText] varchar(250) NULL,
    [ResearchSignup] bit NOT NULL,
    [SubmitDate] datetime NULL,
    PRIMARY KEY ([DatabaseGUID], [UserGUID], [FiscalYear])
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.SyncLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[SyncLog] (
    [SyncLogGUID] uniqueidentifier NOT NULL,
    [SyncDate] datetime NOT NULL,
    [SyncSource] nvarchar(400) NOT NULL,
    [Message] nvarchar(max) NOT NULL,
    [VERSION] timestamp NOT NULL,
    PRIMARY KEY ([SyncLogGUID])
);
GO
ALTER TABLE [dbo].[SyncLog] ADD CONSTRAINT [DF_SyncLog_SyncLogGUID] DEFAULT (newid()) FOR [SyncLogGUID]; GO
ALTER TABLE [dbo].[SyncLog] ADD CONSTRAINT [DF_SyncLog_SyncDate] DEFAULT (getdate()) FOR [SyncDate]; GO
ALTER TABLE [dbo].[SyncLog] ADD CONSTRAINT [DF_SyncLog_SyncSource] DEFAULT ('') FOR [SyncSource]; GO
ALTER TABLE [dbo].[SyncLog] ADD CONSTRAINT [DF_SyncLog_Message] DEFAULT ('') FOR [Message]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SysMessage ------------------
---------------------------------------------
CREATE TABLE [dbo].[SysMessage] (
    [MessageID] int NOT NULL,
    [SeverityVal] tinyint NOT NULL,
    [MessageVal] varchar(max) NOT NULL,
    [DiscriminatorVal] int NOT NULL,
    [IdentifierID] uniqueidentifier NOT NULL,
    [IsDeleted] bit NOT NULL,
    [Tag] nvarchar(100) NOT NULL,
    [TimeStampUtc] datetime NOT NULL,
    PRIMARY KEY ([MessageID])
);

CREATE NONCLUSTERED INDEX [NC_SysMessage_IdentifierID] ON [dbo].[SysMessage] ([IdentifierID]);
GO
ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessage__Tag__098D38CB] DEFAULT ('') FOR [Tag]; GO
ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__Sever__0A6DB34F] DEFAULT ((1)) FOR [SeverityVal]; GO
ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__Messa__0B61D788] DEFAULT ('') FOR [MessageVal]; GO
ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__Discr__0C55FBC1] DEFAULT ((0)) FOR [DiscriminatorVal]; GO
ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__IsDel__0E3E4433] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__TimeS__420BF580] DEFAULT (getutcdate()) FOR [TimeStampUtc]; GO
ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__Ident__0D4A1FFA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentifierID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SystemCenterCategory ------------------
---------------------------------------------
CREATE TABLE [dbo].[SystemCenterCategory] (
    [CategoryGUID] uniqueidentifier NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsMaintenanceMode] bit NOT NULL,
    [NameHtml] nvarchar(200) NOT NULL,
    PRIMARY KEY ([CategoryGUID])
);
GO
ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [FK_SystemCenterCategory_SystemCenterModule] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO
ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCen__Categ__401B89DE] DEFAULT (newid()) FOR [CategoryGUID]; GO
ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCent__Name__410FAE17] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCen__SortO__4203D250] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCen__IsMai__42F7F689] DEFAULT ((0)) FOR [IsMaintenanceMode]; GO
ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCen__NameH__6C02FAA3] DEFAULT ('') FOR [NameHtml]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SystemCenterImportHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[SystemCenterImportHistory] (
    [HistoryGUID] uniqueidentifier NOT NULL,
    [StepGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [UserName] nvarchar(200) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [TempFilePath] nvarchar(4000) NOT NULL,
    PRIMARY KEY ([HistoryGUID])
);
GO
ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [FK_SystemCenterImportHistory_SystemCenterStep] FOREIGN KEY ([StepGUID]) REFERENCES [dbo].[SystemCenterStep] ([StepGUID]); GO
ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__Histo__013B7ADC] DEFAULT (newid()) FOR [HistoryGUID]; GO
ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__UserN__0323C34E] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__DateT__0417E787] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__TempF__050C0BC0] DEFAULT ('') FOR [TempFilePath]; GO
ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__UserG__022F9F15] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SystemCenterModule ------------------
---------------------------------------------
CREATE TABLE [dbo].[SystemCenterModule] (
    [ModuleGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [SolutionGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [IsLicensed] bit NOT NULL,
    [IsSetupComplete] bit NOT NULL,
    [IsUsed_DEPRECATED] bit NOT NULL,
    [NameHtml] nvarchar(200) NOT NULL,
    PRIMARY KEY ([ModuleGUID])
);
GO
ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__Modul__396E8C4F] DEFAULT (newid()) FOR [ModuleGUID]; GO
ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCent__Name__3A62B088] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__SortO__3B56D4C1] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__IsLic__3C4AF8FA] DEFAULT ((0)) FOR [IsLicensed]; GO
ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__IsSet__3D3F1D33] DEFAULT ((0)) FOR [IsSetupComplete]; GO
ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__NameH__6CF71EDC] DEFAULT ('') FOR [NameHtml]; GO
ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__IsUse__708B4DBD] DEFAULT ((1)) FOR [IsUsed_DEPRECATED]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SystemCenterSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[SystemCenterSection] (
    [SectionGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [CategoryGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [LastUserGUID] uniqueidentifier NULL,
    [Date] datetime NOT NULL,
    [SectionState] tinyint NOT NULL,
    [ViewModelClassName] nvarchar(400) NOT NULL,
    [SessionClassName] nvarchar(100) NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [Info] nvarchar(max) NOT NULL,
    [LastUserNameFull] nvarchar(200) NOT NULL,
    [NameHtml] nvarchar(200) NOT NULL,
    PRIMARY KEY ([SectionGUID])
);
GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [FK_SystemCenterSection_SystemCenterCategory] FOREIGN KEY ([CategoryGUID]) REFERENCES [dbo].[SystemCenterCategory] ([CategoryGUID]); GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__Secti__46C8876D] DEFAULT (newid()) FOR [SectionGUID]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__SortO__47BCABA6] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCent__Name__48B0CFDF] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__LastU__49A4F418] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastUserGUID]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCent__Date__4A991851] DEFAULT (CONVERT([datetime],(0))) FOR [Date]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__Secti__4B8D3C8A] DEFAULT ((0)) FOR [SectionState]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__ViewM__4C8160C3] DEFAULT ('') FOR [ViewModelClassName]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__Sessi__4D7584FC] DEFAULT ('') FOR [SessionClassName]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__Globa__4E69A935] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCent__Info__4F5DCD6E] DEFAULT ('') FOR [Info]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__NameH__6B0ED66A] DEFAULT ('') FOR [NameHtml]; GO
ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__LastU__717F71F6] DEFAULT ('') FOR [LastUserNameFull]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SystemCenterSolution ------------------
---------------------------------------------
CREATE TABLE [dbo].[SystemCenterSolution] (
    [SolutionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [Abbreviation] nvarchar(10) NOT NULL,
    [IsStatusDisabled] bit NOT NULL,
    PRIMARY KEY ([SolutionGUID])
);
GO
ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCen__IsSta__0E8826FD] DEFAULT ((0)) FOR [IsStatusDisabled]; GO
ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCen__Solut__34A9D732] DEFAULT (newid()) FOR [SolutionGUID]; GO
ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCent__Name__359DFB6B] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCen__SortO__36921FA4] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCen__Abbre__507383E6] DEFAULT ('') FOR [Abbreviation]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SystemCenterStep ------------------
---------------------------------------------
CREATE TABLE [dbo].[SystemCenterStep] (
    [StepGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [SectionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [PropertyXML] xml NOT NULL,
    [Url] nvarchar(400) NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [HelpID] nvarchar(200) NOT NULL,
    [HelpFileName] nvarchar(200) NOT NULL,
    PRIMARY KEY ([StepGUID])
);
GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [FK_SystemCenterStep_SystemCenterSection] FOREIGN KEY ([SectionGUID]) REFERENCES [dbo].[SystemCenterSection] ([SectionGUID]); GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__HelpI__1223ADB7] DEFAULT ('') FOR [HelpID]; GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__HelpF__4485DBA9] DEFAULT ('') FOR [HelpFileName]; GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__StepG__532E5E52] DEFAULT (newid()) FOR [StepGUID]; GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__SortO__5422828B] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCent__Name__5516A6C4] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__Prope__560ACAFD] DEFAULT ('<Properties></Properties>') FOR [PropertyXML]; GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCente__Url__56FEEF36] DEFAULT ('') FOR [Url]; GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__Globa__57F3136F] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__Descr__58E737A8] DEFAULT ('') FOR [Description]; GO

---------------------------------------------

---------------------------------------------
-- dbo.SystemSection ------------------
---------------------------------------------
CREATE TABLE [dbo].[SystemSection] (
    [SYSTEMSECTIONGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [ID] nvarchar(64) NOT NULL,
    [ParentGUID] uniqueidentifier NOT NULL,
    [FullPath] nvarchar(4000) NOT NULL,
    [ImageName] nvarchar(64) NOT NULL,
    [LootID] varchar(36) NULL,
    [IsCrossBrowser] bit NOT NULL,
    PRIMARY KEY ([SYSTEMSECTIONGUID])
);

CREATE CLUSTERED INDEX [IX_SystemSection] ON [dbo].[SystemSection] ([ID]);
GO
ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_IsCrossBrowser] DEFAULT ((1)) FOR [IsCrossBrowser]; GO
ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_SYSTEMSECTIONGUID] DEFAULT (newid()) FOR [SYSTEMSECTIONGUID]; GO
ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_ID] DEFAULT ('') FOR [ID]; GO
ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_PARENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentGUID]; GO
ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_FULLPATH] DEFAULT ('') FOR [FullPath]; GO
ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_IMAGENAME] DEFAULT ('') FOR [ImageName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TEDisabledDatabase ------------------
---------------------------------------------
CREATE TABLE [dbo].[TEDisabledDatabase] (
    [DisabledDBConnectionGUID] uniqueidentifier NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    PRIMARY KEY ([DisabledDBConnectionGUID])
);
GO
ALTER TABLE [dbo].[TEDisabledDatabase] ADD CONSTRAINT [DF_TEDisabledDatabase_DBCONNECTIONGUID] DEFAULT (newid()) FOR [DisabledDBConnectionGUID]; GO
ALTER TABLE [dbo].[TEDisabledDatabase] ADD CONSTRAINT [DF_TEDisabledDatabase_COMMENT] DEFAULT ('No comment') FOR [Comment]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TEScheduledReminder ------------------
---------------------------------------------
CREATE TABLE [dbo].[TEScheduledReminder] (
    [ScheduledTaskReminderGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [RepeatType] int NOT NULL,
    [RepeatFrequency] int NOT NULL,
    [DayOfWeek] int NOT NULL,
    [DayOfMonth] int NOT NULL,
    [StartDate] datetime NOT NULL,
    [EndDate] datetime NOT NULL,
    [HasEndDate] bit NOT NULL,
    [IsDisabled] bit NOT NULL,
    [HasDisabledExpirationDate] bit NOT NULL,
    [DisabledExpirationDate] datetime NOT NULL,
    [TaskDuration] int NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [LastSubmittedDateUtc] datetime NOT NULL,
    [TimeZoneId] nvarchar(50) NOT NULL,
    [StartTime] time NOT NULL,
    PRIMARY KEY ([ScheduledTaskReminderGUID])
);
GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__DateC__4E71CC65] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__LastS__4F65F09E] DEFAULT (getutcdate()) FOR [LastSubmittedDateUtc]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__TimeZ__505A14D7] DEFAULT ('Central Standard Time') FOR [TimeZoneId]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Start__514E3910] DEFAULT ('00:00:00') FOR [StartTime]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Sched__60D1D8A6] DEFAULT (newid()) FOR [ScheduledTaskReminderGUID]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedule__Name__61C5FCDF] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Repea__63AE4551] DEFAULT ((0)) FOR [RepeatType]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Repea__64A2698A] DEFAULT ((0)) FOR [RepeatFrequency]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__DayOf__65968DC3] DEFAULT ((0)) FOR [DayOfWeek]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__DayOf__668AB1FC] DEFAULT ((0)) FOR [DayOfMonth]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Start__6872FA6E] DEFAULT ('1/1/1900') FOR [StartDate]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__EndDa__69671EA7] DEFAULT ('1/1/1900') FOR [EndDate]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__HasEn__6A5B42E0] DEFAULT ((1)) FOR [HasEndDate]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__IsDis__6C438B52] DEFAULT ((0)) FOR [IsDisabled]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__HasDi__6D37AF8B] DEFAULT ((0)) FOR [HasDisabledExpirationDate]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Disab__6E2BD3C4] DEFAULT ('1/1/1900') FOR [DisabledExpirationDate]; GO
ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__TaskD__6F1FF7FD] DEFAULT ((0)) FOR [TaskDuration]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TEScheduledTask ------------------
---------------------------------------------
CREATE TABLE [dbo].[TEScheduledTask] (
    [ScheduledTaskGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [RepeatType] int NOT NULL,
    [RepeatFrequency] int NOT NULL,
    [DayOfWeek] int NOT NULL,
    [DayOfMonth] int NOT NULL,
    [StartDate] datetime NOT NULL,
    [EndDate] datetime NOT NULL,
    [HasEndDate] bit NOT NULL,
    [SetupXML] nvarchar(max) NOT NULL,
    [AssemblyQualifiedName] nvarchar(450) NOT NULL,
    [HasRun] bit NOT NULL,
    [IsDisabled] bit NOT NULL,
    [HasDisabledExpirationDate] bit NOT NULL,
    [DisabledExpirationDate] datetime NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [LastRunDateUtc] datetime NOT NULL,
    [LastSubmittedDateUtc] datetime NOT NULL,
    [StartTime] time NOT NULL,
    [TimeZoneId] nvarchar(50) NOT NULL,
    PRIMARY KEY ([ScheduledTaskGUID])
);
GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_REPEATFREQUENCY] DEFAULT ((0)) FOR [RepeatFrequency]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_DAYOFWEEK] DEFAULT ((0)) FOR [DayOfWeek]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_DAYOFMONTH] DEFAULT ((0)) FOR [DayOfMonth]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_STARTDATE] DEFAULT ('1/1/1900') FOR [StartDate]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_ENDDATE] DEFAULT ('1/1/1900') FOR [EndDate]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_HASENDDATE] DEFAULT ((1)) FOR [HasEndDate]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_SETUPXML] DEFAULT ('') FOR [SetupXML]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_CLASSFULLNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_HASRUN] DEFAULT ((0)) FOR [HasRun]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_HasDisabledExpirationDate] DEFAULT ((0)) FOR [HasDisabledExpirationDate]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_DisabledExpirationDate] DEFAULT ('1/1/1900') FOR [DisabledExpirationDate]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__DateC__49AD1748] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__LastR__4AA13B81] DEFAULT (getutcdate()) FOR [LastRunDateUtc]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__LastS__4B955FBA] DEFAULT (getutcdate()) FOR [LastSubmittedDateUtc]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__Start__4C8983F3] DEFAULT ('00:00:00') FOR [StartTime]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__TimeZ__4D7DA82C] DEFAULT ('Central Standard Time') FOR [TimeZoneId]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_IsDisabled] DEFAULT ((0)) FOR [IsDisabled]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_SCHEDULEEVENTGUID] DEFAULT (newid()) FOR [ScheduledTaskGUID]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_REPEATTYPE] DEFAULT ((0)) FOR [RepeatType]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TETask ------------------
---------------------------------------------
CREATE TABLE [dbo].[TETask] (
    [TaskID] int NOT NULL,
    [TaskGUID] uniqueidentifier NOT NULL,
    [Name] varchar(450) NOT NULL,
    [Status] int NOT NULL,
    [ContextXML] varchar(max) NOT NULL,
    [CreationTime] datetime NOT NULL,
    [StartTime] datetime NOT NULL,
    [NextRunTime] datetime NOT NULL,
    [LastRunTime] datetime NOT NULL,
    [Priority] int NOT NULL,
    [DBConnectionGUID] uniqueidentifier NOT NULL,
    [AssemblyQualifiedName] varchar(1024) NOT NULL,
    [ISCollapsible] bit NOT NULL,
    [CollapsibleID] nvarchar(max) NOT NULL,
    [RetryCount] int NOT NULL,
    [TokenGUID] uniqueidentifier NOT NULL,
    [FromScheduledTaskGUID] uniqueidentifier NOT NULL,
    [AssemblyKey] varchar(64) NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [TaskSource] varchar(450) NULL,
    [WorkerID] uniqueidentifier NOT NULL,
    [GroupingID] nvarchar(100) NOT NULL,
    [GroupingIndex] smallint NOT NULL,
    [UserName] nvarchar(100) NOT NULL,
    PRIMARY KEY ([TaskGUID], [Status], [Priority], [AssemblyKey])
);

CREATE NONCLUSTERED INDEX [NCNU_Name] ON [dbo].[TETask] ([Name]);
CREATE NONCLUSTERED INDEX [OrderBy] ON [dbo].[TETask] ([Priority], [CreationTime]);
GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_TASKGUID] DEFAULT (newid()) FOR [TaskGUID]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_STATUS] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_CONTEXTXML] DEFAULT ('<CONTEXTXML></CONTEXTXML>') FOR [ContextXML]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_CREATIONTIME] DEFAULT (getdate()) FOR [CreationTime]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_STARTTIME] DEFAULT ('1/1/1900') FOR [StartTime]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_LASTRUNTIME] DEFAULT ('1/1/1900') FOR [LastRunTime]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_PRIORITY] DEFAULT ((0)) FOR [Priority]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_DBCONNECTIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DBConnectionGUID]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_ISCOLLAPSABLE] DEFAULT ((0)) FOR [ISCollapsible]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_COLLAPSABLEID] DEFAULT ('') FOR [CollapsibleID]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_RETRIES] DEFAULT ((0)) FOR [RetryCount]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_TOKENGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TokenGUID]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_FROMSCHEDULEDTASKGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FromScheduledTaskGUID]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_ASSEMBLYKEY] DEFAULT ('') FOR [AssemblyKey]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_TaskSource] DEFAULT ('') FOR [TaskSource]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_GroupingID] DEFAULT ('') FOR [GroupingID]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_GroupingIndex] DEFAULT ((0)) FOR [GroupingIndex]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_NextRunTime] DEFAULT (getdate()) FOR [NextRunTime]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_UserName] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_WorkerID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkerID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TETaskHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[TETaskHistory] (
    [TaskID] int NULL,
    [TaskGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [Status] int NOT NULL,
    [ContextXML] xml NOT NULL,
    [CreationTime] datetime NOT NULL,
    [StartTime] datetime NOT NULL,
    [LastRunTime] datetime NOT NULL,
    [Priority] int NOT NULL,
    [DBConnectionGUID] uniqueidentifier NOT NULL,
    [AssemblyQualifiedName] nvarchar(1024) NOT NULL,
    [IsCollapsible] bit NOT NULL,
    [CollapsibleID] nvarchar(max) NOT NULL,
    [RetryCount] int NOT NULL,
    [TokenGUID] uniqueidentifier NOT NULL,
    [FromScheduledTaskGUID] uniqueidentifier NOT NULL,
    [AssemblyKey] nvarchar(1024) NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [NextRunTime] datetime NOT NULL,
    [DEQUEUETIME] datetime NULL,
    [TASKSOURCE] varchar(450) NULL,
    [WORKERNAME] varchar(1024) NULL,
    [ERRORLOGGUID] uniqueidentifier NULL,
    [TASKENGINEVERSION] varchar(450) NULL,
    [TASKHISTORYID] int NOT NULL,
    [WORKERID] uniqueidentifier NOT NULL,
    [GroupingID] nvarchar(100) NOT NULL,
    [GroupingIndex] smallint NOT NULL,
    [UserName] nvarchar(100) NOT NULL,
    PRIMARY KEY ([TASKHISTORYID])
);

CREATE NONCLUSTERED INDEX [IX_NC_TASKGUID] ON [dbo].[TETaskHistory] ([TaskGUID]);
GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_GroupingID] DEFAULT ('') FOR [GroupingID]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_GroupingIndex] DEFAULT ((0)) FOR [GroupingIndex]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_TASKGUID] DEFAULT (newid()) FOR [TaskGUID]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_WORKERID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WORKERID]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_STATUS] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_CONTEXTXML] DEFAULT ('<CONTEXTXML></CONTEXTXML>') FOR [ContextXML]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_CREATIONTIME] DEFAULT (getdate()) FOR [CreationTime]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_STARTTIME] DEFAULT ('1/1/1900') FOR [StartTime]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_LASTRUNTIME] DEFAULT ('1/1/1900') FOR [LastRunTime]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_PRIORITY] DEFAULT ((0)) FOR [Priority]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_DBCONNECTIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DBConnectionGUID]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_ISCOLLAPSABLE] DEFAULT ((0)) FOR [IsCollapsible]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_COLLAPSABLEID] DEFAULT ('') FOR [CollapsibleID]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_RETRIES] DEFAULT ((0)) FOR [RetryCount]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_TOKENGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TokenGUID]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_FROMSCHEDULEDTASKGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FromScheduledTaskGUID]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_ASSEMBLYKEY] DEFAULT ('') FOR [AssemblyKey]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_NextRunTime] DEFAULT ('1/1/1900') FOR [NextRunTime]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_DEQUEUETIME] DEFAULT (getdate()) FOR [DEQUEUETIME]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_TASKSOURCE] DEFAULT ('') FOR [TASKSOURCE]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_WORKERNAME] DEFAULT ('') FOR [WORKERNAME]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_UserName] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_TASKENGINEVERSION] DEFAULT ('') FOR [TASKENGINEVERSION]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TableDeleteVersion ------------------
---------------------------------------------
CREATE TABLE [dbo].[TableDeleteVersion] (
    [TableName] nvarchar(64) NOT NULL,
    [DeleteVersion] timestamp NOT NULL
);
GO
ALTER TABLE [dbo].[TableDeleteVersion] ADD CONSTRAINT [DF_Table_1_TableName] DEFAULT ('') FOR [TableName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.Tag ------------------
---------------------------------------------
CREATE TABLE [dbo].[Tag] (
    [TagGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(400) NOT NULL,
    PRIMARY KEY ([TagGUID])
);
GO
ALTER TABLE [dbo].[Tag] ADD CONSTRAINT [DF_Tag_TagGUID] DEFAULT (newid()) FOR [TagGUID]; GO
ALTER TABLE [dbo].[Tag] ADD CONSTRAINT [DF_Tag_Tag] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TaskProgressStatus ------------------
---------------------------------------------
CREATE TABLE [dbo].[TaskProgressStatus] (
    [RowID] bigint NOT NULL,
    [TaskGUID] uniqueidentifier NOT NULL,
    [DataXML] xml NOT NULL,
    [StartTime] datetime NOT NULL,
    [TaskStatus] nvarchar(100) NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_TaskGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TaskGUID]; GO
ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_MetaInfoXML] DEFAULT ('<Data></Data>') FOR [DataXML]; GO
ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_StartTime] DEFAULT (getdate()) FOR [StartTime]; GO
ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_TaskStatus] DEFAULT ('') FOR [TaskStatus]; GO
ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_GlobalID] DEFAULT ('') FOR [GlobalID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TemplatePublishRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[TemplatePublishRequest] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [IssuedAt] datetime NOT NULL,
    [FrameworkID] int NOT NULL,
    [ExcludedTemplateGUIDs] nvarchar(max) NOT NULL,
    [PreSQL] nvarchar(max) NOT NULL,
    PRIMARY KEY ([RequestGUID])
);
GO
ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF_TemplatePublishRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF_TemplatePublishRequest_IssuedAt] DEFAULT (getdate()) FOR [IssuedAt]; GO
ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF__TemplateP__Frame__4DA5CB1C] DEFAULT ((0)) FOR [FrameworkID]; GO
ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF__TemplateP__Exclu__58E43C16] DEFAULT ('') FOR [ExcludedTemplateGUIDs]; GO
ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF__TemplateP__PreSQ__78DB70CF] DEFAULT ('') FOR [PreSQL]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TemplatePublishRequestData ------------------
---------------------------------------------
CREATE TABLE [dbo].[TemplatePublishRequestData] (
    [FileGUID] uniqueidentifier NOT NULL,
    [RequestGUID] uniqueidentifier NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [LastModified] datetime NOT NULL,
    [Data] varbinary(max) NOT NULL,
    PRIMARY KEY ([FileGUID])
);
GO
ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [FK_TemplatePublishRequestData_TemplatePublishRequest] FOREIGN KEY ([RequestGUID]) REFERENCES [dbo].[TemplatePublishRequest] ([RequestGUID]); GO
ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [DF_TemplatePublishRequestData_RequestGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RequestGUID]; GO
ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [DF_TemplatePublishRequestData_ModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO
ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [DF_TemplatePublishRequestData_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO
ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [DF_TemplatePublishRequestData_LastModified] DEFAULT (getdate()) FOR [LastModified]; GO

---------------------------------------------

---------------------------------------------
-- dbo.TemplateSettings ------------------
---------------------------------------------
CREATE TABLE [dbo].[TemplateSettings] (
    [TemplateGUID] uniqueidentifier NOT NULL,
    [SettingID] nvarchar(200) NOT NULL,
    [Value] nvarchar(max) NOT NULL
);

CREATE UNIQUE CLUSTERED INDEX [CU_TemplateGUID_SettingID] ON [dbo].[TemplateSettings] ([TemplateGUID], [SettingID]);
GO
ALTER TABLE [dbo].[TemplateSettings] ADD CONSTRAINT [DF__TemplateS__Templ__35A28DAB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TemplateGUID]; GO
ALTER TABLE [dbo].[TemplateSettings] ADD CONSTRAINT [DF__TemplateS__Setti__3696B1E4] DEFAULT ('') FOR [SettingID]; GO
ALTER TABLE [dbo].[TemplateSettings] ADD CONSTRAINT [DF__TemplateS__Value__378AD61D] DEFAULT ('') FOR [Value]; GO

---------------------------------------------

---------------------------------------------
-- dbo.ThemeInfo ------------------
---------------------------------------------
CREATE TABLE [dbo].[ThemeInfo] (
    [ThemeInfoGUID] uniqueidentifier NOT NULL,
    [Theme] nvarchar(64) NOT NULL,
    [InfoType] nvarchar(64) NOT NULL,
    [Value] nvarchar(450) NOT NULL,
    PRIMARY KEY ([ThemeInfoGUID])
);
GO
ALTER TABLE [dbo].[ThemeInfo] ADD CONSTRAINT [DF_ThemeInfo_ThemeInfoGUID] DEFAULT (newid()) FOR [ThemeInfoGUID]; GO
ALTER TABLE [dbo].[ThemeInfo] ADD CONSTRAINT [DF_ThemeInfo_Theme] DEFAULT ('') FOR [Theme]; GO
ALTER TABLE [dbo].[ThemeInfo] ADD CONSTRAINT [DF_ThemeInfo_InfoType] DEFAULT ('') FOR [InfoType]; GO
ALTER TABLE [dbo].[ThemeInfo] ADD CONSTRAINT [DF_ThemeInfo_Value] DEFAULT ('') FOR [Value]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UpgradeLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[UpgradeLog] (
    [ID] int NOT NULL,
    [Version] nvarchar(8) NOT NULL,
    [Step] nvarchar(64) NOT NULL,
    [Message] nvarchar(max) NOT NULL,
    [LogDate] datetime NOT NULL,
    [LogDateUtc] datetime NOT NULL,
    PRIMARY KEY ([ID])
);
GO
ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF__UpgradeLo__LogDa__46D0AA9D] DEFAULT (getutcdate()) FOR [LogDateUtc]; GO
ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF_UpgradeLog_Version] DEFAULT ('') FOR [Version]; GO
ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF_UpgradeLog_Step] DEFAULT ('') FOR [Step]; GO
ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF_UpgradeLog_Message] DEFAULT ('') FOR [Message]; GO
ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF_UpgradeLog_LogDate] DEFAULT (getdate()) FOR [LogDate]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserDirectoryDefaultView ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserDirectoryDefaultView] (
    [UserGUID] uniqueidentifier NOT NULL,
    [WorkspaceGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [ViewGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([UserGUID], [WorkspaceGUID], [PlanTypeGUID])
);
GO
ALTER TABLE [dbo].[UserDirectoryDefaultView] ADD CONSTRAINT [DF_UserDirectoryDefaultView_ViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ViewGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserFavorite ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserFavorite] (
    [UserFavoriteGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [ItemGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [Url] nvarchar(200) NOT NULL,
    [UrlParams] nvarchar(2000) NOT NULL,
    [LinkTypeClassName] nvarchar(100) NOT NULL,
    [LinkTypeConfig] nvarchar(max) NOT NULL,
    [DateCreated] datetime NOT NULL,
    PRIMARY KEY ([UserFavoriteGUID])
);
GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [FK__UserFavor__UserG__6C068FC2] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__UserF__6B126B89] DEFAULT (newid()) FOR [UserFavoriteGUID]; GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__ItemG__6CFAB3FB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ItemGUID]; GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavori__Name__6DEED834] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavorit__Url__6EE2FC6D] DEFAULT ('') FOR [Url]; GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__UrlPa__6FD720A6] DEFAULT ('') FOR [UrlParams]; GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__LinkT__70CB44DF] DEFAULT ('') FOR [LinkTypeClassName]; GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__LinkT__71BF6918] DEFAULT ('') FOR [LinkTypeConfig]; GO
ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__DateC__72B38D51] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserFeedback ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserFeedback] (
    [UserFeedbackGUID] uniqueidentifier NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [DateCreated] datetime NOT NULL,
    PRIMARY KEY ([UserFeedbackGUID])
);
GO
ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__UserF__37601F5E] DEFAULT (newid()) FOR [UserFeedbackGUID]; GO
ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__Autho__38544397] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__Autho__394867D0] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__Comme__3A3C8C09] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__DateC__3B30B042] DEFAULT (getdate()) FOR [DateCreated]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserGroup ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserGroup] (
    [UserGroupGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Type] int NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [Category] nvarchar(64) NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    [IsAdmin] bit NOT NULL,
    [IsSysAdmin] bit NOT NULL,
    PRIMARY KEY ([UserGroupGUID])
);

CREATE NONCLUSTERED INDEX [IX_UserGroup] ON [dbo].[UserGroup] ([Name]);
GO
ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_USERGROUPGUID] DEFAULT (newid()) FOR [UserGroupGUID]; GO
ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_CATEGORY] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_dbo_UserGroup_IsAdmin] DEFAULT ((0)) FOR [IsAdmin]; GO
ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF__UserGroup__Globa__62BB2268] DEFAULT ('') FOR [GlobalID]; GO
ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_dbo_UserGroup_IsSysAdmin] DEFAULT ((0)) FOR [IsSysAdmin]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserLimit ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserLimit] (
    [UserLimitGUID] uniqueidentifier NOT NULL,
    [NumUsers] int NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([UserLimitGUID])
);
GO
ALTER TABLE [dbo].[UserLimit] ADD CONSTRAINT [FK_UserLimit_SystemCenterModule] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO
ALTER TABLE [dbo].[UserLimit] ADD CONSTRAINT [DF_UserLimit_ModuleGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO
ALTER TABLE [dbo].[UserLimit] ADD CONSTRAINT [DF_UserLimit_UserLimitGUID] DEFAULT (newid()) FOR [UserLimitGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserProfile ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserProfile] (
    [UserGUID] uniqueidentifier NOT NULL,
    [UserName] nvarchar(64) NOT NULL,
    [HashedPassword] nvarchar(64) NOT NULL,
    [NameFirst] nvarchar(64) NOT NULL,
    [NameLast] nvarchar(64) NOT NULL,
    [NameFull] nvarchar(130) NOT NULL,
    [EmailAddress] nvarchar(450) NOT NULL,
    [PhoneNumber] nvarchar(64) NOT NULL,
    [IsSysAdmin_DEPRECATED] bit NOT NULL,
    [AuthID] nvarchar(128) NOT NULL,
    [IsDisabled] bit NOT NULL,
    [BackupPassword] nvarchar(64) NOT NULL,
    [DefaultAppModeLevel] tinyint NOT NULL,
    [BrowserVersion] nvarchar(64) NOT NULL,
    [UserAgent] nvarchar(512) NOT NULL,
    [Domain] varchar(64) NOT NULL,
    [HIPAADisclaimerStatus] tinyint NOT NULL,
    [Custom1] nvarchar(450) NOT NULL,
    [Custom2] nvarchar(450) NOT NULL,
    [Custom3] nvarchar(450) NOT NULL,
    [Custom4] nvarchar(450) NOT NULL,
    [IsHidden] bit NOT NULL,
    [DotNetVersion] nvarchar(250) NOT NULL,
    [LastChangedPasswordUtc] datetime NOT NULL,
    [LastLoginDateUtc] datetime NOT NULL,
    [Salt] uniqueidentifier NOT NULL,
    [NeedsPasswordChange] bit NOT NULL,
    PRIMARY KEY ([UserGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_UserProfile] ON [dbo].[UserProfile] ([UserName]);
GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_IsDisabled] DEFAULT ((0)) FOR [IsDisabled]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_BackupPassword] DEFAULT ('') FOR [BackupPassword]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_USERGUID] DEFAULT (newid()) FOR [UserGUID]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__IsHid__1591E9E3] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_UserName] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_HASHEDPASSWORD] DEFAULT ('') FOR [HashedPassword]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_NameFirst] DEFAULT ('') FOR [NameFirst]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_NameLast] DEFAULT ('') FOR [NameLast]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_EmailAddress] DEFAULT ('') FOR [EmailAddress]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_Custom1] DEFAULT ('') FOR [Custom1]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_PhoneNumber] DEFAULT ('') FOR [PhoneNumber]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_Custom2] DEFAULT ('') FOR [Custom2]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_Custom3] DEFAULT ('') FOR [Custom3]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_IsSysAdmin] DEFAULT ((0)) FOR [IsSysAdmin_DEPRECATED]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_Custom4] DEFAULT ('') FOR [Custom4]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_AuthID] DEFAULT ('') FOR [AuthID]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfil__Salt__2F990AE1] DEFAULT (newid()) FOR [Salt]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__Domai__36F27A1A] DEFAULT ('') FOR [Domain]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__HIPAA__398A5D63] DEFAULT ((0)) FOR [HIPAADisclaimerStatus]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_DefaultAppModeLevel] DEFAULT ((1)) FOR [DefaultAppModeLevel]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_BrowserVersion] DEFAULT ('Unknown') FOR [BrowserVersion]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_UserAgent] DEFAULT ('Unknown') FOR [UserAgent]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_NeedsPasswordChange] DEFAULT ((0)) FOR [NeedsPasswordChange]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__LastC__551EC9F4] DEFAULT (getutcdate()) FOR [LastChangedPasswordUtc]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__LastL__5612EE2D] DEFAULT (getutcdate()) FOR [LastLoginDateUtc]; GO
ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__DotNe__6AE25733] DEFAULT ('') FOR [DotNetVersion]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserProfileAppModeAccessLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserProfileAppModeAccessLink] (
    [UserGUID] uniqueidentifier NOT NULL,
    [AccessLevel] tinyint NOT NULL,
    PRIMARY KEY ([UserGUID], [AccessLevel])
);
GO
ALTER TABLE [dbo].[UserProfileAppModeAccessLink] ADD CONSTRAINT [DF__UserProfi__Acces__6D81CC7D] DEFAULT ((1)) FOR [AccessLevel]; GO
ALTER TABLE [dbo].[UserProfileAppModeAccessLink] ADD CONSTRAINT [DF__UserProfi__UserG__6C8DA844] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserRole ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserRole] (
    [UserRoleGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [Type] int NOT NULL,
    [Category] nvarchar(64) NOT NULL,
    [RoleID] smallint NOT NULL,
    [GlobalID] nvarchar(100) NOT NULL,
    PRIMARY KEY ([UserRoleGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_UserRole_RoleID] ON [dbo].[UserRole] ([RoleID]);
GO
ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_USERROLEGUID] DEFAULT (newid()) FOR [UserRoleGUID]; GO
ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_CATEGORY] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF__UserRole__Global__78CA5F18] DEFAULT ('') FOR [GlobalID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserSecurityLastModifiedDate ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserSecurityLastModifiedDate] (
    [UserGUID] uniqueidentifier NOT NULL,
    [LastModifiedDate] datetime NOT NULL,
    PRIMARY KEY ([UserGUID])
);
GO
ALTER TABLE [dbo].[UserSecurityLastModifiedDate] ADD CONSTRAINT [DF_UserSecurityLastModifiedDate_UserGUID] DEFAULT (newid()) FOR [UserGUID]; GO
ALTER TABLE [dbo].[UserSecurityLastModifiedDate] ADD CONSTRAINT [DF_UserSecurityLastModifiedDate_LastModifiedDate] DEFAULT (getdate()) FOR [LastModifiedDate]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserSetting ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserSetting] (
    [UserSettingGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(128) NOT NULL,
    [Setting] nvarchar(max) NOT NULL,
    PRIMARY KEY ([UserSettingGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [CORE_UserGUID_Name] ON [dbo].[UserSetting] ([UserGUID], [Name]);
GO
ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_SETTING] DEFAULT ('') FOR [Setting]; GO
ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_USERSETTINGGUID] DEFAULT (newid()) FOR [UserSettingGUID]; GO
ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_USERPROFILEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_NAME] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- dbo.UserTag ------------------
---------------------------------------------
CREATE TABLE [dbo].[UserTag] (
    [UserTagGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [LicenseGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([UserTagGUID])
);
GO
ALTER TABLE [dbo].[UserTag] ADD CONSTRAINT [FK_UserTag_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO
ALTER TABLE [dbo].[UserTag] ADD CONSTRAINT [DF__UserTag__License__4F638E99] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LicenseGUID]; GO
ALTER TABLE [dbo].[UserTag] ADD CONSTRAINT [DF_UserTag_UserTagGUID] DEFAULT (newid()) FOR [UserTagGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFComment ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFComment] (
    [CommentGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [PositionX] float NOT NULL,
    [PositionY] float NOT NULL,
    [Text] nvarchar(450) NOT NULL,
    PRIMARY KEY ([CommentGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_WFComment] ON [dbo].[WFComment] ([CommentGUID]);
CREATE NONCLUSTERED INDEX [IX_WFComment_ByWorkflowMap] ON [dbo].[WFComment] ([WorkflowMapGUID]);
GO
ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [FK_WFComment_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO
ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_COMMENTGUID] DEFAULT (newid()) FOR [CommentGUID]; GO
ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_WORKFLOWGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO
ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_POSITIONX] DEFAULT ((0)) FOR [PositionX]; GO
ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_POSITIONY] DEFAULT ((0)) FOR [PositionY]; GO
ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_TEXT] DEFAULT ('') FOR [Text]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFCondition ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFCondition] (
    [ConditionGUID] uniqueidentifier NOT NULL,
    [ConditionSetGUID] uniqueidentifier NOT NULL,
    [ConditionType] int NOT NULL,
    [ParentConditionGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Metadata] nvarchar(max) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [AssemblyName] nvarchar(450) NOT NULL,
    [ClassName] nvarchar(450) NOT NULL,
    PRIMARY KEY ([ConditionGUID])
);

CREATE CLUSTERED INDEX [IX_WFCondition_BySet] ON [dbo].[WFCondition] ([ConditionSetGUID]);
CREATE NONCLUSTERED INDEX [IX_WFCondition_ByParent] ON [dbo].[WFCondition] ([ParentConditionGUID]);
GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [FK_WFCondition_WFConditionSet] FOREIGN KEY ([ConditionSetGUID]) REFERENCES [dbo].[WFConditionSet] ([ConditionSetGUID]); GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_CONDITIONGUID] DEFAULT (newid()) FOR [ConditionGUID]; GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_CONDITIONSETGUID] DEFAULT (newid()) FOR [ConditionSetGUID]; GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_CONDITIONTYPE] DEFAULT ((0)) FOR [ConditionType]; GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_PARENTCONDITIONGUID] DEFAULT (newid()) FOR [ParentConditionGUID]; GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_NAME_1] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_FIELDNAME] DEFAULT ('') FOR [Metadata]; GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_DISPLAYVALUE] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_ASSEMBLYNAME] DEFAULT ('') FOR [AssemblyName]; GO
ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_CLASSNAME] DEFAULT ('') FOR [ClassName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFConditionSet ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFConditionSet] (
    [ConditionSetGUID] uniqueidentifier NOT NULL,
    [RootConditionGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ConditionSetGUID])
);
GO
ALTER TABLE [dbo].[WFConditionSet] ADD CONSTRAINT [DF_WFConditionSet_CONDITIONSETGUID] DEFAULT (newid()) FOR [ConditionSetGUID]; GO
ALTER TABLE [dbo].[WFConditionSet] ADD CONSTRAINT [DF_WFConditionSet_ROOTCONDITIONGUID] DEFAULT (newid()) FOR [RootConditionGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFEmailNotificationRequest ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFEmailNotificationRequest] (
    [EmailNotificationRequestGuid] uniqueidentifier NOT NULL,
    [PlanGuid] uniqueidentifier NOT NULL,
    [StepGuid] uniqueidentifier NOT NULL,
    [UserGuid] uniqueidentifier NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    PRIMARY KEY ([EmailNotificationRequestGuid])
);
GO
ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__Email__3FD6CEB2] DEFAULT (newid()) FOR [EmailNotificationRequestGuid]; GO
ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__PlanG__40CAF2EB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGuid]; GO
ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__StepG__41BF1724] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StepGuid]; GO
ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__UserG__42B33B5D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGuid]; GO
ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__DateT__43A75F96] DEFAULT (getdate()) FOR [DateTimeStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFEventPlan ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFEventPlan] (
    [EventPlanGUID] uniqueidentifier NOT NULL,
    [RootEventPlanStatementGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([EventPlanGUID])
);
GO
ALTER TABLE [dbo].[WFEventPlan] ADD CONSTRAINT [FK_WFEventPlan_WFEventPlanStatement] FOREIGN KEY ([RootEventPlanStatementGUID]) REFERENCES [dbo].[WFEventPlanStatement] ([EventPlanStatementGUID]); GO
ALTER TABLE [dbo].[WFEventPlan] ADD CONSTRAINT [DF_WFEventPlan_EVENTPLANGUID] DEFAULT (newid()) FOR [EventPlanGUID]; GO
ALTER TABLE [dbo].[WFEventPlan] ADD CONSTRAINT [DF_WFEventPlan_ROOTEVENTPLANSTATEMENTGUID] DEFAULT (newid()) FOR [RootEventPlanStatementGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFEventPlanStatement ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFEventPlanStatement] (
    [EventPlanStatementGUID] uniqueidentifier NOT NULL,
    [ParentEventPlanStatementGUID] uniqueidentifier NOT NULL,
    [Type] int NOT NULL,
    [StatementGUID] uniqueidentifier NOT NULL,
    [EventPlanGUID] uniqueidentifier NOT NULL,
    [ExecutionOrder] int NOT NULL,
    PRIMARY KEY ([EventPlanStatementGUID])
);

CREATE CLUSTERED INDEX [IX_WFEventPlanStatement] ON [dbo].[WFEventPlanStatement] ([EventPlanGUID]);
GO
ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [FK_WFEventPlanStatement_WFAction] FOREIGN KEY ([StatementGUID]) REFERENCES [dbo].[CustomAction] ([ActionGUID]); GO
ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [FK_WFEventPlanStatement_WFConditionSet] FOREIGN KEY ([StatementGUID]) REFERENCES [dbo].[WFConditionSet] ([ConditionSetGUID]); GO
ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_EVENTPLANSTATEMENTGUID] DEFAULT (newid()) FOR [EventPlanStatementGUID]; GO
ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_PARENTEVENTPLANSTATEMENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentEventPlanStatementGUID]; GO
ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_STATEMENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StatementGUID]; GO
ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_EVENTPLANGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EventPlanGUID]; GO
ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFHistory ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFHistory] (
    [WorkflowHistoryGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [HistoryType] int NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [IsDeleted] bit NOT NULL,
    [SkippingReason] nvarchar(2000) NULL,
    PRIMARY KEY ([WorkflowHistoryGUID])
);

GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [FK_WFHistory_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [FK_WFHistory_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_WorkflowMapGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowMapGUID]; GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_WorkflowStepGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_WorkflowHistoryGUID] DEFAULT (newid()) FOR [WorkflowHistoryGUID]; GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_HistoryType] DEFAULT ((0)) FOR [HistoryType]; GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF__WFHistory__Skipp__7A1719FC] DEFAULT ('') FOR [SkippingReason]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFOverdueReviewLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFOverdueReviewLog] (
    [LogGUID] uniqueidentifier NOT NULL,
    [PlanGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [MessageGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([LogGUID])
);
GO
ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO
ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_WorkflowStepGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO
ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_WorkflowMapGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowMapGUID]; GO
ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_MessageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MessageGUID]; GO
ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_LogGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LogGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFProcess ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFProcess] (
    [ProcessGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [DisplayOrder] int NOT NULL,
    [IsConcurrent] bit NOT NULL,
    PRIMARY KEY ([ProcessGUID])
);

CREATE NONCLUSTERED INDEX [IX_WFProcess_ByMap] ON [dbo].[WFProcess] ([WorkflowMapGUID]);
CREATE NONCLUSTERED INDEX [IX_WFProcess_DisplayOrder] ON [dbo].[WFProcess] ([DisplayOrder]);
GO
ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [FK_WFProcess_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO
ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_PROCESSGUID] DEFAULT (newid()) FOR [ProcessGUID]; GO
ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_WORKFLOWGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO
ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_HASCONCURRENTSTEPS] DEFAULT ((0)) FOR [IsConcurrent]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFProcessStepLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFProcessStepLink] (
    [ProcessStepLinkGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [ProcessGUID] uniqueidentifier NOT NULL,
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ProcessStepLinkGUID])
);

CREATE CLUSTERED INDEX [IX_WFProcessStepLink_ByMap] ON [dbo].[WFProcessStepLink] ([WorkflowMapGUID]);
GO
ALTER TABLE [dbo].[WFProcessStepLink] ADD CONSTRAINT [FK_WFProcessStepLink_WFProcess] FOREIGN KEY ([ProcessGUID]) REFERENCES [dbo].[WFProcess] ([ProcessGUID]); GO
ALTER TABLE [dbo].[WFProcessStepLink] ADD CONSTRAINT [FK_WFProcessStepLink_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO
ALTER TABLE [dbo].[WFProcessStepLink] ADD CONSTRAINT [DF_WFProcessStepLink_WORKFLOWGROUPINGGUID] DEFAULT (newid()) FOR [ProcessStepLinkGUID]; GO
ALTER TABLE [dbo].[WFProcessStepLink] ADD CONSTRAINT [DF_WFProcessStepLink_WORKFLOWMAPGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFReviewValue ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFReviewValue] (
    [ReviewValueGUID] uniqueidentifier NOT NULL,
    [IdentityGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    [ReviewValueTypeGUID] uniqueidentifier NOT NULL,
    [Comments] nvarchar(max) NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    PRIMARY KEY ([ReviewValueGUID])
);

CREATE NONCLUSTERED INDEX [IX_EntityGuid_Workflowstepguid] ON [dbo].[WFReviewValue] ([EntityGUID], [WorkflowStepGUID]);
GO
ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_REVIEWVALUEGUID] DEFAULT (newid()) FOR [ReviewValueGUID]; GO
ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_IDENTITYGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentityGUID]; GO
ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_ENTITYGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO
ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_WORKFLOWSTEPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO
ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_REVIEWVALUETYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReviewValueTypeGUID]; GO
ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_COMMENTS] DEFAULT ('') FOR [Comments]; GO
ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFReviewValueType ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFReviewValueType] (
    [ReviewValueTypeGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [FriendlyName] nvarchar(64) NOT NULL,
    [ImageIndex] int NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [HasRequiredComments] bit NOT NULL,
    [NotificationType] uniqueidentifier NOT NULL,
    [IsMovingForward] bit NOT NULL,
    [IsNotificationEnabled] bit NOT NULL,
    PRIMARY KEY ([ReviewValueTypeGUID])
);
GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_IsNotificationEnabled] DEFAULT ((1)) FOR [IsNotificationEnabled]; GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_REVIEWVALUETYPEGUID] DEFAULT (newid()) FOR [ReviewValueTypeGUID]; GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_IMAGEINDEX] DEFAULT ((0)) FOR [ImageIndex]; GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_HASREQUIREDCOMMENTS] DEFAULT ((0)) FOR [HasRequiredComments]; GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_NOTIFICATIONTYPE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [NotificationType]; GO
ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_IsMovingForward] DEFAULT ((1)) FOR [IsMovingForward]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFReviewerAssignment ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFReviewerAssignment] (
    [ReviewerAssignmentGUID] uniqueidentifier NOT NULL,
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    [IdentityGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ReviewerAssignmentGUID])
);

CREATE CLUSTERED INDEX [IX_WFReviewerAssignment] ON [dbo].[WFReviewerAssignment] ([WorkflowStepGUID]);
GO
ALTER TABLE [dbo].[WFReviewerAssignment] ADD CONSTRAINT [FK_WFReviewerAssignment_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO
ALTER TABLE [dbo].[WFReviewerAssignment] ADD CONSTRAINT [DF_WFReviewerAssignment_REVIEWERASSIGNMENTGUID] DEFAULT (newid()) FOR [ReviewerAssignmentGUID]; GO
ALTER TABLE [dbo].[WFReviewerAssignment] ADD CONSTRAINT [DF_WFReviewerAssignment_WORKFLOWSTEPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO
ALTER TABLE [dbo].[WFReviewerAssignment] ADD CONSTRAINT [DF_WFReviewerAssignment_IDENTITYGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentityGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFReviewerDelegate ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFReviewerDelegate] (
    [ReviewerDelegateGUID] uniqueidentifier NOT NULL,
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [ReviewerUserGUID] uniqueidentifier NOT NULL,
    [DelegateUserGUID] uniqueidentifier NOT NULL,
    [IsFromOutOfOfficeSchedule] bit NOT NULL,
    PRIMARY KEY ([ReviewerDelegateGUID])
);
GO
ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [FK_WFReviewerDelegate_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO
ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_Table_1_ReviewerIdentityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReviewerUserGUID]; GO
ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_WFReviewerDelegate_DelegateUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DelegateUserGUID]; GO
ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_Table_1_DelegateGUID] DEFAULT (newid()) FOR [ReviewerDelegateGUID]; GO
ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_WFReviewerDelegate_WorkflowStepGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO
ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF__WFReviewe__IsFro__6618AC42] DEFAULT ((0)) FOR [IsFromOutOfOfficeSchedule]; GO
ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_WFReviewerDelegate_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFReviewerOutOfOffice ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFReviewerOutOfOffice] (
    [ReviewerGUID] uniqueidentifier NOT NULL,
    [StartDateTime] datetime NOT NULL,
    [EndDateTime] datetime NOT NULL,
    [IsOutOfOffice] bit NOT NULL,
    [DelegatedReviewerGUID] uniqueidentifier NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.WFStepReviewValueTypeLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFStepReviewValueTypeLink] (
    [StepReviewValueTypeLinkGUID] uniqueidentifier NOT NULL,
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    [ReviewValueTypeGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([StepReviewValueTypeLinkGUID])
);

CREATE CLUSTERED INDEX [IX_WFStepReviewValueLink] ON [dbo].[WFStepReviewValueTypeLink] ([WorkflowStepGUID]);
GO
ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [FK_WFStepReviewValueTypeLink_WFReviewValueType] FOREIGN KEY ([ReviewValueTypeGUID]) REFERENCES [dbo].[WFReviewValueType] ([ReviewValueTypeGUID]); GO
ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [FK_WFStepReviewValueTypeLink_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO
ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [DF_WFStepReviewValueLink_STEPREVIEWVALUELINKGUID] DEFAULT (newid()) FOR [StepReviewValueTypeLinkGUID]; GO
ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [DF_WFStepReviewValueLink_WORKFLOWSTEPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO
ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [DF_WFStepReviewValueLink_REVIEWVALUETYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReviewValueTypeGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFToken ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFToken] (
    [WorkflowTokenGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [EntityGUID] uniqueidentifier NOT NULL,
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    [IsFromManualMove] bit NOT NULL,
    PRIMARY KEY ([WorkflowTokenGUID])
);

CREATE NONCLUSTERED INDEX [IX_WFToken_ByMap] ON [dbo].[WFToken] ([WorkflowMapGUID]);
CREATE NONCLUSTERED INDEX [IX_WFToken_ByEntity] ON [dbo].[WFToken] ([EntityGUID]);
CREATE NONCLUSTERED INDEX [IX_WFToken_ByStep] ON [dbo].[WFToken] ([WorkflowStepGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_WFToken_ByStepEntity] ON [dbo].[WFToken] ([WorkflowStepGUID], [EntityGUID]);
GO
ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [FK_WFToken_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO
ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFToken_IsFromManualMove] DEFAULT ((0)) FOR [IsFromManualMove]; GO
ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFWorkflowToken_WORKFLOWTOKENGUID] DEFAULT (newid()) FOR [WorkflowTokenGUID]; GO
ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFToken_WORKFLOWMAPGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO
ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFWorkflowToken_ENTITYGUID] DEFAULT (newid()) FOR [EntityGUID]; GO
ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFWorkflowToken_WORKFLOWSTEPGUID] DEFAULT (newid()) FOR [WorkflowStepGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFTransition ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFTransition] (
    [TransitionGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [WorkflowStepFromGUID] uniqueidentifier NOT NULL,
    [WorkflowStepToGUID] uniqueidentifier NOT NULL,
    [ConditionSetGUID] uniqueidentifier NOT NULL,
    [EventPlanGUID] uniqueidentifier NOT NULL,
    [Text] nvarchar(64) NOT NULL,
    [PortFrom] int NOT NULL,
    [PortTo] int NOT NULL,
    [IsLoopback] bit NOT NULL,
    PRIMARY KEY ([TransitionGUID])
);

CREATE NONCLUSTERED INDEX [IX_WFTransition_ByMap] ON [dbo].[WFTransition] ([WorkflowMapGUID]);
CREATE NONCLUSTERED INDEX [IX_WFTransition_ByStepFrom] ON [dbo].[WFTransition] ([WorkflowStepFromGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_WFTransition_ByFromTo] ON [dbo].[WFTransition] ([WorkflowStepFromGUID], [WorkflowStepToGUID], [IsLoopback]);
GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [FK_WFTransition_WFConditionSet] FOREIGN KEY ([ConditionSetGUID]) REFERENCES [dbo].[WFConditionSet] ([ConditionSetGUID]); GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [FK_WFTransition_WFEventPlan] FOREIGN KEY ([EventPlanGUID]) REFERENCES [dbo].[WFEventPlan] ([EventPlanGUID]); GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [FK_WFTransition_WFWorkflowStep_From] FOREIGN KEY ([WorkflowStepFromGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [FK_WFTransition_WFWorkflowStep_To] FOREIGN KEY ([WorkflowStepToGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_TRANSITIONGUID] DEFAULT (newid()) FOR [TransitionGUID]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_WORKFLOWMAPGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_STEPFROMGUID] DEFAULT (newid()) FOR [WorkflowStepFromGUID]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_STEPTOGUID] DEFAULT (newid()) FOR [WorkflowStepToGUID]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_CONDITIONGUID] DEFAULT (newid()) FOR [ConditionSetGUID]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_CONDITIONALACTIONGUID] DEFAULT (newid()) FOR [EventPlanGUID]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_TEXT] DEFAULT ('') FOR [Text]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_PORTFROM] DEFAULT ((0)) FOR [PortFrom]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_PORTTO] DEFAULT ((0)) FOR [PortTo]; GO
ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_IsLoopback] DEFAULT ((0)) FOR [IsLoopback]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFWorkflowMap ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFWorkflowMap] (
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [IsLocked] bit NOT NULL,
    [FolderGUID] uniqueidentifier NOT NULL,
    [ReviewFolderGUID] uniqueidentifier NOT NULL,
    [IsEmailIntegrationEnabled] bit NOT NULL,
    [AssociatedReportGUID] uniqueidentifier NOT NULL,
    [TimeInStepThreshold] int NOT NULL,
    [IsCopiedWithPlan] bit NOT NULL,
    [IsSkippedStepByAuthor] bit NOT NULL,
    [IsSkippedStepBySubordinates] bit NOT NULL,
    PRIMARY KEY ([WorkflowMapGUID])
);
GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF__WFWorkflo__IsSki__0F61AD3C] DEFAULT ((0)) FOR [IsSkippedStepBySubordinates]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF__WFWorkflo__IsSki__20CB6509] DEFAULT ((0)) FOR [IsSkippedStepByAuthor]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_IsCopiedWithPlan] DEFAULT ((1)) FOR [IsCopiedWithPlan]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_WORKFLOWMAPGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_ISLOCKEDFORREFRESH] DEFAULT ((0)) FOR [IsLocked]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_ReviewFolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReviewFolderGUID]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_IsEmailIntegrationEnabled] DEFAULT ((0)) FOR [IsEmailIntegrationEnabled]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_AssociatedReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssociatedReportGUID]; GO
ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_TimeInStepThreshold] DEFAULT ((0)) FOR [TimeInStepThreshold]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WFWorkflowStep ------------------
---------------------------------------------
CREATE TABLE [dbo].[WFWorkflowStep] (
    [WorkflowStepGUID] uniqueidentifier NOT NULL,
    [WorkflowMapGUID] uniqueidentifier NOT NULL,
    [IsStart] bit NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(4000) NOT NULL,
    [OnStartEventPlanGUID] uniqueidentifier NOT NULL,
    [OnEndEventPlanGUID] uniqueidentifier NOT NULL,
    [PositionX] float NOT NULL,
    [PositionY] float NOT NULL,
    [DisplayOrder] int NOT NULL,
    [Type] int NOT NULL,
    [IsHidden] bit NOT NULL,
    [IsAdvancedCondition] bit NOT NULL,
    [IsAdvancedStartEvent] bit NOT NULL,
    [IsAdvancedEndEvent] bit NOT NULL,
    [QualifyConditionSetGUID] uniqueidentifier NOT NULL,
    [IsAdvancedQualification] bit NOT NULL,
    [IsAdvancedLoopback] bit NOT NULL,
    [IsHiddenInRouting] bit NOT NULL,
    [Version] timestamp NOT NULL,
    [ReviewerAccess] int NOT NULL,
    [ReviewerExitAccess] int NOT NULL,
    [AssociatedReportGUID] uniqueidentifier NOT NULL,
    [Icon] int NOT NULL,
    [ReminderDaysThreshold] int NOT NULL,
    PRIMARY KEY ([WorkflowStepGUID])
);

CREATE NONCLUSTERED INDEX [IX_WFWorkflowStep_ByMap] ON [dbo].[WFWorkflowStep] ([WorkflowMapGUID]);
CREATE NONCLUSTERED INDEX [IX_WFWorkflowStep_DisplayOrder] ON [dbo].[WFWorkflowStep] ([DisplayOrder]);
GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [FK_WFWorkflowStep_WFEventPlan_End] FOREIGN KEY ([OnEndEventPlanGUID]) REFERENCES [dbo].[WFEventPlan] ([EventPlanGUID]); GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [FK_WFWorkflowStep_WFEventPlan_Start] FOREIGN KEY ([OnStartEventPlanGUID]) REFERENCES [dbo].[WFEventPlan] ([EventPlanGUID]); GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IconIndex] DEFAULT ((0)) FOR [Icon]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ReminderDaysThreshold] DEFAULT ((0)) FOR [ReminderDaysThreshold]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ReviewerAccess] DEFAULT ((-1)) FOR [ReviewerAccess]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IsHiddenInRouting] DEFAULT ((0)) FOR [IsHiddenInRouting]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_AssociatedReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssociatedReportGUID]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_WorkflowStepGUID] DEFAULT (newid()) FOR [WorkflowStepGUID]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_WORKFLOWGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IsStart] DEFAULT ((0)) FOR [IsStart]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ONSTARTEVENTGUID] DEFAULT (newid()) FOR [OnStartEventPlanGUID]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ONENDEVENTGUID] DEFAULT (newid()) FOR [OnEndEventPlanGUID]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_POSITIONX] DEFAULT ((0)) FOR [PositionX]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_POSITIONY] DEFAULT ((0)) FOR [PositionY]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_TYPE] DEFAULT ((0)) FOR [Type]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ISHIDDEN] DEFAULT ((0)) FOR [IsHidden]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ISADVANCEDCONDITION] DEFAULT ((1)) FOR [IsAdvancedCondition]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ISADVANCEDSTARTEVENT] DEFAULT ((1)) FOR [IsAdvancedStartEvent]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ISADVANCEDENDEVENT] DEFAULT ((1)) FOR [IsAdvancedEndEvent]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_QualifyConditionSetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [QualifyConditionSetGUID]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IsAdvancedQualification] DEFAULT ((1)) FOR [IsAdvancedQualification]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IsAdvancedLoopback] DEFAULT ((0)) FOR [IsAdvancedLoopback]; GO
ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ReviewerExitAccess] DEFAULT ((-1)) FOR [ReviewerExitAccess]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WorkerLog ------------------
---------------------------------------------
CREATE TABLE [dbo].[WorkerLog] (
    [WorkerID] uniqueidentifier NOT NULL,
    [WorkerGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(150) NOT NULL,
    [IPAddress] nvarchar(50) NOT NULL,
    [CreationTime] datetime NOT NULL,
    [ServerName] nvarchar(150) NOT NULL,
    [StopTime] datetime NULL,
    [TaskEngineVersion] varchar(100) NULL,
    PRIMARY KEY ([WorkerID])
);
GO
ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_WorkerLog_StopTime] DEFAULT ('1/1/1900') FOR [StopTime]; GO
ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_WorkerLog_TaskEngineVersion] DEFAULT ('') FOR [TaskEngineVersion]; GO
ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_WorkerLog_WorkerID] DEFAULT (newid()) FOR [WorkerID]; GO
ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_dbo.WorkerLog_WorkerGUID] DEFAULT (newid()) FOR [WorkerGUID]; GO
ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_dbo.WorkerLog_WorkerName] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_dbo.WorkerLog_IPAddress] DEFAULT ('0.0.0.0') FOR [IPAddress]; GO
ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_dbo.WorkerLog_CreationTime] DEFAULT ('1/1/1900') FOR [CreationTime]; GO
ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_WorkerLog_ServerName] DEFAULT ('') FOR [ServerName]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WorkflowAttachModelFailure ------------------
---------------------------------------------
CREATE TABLE [dbo].[WorkflowAttachModelFailure] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [PlanGUID] uniqueidentifier NOT NULL,
    [ErrorLogGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([MemberGUID])
);
GO
ALTER TABLE [dbo].[WorkflowAttachModelFailure] ADD CONSTRAINT [DF_WorkflowAttachModelFailure_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [dbo].[WorkflowAttachModelFailure] ADD CONSTRAINT [DF_WorkflowAttachModelFailure_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO
ALTER TABLE [dbo].[WorkflowAttachModelFailure] ADD CONSTRAINT [DF__WorkflowA__Error__47CD59C9] DEFAULT (newid()) FOR [ErrorLogGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.Workspace ------------------
---------------------------------------------
CREATE TABLE [dbo].[Workspace] (
    [WorkspaceGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(64) NOT NULL,
    [Description] nvarchar(450) NOT NULL,
    [IsPanelEnabled] bit NOT NULL,
    [CustomMenuGUID] uniqueidentifier NOT NULL,
    [CustomToolbarGUID] uniqueidentifier NOT NULL,
    [CustomContextMenuGUID] uniqueidentifier NOT NULL,
    [DefaultEntityViewGUID] uniqueidentifier NOT NULL,
    [DefaultPlanTypeGUID] uniqueidentifier NOT NULL,
    [FilterEntityViewGUID] uniqueidentifier NOT NULL,
    [DefaultFormDefGUID] uniqueidentifier NOT NULL,
    [ProviderType] int NOT NULL,
    [IsLoadingHierarchyMembers] bit NOT NULL,
    [IsWorkflowColumnsEnabled] bit NOT NULL,
    [ModuleGUID] uniqueidentifier NOT NULL,
    [IsModuleDefault] bit NOT NULL,
    [HelpID] nvarchar(50) NOT NULL,
    PRIMARY KEY ([WorkspaceGUID])
);
GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_ProviderType] DEFAULT ((0)) FOR [ProviderType]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_IsLoadingHierarchyMembers] DEFAULT ((0)) FOR [IsLoadingHierarchyMembers]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_DefaultFormDefGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultFormDefGUID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF__Workspace__IsMod__1EAB16DB] DEFAULT ((0)) FOR [IsModuleDefault]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_IsWorkflowColumnsEnabled] DEFAULT ((0)) FOR [IsWorkflowColumnsEnabled]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF__Workspace__Modul__65F025BE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF__Workspace__HelpI__70701636] DEFAULT ('') FOR [HelpID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_WORKSPACEGUID] DEFAULT (newid()) FOR [WorkspaceGUID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_NAME] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_DESCRIPTION] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_ISPANELENABLED] DEFAULT ((0)) FOR [IsPanelEnabled]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_CUSTOMMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomMenuGUID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_CUSTOMTOOLBARGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomToolbarGUID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_CUSTOMCONTEXTMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomContextMenuGUID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_DefaultEntityViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultEntityViewGUID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_DefaultPlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultPlanTypeGUID]; GO
ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_FilterEntityViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FilterEntityViewGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WorkspaceContentLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[WorkspaceContentLink] (
    [WorkspaceContentLinkGUID] uniqueidentifier NOT NULL,
    [WorkspaceGUID] uniqueidentifier NOT NULL,
    [ContentGUID] uniqueidentifier NOT NULL,
    [ContentType] int NOT NULL,
    [DisplayOrder] int NOT NULL,
    PRIMARY KEY ([WorkspaceContentLinkGUID])
);
GO
ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [FK_WorkspaceContentLink_Workspace] FOREIGN KEY ([WorkspaceGUID]) REFERENCES [dbo].[Workspace] ([WorkspaceGUID]); GO
ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_WORKSPACECONTENTLINKGUID] DEFAULT (newid()) FOR [WorkspaceContentLinkGUID]; GO
ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_WORKSPACEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceGUID]; GO
ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_CONTENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ContentGUID]; GO
ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_CONTENTTYPE] DEFAULT ((0)) FOR [ContentType]; GO
ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_DisplayOrder] DEFAULT ((0)) FOR [DisplayOrder]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WorkspaceDimensionLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[WorkspaceDimensionLink] (
    [WorkspaceDimensionLinkGUID] uniqueidentifier NOT NULL,
    [WorkspaceGUID] uniqueidentifier NOT NULL,
    [DimensionGUID] uniqueidentifier NOT NULL,
    [HierarchyGUID] uniqueidentifier NOT NULL,
    [IsDefault] bit NOT NULL,
    PRIMARY KEY ([WorkspaceDimensionLinkGUID])
);
GO
ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [FK_WorkspaceDimensionLink_Workspace] FOREIGN KEY ([WorkspaceGUID]) REFERENCES [dbo].[Workspace] ([WorkspaceGUID]); GO
ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_HierarchyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HierarchyGUID]; GO
ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_IsDefault] DEFAULT ((0)) FOR [IsDefault]; GO
ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_WorkspaceDimensionLinkGUID] DEFAULT (newid()) FOR [WorkspaceDimensionLinkGUID]; GO
ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_WorkspaceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceGUID]; GO
ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WorkspaceEntityViewLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[WorkspaceEntityViewLink] (
    [WorkspaceEntityViewLinkGUID] uniqueidentifier NOT NULL,
    [WorkspaceGUID] uniqueidentifier NOT NULL,
    [EntityViewGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([WorkspaceEntityViewLinkGUID])
);
GO
ALTER TABLE [dbo].[WorkspaceEntityViewLink] ADD CONSTRAINT [FK_WorkspaceEntityViewLink_Workspace] FOREIGN KEY ([WorkspaceGUID]) REFERENCES [dbo].[Workspace] ([WorkspaceGUID]); GO
ALTER TABLE [dbo].[WorkspaceEntityViewLink] ADD CONSTRAINT [DF_WorkspaceEntityViewLink_WorkspaceEntityViewLinkGUID] DEFAULT (newid()) FOR [WorkspaceEntityViewLinkGUID]; GO

---------------------------------------------

---------------------------------------------
-- dbo.WorkspacePlanTypeLink ------------------
---------------------------------------------
CREATE TABLE [dbo].[WorkspacePlanTypeLink] (
    [WorkspacePlanTypeLinkGUID] uniqueidentifier NOT NULL,
    [WorkspaceGUID] uniqueidentifier NOT NULL,
    [GridTemplateGUID] uniqueidentifier NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [IsDefault] bit NOT NULL,
    [FormDefGUID] uniqueidentifier NOT NULL,
    [HiddenToolIDList] nvarchar(max) NOT NULL,
    [IsEnabled] bit NOT NULL,
    PRIMARY KEY ([WorkspacePlanTypeLinkGUID])
);
GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [FK_WorkspaceGridTemplateLink_GridTemplate] FOREIGN KEY ([GridTemplateGUID]) REFERENCES [dbo].[GridTemplate] ([GRIDTEMPLATEGUID]); GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [FK_WorkspaceGridTemplateLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [FK_WorkspaceGridTemplateLink_Workspace] FOREIGN KEY ([WorkspaceGUID]) REFERENCES [dbo].[Workspace] ([WorkspaceGUID]); GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspaceGridTemplateLink_WorkspaceGridTemplateLinkGUID] DEFAULT (newid()) FOR [WorkspacePlanTypeLinkGUID]; GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspaceGridTemplateLink_WorkspaceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceGUID]; GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspaceGridTemplateLink_GridTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GridTemplateGUID]; GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspaceGridTemplateLink_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspacePlanTypeLink_IsDefault] DEFAULT ((0)) FOR [IsDefault]; GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspacePlanTypeLink_FormDefGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormDefGUID]; GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspacePlanTypeLink_HiddenToolIDList] DEFAULT ('') FOR [HiddenToolIDList]; GO
ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF__Workspace__IsEna__76206499] DEFAULT ((1)) FOR [IsEnabled]; GO

---------------------------------------------

---------------------------------------------
-- dbo.XPlan ------------------
---------------------------------------------
CREATE TABLE [dbo].[XPlan] (
    [PlanGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(450) NOT NULL,
    [ParentEntityGUID] uniqueidentifier NOT NULL,
    [DefaultFormDefGUID] uniqueidentifier NOT NULL,
    [DateCreated] datetime NOT NULL,
    [LastModelTemplateGroupGUID] uniqueidentifier NOT NULL,
    [ModelDatasetGUID] uniqueidentifier NOT NULL,
    [ModelTemplateGUID] uniqueidentifier NOT NULL,
    [ScoreMemberGUID] uniqueidentifier NOT NULL,
    [IsDeletedPlan] bit NOT NULL,
    [IsConsolidation] bit NOT NULL,
    [IsModelRefreshEnabled] bit NOT NULL,
    [PlanTypeGUID] uniqueidentifier NOT NULL,
    [PlanID] int NOT NULL,
    [CachedLootID] nvarchar(128) NOT NULL,
    [AuthorUserGUID] uniqueidentifier NOT NULL,
    [IsArchived] bit NOT NULL,
    [IsFinancialsLocked] bit NOT NULL,
    [IsModelWorkbookCached] bit NOT NULL,
    [CachedWorkflowStep] nvarchar(400) NULL,
    [CachedWorkflowStepGUIDsCSV] nvarchar(800) NULL,
    [LastModifiedFormDate] datetime NOT NULL,
    [LastModifiedFormUserGUID] uniqueidentifier NOT NULL,
    [LastModifiedModelDate] datetime NOT NULL,
    [LastModifiedModelUserGUID] uniqueidentifier NOT NULL,
    [ModelMemoryHit] int NOT NULL,
    [ModelFileCacheHit] int NOT NULL,
    [ModelDatabaseHit] int NOT NULL,
    [LastModelCacheInvalidateReason] nvarchar(100) NOT NULL,
    [LastRefreshModelDate] datetime NOT NULL,
    [FillinTemplateGUID] uniqueidentifier NOT NULL,
    [LastModelCacheInvalidateDate] datetime NOT NULL,
    [AuthorFullName] nvarchar(256) NOT NULL,
    [LastModifiedFormUserName] nvarchar(256) NOT NULL,
    [LastModifiedModelUserName] nvarchar(256) NOT NULL,
    [IsHiddenFromWorkflowNotification] bit NOT NULL,
    [IsCacheable] bit NOT NULL,
    [IsSuspended] bit NOT NULL,
    [SuspendedByUserGUID] uniqueidentifier NOT NULL,
    [SuspendedByUserName] nvarchar(256) NOT NULL,
    [DateSuspended] datetime NOT NULL,
    [SuspensionModeSource] nvarchar(max) NOT NULL,
    PRIMARY KEY ([PlanGUID])
);

CREATE NONCLUSTERED INDEX [idx_XPlan_PlanGUID_With_Name] ON [dbo].[XPlan] ([PlanGUID]) INCLUDE ([Name]);
CREATE NONCLUSTERED INDEX [NCNU_PlanTypeGUID] ON [dbo].[XPlan] ([PlanTypeGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_XPlan_IsDeleted] ON [dbo].[XPlan] ([IsDeletedPlan], [PlanGUID], [PlanTypeGUID]) INCLUDE ([DateCreated]);
CREATE NONCLUSTERED INDEX [IDX_XPlan_CachedLooID_INCL_PlanGUID] ON [dbo].[XPlan] ([CachedLootID]) INCLUDE ([PlanGUID]);
GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_SuspendedByUserName] DEFAULT ('') FOR [SuspendedByUserName]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__AuthorFul__098A6F03] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__FillinTem__1495D444] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinTemplateGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_CachedLootID] DEFAULT ('') FOR [CachedLootID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__IsHiddenF__16DD75DC] DEFAULT ((0)) FOR [IsHiddenFromWorkflowNotification]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastRefreshModelDate] DEFAULT (getdate()) FOR [LastRefreshModelDate]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_AuthorUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorUserGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModelCacheInvalidateDate] DEFAULT (getdate()) FOR [LastModelCacheInvalidateDate]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModifiedFormDate] DEFAULT (getdate()) FOR [LastModifiedFormDate]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_CachedWorkflowStep] DEFAULT ('') FOR [CachedWorkflowStep]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModifiedModelDate] DEFAULT (getdate()) FOR [LastModifiedModelDate]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModifiedFormUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastModifiedFormUserGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_SuspendedByUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SuspendedByUserGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__IsModelWo__3A79BD92] DEFAULT ((0)) FOR [IsModelWorkbookCached]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__LastModif__48BBBCD7] DEFAULT ('') FOR [LastModifiedFormUserName]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__LastModif__49AFE110] DEFAULT ('') FOR [LastModifiedModelUserName]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModifiedModelUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastModifiedModelUserGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_ENTITYGUID] DEFAULT (newid()) FOR [PlanGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_Name] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_PARENTENTITYGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentEntityGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_DEFAULTFORMDEFGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultFormDefGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_LASTMODELDATASETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastModelTemplateGroupGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_MODELDATASETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelDatasetGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_MODELTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModelCacheInvalidateReason] DEFAULT ('') FOR [LastModelCacheInvalidateReason]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_PlaceholderMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreMemberGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_ISDELETED] DEFAULT ((0)) FOR [IsDeletedPlan]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_ISCONSOLIDATION] DEFAULT ((0)) FOR [IsConsolidation]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_IsModelRefreshEnabled] DEFAULT ((1)) FOR [IsModelRefreshEnabled]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_PLANTYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__IsCacheab__5C1D6E18] DEFAULT ((1)) FOR [IsCacheable]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_IsArchived] DEFAULT ((0)) FOR [IsArchived]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__IsFinanci__66056A50] DEFAULT ((0)) FOR [IsFinancialsLocked]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__CachedWor__6D6ABF73] DEFAULT ('') FOR [CachedWorkflowStepGUIDsCSV]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_SuspensionModeSource] DEFAULT ('') FOR [SuspensionModeSource]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_DateSuspended] DEFAULT (getdate()) FOR [DateSuspended]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__ModelMemo__74D0AE23] DEFAULT ((0)) FOR [ModelMemoryHit]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__ModelFile__75C4D25C] DEFAULT ((0)) FOR [ModelFileCacheHit]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__ModelData__76B8F695] DEFAULT ((0)) FOR [ModelDatabaseHit]; GO
ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_IsSuspended] DEFAULT ((0)) FOR [IsSuspended]; GO

---------------------------------------------

---------------------------------------------
-- dbo._data_Fairview_RS_2_d4b011b67c6e4a0ca94ee153867d9e42_ ------------------
---------------------------------------------
CREATE TABLE [dbo].[_data_Fairview_RS_2_d4b011b67c6e4a0ca94ee153867d9e42_] (
    [EncounterID] bigint NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo._data_Rule_Set_Measure_Child_663d423c1a234dea8fba2e3c429437d1_ ------------------
---------------------------------------------
CREATE TABLE [dbo].[_data_Rule_Set_Measure_Child_663d423c1a234dea8fba2e3c429437d1_] (
    [EncounterID] bigint NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo._data_Rule_Set_Measure_Less_Than_And_Less_Than_Equal_Child_c279feaa6d9b4253ab44871e1dba1480_ ------------------
---------------------------------------------
CREATE TABLE [dbo].[_data_Rule_Set_Measure_Less_Than_And_Less_Than_Equal_Child_c279feaa6d9b4253ab44871e1dba1480_] (
    [EncounterID] bigint NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo._data_SingleExclude_ExcludesAllRows_ExpectFalse_eb1eab34ef0041c5b7e3ddcebd30beaa_ ------------------
---------------------------------------------
CREATE TABLE [dbo].[_data_SingleExclude_ExcludesAllRows_ExpectFalse_eb1eab34ef0041c5b7e3ddcebd30beaa_] (
    [EncounterID] bigint NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.aaVersion ------------------
---------------------------------------------
CREATE TABLE [dbo].[aaVersion] (
    [id] int NOT NULL,
    [Name] nvarchar(256) NOT NULL,
    [Value] nvarchar(4000) NOT NULL,
    [ModifiedDate] smalldatetime NOT NULL,
    PRIMARY KEY ([id])
);
GO
ALTER TABLE [dbo].[aaVersion] ADD CONSTRAINT [DF_aaVersion_New_Purpose] DEFAULT ('Not specified') FOR [Name]; GO
ALTER TABLE [dbo].[aaVersion] ADD CONSTRAINT [DF_aaVersion__New_ExpirationDate] DEFAULT ('Not specified') FOR [Value]; GO
ALTER TABLE [dbo].[aaVersion] ADD CONSTRAINT [DF_aaVersion_New_LastSync] DEFAULT (getdate()) FOR [ModifiedDate]; GO

---------------------------------------------

---------------------------------------------
-- dbo.dtproperties ------------------
---------------------------------------------
CREATE TABLE [dbo].[dtproperties] (
    [id] int NOT NULL,
    [objectid] int NULL,
    [property] varchar(64) NOT NULL,
    [value] varchar(255) NULL,
    [uvalue] nvarchar(255) NULL,
    [lvalue] image NULL,
    [version] int NOT NULL,
    PRIMARY KEY ([id], [property])
);
GO
ALTER TABLE [dbo].[dtproperties] ADD CONSTRAINT [DF__dtpropert__versi__77BFCB91] DEFAULT (0) FOR [version]; GO

---------------------------------------------

---------------------------------------------
-- dbo.filterMemberCsvBkp ------------------
---------------------------------------------
CREATE TABLE [dbo].[filterMemberCsvBkp] (
    [filtermembercsvCopy] nvarchar(max) NOT NULL,
    [ClientReportSectionAttributeGUID] uniqueidentifier NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.intClientComment ------------------
---------------------------------------------
CREATE TABLE [dbo].[intClientComment] (
    [ClientCommentGUID] uniqueidentifier NOT NULL,
    [DataInterfaceMapID] uniqueidentifier NOT NULL,
    [ClientComment] nvarchar(2000) NOT NULL,
    [ModifiedUserGUID] uniqueidentifier NOT NULL,
    [DateModifiedUtc] datetime NOT NULL,
    PRIMARY KEY ([ClientCommentGUID])
);
GO
ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [FK_IntClientComment_DataInterfaceMapID] FOREIGN KEY ([DataInterfaceMapID]) REFERENCES [dbo].[IntDataInterfaceMap] ([DataInterfaceMapID]); GO
ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [DF__intClient__DateM__3B5EF7F1] DEFAULT (getutcdate()) FOR [DateModifiedUtc]; GO
ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [DF_IntClientComment_ModifiedUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModifiedUserGUID]; GO
ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [DF_intClientComment_ClientCommentGUID] DEFAULT (newid()) FOR [ClientCommentGUID]; GO
ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [DF_IntClientComment_ClientComment] DEFAULT ('') FOR [ClientComment]; GO

---------------------------------------------

---------------------------------------------
-- dbo.intSFTPConnection ------------------
---------------------------------------------
CREATE TABLE [dbo].[intSFTPConnection] (
    [SFTPConnectionGUID] uniqueidentifier NOT NULL,
    [ConfigID] uniqueidentifier NOT NULL,
    [Server] nvarchar(400) NOT NULL,
    [Port] nvarchar(400) NOT NULL,
    [Directory] nvarchar(400) NOT NULL,
    [UserName] nvarchar(400) NOT NULL,
    [Password] nvarchar(400) NOT NULL,
    [IsArchiveOnImport] bit NOT NULL,
    [IsDeleteFileOnImport] bit NOT NULL,
    [IsEncrypted] bit NOT NULL,
    [ArchiveDirectory] nvarchar(400) NOT NULL,
    PRIMARY KEY ([SFTPConnectionGUID])
);
GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__SFTPC__63D2D322] DEFAULT (newid()) FOR [SFTPConnectionGUID]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Confi__64C6F75B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Serve__65BB1B94] DEFAULT ('') FOR [Server]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCon__Port__66AF3FCD] DEFAULT ('') FOR [Port]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Direc__67A36406] DEFAULT ('') FOR [Directory]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__UserN__6897883F] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Passw__698BAC78] DEFAULT ('') FOR [Password]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__IsArc__6A7FD0B1] DEFAULT ((1)) FOR [IsArchiveOnImport]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__IsDel__6B73F4EA] DEFAULT ((1)) FOR [IsDeleteFileOnImport]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__IsEnc__6C681923] DEFAULT ((0)) FOR [IsEncrypted]; GO
ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Archi__6D5C3D5C] DEFAULT ('') FOR [ArchiveDirectory]; GO

---------------------------------------------

---------------------------------------------
-- dbo.sysdiagrams ------------------
---------------------------------------------
CREATE TABLE [dbo].[sysdiagrams] (
    [name] nvarchar(128) NOT NULL,
    [principal_id] int NOT NULL,
    [diagram_id] int NOT NULL,
    [version] int NULL,
    [definition] varbinary(max) NULL,
    PRIMARY KEY ([diagram_id])
);

CREATE UNIQUE NONCLUSTERED INDEX [UK_principal_name] ON [dbo].[sysdiagrams] ([principal_id], [name]);
GO

---------------------------------------------

---------------------------------------------
-- dbo.tempcosts ------------------
---------------------------------------------
CREATE TABLE [dbo].[tempcosts] (
    [FiscalYearID] smallint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [DepartmentCode] nvarchar(100) NOT NULL,
    [ChargeCode] nvarchar(100) NOT NULL,
    [UnitCost] numeric NOT NULL,
    [Volume] numeric NULL,
    [TotalCost] numeric NULL,
    [CostingResultID] int NOT NULL,
    [FixeddirectUnitCost] numeric NOT NULL,
    [FixedIndirectUnitCost] numeric NOT NULL,
    [VariableDirectUnitCost] numeric NOT NULL,
    [VariableIndirectUnitCost] numeric NOT NULL
);
GO

---------------------------------------------

---------------------------------------------
-- dbo.tempdssDimDRG ------------------
---------------------------------------------
CREATE TABLE [dbo].[tempdssDimDRG] (
    [DRGID] int NOT NULL,
    [DRGCode] varchar(10) NOT NULL,
    [DescriptionShort] varchar(100) NOT NULL,
    [Description] varchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [ServiceLineID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [MDCID] int NOT NULL,
    [Type] nvarchar(25) NOT NULL,
    [FinalRulePostAcuteDRG] nvarchar(25) NOT NULL,
    [ICD9Inclusion] nvarchar(50) NOT NULL,
    [TransactionID] int NULL,
    [DRGSchema] nvarchar(100) NOT NULL,
    [ImportName] nvarchar(100) NOT NULL
);
GO

---------------------------------------------
---------------------------------------------
--  VIEWS
---------------------------------------------

-- dbo.SysViewObjects
CREATE VIEW [dbo].[SysViewObjects]
AS
select
	S.name + '.' + O.name as Expression,
	S.name as SchemaName,
	O.name as Objectname,
	case when O.type_desc = 'VIEW' then CAST(1 as bit) else CAST(0 as bit) end as IsView
from sys.objects O
	inner join sys.schemas S on S.schema_id = O.schema_id
where O.type_desc = 'USER_TABLE' OR O.type_desc = 'VIEW'
GO


---------------------------------------------

-- dbo.ViewSysTables
CREATE view [dbo].[ViewSysTables]
AS
select * from viewSysAllObjects where type_desc = 'USER_TABLE'
GO


---------------------------------------------

-- dbo.ViewSysTriggers
CREATE VIEW [dbo].[ViewSysTriggers]
AS
select 
    T.object_id as [TriggerID],
	T.name as Name, 
	S.name as SchemaName,
	OB.name as ObjectName,
    T.create_date as CreationDate,
    case when OB.type_desc = 'VIEW' then 1 else 0 end as IsViewTrigger,
    M.definition,
    case when M.definition like '%INSTEAD OF%' then 1 else 0 end as [IsInsteadOfTrigger]
from sys.triggers T
	inner join sys.objects O on O.object_id = T.object_id
	inner join sys.schemas S on S.schema_id = O.schema_id
	inner join sys.objects OB on OB.object_id = O.parent_object_id
	inner join sys.sql_modules M on M.object_id = T.object_id
GO


---------------------------------------------

-- dbo.ViewSysViews
CREATE VIEW [dbo].[ViewSysViews]
AS
select 
	 O.*,
	 M.definition as [ViewDefinition]
from viewSysAllObjects  O
	inner join sys.all_sql_modules M on M.object_id = O.ObjectID
where O.type_desc = 'VIEW'
	AND SchemaName <> 'sys' AND SchemaName <> 'INFORMATION_SCHEMA'
GO


---------------------------------------------

-- dbo.viewAMAssumptionView
CREATE view dbo.viewAMAssumptionView
as
SELECT [AssumptionViewGUID]
      ,[AssumptionGroupGUID]
      ,[Name]
      ,[ColumnWidths]
      ,[AssumptionJoinDataGUID]
      ,[FolderGUID]
      ,[IsDistributionModeActive]
      ,cast([DistributionInfo] as nvarchar(max)) as DistributionInfo
      ,[ProviderGUID]
      ,[CreatedDate]
      ,[CreatedBy]
      ,[LastUsedDate]
  FROM [dbo].[AMAssumptionView]
GO


---------------------------------------------

-- dbo.viewActionLog
--Forward
create view viewActionLog
as
	select
		A.RowID,
		A.Action,
		A.SubAction,
		A.Details,
		A.Username,
		A.DateTimeStamp,
		A.Duration,
		A.TokenGUID,
		MAX(D.Version) as Version
	from
		ActionLog A
		inner join viewUpgradeDate D on D.UpgradeDate < A.DateTimeStamp
	group by
		A.RowID,
		A.Action,
		A.SubAction,
		A.Details,
		A.Username,
		A.DateTimeStamp,
		A.Duration,
		A.TokenGUID
GO


---------------------------------------------

-- dbo.viewActionLogSummary
CREATE view viewActionLogSummary as
select 
	YEAR(DateTimeStamp) as Year, 
	MONTH(DateTimeStamp) as Month,
	DAY(DateTimeStamp) as Day, 
	Action, 
	SubAction, 
	SUM(Duration) as SumDuration, 
	avg(Duration) as AvgDuration, 
	Min(Duration) as MinDuration, 
	Max(Duration) as MaxDuration, 
	stdev(Duration) as StdevDuration, 
	COUNT(*)  as Count
from ActionLog
group by YEAR(DateTimeStamp) , MONTH(DateTimeStamp) ,DAY(DateTimeStamp) , Action, SubAction
GO


---------------------------------------------

-- dbo.viewCMBucket
--Forward


CREATE view [dbo].[viewCMBucket]
as

-- hack default member required for foreign key to work in score config tool
Select
	'00000000-0000-0000-0000-000000000000' as MemberGUID, 	
	'00000000-0000-0000-0000-000000000000' as CategoryGUID, 
	'Not Specified' as Name, 
	'Not Specified' as Category

union 

SELECT 
	B.BucketGUID As MemberGUID, 
	B.CategoryGUID, 
	B.Name, 
	C.Name As Category
FROM
	CMBucket B
INNER JOIN
	CMCategory C ON C.CategoryGUID = B.CategoryGUID
GO


---------------------------------------------

-- dbo.viewCMMetric
CREATE view [dbo].[viewCMMetric]
AS
	SELECT 
		CM.*,
		CM.MetricGUID As MemberGUID, CM.Name As Metric, cast(0 as bit) as IsInternal
	FROM
		CMMetric CM with (readuncommitted)
GO


---------------------------------------------

-- dbo.viewCMMetricWithFramework
CREATE view [dbo].[viewCMMetricWithFramework]
AS
	SELECT 
		CM.MetricGUID As MemberGUID, CM.MetricGUID As MetricGUID, CM.Name As Name,
		CM.Name As Metric, CM.MetricCode As MetricCode, CM.IsAggregable, CM.ToleranceValue, CM.TolerancePercent, CM.IsInverted, CM.FormatString, CM.DisplayOrder, cast(0 as bit) as IsInternal,
		COALESCE(VFW.FrameworkID, '0') As FrameworkID,
		COALESCE(VFW.Framework, 'Not Specified') As Framework,
		COALESCE(VFW.FrameworkSchemaName, 'Not Specified') As FrameworkSchema
	FROM
		CMMetric CM with (readuncommitted)
		LEFT JOIN CMMetricFramework FW with (readuncommitted) ON FW.MetricGUID = CM.MetricGUID
		LEFT JOIN viewFramework VFW with (readuncommitted) ON VFW.FrameworkID = FW.FrameworkID
GO


---------------------------------------------

-- dbo.viewCMSampleTableMetricLinks
CREATE view dbo.viewCMSampleTableMetricLinks AS
select ML.*, M.Name from CMSampleTableMetricLink ML
	inner join CMMetric M on M.MetricGUID = ML.MetricGUID
GO


---------------------------------------------

-- dbo.viewCurrentUsers
CREATE VIEW [dbo].[viewCurrentUsers] AS
	SELECT cu.TokenGUID, cu.IPAddress, up.UserName, up.NameFirst, up.NameLast, up.UserGUID, up.PhoneNumber, cu.IdentityServerSessionId, cu.LoginStampUtc, cu.LastActionStampUtc, 
	CASE WHEN LastActionStampUtc > GETUTCDATE() THEN 0 ELSE DATEDIFF(MI, LastActionStampUtc, GETUTCDATE()) END AS inactiveMinutes
	FROM CurrentUser cu LEFT JOIN UserProfile up 
	ON cu.UserGUID = up.UserGUID
GO


---------------------------------------------

-- dbo.viewCustomActionDependencies
CREATE view [dbo].[viewCustomActionDependencies]
as
	select
		'Workflow' as ReferrerType,
		WFM.Name as ReferrerName,
		CA.Description as ActionName,
		WFM.WorkflowMapGUID as ReferrerGUID,
		CA.ActionGUID
	from
		CustomAction CA
		inner join WFEventPlanStatement EPS on EPS.StatementGUID = CA.ActionGUID
		inner join WFEventPlan EP on EP.EventPlanGUID = EPS.EventPlanGUID
		inner join WFWorkflowStep WFS on WFS.OnStartEventPlanGUID = EP.EventPlanGUID or WFS.OnEndEventPlanGUID = EPS.EventPlanGUID
		inner join WFWorkflowMap WFM on WFM.WorkflowMapGUID = WFS.WorkflowMapGUID
	union all
	select
		'Custom Menu' as ReferrerType,
		CM.Name as ReferrerName,
		CA.Description as ActionName,
		CM.CustomMenuGUID as ReferrerGUID,
		CA.ActionGUID
	from
		CustomAction CA
		inner join CustomMenuContent CMC on cast(CMC.ContentXML as nvarchar(max)) like '%G' + replace(CAST(CA.ActionGUID as nvarchar(36)), '-', '') + '%'
		inner join CustomMenu CM on CM.CustomMenuGUID = CMC.CustomMenuGUID
	union all
	select
		'File Listener' as ReferrerType,
		FL.Name as ReferrerName,
		CA.Description as ActionName,
		FL.FileListenerGUID as ReferrerGUID,
		CA.ActionGUID
	from
		CustomAction CA
		inner join FileListener FL on FL.ActionGUID = CA.ActionGUID
	union all
	select
		'Conditional Action' as ReferrerType,
		CA2.Description as ReferrerName,
		CA.Description as ActionName,
		CA2.ActionGUID as ReferrerGUID,
		CA.ActionGUID
	from
		CustomAction CA
		inner join CustomAction CA2 on CA2.ClassName like '%ConditionalAction%' and CA2.Metadata like '%' + CAST(CA.ActionGUID as nvarchar(36)) + '%'
	union all
	select
		'Scheduled Task' as ReferrerType,
		TE.Name as ReferrerName,
		CA.Description as ActionName,
		TE.ScheduledTaskGUID as ReferrerGUID,
		CA.ActionGUID
	from
		CustomAction CA
		inner join TEScheduledTask TE on TE.SetupXML like '%' + CAST(CA.ActionGUID as nvarchar(36)) + '%'
	union all
	select
		'Desktop' as ReferrerType,
		DT.Name as ReferrerName,
		CA.Description as ActionName,
		DW.DesktopTemplateGUID as ReferrerGUID,
		CA.ActionGUID
	from
		CustomAction CA
		inner join DesktopWidget DW on cast(DW.WidgetXML as nvarchar(max)) like '%' + CAST(CA.ActionGUID as nvarchar(36)) + '%'
		inner join DesktopTemplate DT on DT.DesktopTemplateGUID = DW.DesktopTemplateGUID
GO


---------------------------------------------

-- dbo.viewCustomMenuContent
create view viewCustomMenuContent
as
select CustomMenuContentGUID, CustomMenuGUID, cast(ContentXML as nvarchar(max)) as ContentXML from CustomMenuContent
GO


---------------------------------------------

-- dbo.viewCustomScriptDependencies
CREATE view [dbo].[viewCustomScriptDependencies]
as
select 
	'Workflow Condition' as ReferrerType,
	WFM.Name + ' - ' + WFS.Name as ReferrerName,
	CS.Name as ScriptName,
	WFS.WorkflowStepGUID as ReferrerGUID,
	CS.CustomScriptGUID as ScriptGUID
from 
	CustomScript CS
	inner join WFCondition WFC on cast(WFC.Metadata as nvarchar(max)) like '%<SCRIPTGUID>' + CAST(CS.CustomScriptGUID as nvarchar(36)) + '</SCRIPTGUID>%'
	inner join WFConditionSet WFCS on WFC.ConditionSetGUID = WFCS.ConditionSetGUID
	inner join WFTransition WFT on WFT.ConditionSetGUID = WFCS.ConditionSetGUID
	inner join WFWorkflowStep WFS on WFS.WorkflowStepGUID = WFT.WorkflowStepFromGUID
	inner join WFWorkflowMap WFM on WFM.WorkflowMapGUID = WFS.WorkflowMapGUID
union
select 
	'Custom Action' as ReferrerType,
	CA.Description as ReferrerName,
	CS.Name as ScriptName,
	CA.ActionGUID as ReferrerGUID,
	CS.CustomScriptGUID as ScriptGUID
from 
	CustomScript CS
	inner join CustomAction CA on cast(CA.Metadata as nvarchar(max)) like '%<SCRIPTGUID>' + CAST(CS.CustomScriptGUID as nvarchar(36)) + '</SCRIPTGUID>%'
union
select 
	'Scheduled Task' as ReferrerType,
	ST.Name as ReferrerName,
	CS.Name as ScriptName,
	ST.ScheduledTaskGUID as ReferrerGUID,
	CS.CustomScriptGUID as ScriptGUID
from 
	CustomScript CS
	inner join TEScheduledTask ST on cast(ST.SetupXML as nvarchar(max)) like '%' + CAST(CS.CustomScriptGUID as nvarchar(36)) + '%'
union
select
	'Plan Type' as ReferrerType,
	PT.Name as [ReferrerName],
	CS.Name as [ScriptName],
	PT.PlanTypeGUID as [ReferrerGUID],
	CS.CustomScriptGUID as [ScriptGUID]
from
	PlanType PT
	inner join  CustomScript CS on CS.CustomScriptGUID = PT.OnSaveCustomScriptGUID
union
select
	'Plan Type' as ReferrerType,
	PT.Name as [ReferrerName],
	CS.Name as [ScriptName],
	PT.PlanTypeGUID as [ReferrerGUID],
	CS.CustomScriptGUID as [ScriptGUID]
from
	PlanType PT
	inner join  CustomScript CS on CS.CustomScriptGUID = PT.OnSaveCustomScript2GUID
union
select
	'Plan Type' as ReferrerType,
	PT.Name as [ReferrerName],
	CS.Name as [ScriptName],
	PT.PlanTypeGUID as [ReferrerGUID],
	CS.CustomScriptGUID as [ScriptGUID]
from
	PlanType PT
	inner join  CustomScript CS on CS.CustomScriptGUID = PT.OnAfterModelRefreshCustomScriptGUID
union
select
	'Plan Type' as ReferrerType,
	PT.Name as [ReferrerName],
	CS.Name as [ScriptName],
	PT.PlanTypeGUID as [ReferrerGUID],
	CS.CustomScriptGUID as [ScriptGUID]
from
	PlanType PT
	inner join  CustomScript CS on CS.CustomScriptGUID = PT.OnTemplateChangeCustomScriptGUID
GO


---------------------------------------------

-- dbo.viewCustomScriptDependenciesFast
CREATE view [dbo].[viewCustomScriptDependenciesFast]
AS
select 'Plan Type' as [Type], Name, OnSaveCustomScriptGUID as [ScriptGUID] from PlanType where OnSaveCustomScriptGUID <> dbo.ZeroGUID()
UNION ALL
select 'Plan Type' as [Type], Name, OnSaveCustomScript2GUID as [ScriptGUID] from PlanType where OnSaveCustomScript2GUID <> dbo.ZeroGUID()
UNION ALL
select 'Plan Type' as [Type], Name, OnAfterModelRefreshCustomScriptGUID as [ScriptGUID] from PlanType  where OnAfterModelRefreshCustomScriptGUID <> dbo.ZeroGUID()
UNION ALL
select 'Plan Type' as [Type], Name, OnTemplateChangeCustomScriptGUID as [ScriptGUID] from PlanType where OnTemplateChangeCustomScriptGUID <> dbo.ZeroGUID()
UNION ALL
select 
	'Custom Action',
	[Description],
	(CAST(MetaData as XML)).value('(CUSTOMSCRIPTGUID)[1]', 'uniqueidentifier') as [ScriptGUID]
from dbo.CustomAction 
	where ClassName = 'Strata.X.CustomActions.RunCustomScript'
UNION ALL
select 
	'Workflow Condition',
	WFM.Name + ' - ' + WFS.Name,
	(CAST(WFC.MetaData as XML)).value('(//SOURCEPARAMETERS/SCRIPTGUID)[1]', 'uniqueidentifier') as [ScriptGUID]
from dbo.WFCondition WFC
	inner join WFConditionSet WFCS on WFC.ConditionSetGUID = WFCS.ConditionSetGUID
	inner join WFTransition WFT on WFT.ConditionSetGUID = WFCS.ConditionSetGUID
	inner join WFWorkflowStep WFS on WFS.WorkflowStepGUID = WFT.WorkflowStepFromGUID
	inner join WFWorkflowMap WFM on WFM.WorkflowMapGUID = WFS.WorkflowMapGUID
	where WFC.ClassName = 'Strata.X.Biz.Workflow.Conditions.CalculatedValue'
UNION ALL
select 
	'Scheduled Task',
	[Name],
	(CAST(SetupXML as XML)).value('(//CUSTOMSCRIPTSCHEDULEDTASKSETUP/CUSTOMSCRIPTGUID)[1]', 'uniqueidentifier') as [ScriptGUID]
from dbo.TEScheduledTask 
	where AssemblyQualifiedName like 'Strata.X.Biz.ScheduledTasks.CustomScriptScheduledTask%'
GO


---------------------------------------------

-- dbo.viewDataCenterDimensionConfig
CREATE VIEW dbo.viewDataCenterDimensionConfig
AS	
WITH DimensionConfig AS
(
	SELECT c.DimensionName, c.DataCenterPageName, 
	RIGHT(stepExisting.[Url], LEN(stepExisting.[Url])-1) StepURLExisting, 
	CONVERT(VARCHAR(36),stepExisting.StepGUID) StepGUIDExisting, 
	RIGHT(stepNew.[Url], LEN(stepNew.[Url])-1) StepURLNew, 
	CONVERT(VARCHAR(36),stepNew.StepGUID) StepGUIDNew
	FROM dbo.DataCenterDimensionConfig c
	LEFT JOIN dbo.SystemCenterStep stepExisting ON c.SystemCenterStepGlobalIDExisting = stepExisting.GlobalID AND c.SystemCenterStepGlobalIDExisting != ''
	LEFT JOIN dbo.SystemCenterStep stepNew ON c.SystemCenterStepGlobalIDNew = stepNew.GlobalID AND c.SystemCenterStepGlobalIDNew != '' 
)
SELECT DimensionConfig.DimensionName, 
'/DataCenter/Configuration/' + DimensionConfig.DataCenterPageName +'?dimCode=' AS DataCenterURL,
ISNULL(DimensionConfig.StepURLExisting + '?step=' + DimensionConfig.StepGUIDExisting,'') SystemCenterURLExistingMembers,
ISNULL(DimensionConfig.StepURLNew + '?step=' + DimensionConfig.StepGUIDNew,'') SystemCenterURLNewMembers
FROM DimensionConfig
GO


---------------------------------------------

-- dbo.viewDataCenterDimensionModules
CREATE VIEW dbo.viewDataCenterDimensionModules AS 
	SELECT d.GlobalID, d.SQLSchemaName, d.SQLObjectName, keyAttr.SQLColumnName KeyColumnName, a.SQLColumnName, f.[Name] AS ModuleName, f.Abbreviation AS Abbreviation 
	FROM dbo.DataCenterDimensionConfig dcDim
	INNER JOIN dbo.ScoreDimension d ON dcDim.DimensionName = d.GlobalID
	INNER JOIN dbo.ScoreDimensionGroup dg ON d.DimensionGUID = dg.DimensionGUID
	INNER JOIN dbo.ScoreAttribute a ON a.DimensionGroupGUID = dg.DimensionGroupGUID
	INNER JOIN dbo.ScoreAttribute keyAttr ON d.DefaultKeyGUID = keyAttr.AttributeGUID
	INNER JOIN fw.DimFramework f ON f.Abbreviation = 
													CASE
														WHEN REPLACE(a.SQLColumnName, 'IsDefined', '') = 'CI' THEN 'CCI'
														WHEN REPLACE(a.SQLColumnName, 'IsDefined', '') = 'CAP' THEN 'CM'
														WHEN REPLACE(a.SQLColumnName, 'IsDefined', '') = 'PR' THEN 'PI'
														WHEN REPLACE(a.SQLColumnName, 'IsDefined', '') = 'FW' THEN 'GM'
														ELSE REPLACE(a.SQLColumnName, 'IsDefined', '')
													END
	
	WHERE a.SQLColumnName IN (
		'CAPIsDefined',
		'CIIsDefined',
		'DSSIsDefined',
		'FWIsDefined',
		'MRIsDefined',
		'OBIsDefined',
		'PRIsDefined',
		'SPIsDefined'
	)
	AND NOT (d.GlobalID = 'Account' AND a.SQLColumnName = 'CAPIsDefined')
GO


---------------------------------------------

-- dbo.viewDataDictionary
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI	Description
** 1		2017-10-13	IP		D-06327	Change view from using ad-hod calculation of ClientField to precalculated field
** 2		2019-05-07	DF		B-23035	Add ConfigID to apply simple security assigned to IntConfig table
*************************************************************/
CREATE VIEW [dbo].[viewDataDictionary] AS

with SharedPart AS (
	select
		idm.DataInterfaceMapID,
		f1.FieldName as ClientFieldName, 
		isf.SourceSystem as ClientSourceSystem, 
		isfd.ClientField,
		isf.Name as DataSet,
		f1.GivenScoreAttributeGUID,
		f1.ScoreKeyGUID,
		f1.IsMeasure,
		f1.IsKey,
		dis.SectionTypeVal,
		dis.ScoreGuid,
		dis.Name as SectionName,
		f1.IsHidden,
		ic.ConfigID ConfigID,
		ic.Name as ImportConfiguration, 
		IsNull(icc.ClientComment, '') as ClientComments,
		IsNull(icc.DateModifiedUtc, GETUTCDATE()) as DateModifiedUtc,
		IsNull(icc.ModifiedUserGUID, '00000000-0000-0000-0000-000000000000') as ModifiedUserGUID,
		IsNull(up.NameFull, '') as ModifiedUserName,
		CASE   
		  WHEN isf.MatchModeVal = 2 THEN isf.PartialMatchString   
		  ELSE isf.ExpectedFileName   
		END as ClientFile,
		isfd.SourceColumnId,
		dif.DataInterfaceID
		from IntDataInterfaceField f1
			join IntDataInterfaceSection dis on dis.DataInterfaceSectionID=f1.DataInterfaceSectionID
			join IntDataInterface dif on dis.DataInterfaceID=dif.DataInterfaceID
			join IntConfig ic on ic.DataInterfaceID=dif.DataInterfaceID and ic.IsHidden = 0
			join IntTransformation it on it.ConfigID=ic.ConfigID
			cross apply intGetTransformationSourceFileList(it.TransformationID) tsfl
			join IntSourceFile isf on isf.SourceFileID = tsfl.SourceFileID
			join IntDataInterfaceMap idm on f1.DataInterfaceFieldID=idm.DataInterfaceFieldID
			join IntSourceField isfd on isfd.DataSourceID=it.TransformationID and idm.SourceColumnID=isfd.SourceColumnID
			left join intClientComment icc on icc.DataInterfaceMapID = idm.DataInterfaceMapID
			left join UserProfile up on up.UserGUID = icc.ModifiedUserGUID
		where f1.IsHidden = 0)
		
	select distinct sp.DataInterfaceMapID, sa.FriendlyName as FieldName, sa.[Description] as [Description], sd.FriendlyName as DimensionName,
		sp.ClientFieldName, [dbo].[GetSQLColumnFullType](sa.ColumnType, sa.MaxLength, sa.Scale, sa.Precision) as [Type], IsNull(sas.IsCustom, 0) as IsCustom, 
		sp.DateModifiedUtc, sp.ModifiedUserGUID, sp.ModifiedUserName, sp.ClientComments, sa.AttributeGuid as ScoreGuid, sp.ClientSourceSystem, sp.ClientField, 
		sp.ConfigID, sp.ImportConfiguration, sp.DataSet, sp.ClientFile, sp.SectionName, IsNull(ex.ExampleValue, '') as ExampleValue, GivenScoreAttributeGUID
	from SharedPart sp
		join ScoreAttribute sa on sa.AttributeGuid=sp.GivenScoreAttributeGUID and sp.IsMeasure=0 and SectionTypeVal=0
		join ScoreDimension sd on sd.DimensionGuid=sp.ScoreGuid
		left join ScoreAttributeSetting sas on sas.AttributeGuid=sa.AttributeGuid
		left join [dbo].[DataDictionaryFieldValueExample] ex on ex.ScoreGUID = sa.AttributeGuid
	where not exists (
			select * from SharedPart sp2 
			join ScoreDataTableKeyLink dtl on sp2.DataInterfaceID=sp.DataInterfaceID and dtl.KeyGuid=sp2.ScoreKeyGUID and dtl.DataTableGuid=sp2.ScoreGuid
				 and sp2.GivenScoreAttributeGuid=sp.GivenScoreAttributeGuid
			join ScoreAttribute sa on sa.AttributeGuid=sp2.GivenScoreAttributeGUID
			join ScoreDataTable dt on dt.DataTableGuid=dtl.DataTableGuid)
			
	union all

	select distinct sp.DataInterfaceMapID, sm.FriendlyName as FieldName, sm.[Description] as [Description], dt.FriendlyName as DimensionName,
		sp.ClientFieldName, [dbo].[GetSQLColumnFullType](sm.ColumnTypeValue, sm.MaxLength, sm.Scale, sm.Precision) as [Type], IsNull(sms.IsCustom, 0) as IsCustom, 
		sp.DateModifiedUtc, sp.ModifiedUserGUID, sp.ModifiedUserName, sp.ClientComments, sm.MeasureGuid as ScoreGuid, sp.ClientSourceSystem, sp.ClientField, 
		sp.ConfigID, sp.ImportConfiguration, sp.DataSet, sp.ClientFile, sp.SectionName, IsNull(ex.ExampleValue, '') as ExampleValue, GivenScoreAttributeGUID
	from SharedPart sp
		join ScoreMeasure sm on sm.MeasureGuid=sp.GivenScoreAttributeGUID and sp.IsMeasure=1
		join ScoreDataTable dt on dt.DataTableGuid=sm.DataTableGuid
		left join ScoreMeasureSetting sms on sms.MeasureGuid=sm.MeasureGuid
		left join [dbo].[DataDictionaryFieldValueExample] ex on ex.ScoreGUID = sm.MeasureGuid

	union all

	select distinct sp.DataInterfaceMapID, 
		case when SectionTypeVal = 0 then sa.FriendlyName else sd.FriendlyName + ' - ' + sa.FriendlyName end as FieldName, 
		dtl.[Description] as [Description], dt.FriendlyName as DimensionName, 
		sp.ClientFieldName, [dbo].[GetSQLColumnFullType](sa.ColumnType, sa.MaxLength, sa.Scale, sa.Precision) as [Type], IsNull(sks.IsCustom, 0) as IsCustom, 
		sp.DateModifiedUtc, sp.ModifiedUserGUID, sp.ModifiedUserName, sp.ClientComments, dtl.dataTableKeyLinkGuid as ScoreGuid, sp.ClientSourceSystem, sp.ClientField, 
		sp.ConfigID, sp.ImportConfiguration, sp.DataSet,	sp.ClientFile, sp.SectionName, IsNull(ex.ExampleValue, '') as ExampleValue, GivenScoreAttributeGUID
	from SharedPart sp
		join ScoreDataTableKeyLink dtl on dtl.KeyGuid=sp.ScoreKeyGUID and dtl.DataTableGuid=sp.ScoreGuid
		join ScoreAttribute sa on sa.AttributeGuid=sp.GivenScoreAttributeGUID
		join ScoreDimensionGroup sdg on sdg.DimensionGroupGuid=sa.DimensionGroupGuid
		join ScoreDimension sd on sd.DimensionGuid=sdg.DimensionGuid
		join ScoreDataTable dt on dt.DataTableGuid=dtl.DataTableGuid
		left join ScoreKeyLinkSetting sks on sks.KeyGuid=dtl.KeyGuid and sks.DataTableGuid=dtl.DataTableGuid
		left join [dbo].[DataDictionaryFieldValueExample] ex on ex.ScoreGUID = sp.GivenScoreAttributeGUID
GO


---------------------------------------------

-- dbo.viewDataView
CREATE view [dbo].[viewDataView]
	as
		select 
			DV.DataViewGUID,
			DV.Name,
			DV.SQLViewName,
			DV.SecurityColumns,
			coalesce(S.name, 'dbo') as SchemaName,
			coalesce(V.name, '???') as ViewName,
			case when coalesce(C.name, '???') = '???' then 0 else 1 end as SecurityColumnsExistInSQL
		from 
			DataView DV
			left join sys.schemas S on replace(replace(DV.SQLViewName, '[', ''), ']', '') like (S.name + '.%')
			left join sys.views V on coalesce(S.schema_id, (select SDef.schema_id from sys.schemas SDef where SDef.name = 'dbo')) = V.schema_id and V.name = replace(replace(replace(REPLACE(DV.SQLViewName, '[' + coalesce(S.name, 'dbo') + '].', ''), coalesce(S.name, 'dbo') + '.', ''), '[', ''), ']', '')
			left join sys.columns C on C.object_id = V.object_id and C.name = DV.SecurityColumns
		--where DV.SecurityColumns != ''
GO


---------------------------------------------

-- dbo.viewDesktopParameter_Broken
create view dbo.viewDesktopParameter_Broken
as
	select 
		dp.*
	from
		DesktopParameter dp
	where
		ColumnName != AttributeID
		and not exists(select 1 from REReport r inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = r.ReportGUID and cast(ra.AttributeGUID as nvarchar(36)) = dp.AttributeID and ltrim(ra.ColumnName) = ltrim(dp.ColumnName) where dp.ReportGuidsCSV like '%' + cast(r.ReportGUID as nvarchar(36)) + '%')
GO


---------------------------------------------

-- dbo.viewDesktopTemplateByUser
Create view [dbo].viewDesktopTemplateByUser
as

select  
	up.UserGUID,
	up.UserName as UserName, 
	up.NameFull as UserFullName, 
	dt.DesktopTemplateGUID,
	dt.Name as DesktopTemplate, 
	link.IsVisible, 
	case when us.Setting = dt.DesktopTemplateGUID then 1 else 0 end as IsDefault
from 
	DesktopTemplateUserLink link
	inner join UserProfile up on link.UserGUID=up.UserGUID
	inner join DesktopTemplate dt on dt.DesktopTemplateGUID = link.DesktopTemplateGUID
	inner join UserSetting us on us.UserGUID = up.UserGUID and us.Name = 'DESKTOPDEFAULTTEMPLATE'
GO


---------------------------------------------

-- dbo.viewDimRiskOutputs
CREATE view [dbo].[viewDimRiskOutputs] as
select ROW_NUMBER() OVER(ORDER BY rrd.RiskConfigOutputName ASC) as RowID
	, newid() as MemberGUID
	, rrd.OutputUniqueID
	, rrd.RiskResultName
	, rrd.RiskConfigOutputName + ' - ' + rrd.RiskResultName as RiskConfigOutputName
	, rrd.RiskResultGUID
	,  0 as IsDeleted
from [dbo].[viewSR2RiskResultDetail] rrd
group by rrd.OutputUniqueID, rrd.RiskResultName, rrd.RiskConfigOutputName, RiskResultGUID
GO


---------------------------------------------

-- dbo.viewDimSensitivityOutputs
CREATE view [dbo].[viewDimSensitivityOutputs] as
select ROW_NUMBER() OVER(ORDER BY srd.SensitivityConfigOutputName ASC) as RowID
	, newid() as MemberGUID
	, srd.OutputUniqueID
	, srd.SensitivityResultName
	, srd.SensitivityConfigOutputName + ' - ' + srd.SensitivityResultName As SensitivityConfigOutputName
	, srd.SensitivityResultGUID
	,  0 as IsDeleted
from [dbo].[viewSR2SensitivityResultDetail] srd
group by srd.OutputUniqueID, srd.SensitivityResultName, srd.SensitivityConfigOutputName, srd.SensitivityResultGUID
GO


---------------------------------------------

-- dbo.viewEMFFillIns
CREATE view [dbo].[viewEMFFillIns] as --with schemabinding as 
select  
	ModelGUID, 
	p.Name as PlanName,
	PlaceholderMemberGuid, 
	phm.Name as PlaceholderName,
	FilledInMemberGuid,
	fi.name as FillInName, 
	phm.sortorderfullpath as PlaceholderSort, 
	fi.SortOrderFullPath as FillinSort, 
	phmp.listmemberguid as PlaceholderSectionGUID, 
	phmp.Name as PlaceholderSection
from 
	dbo.emffillin efi (readuncommitted)
	inner join dbo.XPlan p (readuncommitted) on p.PlanGUID = efi.ModelGUID
	inner join dbo.securelistmember phm (readuncommitted) on efi.placeholdermemberguid = phm.listmemberguid
	inner join dbo.SecureListMember phmp (readuncommitted) on phm.ParentListMemberGUID = phmp.ListMemberGUID
	inner join dbo.securelistmember fi (readuncommitted) on efi.filledinmemberguid = fi.listmemberguid
GO


---------------------------------------------

-- dbo.viewEMFFillInsPossibleDupes
CREATE view [dbo].[viewEMFFillInsPossibleDupes] as --with schemabinding as
--select * from viewEMFfillins fi
--where
--exists (
--	select 1
--	from emffillin fidupe
--	group by modelguid, filledinmemberguid
--	having 
--		fi.modelguid = fidupe.modelguid
--		and fi.filledinmemberguid = fidupe.filledinmemberguid
--		and count(*) > 1
--	)
select 
	modelguid,  placeholdermemberguid, filledinmemberguid, planname,placeholdername, fillinname
from dbo.viewemffillins vfi
where 
	exists ( 
		select modelguid, filledinmemberguid from dbo.emffillin fi group by modelguid, filledinmemberguid
		having count(*) > 1
		and fi.modelguid = vfi.modelguid and fi.filledinmemberguid = vfi.filledinmemberguid
		)
GO


---------------------------------------------

-- dbo.viewEMFFillinsOutOfOrder
CREATE view [dbo].[viewEMFFillinsOutOfOrder] as --with schemabinding as		
select  
	fi.SortedPHIndex , 
	fi.ModelGUID, 
	fi.PlanName, 
	fi.PlaceholderMemberGuid, 
	fi.PlaceholderName,
	fi.FilledInMemberGuid,
	fi.FillInName, 
	fi.PlaceholderSort, 
	fi.FillinSort, 
	fi.PlaceholderSectionGUID, 
	fi.PlaceholderSection,
	REPL.PlaceholderMember as SortedPHMember, REPL.PlaceholderMemberGUID as SortedPHMemberGUID
from
	dbo.viewEMFFillinsSorted FI
	left join dbo.viewPlaceholders REPL on FI.PlaceholderSectionGUID = REPL.PlaceholderParentMemberGUID
		and FI.SortedPHIndex = REPL.PHIndex
where
	FI.PlaceholderMemberGuid <> REPL.PlaceholderMemberGUID
GO


---------------------------------------------

-- dbo.viewEMFFillinsSorted
CREATE view [dbo].[viewEMFFillinsSorted] as --with schemabinding as
select 
	row_number() over (partition by  fi.modelguid, 
	fi.placeholdersection order by fi.fillinsort) -1 as SortedPHIndex , 
	ModelGUID, 
	PlanName, 
	PlaceholderMemberGuid, 
	PlaceholderName,
	FilledInMemberGuid,
	FillInName, 
	PlaceholderSort, 
	FillinSort, 
	PlaceholderSectionGUID, 
	PlaceholderSection
from 
	dbo.viewemffillins fi
GO


---------------------------------------------

-- dbo.viewEMFFillinsUsage
create view viewEMFFillinsUsage
as
select
	PD.Name as Dimension,
	P.Name as Section,
	(select COUNT(*) from SecureListMember PC where PC.ParentListMemberGUID = P.ListMemberGUID) as SectionChildCount,
	coalesce((select MAX(U.UsedCount) from(select FI.ModelGUID, LM.ParentListMemberGUID, COUNT(*) as UsedCount from EMFFillIn FI inner join SecureListMember LM on LM.ListMemberGUID = FI.PlaceholderMemberGUID and LM.ParentListMemberGUID = P.ListMemberGUID group by FI.ModelGUID,	LM.ParentListMemberGUID) U), 0) as UsedCount
from
	SecureListMember P
	inner join SecureList PD on PD.ListGUID = P.ListGUID
where
	P.OutlineLevel = 0
	and (select COUNT(*) from SecureListMember PC where PC.ParentListMemberGUID = P.ListMemberGUID) > 0
GO


---------------------------------------------

-- dbo.viewEMFModelDataConfigDimensionLinkDetail
--Author: gforeman
--Branch: DSS
--Forward
CREATE view viewEMFModelDataConfigDimensionLinkDetail as 
select 
	dbo.GetFolderFullPath(mdc.FolderGUID) as FolderFullpath, 
	mdc.Name,sl.Name as DimensionName, 
	mdc.ModelDataConfigGUID,  
	sl.ListGUID as DimensionGUID, 
	case when sl.ListGUID = mdc.FormatOverrideDimensionGUID then 1 else 0 end as IsFormatOverride, 
	sl.IsSecured,
	sl.IsPlaceholder,
	fisl.ListGUID as FillInDimensionGUID,
	fisl.Name as FillInDimensionName,
	mdcdl.IsModelKey
from
	emfmodeldataconfig mdc
	inner join EMFModelDataConfigDimensionLink mdcdl on mdc.ModelDataConfigGUID = mdcdl.ModelDataConfigGUID
	inner join SecureList sl on mdcdl.DimensionGUID = sl.ListGUID
	left join securelist fisl on sl.FillInDimensionGUID = fisl.ListGUID
GO


---------------------------------------------

-- dbo.viewEMFModelDataLink
CREATE view [dbo].[viewEMFModelDataLink] as --with schemabinding as 
select  
	p.PlanGUID as ModelGUID,
	p.Name as ModelName,
	p.PlanTypeGUID as PlanTypeGUID,
	pt.Name as PlanTypeName,
	mt.ModelTemplateGUID,
	mt.Name as ModelTemplateName,
	ls.LinkSourceGUID,
	ls.Name as LinkSourceName,
	mdl.ParentModelGUID,
	pp.Name as ParentModelName,
	pp.PlanTypeGUID as ParentPlanTypeGUID,
	ppt.Name as ParentPlanTypeName
from 
	XPlan p
	left join EMFModelTemplate mt on p.ModelTemplateGUID = mt.ModelTemplateGUID
	left join PlanType pt on p.PlanTypeGUID = pt.PlanTypeGUID
	left join EMFModelTemplateLinkSource ls on mt.ModelTemplateGUID = ls.ModelTemplateGUID
	left join EMFModelDataLink mdl on ls.LinkSourceGUID = mdl.LinkSourceGUID and p.PlanGUID = mdl.ModelGUID
	left join XPlan pp on mdl.ParentModelGUID = pp.PlanGUID
	left join PlanType ppt on pp.PlanTypeGUID = ppt.PlanTypeGUID
GO


---------------------------------------------

-- dbo.viewEMFModelTemplateExpansion
CREATE view [dbo].[viewEMFModelTemplateExpansion] as
select 
	map.*,
	slm.ListGUID as DimensionGUID,
	ws.ModelTemplateGUID,
	ws.name as SheetName,
	cell.ExcelSheetGUID as WorksheetGUID,
	cell.Row as Row1OneBased,
	cell.Row2 as Row2OneBased,
	cell.Col as ColOneBased
from
	EMFModelTemplateExpansion map
	inner join SecureListMember slm on map.DimensionMemberGUID = slm.ListMemberGUID
	inner join MEExcelCell cell on map.CellGUID = cell.ExcelCellGUID --left for backwards compat :(
	inner join EMFModelTemplateWorksheet ws on cell.ExcelSheetGUID = ws.WorksheetGUID --left for backwards compat :(
	
	
	--left join MEExcelSheet sheet on cell.ExcelSheetGUID = sheet.ExcelSheetGUID
GO


---------------------------------------------

-- dbo.viewEMFModelTemplateFormFieldMapping
CREATE view [dbo].[viewEMFModelTemplateFormFieldMapping] as
select 
	map.FormFieldGUID,
	map.[CellGUID],
	ws.ModelTemplateGUID,
	ws.name as WorksheetName,
	cell.ExcelSheetGUID as WorksheetGUID,
	cell.Row,
	cell.Col
from
	EMFModelTemplateFormFieldMapping map
	inner join MEExcelCell cell on map.CellGUID = cell.ExcelCellGUID 
	inner join EMFModelTemplateWorksheet ws on cell.ExcelSheetGUID = ws.WorksheetGUID
GO


---------------------------------------------

-- dbo.viewEMFModelTemplateFormFieldMappingData
CREATE view [dbo].[viewEMFModelTemplateFormFieldMappingData] as
SELECT  
	map.CellGUID,
	MAP.ModelTemplateGUID,
	map.WorksheetGUID,
	map.WorksheetName,
	map.Row -1 as RowZeroBased,
	map.Col -1 as ColZeroBased,
	FF.FormFieldGUID,
	'' as Value
FROM
	viewEMFModelTemplateFormFieldMapping MAP 
	INNER JOIN FE2FormField FF ON FF.formfieldguid = map.formfieldguid
GO


---------------------------------------------

-- dbo.viewEMFModelTemplateLastPublished
CREATE view viewEMFModelTemplateLastPublished as
select 
	mt.ModelTemplateGUID, 
	mt.Name,
	isnull(MAX(DATETIMESTAMP), cast('2000-01-01' as datetime)) as LastPublished
from 
	EMFModelTemplate mt
	left join HistoryItem hi on mt.ModelTemplateGUID = hi.OBJECTGUID
group by
	mt.ModelTemplateGUID,
	mt.Name
GO


---------------------------------------------

-- dbo.viewEMFModelTemplateLinkSource
CREATE view [dbo].[viewEMFModelTemplateLinkSource] as 


select 
	mt.name as TemplateName,
	ls.name as LinkSourceName,
	mdc.name as StructureName,
	st.name as SubtableName,
	sc.FriendlyName as CompositeName,
	sd1.FriendlyName as ScoreMappingDataTableName,
	sd2.FriendlyName as ScoreDataDataTableName,
	mt.ModelTemplateGUID,
	ls.LinkSourceGUID,
	st.SubtableGUID,
	mdc.modeldataconfigguid as StructureGUID,
	sc.CompositeGUID,
	sd1.datatableguid as ScoreMappingDataTableGUID,
	sd2.datatableguid as ScoreDataDataTableGUID
from 
	emfmodeltemplate mt
	inner join emfmodeltemplatelinksource ls on mt.modeltemplateguid = ls.modeltemplateguid
	left join emfsubtable st on ls.parentsubtableguid = st.subtableguid
	left join emfmodeldataconfig mdc on isnull(st.modeldataconfigguid,ls.parentmodeldataconfigguid) = mdc.modeldataconfigguid
	left join scorecomposite sc on ls.parentscorecompositetableguid = sc.compositeguid
	left join scoredatatable sd1 on sc.datatableguid1 = sd1.datatableguid 
	left join scoredatatable sd2 on sc.datatableguid2 = sd2.datatableguid
GO


---------------------------------------------

-- dbo.viewEMFModelTemplateMDCs
create view viewEMFModelTemplateMDCs as 
select ls.modeltemplateguid, coalesce(st.MODELDATACONFIGGUID,ls.parentmodeldataconfigguid) as modeldataconfigguid from EMFModelTemplateLinkSource ls left join EMFSubtable st on ls.ParentSubtableGUID = st.SUBTABLEGUID
GO


---------------------------------------------

-- dbo.viewEMFModelTemplateNewLabelsOnly
create view viewEMFModelTemplateNewLabelsOnly
as
select 
	mt2.modeltemplateguid,
	
	case when
		mt2.isnewlabelsonly = 1
		or not exists (
		select 1
		from
			EMFModelTemplate mt
			inner join EMFModelTemplateLinkSource ls on mt.ModelTemplateGUID = ls.ModelTemplateGUID
			inner join EMFModelDataConfigMeasureLink ml on ls.ParentModelDataConfigGUID = ml.ModelDataConfigGUID
			inner join EMFMeasure m on ml.MeasureGUID = m.MEASUREGUID
		where
			m.IsPlaceholderLabel = 1
			and mt.modeltemplateguid = mt2.modeltemplateguid
		) 
		then cast(1 as bit)
	else
		cast(0 as bit) end as IsNewLabelsOnly
from
	emfmodeltemplate mt2
GO


---------------------------------------------

-- dbo.viewEMFModelTemplatePlaceholderLabelMapping
CREATE view [dbo].[viewEMFModelTemplatePlaceholderLabelMapping] as
select 
	map.[MappingGUID]
	,map.[PlaceholderDimensionGUID]
	,map.[PlaceholderMemberGUID]
	,map.[LabelPropertyGUID]
	,map.[IsHidingRow]
	,map.[IsHidingCol]
	,map.[IsClearingRow]
	,map.[IsClearingCol]
	,map.[RowExpanded]
	,map.[CellGUID]
	,map.[IsUserMapped],
	ws.modeltemplateguid as BookGUID,
	ws.name as SheetName,
	cell.ExcelSheetGUID,
	cell.Row,
	cell.Col
from
	EMFModelTemplatePlaceholderLabelMapping map (readuncommitted)
	inner join MEExcelCell cell (readuncommitted) on map.CellGUID = cell.ExcelCellGUID 
	inner join EMFModelTemplateWorksheet ws (readuncommitted) on cell.ExcelSheetGUID = ws.WorksheetGUID
GO


---------------------------------------------

-- dbo.viewEMFModelTemplatePlaceholderLabelMappingDetail
CREATE view [dbo].[viewEMFModelTemplatePlaceholderLabelMappingDetail] as
select 
	map.[MappingGUID]
	,map.[PlaceholderDimensionGUID]
	,phsl.Name as PlaceholderDimensionName
	,map.[PlaceholderMemberGUID]
	,phslm.Name as PlaceholderMemberName
	,map.[LabelPropertyGUID]
	,case when map.LabelPropertyGUID = dbo.ZeroGUID() then 'Name' else slp.name end as  LabelPropertyName
	,map.[IsHidingRow]
	,map.[IsHidingCol]
	,map.[IsClearingRow]
	,map.[IsClearingCol]
	,map.[RowExpanded]
	,map.[CellGUID]
	,map.[IsUserMapped],
	ws.modeltemplateguid as BookGUID,
	mt.Name as TemplateName,
	ws.name as SheetName,
	cell.ExcelSheetGUID,
	cell.Row,
	cell.Col
from
	EMFModelTemplatePlaceholderLabelMapping map
	inner join MEExcelCell cell on map.CellGUID = cell.ExcelCellGUID --left for backwards compat :(
	inner join EMFModelTemplateWorksheet ws on cell.ExcelSheetGUID = ws.WorksheetGUID --left for backwards compat :(
	left join SecureListMember phslm on map.PlaceholderMemberGUID = phslm.ListMemberGUID
	left join SecureList phsl on map.PlaceholderDimensionGUID = phsl.ListGUID
	left join SecureListProperty slp on map.LabelPropertyGUID = slp.ListPropertyGUID
	left join EMFModelTemplate mt on ws.ModelTemplateGUID = mt.ModelTemplateGUID	
	--left join MEExcelSheet sheet on cell.ExcelSheetGUID = sheet.ExcelSheetGUID
GO


---------------------------------------------

-- dbo.viewEMFModelTemplatePossibleLinks
create view viewEMFModelTemplatePossibleLinks as
select distinct
	tgt.ModelTemplateGuid as TargetModelTemplateGuid,
	tgt.ModelDataConfigGuid as TargetModelDataConfigGuid,
	tgt.IsSubtable as TargetIsSubtable,
	isnull(tgt.SubtableGuid, dbo.zeroguid()) as TargetSubtableGuid
from
	(select 
		ls.ModelTemplateGUID, mdc.ModelDataConfigGUID, case when st.NAME is null then cast(0 as bit) else cast(1 as bit) end as IsSubtable, st.SUBTABLEGUID
	from 
		[dbo].[EMFModelTemplateLinkSource] ls
		left join [dbo].[EMFSubtable] st on ls.ParentSubtableGUID = st.SUBTABLEGUID
		left join [dbo].[EMFModelDataConfig] mdc on isnull(st.MODELDATACONFIGGUID, ls.ParentModelDataConfigGUID) = mdc.ModelDataConfigGUID
	where
		ls.IsSelf = 0
	) tgt 
	inner join 
		(select 
			ls.ModelTemplateGUID, mdc.ModelDataConfigGUID, ls.Name
		from 
			[dbo].[EMFModelTemplateLinkSource] ls
			inner join [dbo].[EMFModelDataConfig] mdc on ls.ParentModelDataConfigGUID = mdc.ModelDataConfigGUID
		where
			ls.IsSelf = 1
		) src on src.ModelDataConfigGuid = tgt.ModelDataConfigGuid
GO


---------------------------------------------

-- dbo.viewEMFPlaceholderSummary
CREATE view viewEMFPlaceholderSummary as 
select 
	sl.ListGUID as PHDimensionGUID, 
	sl.name as PHDimensionName, 
slm.ListMemberGUID as PHSectionGUID , 
slm.name as PHSectionName, 
(select count(*) from securelistmember cslm where cslm.parentlistmemberguid = slm.listmemberguid) as Children, 
(select top 1 listmemberguid from securelistmember cslm where cslm.parentlistmemberguid = slm.listmemberguid order by cslm.SortOrderFullPath) as FirstPHMemberGUID,
	 slm.SortOrderFullPath
from 
	securelistmember slm
	inner join securelist sl on slm.listguid = sl.listguid
where
	sl.isplaceholder = 1
	and slm.outlinelevel = 0
GO


---------------------------------------------

-- dbo.viewEMFStructuresInTemplates
CREATE VIEW [dbo].[viewEMFStructuresInTemplates]
AS
SELECT     
	TE.ModelTemplateGUID,
	TE.Name As [Template Name],
	COALESCE(MDC.ModelDataConfigGUID, SV.SubtableGUID, COMP.CompositeGUID) as [StructureGUID],
	COALESCE(MDC.Name, SV.Name, COMP.FriendlyName) as [Structure Name],
	CASE
		WHEN TLS.ParentModelDataConfigGUID <> '00000000-0000-0000-0000-000000000000' THEN 'EMF Structure'
		WHEN TLS.ParentSubtableGUID <> '00000000-0000-0000-0000-000000000000' THEN 'EMF Subtable'
		WHEN TLS.ParentScoreCompositeTableGUID <> '00000000-0000-0000-0000-000000000000' Then 'Score Composite'
	END AS [Config Type]
FROM
	dbo.EMFModelTemplate AS TE 
	INNER JOIN	dbo.EMFModelTemplateLinkSource AS TLS ON TLS.ModelTemplateGUID = TE.ModelTemplateGUID
	LEFT JOIN dbo.EMFModelDataConfig MDC ON MDC.ModelDataConfigGUID = TLS.ParentModelDataConfigGUID
	LEFT JOIN dbo.EMFSubtable SV ON SV.SUBTABLEGUID = TLS.ParentSubtableGUID
	LEFT JOIN dbo.ScoreComposite COMP ON COMP.CompositeGUID = TLS.ParentScoreCompositeTableGUID
GO


---------------------------------------------

-- dbo.viewEmailMessage
CREATE view [dbo].[viewEmailMessage]
as
	select
		M.*,
		coalesce(U.NameFull, '') as SenderFullName,
		coalesce(U.EmailAddress, '') as SenderEmailAddress
	from
		[dbo].[EmailMessage] M
		left join [dbo].[UserProfile] U (readuncommitted) on U.UserGUID = M.SenderUserGUID
GO


---------------------------------------------

-- dbo.viewEmailRecipient
CREATE view dbo.viewEmailRecipient
as
select 
	R.*,
	coalesce(coalesce(coalesce(U.NameFull, UG.Name), UR.Name), '') as IdentityFullName
from 
	EmailRecipient R
	left join UserProfile U (readuncommitted) on U.UserGUID = R.IdentityGUID and R.IdentityType = 0
	left join UserGroup UG (readuncommitted) on UG.UserGroupGUID = R.IdentityGUID and R.IdentityType = 1
	left join UserRole UR (readuncommitted) on UR.UserRoleGUID = R.IdentityGUID and R.IdentityType = 2
GO


---------------------------------------------

-- dbo.viewFE2FormField
CREATE VIEW [dbo].[viewFE2FormField]
AS
SELECT 
	FF.*,
	isnull(SA.AttributeGUID, dbo.ZeroGUID()) as AttributeGUID, 
	isnull(SA.IsCopiedWithPlan,0) as IsCopiedWithPlan,
	isnull(SA.SQLColumnName, '') as ColumnName,
	isnull(SA.ColumnType, 0) as ColumnType,
	isnull(SA.Precision, 0) as ColumnPrecision,
	isnull(SA.Scale, 0) as ColumnScale,
	isnull(SA.MaxLength, 0) as ColumnMaxLength,
	ISNULL(SA.IsFormField, 1) as IsAttributeEditable,	
	case when isnull(SA.IsSecuredLootID, 0) = 1 or isnull(SA.IsSecuredLootGroupID, 0) = 1 then cast(1 as bit) else cast(0 as bit) end as IsAttributeSecured,
	isnull(DG.DimensionGUID, dbo.ZeroGUID()) as DimensionGUID,
	isnull(DG.SchemaName + '.' + DG.ObjectName, '') as DimensionGroupSQLExpression,
	isnull(SD.SQLSchemaName + '.' + SD.SQLObjectName, '') as DimensionSQLExpression,
	coalesce(F.PlanTypeGUID, dbo.ZeroGUID()) as PlanTypeGUID,
	coalesce(F.FormGUID, dbo.ZeroGUID()) as FormGUID,
	isnull(F.IsHidden, 0) as IsDirectoryOnly,
	coalesce(FT.Name, '') as FormTab,
	coalesce(FT.DisplayOrder, 0) as FormTabDisplayOrder,
	coalesce(FS.DisplayOrder, 0) as FormSectionDisplayOrder
 
FROM 
	FE2FormField FF (readuncommitted) 
	left join [dbo].[ScoreAttribute] SA (readuncommitted) on SA.AttributeGUID = FF.DataSourceGUID 
	left join [dbo].[ScoreDimensionGroup] DG (readuncommitted) on DG.DimensionGroupGUID = SA.DimensionGroupGUID 
	left join [dbo].[ScoreDimension] SD (readuncommitted) on SD.DimensionGUID = DG.DimensionGUID
	left join [dbo].[FE2FormSection] FS (readuncommitted) on FS.FormSectionGUID = FF.FormSectionGUID 
	left join [dbo].[FE2FormTab] FT (readuncommitted) on FT.FormTabGUID = FS.FormTabGUID 
	left join [dbo].[FE2Form] F (readuncommitted) on F.FormGUID = FT.FormGUID
GO


---------------------------------------------

-- dbo.viewFE2FormFieldComputed
CREATE VIEW dbo.viewFE2FormFieldComputed
AS
	select
		case when cast(cast(ComputedFieldConfig as xml).query('//IsActive[1]/text()') as nvarchar(10)) = 'true' then cast(1 as bit) else cast(0 as bit) end as IsComputedFieldActive,
		cast(cast(cast(ComputedFieldConfig as xml).query('//LastRefreshErrorGUID[1]/text()') as nvarchar(36)) as uniqueidentifier) as LastRefreshErrorGUID,
		cast(cast(ComputedFieldConfig as xml).query('//LastRunTime[1]/text()') as nvarchar(100)) as LastRunTimeSeconds,
		cast(cast(ComputedFieldConfig as xml).query('//SQL[1]/text()') as nvarchar(max)) as SQL,
		cast(cast(ComputedFieldConfig as xml).query('//LastRefreshSQL[1]/text()') as nvarchar(max)) as LastRefreshSQL,
		cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int) as CustomSQLType,
		case 
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=0 then 'Unspecified'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=1 then 'DateCreated'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=2 then 'DBSetting'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=3 then 'DimensionDriven'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=4 then 'FileAttachment'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=5 then 'FillinDriven'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=6 then 'FormFieldDriven'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=7 then 'ModelDriven'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=8 then 'Workflow'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=9 then 'NotApplicable'
			when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=10 then 'AlwaysUpdate' end as CustomSQLTypeName,
		case when cast(cast(ComputedFieldConfig as xml).query('//IsAsynchronous[1]/text()') as nvarchar(5)) = 'true' then cast(1 as bit) else cast(0 as bit) end as IsAsynchronous,
		*
	from
		[dbo].[viewFE2FormField]
	where
		ComputedFieldClassName != ''
GO


---------------------------------------------

-- dbo.viewFE2ScriptSnippetHistory
CREATE view [dbo].[viewFE2ScriptSnippetHistory]  
AS  
select
	S.*,
	H.Name,
	H.Type,
	H.ErrorGUID
from
	[dbo].[FE2ScriptSnippetHistory] S
	inner join [dbo].[viewFE2ScriptUpgradeHistory] H on H.HistoryGUID = S.HistoryGUID
GO


---------------------------------------------

-- dbo.viewFE2ScriptUpgradeHistory
CREATE view dbo.viewFE2ScriptUpgradeHistory
as
 	
select
		H.HistoryGUID,
		'SQL Object' as Type,
		H.SQLObjectName as Name,
		H.OldValue,
		H.NewValue,
		H.RiskLevel,
		H.IsComplete,
		H.CustomScriptGUID,
		H.ErrorGUID
	from
		[dbo].[FE2ScriptUpgradeHistory] H
	where
		H.SQLObjectName != ''
	union all
	select
		H.HistoryGUID,
		'Registered Script' as Type,
		CS.Name as Name,
		H.OldValue,
		H.NewValue,
		H.RiskLevel,
		H.IsComplete,
		H.CustomScriptGUID,
		H.ErrorGUID
	from
		[dbo].[FE2ScriptUpgradeHistory] H
		inner join [dbo].[CustomScript] CS on CS.CustomScriptGUID = H.CustomScriptGUID
	union all
	select
		H.HistoryGUID,
		'Calculated Field' as Type,
		FF.Name as Name,
		H.OldValue,
		H.NewValue,
		H.RiskLevel,
		H.IsComplete,
		H.CustomScriptGUID,
		H.ErrorGUID
	from
		[dbo].[FE2ScriptUpgradeHistory] H
		inner join [dbo].[FEFormField] FF on FF.FORMFIELDGUID = H.CustomScriptGUID
GO


---------------------------------------------

-- dbo.viewFE2ScriptUpgradeWorkflow
CREATE view dbo.viewFE2ScriptUpgradeWorkflow
as
	select 
		cs.CustomScriptGUID, cs.Name as CustomScriptName, dbo.straggr(distinct wfm.Name, ', ', '') as WorkflowNames
	from 
		WFEventPlanStatement eps (readuncommitted) 
		inner join [dbo].[CustomAction] ca (readuncommitted) on ca.ActionGUID = eps.StatementGUID 
		inner join [dbo].[CustomScript] cs (readuncommitted) on ca.Metadata = '<CUSTOMSCRIPTGUID>' + cast(cs.CustomScriptGUID as nvarchar(36)) + '</CUSTOMSCRIPTGUID>'
		inner join WFEventPlan ep (readuncommitted) on ep.EventPlanGUID = eps.EventPlanGUID
		inner join WFWorkflowStep wfs (readuncommitted) on wfs.OnStartEventPlanGUID = ep.EventPlanGUID or wfs.OnEndEventPlanGUID = ep.EventPlanGUID
		inner join WFWorkflowMap wfm (readuncommitted) on wfm.WorkflowMapGUID = wfs.WorkflowMapGUID
		inner join FE2ScriptUpgradeHistory suh (readuncommitted) on suh.CustomScriptGUID = cs.CustomScriptGUID
	group by
		cs.CustomScriptGUID, cs.Name
	having
		count(distinct wfm.Name) > 1
	union all
	select 
		cs.CustomScriptGUID, cs.Name as CustomScriptName, dbo.straggr(distinct wfm.Name, ', ', '') as WorkflowNames
	from
		WFCondition c (readuncommitted)
		inner join [dbo].[CustomScript] cs (readuncommitted) on cast(cast(c.Metadata as xml).query('//CUSTOMSCRIPTGUID[1]/text()') as nvarchar(36)) = cast(cs.CustomScriptGUID as nvarchar(36))
		inner join WFConditionSet wfcs (readuncommitted) on wfcs.ConditionSetGUID = c.ConditionSetGUID
		inner join WFEventPlanStatement eps (readuncommitted) on eps.StatementGUID = wfcs.ConditionSetGUID
		inner join WFEventPlan ep (readuncommitted) on ep.EventPlanGUID = eps.EventPlanGUID
		inner join WFWorkflowStep wfs (readuncommitted) on wfs.OnStartEventPlanGUID = ep.EventPlanGUID
		inner join WFWorkflowMap wfm (readuncommitted) on wfm.WorkflowMapGUID = wfs.WorkflowMapGUID or wfs.OnEndEventPlanGUID = ep.EventPlanGUID or wfs.QualifyConditionSetGUID = wfcs.ConditionSetGUID
		inner join FE2ScriptUpgradeHistory suh (readuncommitted) on suh.CustomScriptGUID = cs.CustomScriptGUID
	group by
		cs.CustomScriptGUID, cs.Name
	having
		count(distinct wfm.Name) > 1
	union all
	select 
		cs.CustomScriptGUID, cs.Name as CustomScriptName, dbo.straggr(distinct wfm.Name, ', ', '') as WorkflowNames
	from
		WFCondition c (readuncommitted)
		inner join [dbo].[CustomScript] cs (readuncommitted) on cast(cast(c.Metadata as xml).query('//CUSTOMSCRIPTGUID[1]/text()') as nvarchar(36)) = cast(cs.CustomScriptGUID as nvarchar(36))
		inner join WFConditionSet wfcs (readuncommitted) on wfcs.ConditionSetGUID = c.ConditionSetGUID
		inner join WFTransition t (readuncommitted) on t.ConditionSetGUID = wfcs.ConditionSetGUID
		inner join WFWorkflowStep wfs (readuncommitted) on wfs.WorkflowStepGUID = t.WorkflowStepFromGUID
		inner join WFWorkflowMap wfm (readuncommitted) on wfm.WorkflowMapGUID = wfs.WorkflowMapGUID
		inner join FE2ScriptUpgradeHistory suh (readuncommitted) on suh.CustomScriptGUID = cs.CustomScriptGUID
	group by
		cs.CustomScriptGUID, cs.Name
	having
		count(distinct wfm.Name) > 1
GO


---------------------------------------------

-- dbo.viewFEFormDataHistory
CREATE VIEW [dbo].[viewFEFormDataHistory] AS
SELECT
	HIST.RowID
	, HIST.EntityGUID as PlanGUID
	,isnull(fd.name,hist.EntityName)  as PlanName
	,HIST.FormFieldGUID
	,ISNULL(ff.name,hist.FormFieldName) as FormFieldName
	,HIST.DateTimeStamp
	,CASE
		WHEN FF.FieldType IN (1,2,3,15,17) THEN CAST(HIST.ValueFloat AS NVARCHAR(MAX))
		ELSE HIST.ValueVarChar
	END AS [Value]
	,HIST.ValueBit
	,HIST.ValueDate
	,HIST.ValueFloat
	,HIST.ValueGUID
	,HIST.ValueGUIDS
	,HIST.ValueVarChar
FROM 
	dbo.FEFormDataHistory HIST (readuncommitted)
	LEFT JOIN	dbo.FE2FormField FF (readuncommitted)	ON		(hist.FormFieldGUID = FF.FormFieldGUID)
	left join   XPlan fd (readuncommitted) on HIST.EntityGUID = fd.PlanGUID
GO


---------------------------------------------

-- dbo.viewFEFormField
--used for framework transfers, which require xml cols to be cast to varchar for cross-db scripting
create view dbo.viewFEFormField
as
SELECT [FormFieldGUID]
      ,[GlobalID]
      ,[Name]
      ,[FieldType]
      ,[MaxLength]
      ,[MinLength]
      ,[DataFormat]
      ,[DefaultValue]
      ,[HelpText]
      ,[IsReadOnly]
      ,[HasNumericMaxValue]
      ,[NumericMaxValue]
      ,[HasNumericMinValue]
      ,[NumericMinValue]
      ,[StringMask]
      ,[DecimalPlaces]
      ,[UseThousandsSeparator]
      ,[UseNegParentheses]
      ,[HasLabel]
      ,[LabelDisplayType]
      ,[LabelWidth]
      ,[IsInDirectory]
      ,[SourceType]
      ,[SourcePath]
      ,[SourceGUID]
      ,[Rows]
      ,[UsePicker]
      ,[DefaultSortOrder]
      ,[IsRequired]
      ,[Mask]
      ,[HelpTextDisplayType]
      ,[HasOptionHelpText]
      ,[DefaultValueType]
      ,[Label]
      ,[HasRowNumbers]
      ,[FolderGUID]
      ,[SpecialFieldType]
      ,[SourceDisplayFormat]
      ,[ExecutionOrder]
      ,[DirectoryName]
      ,[ScaleDisplayFactor]
      ,[DateCreated]
      ,[DateModified]
      ,[IsRecordingHistory]
      ,[IsCleared]
      ,[DisplayFormatOverride]
      ,[ResizeOffset]
      ,[IsSetupLocked]
      ,[IsCoolite]
      ,[IsCopied]
      ,[RenderType]
      ,[RenderThreshold]
      ,[RenderComparisonFieldGUID]
      ,[RenderComparisonOperator]
      ,[RefreshMode]
      ,cast([TypeConfigXML] as nvarchar(max)) as [TypeConfigXML]
  FROM [dbo].[FEFormField]
GO


---------------------------------------------

-- dbo.viewFEFormFieldCore
CREATE VIEW [dbo].[viewFEFormFieldCore] as
SELECT [FormFieldGUID]
      ,[GlobalID]
      ,[Name]
      ,[FieldType]
      ,[MaxLength]
      ,[MinLength]
      ,[IsReadOnly]
      ,[HasNumericMaxValue]
      ,[NumericMaxValue]
      ,[HasNumericMinValue]
      ,[NumericMinValue]
      ,[DecimalPlaces]
      ,[UseThousandsSeparator]
      ,[UseNegParentheses]
      ,[HasLabel]
      ,[LabelDisplayType]
      ,[LabelWidth]
      ,[IsInDirectory]
      ,[SourceType]
      ,[SourceGUID]
      ,[Rows]
      ,[UsePicker]
      ,[DefaultSortOrder]
      ,[IsRequired]
      ,[HelpTextDisplayType]
      ,[HasOptionHelpText]
      ,[DefaultValueType]
      ,[HasRowNumbers]
      --,[IsInheritingPermissions] 
      --,[IsAdvancedMode] 
      ,[FolderGUID]
      ,[SpecialFieldType]
      ,[ExecutionOrder]
	  ,[DirectoryName]
	  ,[ScaleDisplayFactor]
	  ,[DisplayFormatOverride]
	  ,[ResizeOffset]
      ,[IsSetupLocked]
      ,[IsCoolite]
      ,[IsCopied]
      ,[RenderType]
      ,[RenderThreshold]
      ,[RenderComparisonFieldGUID]
      ,[RenderComparisonOperator]
      ,[RefreshMode]
      ,[DateCreated]
      ,[DateModified]
      ,[IsRecordingHistory]
      ,[IsCleared]
      ,'' as [StringMask]
      ,'' as [SourcePath]
      ,'' as [Mask]
      ,'' as [Label]
      ,'' as [SourceDisplayFormat]
      ,'' as [DataFormat]
      ,'' as [DefaultValue]
      ,'' as [HelpText]
  FROM [dbo].[FEFormField]
GO


---------------------------------------------

-- dbo.viewFEFormSectionRule
CREATE view [dbo].[viewFEFormSectionRule]
as
select FormSectionRuleGUID, FormSectionGUID, cast(RuleXML as nvarchar(max)) as RuleXML, Description, RuleType from FEFormSectionRule
GO


---------------------------------------------

-- dbo.viewFormFieldUsage
CREATE view viewFormFieldUsage
as
select
	FF.FormFieldGUID,
	FF.Name as FormFieldName,
	--FFS.FormDefGUID,
	FD.Name as FormName,
	--FFS.FormSectionGUID,
	FS.Name as FormSectionName
from
	FE2FormField FF
	inner join [dbo].[FE2FormSection] FS on FS.FormSectionGUID = FF.FormSectionGUID
	inner join [dbo].[FE2FormTab] FT on FT.FormTabGUID = FS.FormTabGUID
	inner join [dbo].[FE2Form] FD on FT.FormGUID = FD.FormGUID
GO


---------------------------------------------

-- dbo.viewFramework
CREATE view [dbo].[viewFramework]
AS
	SELECT 
		FrameworkID, Framework, FrameworkSchemaName, ClientSchemaName, Abbreviation
	FROM 
		(SELECT 
			1 AS FrameworkID, 'Capital Management' AS Framework, 'cap' AS FrameworkSchemaName, 'clientcap' AS ClientSchemaName, 'CAP' AS Abbreviation
		UNION ALL
		SELECT
			2 AS FrameworkID, 'Management Reporting' AS Framework, 'mr' AS FrameworkSchemaName, 'clientmr' AS ClientSchemaName, 'MR' AS Abbreviation
		UNION ALL
		SELECT
			3 AS FrameworkID, 'Productivity Improvement' AS Framework, 'pi' AS FrameworkSchemaName, 'clientpi' AS ClientSchemaName, 'PI' AS Abbreviation
		UNION ALL
		SELECT
			4 AS FrameworkID, 'Operating Budgeting' AS Framework, 'ob' AS FrameworkSchemaName, 'clientob' AS ClientSchemaName, 'OB' AS Abbreviation
		UNION ALL
		SELECT 
			5 AS FrameworkID, 'Stategic Planning' AS Framework, 'lrfp' AS FrameworkSchemaName, 'clientlrfp' AS ClientSchemaName, 'LRPF' AS Abbreviation) FRAMEWORKS
GO


---------------------------------------------

-- dbo.viewHistoryItem
create view dbo.viewHistoryItem
as
	--casting xml columns to nvarchar so this can be used for cross-server scripts (Alchemy only)
	SELECT [HISTORYITEMGUID], [OBJECTGUID], [OBJECTTYPE], [DATETIMESTAMP], [MODIFIERUSERGUID], [CATEGORY], [DESCRIPTION], [USERCOMMENTS], cast([METAXML] as nvarchar(max)) as [METAXML], [VERSION], [MODIFIERUSERNAME], [ITEMCOUNT], [ELAPSEDMS], [TransactionID]
	FROM [dbo].[HistoryItem]
GO


---------------------------------------------

-- dbo.viewIRCChat
CREATE view [dbo].[viewIRCChat]
as
select 
   C.IRCChatGUID,
   C.Name,
   C.Description,
   C.CreationTime,
   C.SQLTableName,
   C.AuthorGUID,
   C.LastModifiedUserGUID,
   C.RowID,
   C.HistoryItemGUID,
   C.Version,
   C.IsChatDeleted,
   coalesce(UP.NAMELAST + ', ' + UP.NameFirst, CASE WHEN C.AuthorGUID = dbo.GetSuperUserGUID() THEN 'Strata' else 'Unknown' end) as Author,
   coalesce(UP1.NAMELAST + ', ' + UP1.NameFirst, CASE WHEN C.LastModifiedUserGUID = dbo.GetSuperUserGUID() THEN 'Strata' else 'Unknown' end) as LastModifiedBy
from dbo.IRCChat C
	left join dbo.UserProfile UP on C.AuthorGUID = UP.UserGUID
	left join dbo.UserProfile UP1 on C.LastModifiedUserGUID = UP1.UserGUID
GO


---------------------------------------------

-- dbo.viewIRCChatMembership
CREATE view [dbo].[viewIRCChatMembership]
AS
	select  
		C.Name as [Chat],
		UP.NameLast + ', ' + UP.NameFirst as [UserFullName],
		UP.UserName as [UserName],
		M.LastCheckinTime as [LastCheckin]	
	from dbo.IRCChat C
		inner join dbo.IRCChatMembership M on C.IRCChatGUID = M.IRCChatGUID
		inner join dbo.UserProfile UP on UP.UserGUID = M.UserGUID
GO


---------------------------------------------

-- dbo.viewImportCSVConfig
CREATE view [dbo].[viewImportCSVConfig]
as
SELECT [ImportCSVConfigGUID]
      ,[Name]
      ,[Description]
      ,cast([ConfigXML] as nvarchar(max)) as ConfigXML
      ,[TimeoutSeconds]
  FROM [dbo].[ImportCSVConfig]
GO


---------------------------------------------

-- dbo.viewIntTransaction
CREATE VIEW [dbo].[viewIntTransaction] 
AS
	with IntTransactionDataAgg as (
		select 
			TransactionGUID, 
			SUM(RowsImported) as RowsImported,
			SUM(RowsRejected) AS RowsRejected,
			case when SUM(cast(IsImportDeleted as int)) > 0 then CAST(1 as bit) else CAST(0 as bit) end as IsImportDeleted,
			case when SUM(cast(HasDummyFile as int)) > 0 then CAST(1 as bit) else CAST(0 as bit) end as HasDummyFile,
			CAST(MAX(CAST(IsAdhocImport AS INT)) AS BIT) as IsAdhocImport
		from 
			[dbo].[IntTransactionData]
		group by
			TransactionGUID
	)
	select
		trn.*,
		isnull(cfg.Name, 'Unknown') as ConfigName,
		isnull(cfg.IntegrationTypeVal, 0) as IntegrationTypeVal,
		DateDiff(second, trn.StartTimeUtc, trn.EndTimeUtc) as Duration,
		isnull(usr.NameFirst, case when UserId = '10101010-1111-0000-1111-101010101010' then 'Strata' else 'Unknown' end) as UserNameFirst,
		isnull(usr.NameLast, case when UserId = '10101010-1111-0000-1111-101010101010' then 'Strata' else 'Unknown' end) as UserNameLast,
		isnull(usr.UserName, case when UserId = '10101010-1111-0000-1111-101010101010' then 'Strata' else 'Unknown' end) as UserName,
		isnull(usr.EmailAddress, 'Unknown') as UserEmailAddress,
		isnull(td.IsImportDeleted, cast(0 as bit)) as IsImportDeleted,
		isnull(td.RowsImported, 0) as RowsImported,
		ISNULL(td.RowsRejected, 0) AS RowsRejected,
		isnull(td.HasDummyFile, cast(0 as bit)) as HasDummyFile,
		ISNULL(td.IsAdhocImport, CAST(0 AS BIT)) AS IsAdhocImport
	from 
		[dbo].[IntTransaction] trn
		left join IntTransactionDataAgg td on td.TransactionGUID = trn.TransactionGUID
		left join [dbo].[IntConfig] cfg on trn.ConfigID = cfg.ConfigID
		left join [dbo].[UserProfile] usr on trn.UserID = usr.UserGUID
GO


---------------------------------------------

-- dbo.viewKeys
CREATE VIEW dbo.viewKeys
AS
select  S.name as SchemaName, O1.name as ObjectName, CST.name as [Name] from sys.key_constraints  CST
	inner join sys.schemas S on S.schema_id = CST.schema_id
	inner join sys.objects O on CST.object_id = O.object_id
	inner join sys.objects O1 on O1.object_id = CST.parent_object_id
UNION ALL
select S.name as SchemaName, O1.name as ObjectName, FK.name as [Name]  from sys.foreign_keys FK
	inner join sys.schemas S on S.schema_id = FK.schema_id
	inner join sys.objects O on FK.object_id = O.object_id
	inner join sys.objects O1 on O1.object_id = FK.parent_object_id
GO


---------------------------------------------

-- dbo.viewMDCs
CREATE view [dbo].[viewMDCs] as 
select *,'zzEMFModelData_' + lower(replace(cast(modeldataconfigguid as varchar(36)), '-', '_')) as dataName from emfmodeldataconfig
GO


---------------------------------------------

-- dbo.viewMECell
CREATE view [dbo].[viewMECell] as
select 
	cell.*,
	cell.ExcelCellGUID as CellGUID,
	cell.ExcelSheetGUID as SheetGUID,
	book.ModelTemplateGUID,
	book.Name as TemplateName,  
	SHEET.Name as WorksheetName,
	book.ModelTemplateGUID as BookGUID,	  --duplicate for backwards compat
	book.Name as BookName, --duplicate for backwards compat
	sheet.Name as SheetName --duplicate for backwards compat
from
	MEExcelCell CELL (readuncommitted)
	inner join EMFModelTemplateWorksheet SHEET (readuncommitted) ON SHEET.WorksheetGUID = CELL.ExcelSheetGUID
	inner join emfmodeltemplate BOOK (readuncommitted) on BOOK.ModelTemplateGUID = SHEET.ModelTemplateGUID
GO


---------------------------------------------

-- dbo.viewMEModelRefreshQueue
CREATE view [dbo].[viewMEModelRefreshQueue]
as
	select 
		Q.ModelGUID,
		Q.DateTimeStamp,
		Q.ErrorLogGUID,
		Q.UserName,
		Q.Source,
		Q.CompositeGUID,
		isnull(C.FriendlyName, 'All') as CompositeName,
		isnull(P.ModelTemplateGUID, dbo.ZeroGUID()) as ModelTemplateGUID
	from
		[dbo].[MEModelRefreshQueue] Q with (readuncommitted)
		left join [dbo].[XPlan] P with (readuncommitted) on P.PlanGUID = Q.ModelGUID
		left join [dbo].[ScoreComposite] C with (readuncommitted) on C.CompositeGUID = Q.CompositeGUID
GO


---------------------------------------------

-- dbo.viewMEPHSection
-- Forward

CREATE view [dbo].[viewMEPHSection] as
select 
	phsc.*, 
	phdim.FriendlyName as PHDimensionFriendlyName,
	fidim.DimensionGUID as FillInDimensionGUID,
	fidim.FriendlyName as FillInDimensionFriendlyName
from 
	dbo.MEPHSection phsc
	inner join dbo.ScoreDimension phdim on phsc.PHSectionDimensionGUID = phdim.DimensionGUID
	inner join dbo.EMFModelTemplate mt on phsc.ModelTemplateGUID = mt.ModelTemplateGUID
	
	--is there a better way?
	inner join dbo.ScoreDimension fidim on fidim.DimensionGUID = (
		select distinct
			sdg2.DimensionGUID 
		from
			EMFModelTemplateLinkSource ls 
			inner join ScoreComposite sc on ls.ParentScoreCompositeTableGUID = sc.CompositeGUID
			inner join ScoreCompositeLink scl on sc.CompositeGUID = scl.CompositeGUID
			inner join ScoreAttribute k1 on scl.Key1GUID = k1.AttributeGUID
			inner join ScoreDimensionGroup sdg1 on sdg1.DimensionGroupGUID=k1.DimensionGroupGUID
			inner join ScoreAttribute k2 on scl.Key2GUID = k2.AttributeGUID
			inner join ScoreDimensionGroup sdg2 on sdg2.DimensionGroupGUID=k2.DimensionGroupGUID
		where
			sdg1.DimensionGUID = phsc.PHSectionDimensionGUID
			and ls.ModelTemplateGUID = mt.modeltemplateguid
		)
GO


---------------------------------------------

-- dbo.viewMEPHSectionAnalysis
CREATE view dbo.viewMEPHSectionAnalysis
as
	select 
		ModelTemplateGUID,
		PlaceholderSectionMemberGUID,
		MemberName as PlaceholderSectionMemberName,
		isnull([1],1) as Decile01,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([2],1) end as Decile02,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([3],1) end as Decile03,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([4],1) end as Decile04,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([5],1) end as Decile05,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([6],1) end as Decile06,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([7],1) end as Decile07,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([8],1) end as Decile08,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([9],1) end as Decile09,
		case when isnull([1],1) < 25 then isnull([1],1) else isnull([10],1) end as Decile10
	from (
		select 
			ModelTemplateGUID,
			PlaceholderSectionMemberGUID, 
			MemberName, 
			max(Total) as [Count],
			Decile 
		from (
			select 
				PlanGUID, 
				Name, 
				ModelTemplateGUID,
				PlaceholderSectionMemberGUID, 
				MemberName, 
				Total, 
				NTILE(10) OVER(PARTITION BY PlaceholderSectionMemberGUID ORDER BY TOTAL DESC) as Decile 
			from (
				select 
					ModelGUID as PlanGUID, 
					db.Name, 
					db.ModelTemplateGUID,
					PlaceholderSectionMemberGUID, 
					MEPH.FriendlyName as MemberName, 
					Count(FillinMemberGUID) as Total
				from 
					[dbo].[ScoreFillin] fill with (readuncommitted)
					inner join [dbo].[XPlan] db with (readuncommitted) on db.PlanGUID=fill.ModelGUID
					inner join [dbo].[MEPHSection] MEPH with (readuncommitted) on MEPH.PHSectionMemberGUID = fill.PlaceholderSectionMemberGUID and MEPH.ModelTemplateGUID = db.ModelTemplateGUID
					inner join [dbo].[ScoreDimension] SD with (readuncommitted) on SD.DimensionGUID = MEPH.PHSectionDimensionGUID
				where 
					db.IsDeletedPlan = 0
					and MEPH.PHSectionMemberGUID != '00000000-0000-0000-0000-000000000000'
					and SD.GlobalID not in('Fiscal Year PH','OB Departmental Budget PH','Time Class PH')
				group by 
					ModelGUID, 
					db.Name,
					db.ModelTemplateGUID,
					PlaceholderSectionMemberGUID, 
					MEPH.FriendlyName
				) as groupedTable
			) as deciletable
		group by 
			ModelTemplateGUID,
			PlaceholderSectionMemberGUID, 
			MemberName,
			Decile 
		) as maxtable
	pivot (
		max([Count]) FOR Decile IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
		) as PivotTable
GO


---------------------------------------------

-- dbo.viewMEPHSectionAnalysisRecommendation
CREATE VIEW [dbo].[viewMEPHSectionAnalysisRecommendation]
AS
	SELECT
		SUGGESTED.[ModelTemplateGUID],
		SUGGESTED.[ExpansionGlobalID],
		SUGGESTED.[Count],
		CASE
			WHEN SUGGESTED.[CountOverride] <= ISNULL(RECOMMENDED.[RecommendedMaxCount], SUGGESTED.[CountOverride])
			THEN SUGGESTED.[CountOverride]
			ELSE RECOMMENDED.[RecommendedMaxCount]
		END  AS [CountOverride]
	FROM 
		(
			SELECT 
				A.[ModelTemplateGUID],
				A.[PlaceholderSectionMemberName] AS [ExpansionGlobalID],
				MAX(E.[Count]) AS [Count],
				(A.[Decile02] + 10) AS [CountOverride]
			FROM 
				[dbo].[viewMEPHSectionAnalysis] AS A
				INNER JOIN [dbo].[MEScoreExpansion] AS E WITH (READUNCOMMITTED) ON E.[GlobalID] = A.[PlaceholderSectionMemberName]
				INNER JOIN [dbo].[viewMECell] AS C ON C.ExcelCellGUID = E.[ExcelCellGUID] AND C.[ModelTemplateGUID] = A.[ModelTemplateGUID]
			GROUP BY
				A.[ModelTemplateGUID],
				A.[PlaceholderSectionMemberName],
				A.[Decile01],
				A.[Decile02]
			HAVING
					A.[Decile01] != A.[Decile02]
				AND A.[Decile02] <= MAX(E.[Count]) - 10 - 25		-- count - padding - useful threshold
		) AS SUGGESTED
		LEFT JOIN [dbo].[MEScoreExpansionRecommendedMaxCount] AS RECOMMENDED ON RECOMMENDED.[SectionName] = SUGGESTED.[ExpansionGlobalID]
GO


---------------------------------------------

-- dbo.viewMEPHSectionAnalysisRecommendationOutliers
CREATE view dbo.viewMEPHSectionAnalysisRecommendationOutliers
as
	select 
		P.ModelTemplateGUID,
		MT.Name as ModelTemplateName,
		P.PlanGUID,
		P.Name as PlanName,
		PHS.FriendlyName as ExpansionGlobalID,
		max(AR.CountOverride) as ExpansionRecommendation,
		count(*) as PlanCount,
		max(AR.[Count]) as ExpansionMax
	from 
		[dbo].[XPlan] P with (readuncommitted)
		inner join [dbo].[EMFModelTemplate] MT with (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID
		inner join [dbo].[ScoreFillin] FI with (readuncommitted) on FI.ModelGUID = P.PlanGUID
		inner join [dbo].[MEPHSection] PHS with (readuncommitted) on PHS.PHSectionMemberGUID = FI.PlaceholderSectionMemberGUID and PHS.ModelTemplateGUID = P.ModelTemplateGUID
		inner join [dbo].[viewMEPHSectionAnalysisRecommendation] AR on AR.ModelTemplateGUID = P.ModelTemplateGUID and AR.ExpansionGlobalID = PHS.FriendlyName
	group by
		P.ModelTemplateGUID,
		MT.Name,
		P.PlanGUID,
		P.Name,
		PHS.FriendlyName
	having
		count(*) > max(AR.CountOverride)
	union all
	select 
		MT.ModelTemplateGUID,
		MT.Name as ModelTemplateName,
		P.PlanGUID,
		P.Name as PlanName,
		PHS.FriendlyName as ExpansionGlobalID,
		E.[Count] as ExpansionRecommendation,
		count(*) as PlanCount,
		E.[Count] as ExpansionMax
	from 
		[dbo].[XPlan] P with (readuncommitted)
		inner join [dbo].[EMFModelTemplate] MT with (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID
		inner join [dbo].[ScoreFillin] FI with (readuncommitted) on FI.ModelGUID = P.PlanGUID
		inner join [dbo].[MEPHSection] PHS with (readuncommitted) on PHS.PHSectionMemberGUID = FI.PlaceholderSectionMemberGUID and PHS.ModelTemplateGUID = P.ModelTemplateGUID
		inner join (
			select 
				C.ModelTemplateGUID,
				E.GlobalID,
				max(E.[Count]) as [Count]
			from 
				[dbo].[MEScoreExpansion] E with (readuncommitted) 
				inner join [dbo].[viewMECell] C on C.ExcelCellGUID = E.ExcelCellGUID
			group by
				C.ModelTemplateGUID,
				E.GlobalID) E on E.GlobalID = PHS.FriendlyName and E.ModelTemplateGUID = MT.ModelTemplateGUID 
	where
		not exists(select 1 from [dbo].[viewMEPHSectionAnalysisRecommendation] AR where AR.ModelTemplateGUID = MT.ModelTemplateGUID and AR.ExpansionGlobalID = PHS.FriendlyName)
	group by
		MT.ModelTemplateGUID,
		MT.Name,
		P.PlanGUID,
		P.Name,
		PHS.FriendlyName,
		E.[Count]
	having
		count(*) > E.[Count]
GO


---------------------------------------------

-- dbo.viewMEPHSectionAnalysis_InvalidConfigs
CREATE view dbo.viewMEPHSectionAnalysis_InvalidConfigs
AS
	select 
		MT.ModelTemplateGUID,
		MT.Name as ModelTemplateName,
		P.PlanGUID,
		P.Name as PlanName,
		PHS.FriendlyName as ExpansionGlobalID,
		E.[Count] as ExpansionRecommendation,
		count(*) as PlanCount,
		E.[Count] as ExpansionMax
	from 
		[dbo].[XPlan] P with (readuncommitted)
		inner join [dbo].[EMFModelTemplate] MT with (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID
		inner join [dbo].[ScoreFillin] FI with (readuncommitted) on FI.ModelGUID = P.PlanGUID
		inner join [dbo].[MEPHSection] PHS with (readuncommitted) on PHS.PHSectionMemberGUID = FI.PlaceholderSectionMemberGUID and PHS.ModelTemplateGUID = P.ModelTemplateGUID
		inner join (
			select 
				C.ModelTemplateGUID,
				E.GlobalID,
				max(E.[Count]) as [Count]
			from 
				[dbo].[MEScoreExpansion] E with (readuncommitted) 
				inner join [dbo].[viewMECell] C on C.ExcelCellGUID = E.ExcelCellGUID
			group by
				C.ModelTemplateGUID,
				E.GlobalID) E on E.GlobalID = PHS.FriendlyName and E.ModelTemplateGUID = MT.ModelTemplateGUID 
	where
		not exists(select 1 from [dbo].[viewMEPHSectionAnalysisRecommendation] AR where AR.ModelTemplateGUID = MT.ModelTemplateGUID and AR.ExpansionGlobalID = PHS.FriendlyName)
	group by
		MT.ModelTemplateGUID,
		MT.Name,
		P.PlanGUID,
		P.Name,
		PHS.FriendlyName,
		E.[Count]
	having
		count(*) > E.[Count]
GO


---------------------------------------------

-- dbo.viewMEPHSectionAnalysis_LargeDepartments
CREATE view dbo.viewMEPHSectionAnalysis_LargeDepartments
AS
	select 
		P.ModelTemplateGUID,
		MT.Name as ModelTemplateName,
		P.PlanGUID,
		P.Name as PlanName,
		PHS.FriendlyName as ExpansionGlobalID,
		max(AR.CountOverride) as ExpansionRecommendation,
		count(*) as PlanCount,
		max(AR.[Count]) as ExpansionMax
	from 
		[dbo].[XPlan] P with (readuncommitted)
		inner join [dbo].[EMFModelTemplate] MT with (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID
		inner join [dbo].[ScoreFillin] FI with (readuncommitted) on FI.ModelGUID = P.PlanGUID
		inner join [dbo].[MEPHSection] PHS with (readuncommitted) on PHS.PHSectionMemberGUID = FI.PlaceholderSectionMemberGUID and PHS.ModelTemplateGUID = P.ModelTemplateGUID
		inner join [dbo].[viewMEPHSectionAnalysisRecommendation] AR on AR.ModelTemplateGUID = P.ModelTemplateGUID and AR.ExpansionGlobalID = PHS.FriendlyName
	group by
		P.ModelTemplateGUID,
		MT.Name,
		P.PlanGUID,
		P.Name,
		PHS.FriendlyName
	having
		count(*) > max(AR.CountOverride)
GO


---------------------------------------------

-- dbo.viewMEPHSectionDuplicates
create view dbo.viewMEPHSectionDuplicates
as
	select 
		phs.* 
	from 
		[dbo].[MEPHSection] phs 
	where 
		exists(select 1 from [dbo].[MEPHSection] d where d.ModelTemplateGUID = phs.ModelTemplateGUID and d.PHSectionDimensionGUID = phs.PHSectionDimensionGUID and d.PHSectionMemberGUID = phs.PHSectionMemberGUID and d.PlanTypeGUID = phs.PlanTypeGUID group by d.ModelTemplateGUID, d.PHSectionDimensionGUID, d.PHSectionMemberGUID, d.PlanTypeGUID having count(*) > 1)
GO


---------------------------------------------

-- dbo.viewMEReportLinkTemplateMapping
CREATE view [dbo].[viewMEReportLinkTemplateMapping] as
select	
	map.ReportLinkTemplateMappingGUID,
	map.ReportGUID,
	map.CellGUID,
	map.RowExpanded,
	map.ReportParams,
	sheet.ModelTemplateGUID as BookGUID,
	sheet.Name as SheetName,
	cell.ExcelSheetGUID,
	cell.Row,
	cell.Col
from
	MEReportLinkTemplateMapping map
	inner join MEExcelCell cell on map.CellGUID = cell.ExcelCellGUID
	inner join EMFModelTemplateWorksheet sheet on cell.ExcelSheetGUID = sheet.WorksheetGUID
GO


---------------------------------------------

-- dbo.viewMEScoreExpansion
CREATE view [dbo].[viewMEScoreExpansion] as
select 
	scexp.*,
	cell.ExcelSheetGUID,
	cell.Row,
	cell.Row2,
	cell.Col,
	sheet.Name as SheetName,
	book.ModelTemplateGUID as ExcelBookGUID,
	book.Name as BookName
from 
	MEScoreExpansion scexp
	inner join MEExcelCell cell on scexp.excelcellguid = cell.ExcelCellGUID
	inner join EMFModelTemplateWorksheet sheet on cell.ExcelSheetGUID = sheet.WorksheetGUID
	inner join EMFModelTemplate book on sheet.ModelTemplateGUID = book.ModelTemplateGUID
GO


---------------------------------------------

-- dbo.viewMEScoreExpansionOutliers
create view dbo.viewMEScoreExpansionOutliers
as
	select
		p.Name as Budget,
		phs.FriendlyName as ModelSection,
		COUNT(*) as FillinCount,
		mx.RecommendedMaxCount as MaxCount
	from
		dbo.MEScoreExpansionRecommendedMaxCount mx
		inner join MEPHSection phs on phs.FriendlyName = mx.SectionName
		inner join ScoreFillin fi on fi.PlaceholderSectionMemberGUID = phs.PHSectionMemberGUID
		inner join XPlan p on p.PlanGUID = fi.ModelGUID
		inner join EMFModelTemplate mt on mt.ModelTemplateGUID = p.ModelTemplateGUID
	where
		mt.Name like 'ob departmental%'
	group by
		p.Name,
		phs.FriendlyName,
		mx.RecommendedMaxCount
	having
		COUNT(*) > mx.RecommendedMaxCount
GO


---------------------------------------------

-- dbo.viewMEScoreExpansionOverride
CREATE view dbo.viewMEScoreExpansionOverride 
as
	select 
		EO.OverrideGUID,
		EO.ExpansionProfileGUID,
		EO.ExpansionGlobalID,
		max(E.[Count]) as [Count],
		EO.CountOverride
	from 
		[dbo].[MEScoreExpansionOverride] EO with (readuncommitted)
		inner join [dbo].[MEScoreExpansionProfile] EP with (readuncommitted) on EP.ExpansionProfileGUID = Eo.ExpansionProfileGUID
		inner join [dbo].[MEScoreExpansion] E with (readuncommitted) on E.GlobalID = EO.ExpansionGlobalID
		inner join [dbo].[viewMECell] C on C.ExcelCellGUID = E.ExcelCellGUID and C.ModelTemplateGUID = EP.ParentModelTemplateGUID		
	group by
		EO.OverrideGUID,
		EO.ExpansionProfileGUID,
		EO.ExpansionGlobalID,
		EO.CountOverride
GO


---------------------------------------------

-- dbo.viewMEScorePlaceholderLabel
CREATE view [dbo].[viewMEScorePlaceholderLabel] as
select 
	map.*,
	sheet.ModelTemplateGUID as BookGUID,
	sheet.Name as SheetName,
	cell.ExcelSheetGUID,
	cell.Row,
	cell.Col
from
	MEScorePlaceholderLabel map (readuncommitted)
	inner join MEExcelCell cell (readuncommitted) on map.CellGUID = cell.ExcelCellGUID
	inner join EMFModelTemplateWorksheet sheet (readuncommitted) on cell.ExcelSheetGUID = sheet.WorksheetGUID
GO


---------------------------------------------

-- dbo.viewMEScoreSource
CREATE view viewMEScoreSource as
select
	ModelTemplateGUID as BookGUID, linksourceguid as SourceGUID, ParentScoreCompositeTableGUID as CompositeGUID, Name, IsSelf 
from
	EMFModelTemplateLinkSource
where
	ParentScoreCompositeTableGUID <> '00000000-0000-0000-0000-000000000000'
GO


---------------------------------------------

-- dbo.viewMessageQueue
CREATE VIEW [dbo].[viewMessageQueue]
AS
SELECT TOP 100 PERCENT
	t.Name as ThreadName,
	m.subject as [Subject],
	m.body as Body,
	coalesce(mt.Name, '') as MessageTypeName,
	coalesce(author.UserName, '') as Author,
	m.datecreated as DateCreated,
	m.hasattachments as HasAttachments,
	u.UserName as RecipientUsername,
	u.namefirst as RecipientFirstName,
	u.namelast as RecipientLastName,
	u.emailaddress as RecipientEmailAddress
FROM
	msgmessage m inner join msgtopic t on t.topicguid = m.topicguid
	inner join viewS3ACLSimple acl on acl.LootID = t.TopicGUID
	inner join userprofile u on u.userguid = acl.UserGUID
	LEFT join UserProfile author on m.AuthorGUID = author.UserGUID
	left join MsgMessageType mt on mt.MessageTypeGUID = m.MessageTypeGUID
	left join msgforum f on f.forumguid = t.forumguid
WHERE u.userguid != m.authorguid and m.issent = 0
GROUP BY
	t.Name,
	m.subject,
	m.body,
	mt.Name,
	author.UserName,
	m.datecreated,
	m.hasattachments,
	u.username,
	u.namefirst,
	u.namelast,
	u.emailaddress
ORDER BY m.DateCreated
GO


---------------------------------------------

-- dbo.viewModelDependencies
CREATE view [dbo].[viewModelDependencies]
AS
	select 
		EL.ModelGUID as [ModelGUID], 
		EL.ParentModelGUID as [ParentModelGUID] 
	from 
		EMFModelDataLink EL (readuncommitted)
	where
		exists(select 1 from XPlan P1 (readuncommitted) where P1.PlanGUID = EL.ModelGUID and IsDeletedPlan = 0)
		and exists(select 1 from XPlan P2 (readuncommitted) where P2.PlanGUID = EL.ModelGUID and IsDeletedPlan = 0)
	UNION ALL
	select
		FI.ModelGUID,
		FI.FillinMemberGUID as ParentModelGUID
	from
		[dbo].[ScoreFillin] FI (readuncommitted)
	where
		exists(select 1 from XPlan P1 (readuncommitted) where P1.PlanGUID = FI.ModelGUID and IsDeletedPlan = 0)
		and exists(select 1 from XPlan P2 (readuncommitted) where P2.PlanGUID = FI.FillinMemberGUID and IsDeletedPlan = 0)
GO


---------------------------------------------

-- dbo.viewModelSectionSecured
CREATE view dbo.viewModelSectionSecured
as
	with ModelSectionInheritance as (
		select 
			ms.ModelSectionGUID,
			case when ms.ParentGUID != '00000000-0000-0000-0000-000000000000' and ms.IsInherit = 1 and isnull(pms.ModelSectionGUID, '00000000-0000-0000-0000-000000000000') != '00000000-0000-0000-0000-000000000000' then (
				case when pms.ParentGUID != '00000000-0000-0000-0000-000000000000' and pms.IsInherit = 1 and isnull(ppms.ModelSectionGUID, '00000000-0000-0000-0000-000000000000') != '00000000-0000-0000-0000-000000000000' then (
					case when ppms.ParentGUID != '00000000-0000-0000-0000-000000000000' and ppms.IsInherit = 1 and isnull(pppms.ModelSectionGUID, '00000000-0000-0000-0000-000000000000') != '00000000-0000-0000-0000-000000000000' then (
						case when pppms.ParentGUID != '00000000-0000-0000-0000-000000000000' and pppms.IsInherit = 1 then pppms.ParentGUID else pppms.ModelSectionGUID end
					) else ppms.ModelSectionGUID end
				) else pms.ModelSectionGUID end
			) else ms.ModelSectionGUID end as LootGUID
		from 
			ModelSection ms
			left join ModelSection pms on pms.ModelSectionGUID = ms.ParentGUID
			left join ModelSection ppms on ppms.ModelSectionGUID = pms.ParentGUID
			left join ModelSection pppms on pppms.ModelSectionGUID = ppms.ParentGUID
	)
	select
		ms.ModelSectionGUID,
		ms.Name,
		ms.[Range],
		ms.[Address],
		ms.SheetGUID,
		ms.ParentGUID,
		msi.LootGUID,
		ws.Name as SheetName,
		acl.UserGUID,
		isnull(acl.IsReadable, cast(1 as bit)) as IsReadable,
		isnull(acl.IsWritable, cast(1 as bit)) as IsWritable
	from 
		ModelSection ms with (readuncommitted)
		inner join ModelSectionInheritance msi with (readuncommitted) on msi.ModelSectionGUID = ms.ModelSectionGUID
		inner join EMFModelTemplateWorksheet ws with (readuncommitted) on ws.WorksheetGUID = ms.SheetGUID
		inner join viewS3ACLSimple acl on acl.LootID = msi.LootGUID
	where
		acl.IsReadable = 0 or acl.IsWritable = 0
	union all
	select
		ws.WorksheetGUID as ModelSectionGUID,
		ws.Name,
		'' as [Range],
		'' as [Address],
		ws.WorksheetGUID as SheetGUID,
		dbo.ZeroGUID() as ParentGUID,
		ws.WorksheetGUID as LootGUID,
		ws.Name as SheetName,
		acl.UserGUID,
		isnull(acl.IsReadable, cast(1 as bit)) as IsReadable,
		isnull(acl.IsWritable, cast(1 as bit)) as IsWritable
	from
		EMFModelTemplateWorksheet ws with (readuncommitted)
		inner join viewS3ACLSimple acl on acl.LootID = ws.WorksheetGUID
	where
		acl.IsReadable = 0 or acl.IsWritable = 0
GO


---------------------------------------------

-- dbo.viewMsgEmailActivity
CREATE VIEW [dbo].[viewMsgEmailActivity]
AS
SELECT
	ea.EmailActivityID,
	ea.EmailSummaryID,
	ea.UserGUID,
	ea.EmailAddress,
	u.UserName,
	ea.MessageGUID,
	m.Subject,
	ea.Timestamp,
	ea.IsSuccess,
	ea.Description    
FROM        
	dbo.MsgEmailActivity ea (readuncommitted)
	left join MsgMessage m (readuncommitted) on ea.MessageGUID = m.MessageGUID
	left join UserProfile u (readuncommitted) on ea.UserGUID = u.UserGUID
GO


---------------------------------------------

-- dbo.viewOMZProviderSettings
CREATE view [dbo].[viewOMZProviderSettings]
as
SELECT [ProviderSettingsGUID]
      ,[Name]
      ,[AssemblyQualifiedName]
      ,cast([Metadata] as nvarchar(max)) as Metadata
      ,[ProviderAssemblyQualifiedName]
      ,[PoolDimensionGUID]
      ,[DefaultEvaluatorRoleGUID]
      ,[DefaultGridTemplateGUID]
      ,[DefaultApprovedFieldGUID]
      ,[DefaultScoringReportGUID]
      ,[DefaultPlanTypeGUID]
  FROM [dbo].[OMZProviderSettings]
GO


---------------------------------------------

-- dbo.viewPlaceholders
CREATE view [dbo].[viewPlaceholders] with schemabinding as 
select 
	sl.listguid as PlaceholderDimensionGUID,
	slm.listmemberguid as PlaceholderMemberGUID,
	sortorderfullpath as SortOrder,
	slm.parentlistmemberguid as PlaceholderParentMemberGUID,
	ROW_NUMBER() over (partition by slm.parentlistmemberguid order by sortorderfullpath) -1 as PHIndex,
	slm.Name as PlaceholderMember
from 
	dbo.securelist sl
	inner join dbo.securelistmember slm on sl.listguid = slm.listguid
where 
	sl.isplaceholder = 1
	and slm.outlinelevel = 1
GO


---------------------------------------------

-- dbo.viewPlanLocks
create view viewPlanLocks
as
select 
	P.PlanGUID,
	dbo.GetPlanName(P.PlanGUID) as PlanName,
	L.UserGUID, 
	UP.UserName,
	L.DateLocked,
	L.DateLastActive
from
	Lock L
	inner join XPlan P on L.ItemGUID =  P.PlanGUID
	left join UserProfile UP on L.UserGUID = UP.UserGUID
where 
	L.LockGroup = 'PlanLock'
GO


---------------------------------------------

-- dbo.viewPlanTypeModelTemplate
CREATE view dbo.viewPlanTypeModelTemplate as --with schemabinding as 
select  
	p.PlanTypeGUID,
	p.ModelTemplateGUID,
	mt.DefaultFormGUID,
	mt.Description,
	mt.IsExpanded,
	mt.IsNewLabelsOnly,
	mt.IsPublished,
	mt.IsSafeModeOn,
	mt.Name,
	mt.Type,
	mt.Version
from 
	PlanTypeModelTemplateLink p
	inner join EMFModelTemplate mt on p.ModelTemplateGUID = mt.ModelTemplateGUID
GO


---------------------------------------------

-- dbo.viewPlanTypeWorkflowMapLink
CREATE view [dbo].[viewPlanTypeWorkflowMapLink] as
SELECT 
	WML.PlanTypeGuid, 
	WML.WorkflowMapGuid, 
	WML.IsRequiredWorkflow, 
	WM.Name as WorkflowName, 
	PT.Name as PlanTypeName 
FROM 
	PlanTypeWorkflowMapLink WML 
	INNER JOIN WFWorkflowMap WM on WML.WorkflowMapGUID = WM.WorkflowMapGUID 
	INNER JOIN PlanType PT ON WML.PlanTypeGUID = PT.PlanTypeGUID
GO


---------------------------------------------

-- dbo.viewPlans
CREATE view [dbo].[viewPlans] as 
select 
	planguid, 
	p.Name , 
	p.plantypeguid, 
	pt.name as PlanTypeName,
	p.ModelTemplateGUID,
	mt.Name as TemplateName,
	p.DefaultFormDefGUID,
	f.Name as FormName,
	p.CachedLootID,
	l.PermissionSetID,
	ps.Name as PermissionSet,
	pt.DimensionGUID,
	sd.FriendlyName as DimensionName,
	p.DateCreated,
	p.IsDeletedPlan
from 
	xplan p (readuncommitted)
	left join plantype pt (readuncommitted) on pt.plantypeguid = p.plantypeguid
	left join EMFModelTemplate mt (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID
	left join FE2Form f (readuncommitted) on p.DefaultFormDefGUID = f.FORMGUID
	left join ScoreDimension sd (readuncommitted) on pt.DimensionGUID = sd.DimensionGUID
	left join S3Loot l (readuncommitted) on l.LootID = p.CachedLootID
	left join S3PermissionSet ps (readuncommitted) on ps.PermissionSetID = l.PermissionSetID
GO


---------------------------------------------

-- dbo.viewPlansRecentlyOpened
CREATE VIEW dbo.viewPlansRecentlyOpened
AS
select A.*, P.Name, P.PlanGUID, U.UserGUID

from ActionLog A 
	inner join XPlan P on A.Details = CAST(P.PlanGUID as nvarchar(36))
	inner join UserProfile U on U.UserName = A.Username

where  A.Action='Form Edit' and A.SubAction='Initial Load' and  DATEDIFF(DD, DateTimeStamp, GETDATE()) < 5
GO


---------------------------------------------

-- dbo.viewREClientReportParameter_Broken
CREATE view dbo.viewREClientReportParameter_Broken
as
	select
		'Invalid attribute' as Issue,
		r.Name as ReportName,
		p.*
	from 
		REReport r 
		inner join REClientReportParameter p on p.ReportGUID = r.ReportGUID
	where 
		exists (select 1 from REClientReportDataSourceLink ds where ds.ReportGUID = r.ReportGUID and ds.ProviderAssemblyQualifiedName like '%SQLProvider%')
		and not exists(
			select 1 
			from 
				REClientReportDataSourceLink ds
				inner join DataView dv on dv.DataViewGUID = ds.DataSourceGUID
				inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = dv.DataViewGUID and cast(rd.DimensionGUID as nvarchar(36)) = p.DimensionID
				inner join RESQLReportRegisteredAttribute ra on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID and cast(ra.AttributeGUID as nvarchar(36)) = p.AttributeID
				inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
			where
				ltrim(p.ColumnName) = case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end	
				and ds.ReportGUID = r.ReportGUID
		)
		and p.SourceTypeValue = 0
	union all
	--MR-specific parameter issues
	select
		'Invalid selection' as Issue,
		r.Name as ReportName,
		p.*
	from 
		REReport r 
		inner join REClientReportParameter p on p.ReportGUID = r.ReportGUID
	where 
		(p.DimensionID = 'ae2104b1-e2d5-4cc0-88a5-e729b744fde7' and cast(p.parameterxml as nvarchar(max)) like '%dept|%' and cast(p.parameterxml as nvarchar(max)) not like '%mrdept|%')
		or (p.parameterxml like '%MRDEPT|KEY|%' and p.parameterxml like '%MRDepartmentID%' and p.parameterxml not like '%MRDEPT|KEY|' + (select cast(defaultkeyguid as nvarchar(36)) from scoredimension where friendlyname = 'mr department') + '%' )
GO


---------------------------------------------

-- dbo.viewREClientReportSectionAttribute_Broken
CREATE view dbo.viewREClientReportSectionAttribute_Broken 
as
	select
		r.ReportGUID,
		r.Name as ReportName,
		sa.*
	from
		REReport r
		inner join REClientReportSectionLink sl on sl.ReportGUID = r.ReportGUID
		inner join REClientReportSectionAttribute sa on sa.ClientReportSectionGUID = sl.ClientReportSectionGUID
	where 
		exists (select 1 from REClientReportDataSourceLink ds where ds.ReportGUID = r.ReportGUID and ds.ProviderAssemblyQualifiedName like '%SQLProvider%')
		and not exists(
			select 1 
			from 
				REClientReportDataSourceLink ds
				inner join DataView dv on dv.DataViewGUID = ds.DataSourceGUID
				inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = dv.DataViewGUID and cast(rd.DimensionGUID as nvarchar(36)) = sa.DimensionID
				inner join RESQLReportRegisteredAttribute ra on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID and cast(ra.AttributeGUID as nvarchar(36)) = sa.AttributeID
				inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
			where
				ltrim(sa.ColumnName) = case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end	
				and ds.ReportGUID = r.ReportGUID
		)
GO


---------------------------------------------

-- dbo.viewRESQLReportDisplayColumn_Broken
CREATE view dbo.viewRESQLReportDisplayColumn_Broken
as
	with cols_physical as (
		select
			t.object_id,
			s.name + '.' + t.name as obj,
			c.name as col
		from
			sys.columns c
			inner join sys.tables t on t.object_id = c.object_id
			inner join sys.schemas s on s.schema_id = t.schema_id
			inner join dbo.dataview dv on s.name + '.' + t.name = replace(replace(dv.SQLViewName, '[', ''), ']', '')
		union all
		select
			v.object_id,
			s.name + '.' + v.name as obj,
			c.name as col
		from
			sys.columns c
			inner join sys.views v on v.object_id = c.object_id
			inner join sys.schemas s on s.schema_id = v.schema_id
			inner join dbo.dataview dv on s.name + '.' + v.name = replace(replace(dv.SQLViewName, '[', ''), ']', '')
	),
	cols_registered as (
		select
			ax.attributeguid,
			rdx.dataviewguid,
			case when rax.columnalias = '' then ax.sqlcolumnname else ltrim(rax.columnalias) end as columnname
		from 
			resqlreportregistereddimension rdx 
			inner join resqlreportregisteredattribute rax on rax.registereddimensionguid = rdx.registereddimensionguid 
			inner join viewscoreattribute ax on ax.attributeguid = rax.attributeguid 
	)
	select
		r.ReportGUID,
		r.Name as ReportName,
		dc.*
	from 
		REReport r 
		inner join RESQLReportSetup rs on rs.ReportGUID = r.ReportGUID
		inner join DataView dv on dv.dataviewguid = rs.dataviewguid
		inner join resqlreportdisplaycolumn dc on dc.sqlreportsetupguid = rs.sqlreportsetupguid		
		left join cols_physical cp on cp.obj = replace(replace(dv.SQLViewName, '[', ''), ']', '') and cp.col = ltrim(dc.columnname)
		left join cols_registered cr on cr.dataviewguid = dv.dataviewguid and cr.columnname = ltrim(dc.columnname)
	where 
		cp.object_id is null
		and cr.attributeguid is null
GO


---------------------------------------------

-- dbo.viewRESQLReportFilterColumn_Broken
CREATE view dbo.viewRESQLReportFilterColumn_Broken
as
	with cols_physical as (
		select
			t.object_id,
			s.name + '.' + t.name as obj,
			c.name as col
		from
			sys.columns c
			inner join sys.tables t on t.object_id = c.object_id
			inner join sys.schemas s on s.schema_id = t.schema_id
			inner join dbo.dataview dv on s.name + '.' + t.name = replace(replace(dv.SQLViewName, '[', ''), ']', '')
		union all
		select
			v.object_id,
			s.name + '.' + v.name as obj,
			c.name as col
		from
			sys.columns c
			inner join sys.views v on v.object_id = c.object_id
			inner join sys.schemas s on s.schema_id = v.schema_id
			inner join dbo.dataview dv on s.name + '.' + v.name = replace(replace(dv.SQLViewName, '[', ''), ']', '')
	),
	cols_registered as (
		select
			ax.attributeguid,
			rdx.dataviewguid,
			case when rax.columnalias = '' then ax.sqlcolumnname else ltrim(rax.columnalias) end as columnname
		from 
			resqlreportregistereddimension rdx 
			inner join resqlreportregisteredattribute rax on rax.registereddimensionguid = rdx.registereddimensionguid 
			inner join viewscoreattribute ax on ax.attributeguid = rax.attributeguid 
	)
	select
		'Invalid attribute' as Issue,
		r.ReportGUID,
		r.Name as ReportName,
		dc.*
	from 
		REReport r 
		inner join RESQLReportSetup rs on rs.ReportGUID = r.ReportGUID
		inner join DataView dv on dv.dataviewguid = rs.dataviewguid
		inner join resqlreportFiltercolumn dc on dc.sqlreportsetupguid = rs.sqlreportsetupguid
		left join cols_physical cp on cp.obj = replace(replace(dv.SQLViewName, '[', ''), ']', '') and cp.col = ltrim(dc.columnname)
		left join cols_registered cr on cr.dataviewguid = dv.dataviewguid and cr.columnname = ltrim(dc.columnname)
	where 
		cp.object_id is null
		and cr.attributeguid is null
	union all
	--MR-specific issues
	select 
		'Invalid selection' as Issue,
		r.ReportGUID,
		r.Name as ReportName,
		fc.* 
	from 
		resqlreportsetup rs 
		inner join rereport r on r.reportguid = rs.reportguid
		inner join RESQLReportFilterColumn fc on fc.SQLReportSetupGUID = rs.SQLReportSetupGUID 
	where 
		exists(select 1 from RESQLReportRegisteredDimension rd where rd.DataViewGUID = rs.DataViewGUID and rd.DimensionGUID = 'AE2104B1-E2D5-4CC0-88A5-E729B744FDE7') 
		and fc.ParameterXML like '%DEPT|%' and fc.ParameterXML not like '%MRDEPT|%'
GO


---------------------------------------------

-- dbo.viewRESQLReportRegisteredAttribute
create view dbo.viewRESQLReportRegisteredAttribute
as
	select 
		dv.DataViewGUID,
		dv.Name,
		dv.SQLViewName,
		rd.RegisteredDimensionGUID,
		rd.DimensionGUID,
		rd.KeyGUID,
		rd.KeyColumnName,
		ra.RegisteredAttributeGUID,
		ra.AttributeGUID,
		ra.ColumnAlias
	from
		dbo.DataView dv with (readuncommitted)
		inner join dbo.RESQLReportRegisteredDimension rd with (readuncommitted) on rd.DataViewGUID = dv.DataViewGUID
		inner join dbo.RESQLReportRegisteredAttribute ra with (readuncommitted) on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID
GO


---------------------------------------------

-- dbo.viewRESQLReportRegisteredAttribute_ByReport
CREATE view dbo.viewRESQLReportRegisteredAttribute_ByReport
as
	select distinct
		r.ReportGUID,
		a.AttributeGUID,
		case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end as ColumnName
	from 
		REReport r
		inner join REClientReportDataSourceLink ds on ds.ReportGUID = r.ReportGUID
		inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = ds.DataSourceGUID
		inner join RESQLReportRegisteredAttribute ra on rd.RegisteredDimensionGUID = ra.RegisteredDimensionGUID
		inner join ScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
	union all
	select distinct
		r.ReportGUID,
		a.AttributeGUID,
		case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end as ColumnName
	from 
		REReport r
		inner join REDataSource ds on ds.ReportGUID = r.ReportGUID
		inner join RESQLReportSetup rs on rs.ReportGUID = ds.SourceGUID
		inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = rs.DataViewGUID
		inner join RESQLReportRegisteredAttribute ra on rd.RegisteredDimensionGUID = ra.RegisteredDimensionGUID
		inner join ScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
	union all
	select distinct
		r.ReportGUID,
		a.AttributeGUID,
		case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end as ColumnName
	from 
		REReport r
		inner join RESQLReportSetup rs on rs.ReportGUID = r.ReportGUID
		inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = rs.DataViewGUID
		inner join RESQLReportRegisteredAttribute ra on rd.RegisteredDimensionGUID = ra.RegisteredDimensionGUID
		inner join ScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
GO


---------------------------------------------

-- dbo.viewRESQLReportRegisteredAttribute_Duplicates
create view dbo.viewRESQLReportRegisteredAttribute_Duplicates
as
	select
		dv.DataViewGUID,
		dv.Name,
		case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end as Attribute,
		count(*) as DuplicateCount
	from
		RESQLReportRegisteredAttribute ra
		inner join RESQLReportRegisteredDimension rd on rd.RegisteredDimensionGUID = ra.RegisteredDimensionGUID
		inner join DataView dv on dv.DataViewGUID = rd.DataViewGUID
		inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
	group by
		dv.DataViewGUID,
		dv.Name,
		case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end
	having 
		count(*) > 1
GO


---------------------------------------------

-- dbo.viewRESQLReportRegisteredDimension
CREATE view [dbo].[viewRESQLReportRegisteredDimension] as 

 select 
	dv.name as DataviewName, 
	dv.sqlviewname, 
	sd.friendlyname as ScoreDimension,
	sa.friendlyname as AttributeKeyName,
	rd.* from dbo.RESQLReportRegisteredDimension rd
	left join dataview dv
		on dv.dataviewguid = rd.dataviewguid
	left join scoredimension sd
		on sd.dimensionguid = rd.dimensionguid
	left join scoreattribute sa
		on sa.attributeguid = rd.keyguid
GO


---------------------------------------------

-- dbo.viewRESortingParameter_Broken
CREATE view dbo.viewRESortingParameter_Broken
as
	select
		r.ReportGUID,
		r.Name as ReportName,
		ds.SourceGUID as DataViewGUID,
		p.*
	from 
		REDataSource ds 
		inner join REReport r on r.ReportGUID = ds.ReportGUID
		inner join RESortingParameter p on p.DataSourceGUID = ds.DataSourceGUID 
	where 
		not exists(
			select 1 
			from 
				RESQLReportDisplayColumn dc
				inner join RESQLReportSetup rs on dc.sqlreportsetupguid = rs.sqlreportsetupguid and rs.reportguid = ds.sourceguid
			where
				dc.columnname = p.columnname
		)
GO


---------------------------------------------

-- dbo.viewRandomNumber
CREATE VIEW viewRandomNumber
AS
SELECT RAND() as RandNumber
GO


---------------------------------------------

-- dbo.viewReportRunHistory
CREATE VIEW [dbo].[viewReportRunHistory]
AS

select 
	L.Username as [UserName],
	case L.Action
		when 'ZEROVIEWER' then 'Excel'
		when 'Excel Reporter' then 'Excel'
		when 'SQL Report' then 'SQL'
		else 'Not Specified'
	end as [Report Type],		
	replace(coalesce(R.Name, L.SubAction) , 'BATCH_', '')as [ReportName],
	L.DatetimeStamp as [LaunchTime],
	L.Duration/1000 as [DurationInSeconds]
from 
	ActionLog L (nolock)
	inner join REReport R on RIGHT(L.SubAction, 36) = cast(R.ReportGUID as nvarchar(36)) or replace(L.SubAction, 'BATCH_', '')=R.Name
where 
	L.Action in ('ZEROVIEWER', 'Excel Reporter', 'SQL Report')	
	and L.SubAction not like 'DrillDown%'
GO


---------------------------------------------

-- dbo.viewRoleVisibilityRule
CREATE view dbo.viewRoleVisibilityRule as
select 
	ISNULL(rvr.RoleVisibilityRuleGUID, newid()) as RoleVisibilityRuleGUID
	,ps.PermissionSetID as PermissionSetID
	,ps.RoleID as RoleID
	,ps.RoleName as RoleName
	,ISNULL(rvr.UserGroupGUID , '00000000-0000-0000-0000-000000000001') as UserGroupGUID
	,ISNULL(rvr.IsVisible, 1) as IsVisible
	,cast(case when rvr.IsVisible is null then 1 else 0 end as bit) as IsViewGenerated
from [dbo].[RoleVisibilityRule] rvr
right join [dbo].[viewS3PermissionSet] ps on rvr.PermissionSetID = ps.PermissionSetID and rvr.RoleID = ps.RoleID
GO


---------------------------------------------

-- dbo.viewS3ACL
CREATE view [dbo].[viewS3ACL] as
	SELECT 
		il.MemberGUID AS UserGUID,
		acl.LootID,
		acl.LootGroupPrefix,
		case when sum(acl.ReadAllowpts) > sum(acl.ReadDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsReadable,
		case when sum(acl.WriteAllowpts) > sum(acl.WriteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsWritable,
		case when sum(acl.SecureAllowpts) > sum(acl.SecureDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsSecurable,
		case when sum(acl.DeleteAllowpts) > sum(acl.DeleteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsDeletable,
		case when sum(acl.CreateAllowpts) > sum(acl.CreateDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsCreatable
	FROM 
		(
			SELECT
				RA.IdentityGUID,
				L.LootID,
				L.LootGroupPrefix,
				ReadAllowPts,
				ReadDenyPts,
				WriteAllowPts,
				WriteDenyPts,
				SecureAllowPts,
				SecureDenyPts,
				DeleteAllowPts,
				DeleteDenyPts,
				CreateAllowPts,
				CreateDenyPts
			FROM	
				 dbo.S3LootGroup LG WITH (READUNCOMMITTED)
				 INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
				 INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
				 INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
		 ) AS acl
		INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) ON acl.identityguid = il.GroupingGUID
	GROUP BY
		il.MemberGUID,
		acl.LootID,
		acl.LootGroupPrefix
GO


---------------------------------------------

-- dbo.viewS3ACLDepartment
CREATE view [dbo].[viewS3ACLDepartment] as

	SELECT 
		il.MemberGUID as UserGUID, 
		Cast(Replace(LootID, 'DEPT|', '') as int)  as DepartmentID,
		1 as IsReadable,
		case when sum(acl.WriteAllowpts) > sum(acl.WriteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsWritable
	FROM 
		(
			SELECT
				RA.IdentityGUID,
				L.LootID,
				ReadAllowPts,
				ReadDenyPts,
				WriteAllowPts,
				WriteDenyPts
			FROM	
				 dbo.S3LootGroup LG WITH (READUNCOMMITTED)
				 INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
				 INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
				 INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
			where L.LootGroupPrefix='DEPT'
		 ) AS acl
		INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) ON acl.identityguid = il.GroupingGUID
	GROUP BY
		il.MemberGUID,
		acl.LootID
	HAVING
		sum(ReadAllowPts) > sum(ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLDepartmentForOB
CREATE view [dbo].[viewS3ACLDepartmentForOB] as

	SELECT 
		il.MemberGUID as UserGUID, 
		Cast(Replace(LootID, 'DEPT|', '') as int)  as DepartmentID,
		1 as IsReadable,
		case when sum(acl.WriteAllowpts) > sum(acl.WriteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsWritable
	FROM 
		(
			SELECT
				RA.IdentityGUID,
				L.LootID,
				ReadAllowPts,
				ReadDenyPts,
				WriteAllowPts,
				WriteDenyPts
			FROM	
				 dbo.S3LootGroup LG WITH (READUNCOMMITTED)
				 INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
				 INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
				 INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID				 
			     INNER JOIN dbo.UserRole AS UR ON UR.RoleID = RA.RoleID
			where L.LootGroupPrefix='DEPT' and ur.Category = 'OB'
		 ) AS acl
		INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) ON acl.identityguid = il.GroupingGUID
	GROUP BY
		il.MemberGUID,
		acl.LootID
	HAVING
		sum(ReadAllowPts) > sum(ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLDetail
CREATE view [dbo].[viewS3ACLDetail]    
	as
SELECT
	IL.MemberGUID as UserGUID,
	up.NameFull as UserName,
	IL.Distance,
	IL.GroupingGUID as IdentityGUID,
	coalesce(ug.Name,up2.namefull) as IdentityName,
	RA.RoleID,
	ur.Name as RoleName,
	L.LootID,
	LG.LootGroupID,
	P.ReadAllowPts as ReadAllowPts,
	P.ReadDenyPts as ReadDenyPts,
	P.WriteAllowPts as WriteAllowPts,
	P.WriteDenyPts as WriteDenyPts,
	P.SecureAllowPts as SecureAllowPts,
	P.SecureDenyPts as SecureDenyPts,
	P.DeleteAllowPts as DeleteAllowPts,
	P.DeleteDenyPts as DeleteDenyPts,
	P.CreateAllowPts as CreateAllowPts,
	P.CreateDenyPts as CreateDenyPts
FROM
	dbo.S3LootGroup LG
		INNER JOIN dbo.S3Loot L on L.LootID = LG.LootID
		INNER JOIN dbo.S3RoleAssignment RA on LG.LootGroupID = RA.LootGroupID
		INNER JOIN dbo.S3IdentityLink IL on IL.GroupingGUID = RA.IdentityGUID
		inner JOIN dbo.S3Permission P on RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID		
		LEFT JOIN UserGroup ug on IL.GroupingGUID = ug.UserGroupGUID
		LEFT JOIN UserProfile up on IL.MemberGUID = up.UserGUID
		LEFT JOIN UserProfile up2 on IL.GroupingGUID = up2.UserGUID
		LEFT JOIN UserRole ur on RA.RoleID = ur.RoleID
--WHERE
--	IL.IsUser = 1  --slows it down cause it goes out of order, filtering first on this  :(
	
/*
	create unique clustered  index idx_s3acl on dbo.viewS3ACLsb (userguid, lootid) 
*/
GO


---------------------------------------------

-- dbo.viewS3ACLRead
------------------------------------------------------------------------------------------------------------

CREATE view [dbo].[viewS3ACLRead] as
select 
	il.MemberGUID as UserGUID, 
	LootID
from 
   (SELECT
		RA.IdentityGUID,
		L.LootID,
		ReadAllowPts,
		ReadDenyPts,
		WriteAllowPts,
		WriteDenyPts,
		SecureAllowPts,
		SecureDenyPts,
		DeleteAllowPts,
		DeleteDenyPts,
		CreateAllowPts,
		CreateDenyPts
	FROM	
		 dbo.S3LootGroup LG WITH (READUNCOMMITTED)
		 INNER JOIN 
		 dbo.S3Loot L WITH (READUNCOMMITTED)
			 ON L.LootID = LG.LootID
		 INNER JOIN
		 dbo.S3RoleAssignment RA WITH (READUNCOMMITTED)
			 ON LG.LootGroupID = RA.LootGroupID
		 INNER JOIN
		 dbo.S3Permission P WITH (READUNCOMMITTED)
			 ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID) AS acl
	inner join
	dbo.S3IdentityLink il on acl.identityguid = il.GroupingGUID
group by
	il.MemberGUID,
	LootID
having
	sum(ReadAllowPts) > sum(ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLReadDepartment
CREATE view [dbo].[viewS3ACLReadDepartment] as

select 
	il.MemberGUID as UserGUID, 
	Cast(Replace(LootID, 'DEPT|', '') as int) as DepartmentID 
from 
   (
		SELECT
			RA.IdentityGUID,
			L.LootID,
			ReadAllowPts,
			ReadDenyPts
		FROM	
			dbo.S3LootGroup LG WITH (READUNCOMMITTED)
			INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
			INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
			INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
		where L.LootGroupPrefix='DEPT'
	) AS acl
	INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID

group by
	il.MemberGUID,
	LootID

having
	sum(ReadAllowPts) > sum(ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLReadDepartmentForMRRoles
CREATE VIEW [dbo].[viewS3ACLReadDepartmentForMRRoles] as
/** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2022-06-27	HV		JAZZ-39147	PR Roles - Prepare databases for MR PR security separation
*************************************************************/
SELECT 
	DISTINCT 
	il.MemberGUID as UserGUID,
	Cast(Replace(LootID, 'MRDEPT|', '') as int) as DepartmentID
FROM 
   (
		SELECT
			RA.IdentityGUID,
			L.LootID,
			P.ReadAllowPts,
			P.ReadDenyPts
		FROM	
			dbo.S3LootGroup LG WITH (READUNCOMMITTED)
			INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
			INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
			INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
			INNER JOIN dbo.UserRole AS UR ON UR.RoleID = RA.RoleID
		WHERE L.LootGroupPrefix='MRDEPT' AND UR.Category = 'MR'
	) AS acl
	INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID
	INNER JOIN dbo.UserProfile UP ON up.UserGUID = il.MemberGUID
GROUP BY
	il.MemberGUID,
	LootID
HAVING
	SUM(acl.ReadAllowPts) > SUM(acl.ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLReadDepartmentForPRRoles
CREATE VIEW [dbo].[viewS3ACLReadDepartmentForPRRoles] as
/** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2022-06-27	HV		JAZZ-39147	PR Roles - Prepare databases for MR PR security separation
*************************************************************/
SELECT 
	DISTINCT 
	il.MemberGUID as UserGUID,
	Cast(Replace(LootID, 'MRDEPT|', '') as int) as DepartmentID
FROM 
   (
		SELECT
			RA.IdentityGUID,
			L.LootID,
			P.ReadAllowPts,
			P.ReadDenyPts
		FROM	
			dbo.S3LootGroup LG WITH (READUNCOMMITTED)
			INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
			INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
			INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
			INNER JOIN dbo.UserRole AS UR ON UR.RoleID = RA.RoleID
		WHERE L.LootGroupPrefix='MRDEPT' AND UR.Category = 'PR'
	) AS acl
	INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID
	INNER JOIN dbo.UserProfile UP ON up.UserGUID = il.MemberGUID
GROUP BY
	il.MemberGUID,
	LootID
HAVING
	SUM(acl.ReadAllowPts) > SUM(acl.ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLReadMRDepartment
Create view [dbo].[viewS3ACLReadMRDepartment] as

select 
	distinct 
	il.MemberGUID as UserGUID, 
	up.EmailAddress,
	Cast(Replace(Replace(LootID, 'MRDEPT|', ''), 'DEPT|', '') as int) as DepartmentID 
from 
   (
		SELECT
			RA.IdentityGUID,
			L.LootID,
			ReadAllowPts,
			ReadDenyPts
		FROM	
			dbo.S3LootGroup LG WITH (READUNCOMMITTED)
			INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
			INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
			INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
		where L.LootGroupPrefix='MRDEPT' or L.LootGroupPrefix='DEPT'
	) AS acl
	INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID
	INNER JOIN dbo.UserProfile UP ON up.UserGUID = il.MemberGUID

group by
	il.MemberGUID,
	up.EmailAddress,
	LootID

having
	sum(ReadAllowPts) > sum(ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLReadMROnlyDepartment
CREATE VIEW [dbo].[viewS3ACLReadMROnlyDepartment] as
/** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2021-02-02	KF		JAZZ-14166	MR - Performance - Security / Dashboard Optimizations
*************************************************************/
SELECT 
	DISTINCT 
	il.MemberGUID as UserGUID,
	Cast(Replace(LootID, 'MRDEPT|', '') as int) as DepartmentID
FROM 
   (
		SELECT
			RA.IdentityGUID,
			L.LootID,
			P.ReadAllowPts,
			P.ReadDenyPts
		FROM	
			dbo.S3LootGroup LG WITH (READUNCOMMITTED)
			INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
			INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
			INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
		WHERE L.LootGroupPrefix='MRDEPT'
	) AS acl
	INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID
	INNER JOIN dbo.UserProfile UP ON up.UserGUID = il.MemberGUID
GROUP BY
	il.MemberGUID,
	LootID
HAVING
	SUM(acl.ReadAllowPts) > SUM(acl.ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLReadWMOnlyDepartment
CREATE VIEW [dbo].[viewS3ACLReadWMOnlyDepartment] as  
SELECT  DISTINCT   
	il.MemberGUID as UserGUID,
	Cast(Replace(LootID, 'DEPT|', '') as int) as DepartmentID 
	FROM     
		(  
		SELECT 
		RA.IdentityGUID, 
		L.LootID, 
		P.ReadAllowPts, 
		P.ReadDenyPts  
		FROM
			dbo.S3LootGroup LG WITH (READUNCOMMITTED)      
			INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED)
				ON L.LootID = LG.LootID  
			INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED)
				ON LG.LootGroupID = RA.LootGroupID      
			INNER JOIN dbo.USERROLE RR WITH (READUNCOMMITTED)
				ON RA.RoleID = RR.RoleID  
			INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) 
				ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID  
			WHERE RR.Category='WM' AND L.LootGroupPrefix='DEPT'
		) AS acl    
	INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) 
		ON acl.identityguid = il.GroupingGUID    
	INNER JOIN dbo.UserProfile UP ON 
		UP.UserGUID = il.MemberGUID 
	GROUP BY  
		il.MemberGUID,  
		LootID  
	HAVING  SUM(acl.ReadAllowPts) > SUM(acl.ReadDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLSimple
CREATE view dbo.viewS3ACLSimple
as
	SELECT
        IL.MemberGUID as UserGUID,
        P.LootID as LootID,
        cast(sum(cast(P.ReadValue as int)) as bit) as IsReadable,
        cast(sum(cast(P.WriteValue as int)) as bit) as IsWritable,
        cast(sum(cast(P.SecureValue as int)) as bit) as IsSecurable
    FROM 
        dbo.UserProfile U with (readuncommitted)
        INNER JOIN dbo.S3IdentityLink IL with (readuncommitted) on U.UserGUID = IL.MemberGUID
        inner join dbo.S3SimplePermission P with (readuncommitted) on P.IdentityGUID = IL.GroupingGUID
    GROUP BY
        IL.MemberGUID, P.LootID
GO


---------------------------------------------

-- dbo.viewS3ACLWrite
------------------------------------------------------------------------------------------------------------

CREATE view [dbo].[viewS3ACLWrite] as
select 
	il.MemberGUID as UserGUID, 
	LootID
from 
   (SELECT
		RA.IdentityGUID,
		L.LootID,
		ReadAllowPts,
		ReadDenyPts,
		WriteAllowPts,
		WriteDenyPts,
		SecureAllowPts,
		SecureDenyPts,
		DeleteAllowPts,
		DeleteDenyPts,
		CreateAllowPts,
		CreateDenyPts
	FROM	
		 dbo.S3LootGroup LG WITH (READUNCOMMITTED)
		 INNER JOIN 
		 dbo.S3Loot L WITH (READUNCOMMITTED)
			 ON L.LootID = LG.LootID
		 INNER JOIN
		 dbo.S3RoleAssignment RA WITH (READUNCOMMITTED)
			 ON LG.LootGroupID = RA.LootGroupID
		 INNER JOIN
		 dbo.S3Permission P WITH (READUNCOMMITTED)
			 ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID) AS acl
	inner join
	dbo.S3IdentityLink il on acl.identityguid = il.GroupingGUID
group by
	il.MemberGUID,
	LootID
having
	sum(WriteAllowPts) > sum(WriteDenyPts)
GO


---------------------------------------------

-- dbo.viewS3ACLWriteDepartment
CREATE view [dbo].[viewS3ACLWriteDepartment] as

select 
	il.MemberGUID as UserGUID, 
	Cast(Replace(LootID, 'DEPT|', '') as int) as DepartmentID 
from 
   (
		SELECT
			RA.IdentityGUID,
			L.LootID,
			WriteAllowPts,
			WriteDenyPts
		FROM	
			dbo.S3LootGroup LG WITH (READUNCOMMITTED)
			INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
			INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
			INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
		where L.LootGroupPrefix='DEPT'
	) AS acl
	INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID

group by
	il.MemberGUID,
	LootID

having
	sum(WriteAllowPts) > sum(WriteDenyPts)
GO


---------------------------------------------

-- dbo.viewS3GroupAssignment
CREATE view [dbo].[viewS3GroupAssignment] as
select 
	UG.UserGroupGUID,
	UG.Name as UserGroupName,
	UP.UserGUID as UserGUID,
	UP.NameFirst + ' ' + UP.NameLast as UserName
from
	S3IdentityLink IL
	inner join UserGroup UG with (readuncommitted) on UG.UserGroupGUID = IL.GroupingGUID
	inner join UserProfile UP with (readuncommitted) on UP.UserGUID = IL.MemberGUID
GO


---------------------------------------------

-- dbo.viewS3IdentityLinkOrphans
CREATE view viewS3IdentityLinkOrphans
as
	select
		il.*,
		'Broken Link' as Reason
	from
		[dbo].[S3IdentityLink] il (readuncommitted)
		left join [dbo].[S3IdentityLink] p (readuncommitted) on p.Fullpath = replace(il.Fullpath, '\' + cast(il.GroupingGUID as nvarchar(36)), '')
	where
		il.Distance > 0
		and p.MemberGUID is null
		
	union all
	
	select
		il.*,
		'Invalid Group' as Reason
	from
		[dbo].[S3IdentityLink] il (readuncommitted)
	where
		il.MemberGUID != il.GroupingGUID
		and il.GroupingGUID not in(select ug.UserGroupGUID from [dbo].[UserGroup] ug)
		
	union all
	
	select
		il.*,
		'Missing Member' as Reason
	from
		[dbo].[S3IdentityLink] il (readuncommitted)
	where
		not exists (select 1 from [dbo].[UserProfile] up (readuncommitted) where up.UserGUID = il.MemberGUID)
		and not exists (select 1 from [dbo].[UserGroup] ug (readuncommitted) where ug.UserGroupGUID = il.MemberGUID)
GO


---------------------------------------------

-- dbo.viewS3PermissionSet
create view viewS3PermissionSet as
select 
	ps.PermissionSetID, ps.Name as PermissionSetName, ur.RoleID, ur.Name as RoleName, p.Weight, p.ReadValue, p.WriteValue, p.SecureValue, p.CreateValue, p.DeleteValue
from 
	S3PermissionSet ps
	inner join S3Permission p on ps.PermissionSetID = p.PermissionSetID
	inner join UserRole ur on p.RoleID = ur.RoleID
GO


---------------------------------------------

-- dbo.viewS3RoleAssignment
CREATE view [dbo].[viewS3RoleAssignment] as
select 
	lg.LootID as LootGroupID,
	ra.RoleID,
	il.memberguid as IdentityGUID,
	case when min(il.Distance ) = 0 and max(case when lg.LootID = lg.LootGroupID then 1 else 0 end) = 1 then cast(1 as bit) else cast(0 as bit) end as IsDirectlyAssigned
from 
	S3LootGroup lg with (readuncommitted) 
	inner join S3RoleAssignment ra with (readuncommitted) on lg.LootGroupID = ra.LootGroupID
	inner join S3identitylink il with (readuncommitted) on ra.IdentityGUID = il.GroupingGUID
group by
	il.memberguid,
	lg.LootID,
	ra.RoleID
GO


---------------------------------------------

-- dbo.viewS3RoleAssignmentDetail
CREATE view [dbo].[viewS3RoleAssignmentDetail] as
select 
	RA.RowID,
	UP.UserGUID,
	UP.NameFirst + ' ' + UP.NameLast as UserName,
	RA.IdentityGUID,
	isnull(IUG.Name, IUP.NameFull) as IdentityName,
	il.distance  as UserGroupDistance,
	case when LG.LootGroupID = LG.LootID then 0 else 1 end as LootDistance,
	il.Distance + case when LG.LootGroupID = LG.LootID then 0 else 1 end as Distance,
	RA.RoleID,
	UR.Name as RoleName,
	LG.LootID,
	LG.LootGroupID,
	isnull(case when LG.LootID = LG.LootGroupID then cast(1 as bit) else cast(0 as bit) end, cast(0 as bit)) as IsDirectAssignment
from
	S3RoleAssignment RA (readuncommitted)
	inner join S3LootGroup LG (readuncommitted) on LG.LootGroupID = RA.LootGroupID
	inner join S3IdentityLink IL (readuncommitted) on IL.GroupingGUID = RA.IdentityGUID
	inner join UserProfile UP (readuncommitted) on UP.UserGUID = IL.MemberGUID
	inner join UserRole UR (readuncommitted) on UR.RoleID = RA.RoleID
	left join UserProfile IUP (readuncommitted) on IUP.UserGUID = IL.GroupingGUID
	left join UserGroup IUG (readuncommitted) on IUG.UserGroupGUID = IL.GroupingGUID
GO


---------------------------------------------

-- dbo.viewS3RoleAssignmentDirect
CREATE view [dbo].[viewS3RoleAssignmentDirect] as
select 
	ra.LootGroupID, 
	ra.RoleID,
	ra.IdentityGUID as IdentityGUID,
	isnull(cast(1 as bit),cast(1 as bit)) as IsDirectlyAssigned
from 
	--S3LootGroup lg with (readuncommitted) 
	--inner join 
	S3RoleAssignment ra with (readuncommitted) --on lg.LootGroupID = ra.LootGroupID
	
group by
	ra.IdentityGUID,
	ra.LootGroupID, 
	ra.RoleID
GO


---------------------------------------------

-- dbo.viewS3RoleAssignmentNoGroupBy
create view [dbo].[viewS3RoleAssignmentNoGroupBy] as
select 
	lg.LootID as LootGroupID,
	ra.RoleID,
	il.memberguid as IdentityGUID,
	case when il.Distance  = 0 and lg.LootID = lg.LootGroupID then cast(1 as bit) else cast(0 as bit) end as IsDirectlyAssigned
from 
	S3LootGroup lg with (readuncommitted) 
	inner join S3RoleAssignment ra with (readuncommitted) on lg.LootGroupID = ra.LootGroupID
	inner join S3identitylink il with (readuncommitted) on ra.IdentityGUID = il.GroupingGUID
GO


---------------------------------------------

-- dbo.viewSR2CorrelationGroupMember
create view [dbo].[viewSR2CorrelationGroupMember]
as
	select
		cgm.*, cg.Name as GroupName
	from
		SR2CorrelationGroupMember cgm
		inner join SR2CorrelationGroup cg on cgm.CorrelationGroupGUID = cg.CorrelationGroupGUID
GO


---------------------------------------------

-- dbo.viewSR2RiskResultDetail
CREATE view dbo.viewSR2RiskResultDetail as
select 
	rrdet.RowID
	,rrdet.DetailGUID
	,rrdet.RiskResultGUID
	,rrdet.TrialNumber
	,rrdet.OutputGUID
	,rr.Bincount as BinNumber
	,rrdet.Value
	,rrdet.HistoryItemGUID
	,rrdet.IsDeleted
	,rr.RiskConfigGUID
	,rr.Name as RiskResultName
	,rr.DateCreated
	,rrdet.CachedOutputName as [RiskConfigOutputName]
	,rrdet.OutputUniqueID
	,rrdet.CachedOutputDisplayFormat
	,(select top 1 srdet.valuebaseline 
		from [dbo].[SR2SensitivityResultDetail] srdet (readuncommitted) 
		inner join [dbo].[SR2SensitivityResult] sr (readuncommitted) on sr.SensitivityResultGUID = srdet.SensitivityResultGUID
		where rrdet.OutputGUID=srdet.OutputGUID
		order by sr.DateCreated desc) as SensitivityBaseline
from [dbo].[SR2RiskResultDetail] rrdet (readuncommitted)
inner join [dbo].[SR2RiskResult] rr (readuncommitted) on rr.RiskResultGUID = rrdet.RiskResultGUID
GO


---------------------------------------------

-- dbo.viewSR2SensitivityResultDetail
CREATE view [dbo].[viewSR2SensitivityResultDetail] as

select 
	srdet.OutputGUID
	,Max(srdet.ValueBaseline) as [ValueBaseline]
	,srdet.IsDeleted
	,sr.SensitivityResultGUID
	,sr.Name as [SensitivityResultName]
	,sr.DateCreated
	,srdet.CachedOutputName as [SensitivityConfigOutputName]
	,srdet.OutputUniqueID
	,srdet.CachedGroupName as [GroupName]
	,ABS(Sum(srdet.ValueHigh)-Sum(srdet.ValueLow)) as SensitivityCalculation
	,Case When Sum(srdet.ValueHigh) > Sum(srdet.ValueBaseline) Then (Sum(srdet.ValueHigh) - Sum(srdet.ValueBaseline)) Else (Sum(srdet.ValueBaseline) - Sum(srdet.ValueHigh)) End as DeltaHigh
	,Case When Sum(srdet.ValueLow) < Sum(srdet.ValueBaseline) Then (Sum(srdet.ValueLow) - Sum(srdet.ValueBaseline)) Else (Sum(srdet.ValueBaseline) - Sum(srdet.ValueLow)) End as DeltaLow
	,srdet.CachedOutputDisplayFormat
from [dbo].[SR2SensitivityResultDetail] srdet (readuncommitted)
inner join [dbo].[SR2SensitivityResult] sr (readuncommitted) on sr.SensitivityResultGUID = srdet.SensitivityResultGUID where srdet.CachedGroupName<>''
Group By
	srdet.OutputGUID
	,srdet.IsDeleted
	,sr.SensitivityResultGUID
	,sr.Name
	,sr.DateCreated
	,srdet.CachedOutputName
	,srdet.OutputUniqueID
	,srdet.CachedGroupName
	,srdet.CachedOutputDisplayFormat

Union All

select 
	srdet.OutputGUID
	,srdet.ValueBaseline
	,srdet.IsDeleted
	,sr.SensitivityResultGUID
	,sr.Name as [SensitivityResultName]
	,sr.DateCreated
	,srdet.CachedOutputName as [SensitivityConfigOutputName]
	,srdet.OutputUniqueID
	,srdet.CachedInputName as [GroupName]
	,ABS(srdet.ValueHigh-srdet.ValueLow) as SensitivityCalculation
	,Case When srdet.ValueHigh > srdet.ValueBaseline Then (srdet.ValueHigh - srdet.ValueBaseline) Else (srdet.ValueBaseline - srdet.ValueHigh) End as DeltaHigh
	,Case When srdet.ValueLow < srdet.ValueBaseline Then (srdet.ValueLow - srdet.ValueBaseline) Else (srdet.ValueBaseline - srdet.ValueLow) End as DeltaLow
	,srdet.CachedOutputDisplayFormat
from [dbo].[SR2SensitivityResultDetail] srdet (readuncommitted)
inner join [dbo].[SR2SensitivityResult] sr (readuncommitted) on sr.SensitivityResultGUID = srdet.SensitivityResultGUID where srdet.CachedGroupName=''
GO


---------------------------------------------

-- dbo.viewScoreAttribute
CREATE view [dbo].[viewScoreAttribute]  
AS  
select   
    *
from dbo.viewScoreAttributeCore30
GO


---------------------------------------------

-- dbo.viewScoreAttributeCore30
CREATE VIEW [dbo].[viewScoreAttributeCore30]  
AS  
select   
	A.AttributeGUID,  
	D.DimensionGUID,  
	A.DimensionGroupGUID,  
	A.FriendlyName,  
	A.IsWrittenToDB,  
	A.IsSecuredLootConfigID,  
	A.IsSecuredLootGroupID,  
	A.IsSecuredLootID,  
	A.SecuredLootGroupPrefix,  
	A.DefaultSortAttributeGUID,  
	A.ForeignKeyGUID,  
	A.IsRequired,   
	A.SpecialAttributeIndex,  
	A.IsCopiedWithPlan,
	A.[CustomNumberFormat],
	A.[IsCustomNumberFormat],
	A.DisplayOrder,  
	A.IsHidden,
	A.DSSIsUsed,	
	A.IsLocked, 
	A.IsKey,  
	A.JoinTypeVal,
	A.DateModified,  
	A.SQLColumnName, -- need to use this, cause we have to update it , the join pulls in the rest of the data  
	A.AttributeType,  
	A.MetaXML,  
	A.InferredSourceGUID,  
	A.InferredAttributeGUID,  
	A.InferredColumnName,  
	A.HelpText,  
	dbo.GetSQLTableExpression(D.SQLSchemaName, D.SQLObjectName) as [DimensionSQLObjectExpression],  
	g.SchemaName as DimensionGroupSQLSchemaName,  
	g.ObjectName as DimensionGroupSQLObjectName,  
	g.Name as [CachedDimensionGroupName],  
	isnull(case when 1 = dbo.TableExists(g.SchemaName,g.ObjectName) then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as DimensionGroupIsTable,  
	D.SQLTableAlias as [DimensionSQLTableAlias],  
	D.sqltablealias + A.SQLColumnName as SQLColumnAlias,  
	D.IsSecured as [IsDimensionSecured],  
	D.IsSecuredSetupOnly as [IsDimensionSecuredSetupOnly],
	D.FriendlyName as [DimensionName],  
	A.[ColumnType],  
	A.[ComputedValueDefinition],  
	A.[IsComputed],  
	A.[IsIdentity],  
	A.[IdentityIncrement],  
	A.[IdentitySeed],  
	A.[IsNullable],   
	A.[DefaultValueDefinition],  
	A.[Precision],  
	A.[Scale],  
	A.[MaxLength],  
	A.[IsColumnExist],
	A.ForeignKeyHierarchyGUID,
	ISNULL(FH.FriendlyName, '') as [CachedFKHierarchyName],  
	ISNULL(FK.FriendlyName,'') as [CachedFKMemberName],  
	ISNULL(FKD.FriendlyName,'') as [CachedFKDimensionName],  
	ISNULL(FKD.DimensionGUID,dbo.ZeroGUID()) as [CachedFKDimensionGUID],  
	ISNULL(FKD.DefaultLookupKeyGUID, dbo.ZeroGUID()) as [CachedFKDefaultLookupKeyGUID],
	--ISNULL(FKG.Name,'') as [CachedDimensionGroupName],  
	A.IsForeignKeyed,  
	A.ForeignKeySchema,  
	A.ForeignKeyTable,  
	A.ForeignKeyColumn,  
	A.ForeignKeyOnDelete  
	,ISNULL(IA.SQLColumnName, '') as [CachedInferredSQLColumnName]
	,ISNULL(IAG.SchemaName, '') as [CachedInferredSQLSchemaName]  
	,ISNULL(IAG.ObjectName, '') as [CachedInferredSQLObjectName]  
	,A.[CachedInferredSQLColumnType]  
	,A.IsFKAutoFilter  
	,D.DimensionVersion as [DimensionVersion]
	,A.IsFormField
	,A.FrameworkID
	,A.IsModelDriver
from ScoreAttribute A (readuncommitted) 
	inner join ScoreAttributeType AT (readuncommitted) on AT.ScoreAttributeTypeID = A.AttributeType  
	inner join ScoreDimensionGroup G (readuncommitted) on A.DimensionGroupGUID = G.DimensionGroupGUID  
	inner join ScoreDimension D (readuncommitted) on G.DimensionGUID = D.DimensionGUID  

	--foreign key  
	left join ScoreAttribute FK (readuncommitted) on FK.AttributeGUID = A.ForeignKeyGUID  
	left join ScoreDimensionGroup FKG (readuncommitted) on FKG.DimensionGroupGUID = FK.DimensionGroupGUID  
	left join ScoreDimension FKD (readuncommitted) on FKD.DimensionGUID = FKG.DimensionGUID  
	--foreign hierarchy
	left join ScoreHierarchy FH (readuncommitted) on FH.HierarchyGUID = A.ForeignKeyHierarchyGUID
	--infer  
	left join ScoreAttribute IA (readuncommitted) on IA.AttributeGUID = A.InferredAttributeGUID  
	left join ScoreDimensionGroup IAG (readuncommitted) on IA.DimensionGroupGUID = IAG.DimensionGroupGUID  
	left join ScoreDimension IAD (readuncommitted) on IAD.DimensionGUID = IAG.DimensionGUID
GO


---------------------------------------------

-- dbo.viewScoreAttributeFramework
CREATE view dbo.viewScoreAttributeFramework
as
	select distinct * from (
		select
			a.AttributeGUID,
			a.FrameworkID
		from
			viewScoreAttribute a
		where
			a.FrameworkID != 0
		union all
		select
			a.AttributeGUID,
			df.FrameworkID
		from
			viewScoreAttribute a
			inner join ScoreDimension d on d.DimensionGUID = a.DimensionGUID
			inner join ScoreDimensionFramework df on df.DimensionGUID = d.DimensionGUID
		where
			a.FrameworkID = 0
		union all
		select
			a.AttributeGUID,
			fkdf.FrameworkID
		from
			viewScoreAttribute a
			inner join ScoreDimension d on d.DimensionGUID = a.DimensionGUID
			inner join ScoreDimension fkd on fkd.FriendlyName = a.CachedFKDimensionName
			inner join ScoreDimensionFramework fkdf on fkdf.DimensionGUID = fkd.DImensionGUID
		where
			a.FrameworkID = 0
		union all
		select
			a.AttributeGUID,
			idf.FrameworkID
		from
			viewScoreAttribute a
			inner join ScoreDimension d on d.DimensionGUID = a.DimensionGUID
			inner join viewScoreAttribute ia on ia.AttributeGUID = a.InferredSourceGUID
			inner join ScoreDimension id on id.FriendlyName = ia.CachedFKDimensionName
			inner join ScoreDimensionFramework idf on idf.DimensionGUID = id.DImensionGUID
		where
			a.FrameworkID = 0
	) a
GO


---------------------------------------------

-- dbo.viewScoreAttributeSchemaInfo
CREATE VIEW [viewScoreAttributeSchemaInfo]
AS
select 
    A.AttributeGUID,
    isnull(case when 1 = dbo.TableExists(g.SchemaName,g.ObjectName) then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as DimensionGroupIsTable,
    case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.ColumnTypeValue,0) else ISNULL(COL.ColumnTypeValue,0) end  as [ColumnType],
    case when AT.ScoreAttributeTypeID = 3 then '' else ISNULL(COL.ComputedValueDefinition,'') end as [ComputedValueDefinition],
    case when AT.ScoreAttributeTypeID = 3 then 0 else ISNULL(COL.IsComputed, 0) end as [IsComputed],
    case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.IsIdentity, 0) else ISNULL(COL.IsIdentity, 0) end as [IsIdentity],
    case when AT.ScoreAttributeTypeID = 3 then -1 else ISNULL(COL.IdentityIncrement, 1) end as [IdentityIncrement],
    case when AT.ScoreAttributeTypeID = 3 then -1 else ISNULL(COL.IdentitySeed, 1) end as [IdentitySeed],
    case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.IsNullable, 0) else ISNULL(COL.IsNullable, 0) end as [IsNullable], 
    case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.DefaultValueDefinition, '') else ISNULL(COL.DefaultValueDefinition, '') end as [DefaultValueDefinition],
    case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.Precision, 0) else ISNULL(COL.Precision, 0) end as [Precision],
    case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.Scale,0) else ISNULL(COL.Scale,0) end as [Scale],
    case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.MaxLength,0) else ISNULL(COL.MaxLength,0) end as [MaxLength],
    ISNULL(cast((case when COL.ColumnName is null then 0 else 1 end) as bit), 0)  as [IsColumnExist],
	isnull(COL.IsForeignKeyed,CAST(0 as bit)) as IsForeignKeyed,
	isnull(COL.ForeignKeySchema,'') as ForeignKeySchema,
	isnull(COL.ForeignKeyTable,'') as ForeignKeyTable,
	isnull(COL.ForeignKeyColumn,'') as ForeignKeyColumn,
	isnull(COL.ForeignKeyOnDelete,'') as ForeignKeyOnDelete
	,isnull(IA.SQLColumnName, '') as [CachedInferredSQLColumnName]
	,isnull(IAC.ColumnTypeValue,0) as [CachedInferredSQLColumnType]
from ScoreAttribute A
	inner join ScoreAttributeType AT on AT.ScoreAttributeTypeID = A.AttributeType
	inner join ScoreDimensionGroup G on A.DimensionGroupGUID = G.DimensionGroupGUID
	inner join ScoreDimension D on G.DimensionGUID = D.DimensionGUID
	left join viewSysColumns COL on COL.ColumnName = A.SQLColumnName 
		AND case when AT.ScoreAttributeTypeID = 1 then G.ObjectName ELSE D.SQLObjectName end = COL.ObjectName --CHANGED
		and case when AT.ScoreAttributeTypeID = 1 then G.SchemaName ELSE D.SQLSchemaName end = COL.SchemaName --CHANGED group could have different schema

	--foreign key
	left join ScoreAttribute FK on FK.AttributeGUID = A.ForeignKeyGUID
	left join ScoreDimensionGroup FKG on FKG.DimensionGroupGUID = FK.DimensionGroupGUID
	left join ScoreDimension FKD on FKD.DimensionGUID = FKG.DimensionGUID
	
	--infer
	left join ScoreAttribute IA on IA.AttributeGUID = A.InferredAttributeGUID
	left join ScoreAttributeType AIT on AIT.ScoreAttributeTypeID = IA.AttributeType --CHANGED Was looking at the base Attribute type not the type of the inferred
	left join ScoreDimensionGroup IAG on IA.DimensionGroupGUID = IAG.DimensionGroupGUID
	left join ScoreDimension IAD on IAD.DimensionGUID = IAG.DimensionGUID
		left join viewSysColumns IAC on IAC.ColumnName = IA.SQLColumnName 
		AND case when AIT.ScoreAttributeTypeID = 1 then IAG.ObjectName ELSE IAD.SQLObjectName end = IAC.ObjectName  --CHANGED Was a straight join on the inferred attribute info (could be calculated on the base)
		and case when AIT.ScoreAttributeTypeID = 1 then IAG.SchemaName ELSE IAD.SQLSchemaName end = IAC.SchemaName  --CHANGED schema same as above
GO


---------------------------------------------

-- dbo.viewScoreAttribute_StrataSchema
CREATE   view [dbo].[viewScoreAttribute_StrataSchema] 
AS  
select   
    A.AttributeGUID
	,A.DimensionGUID
	,A.DimensionGroupGUID
	,A.FriendlyName
	,A.IsWrittenToDB
	,A.IsSecuredLootConfigID
	,A.IsSecuredLootGroupID
	,A.IsSecuredLootID
	,A.SecuredLootGroupPrefix
	,A.DefaultSortAttributeGUID
	,A.ForeignKeyGUID
	,A.IsRequired
	,A.SpecialAttributeIndex
	,A.IsCopiedWithPlan
	,A.CustomNumberFormat
	,A.IsCustomNumberFormat
	,A.DisplayOrder
	,A.IsHidden
	,A.DSSIsUsed
	,A.IsLocked
	,A.IsKey
	,A.JoinTypeVal
	,A.DateModified 
	,A.SQLColumnName
	,A.AttributeType
	,A.MetaXML
	,A.InferredSourceGUID
	,A.InferredAttributeGUID
	,A.InferredColumnName
	,A.HelpText
	,A.DimensionSQLObjectExpression
	,A.DimensionGroupSQLSchemaName
	,A.DimensionGroupSQLObjectName
	,A.CachedDimensionGroupName
	,A.DimensionGroupIsTable  
	,A.DimensionSQLTableAlias
	,A.SQLColumnAlias
	,A.IsDimensionSecured
	,A.IsDimensionSecuredSetupOnly
	,A.DimensionName 
	,A.ColumnType
	,A.ComputedValueDefinition
	,A.IsComputed
	,A.IsIdentity
	,A.IdentityIncrement
	,A.IdentitySeed
	,A.IsNullable
	,A.DefaultValueDefinition
	,A.Precision
	,A.Scale
	,A.MaxLength
	,A.IsColumnExist
	,A.ForeignKeyHierarchyGUID
	,A.CachedFKHierarchyName
	,A.CachedFKMemberName
	,A.CachedFKDimensionName
	,A.CachedFKDimensionGUID
	,A.CachedFKDefaultLookupKeyGUID
	,A.IsForeignKeyed  
	,A.ForeignKeySchema
	,A.ForeignKeyTable  
	,A.ForeignKeyColumn
	,A.ForeignKeyOnDelete  
	,A.CachedInferredSQLColumnName
	,A.CachedInferredSQLSchemaName  
	,A.CachedInferredSQLObjectName  
	,A.CachedInferredSQLColumnType  
	,A.IsFKAutoFilter  
	,A.DimensionVersion
	,A.IsFormField
	,A.FrameworkID
	,A.IsModelDriver
	,CAST(COALESCE(ATS.IsCustom, 0) AS BIT) AS IsCustom
	,CAST(COALESCE(ATS.IsMarkedForDeletion, 0) AS BIT) AS IsMarkedForDeletion
	,CAST(COALESCE(ATS.IsUsed, 1) AS BIT)  AS IsUsed
	,CAST(COALESCE(ATS.CAPIsUsed, 1) AS BIT)  AS CAPIsUsed
	,CAST(COALESCE(ATS.MRIsUsed, 1) AS BIT)  AS MRIsUsed
	,CAST(COALESCE(ATS.OBIsUsed, 1) AS BIT)  AS OBIsUsed
	,CAST(COALESCE(ATS.PRIsUsed, 1) AS BIT)  AS PRIsUsed
	,CAST(COALESCE(ATS.SPIsUsed, 1) AS BIT)  AS SPIsUsed
from dbo.viewScoreAttributeCore30 A
LEFT JOIN [dbo].[ScoreAttributeSetting] ATS ON ATS.AttributeGUID = A.AttributeGUID
GO


---------------------------------------------

-- dbo.viewScoreCompositeLinkDetail
CREATE view [dbo].[viewScoreCompositeLinkDetail] as
select
	scl.*,
	sc.FriendlyName as CompositeName,
	dt1.DataTableGUID as DataTable1GUID,
	dt1.FriendlyName as DataTable1Name,
	dt2.DataTableGUID as DataTable2GUID,
	dt2.FriendlyName as DataTable2Name,
	sk1.AttributeGUID as MappingKeyGUID,
	sk1.FriendlyName as MappingKeyName,
	isnull(msr.MeasureGUID, dbo.ZeroGUID()) as PlaceholderMeasureGUID,
	isnull(msr.FriendlyName, '') as PlaceholderMeasureName,
	sk2.AttributeGUID as DataKeyGUID,
	sk2.FriendlyName as DataKeyName,
	sdg1.DimensionGUID as MappingDimensionGUID,
	sdg2.DimensionGUID as DataDimensionGUID,
	sd2.FriendlyName as DataDimensionName
from
	ScoreComposite sc
	inner join scoredatatable dt1 on sc.DataTableGUID1 = dt1.DataTableGUID
	inner join scoredatatable dt2 on sc.DataTableGUID2 = dt2.DataTableGUID
	inner join ScoreCompositeLink scl on sc.CompositeGUID = scl.CompositeGUID
	inner join ScoreAttribute sk1 on scl.Key1GUID = sk1.AttributeGUID
	inner join ScoreDimensionGroup sdg1 on sk1.DimensionGroupGUID = sdg1.DimensionGroupGUID
	inner join ScoreAttribute sk2 on scl.Key2GUID = sk2.AttributeGUID
	inner join ScoreDimensionGroup sdg2 on sk2.DimensionGroupGUID = sdg2.DimensionGroupGUID
	inner join ScoreDimension sd2 on sdg2.DimensionGUID = sd2.DimensionGUID
	left join ScoreMeasure msr on scl.PlaceholderIndexMeasureGUID = msr.MeasureGUID
GO


---------------------------------------------

-- dbo.viewScoreDataSource
CREATE View [dbo].[viewScoreDataSource]
AS
select * from 
(
	select 
		DatatableGUID as DataSourceGUID,
		FriendlyName as FriendlyName,
		0 as DataSourceType
	from 
		ScoreDataTable

	UNION

	select 
		CompositeGUID as DataSourceGUID,
		FriendlyName as FriendlyName,
		1 as DataSourceType
	from
		ScoreComposite
) AS Test
GO


---------------------------------------------

-- dbo.viewScoreDataTable
CREATE VIEW [dbo].[viewScoreDataTable]
	AS
	select 
		DataTableGUID, 
		FriendlyName,
		Description,
		SQLTableAlias,
		IsWrittenToDB,
		DisplayFormatAttributeGUID,
		DisplayFormatAttributeDimensionGUID,
		IsCompositeMappingTable,
		IsCompositeBoundsTable,
		FrameworkID,
		SQLSchemaName,
		SQLObjectName,
		IsWrittenIfZero,
		GlobalID,
		ModifiedAt,
		IsClientFriendly,
		OverrideLoadBySQLSchemaName,
		OverrideLoadBySQLObjectName,
		IsGeneratingSelectIntoTempTable,
		ModelQueryHint,
		DIDeleteQueryHint,
		ISNULL(cast(case when object_ID(dbo.GetSQLTableExpression(SQLSchemaName, SQLObjectName)) is not null then 1 else 0 end as bit), cast(0 as bit)) as [IsBackingObjectExist],
		ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(SQLSchemaName, SQLObjectName)), 'IsView') as bit), cast(0 as bit)) as [IsView] 	
from 
	ScoreDataTable
GO


---------------------------------------------

-- dbo.viewScoreDataTableBadColumns
create view viewScoreDatatableBadColumns as
select sd.datatableguid, sd.friendlyname, sa.attributeguid, sa.sqlcolumnname, sm.measureguid
from 
	scoredatatable sd
	inner join scoredatatablekeylink kl on sd.datatableguid = kl.datatableguid
	inner join scoreattribute sa on kl.keyguid = sa.attributeguid
	left join scoremeasure sm on sm.datatableguid = kl.datatableguid and sm.sqlcolumnname = sa.sqlcolumnname
where
	sm.measureguid is not null
GO


---------------------------------------------

-- dbo.viewScoreDataTableKeyLink
CREATE view [dbo].[viewScoreDataTableKeyLink] as
select 

	dt.SQLTableAlias,
	sd.FriendlyName as DimensionName,
	sd.GlobalID as DimensionGlobalID,
	sa.FriendlyName,
	
	--dt.SQLSchemaName,
	--dt.SQLObjectName,
	--sa.SQLColumnName,
	sdg.DimensionGUID,
	--careful if you edit this view as these col columns need to be last! 
	--and if you add/remove columns before them you need to update the codegen
	dtkl.IsRequired,
	dtkl.DataTableKeyLinkGUID,
	dtkl.DataTableGUID,
	dtkl.KeyGUID,
	dtkl.ObjectID,
	dtkl.ColumnID,
	dtkl.SchemaName,
	dtkl.ObjectName,
	dtkl.ColumnName,
	dtkl.ObjectType,
	dtkl.MaxLength,
	dtkl.IsComputed,
	dtkl.IsNullable,
	dtkl.Scale,
	dtkl.Precision,
	dtkl.IsIdentity,
	dtkl.ColumnTypeValue,
	dtkl.IdentityIncrement,
	dtkl.IdentitySeed,
	dtkl.DefaultValueDefinition,
	dtkl.IsPartOfUniqueIndex,
	dtkl.IsUniqueIndex,
	dtkl.IsPartOfPrimaryKey,
	dtkl.IsPrimaryKey,
	dtkl.ComputedValueDefinition,
	dtkl.IsForeignKeyed,
	dtkl.ForeignKeySchema,
	dtkl.ForeignKeyTable,
	dtkl.ForeignKeyColumn,
	dtkl.ForeignKeyOnDelete,
	dtkl.ModifiedAt

from
	ScoreDataTableKeyLink dtkl 
	inner join ScoreDataTable  dt on dt.DataTableGUID = dtkl.DataTableGUID
	inner join ScoreAttribute sa on dtkl.KeyGUID = sa.AttributeGUID
	inner join ScoreDimensionGroup sdg on sa.DimensionGroupGUID = sdg.DimensionGroupGUID
	inner join ScoreDimension sd on sdg.DimensionGUID = sd.DimensionGUID
GO


---------------------------------------------

-- dbo.viewScoreDataTableKeyLinkSchemaInfo
create view viewScoreDataTableKeyLinkSchemaInfo as
select
	m.DataTableKeyLinkGUID,
	col.*
from
	ScoreDataTableKeyLink m
	INNER JOIN dbo.ScoreDataTable dt ON m.DataTableGUID = dt.DataTableGUID
	INNER JOIN dbo.ScoreAttribute SA on m.keyguid = sa.attributeguid
										
	--should be inner?  should it use something more specialized?
	INNER JOIN viewSysColumns col on 
		col.SchemaName = dt.SQLSchemaName
		and col.ObjectName = dt.SQLObjectName
		and col.ColumnName = sa.SQLColumnName
GO


---------------------------------------------

-- dbo.viewScoreDataTableKeyLink_StrataSchema
CREATE   VIEW dbo.viewScoreDataTableKeyLink_StrataSchema AS
SELECT 
	 DTKL.DataTableKeyLinkGUID
	,DTKL.DataTableGUID
	,DTKL.KeyGUID
	,DTKL.ObjectID
	,DTKL.ColumnID
	,DTKL.SchemaName
	,DTKL.ObjectName
	,DTKL.ColumnName
	,DTKL.ObjectType
	,DTKL.MaxLength
	,DTKL.IsComputed
	,DTKL.IsNullable
	,DTKL.Scale
	,DTKL.Precision
	,DTKL.IsIdentity
	,DTKL.ColumnTypeValue
	,DTKL.IdentityIncrement
	,DTKL.IdentitySeed
	,DTKL.DefaultValueDefinition
	,DTKL.IsPartOfUniqueIndex
	,DTKL.IsUniqueIndex
	,DTKL.IsPartOfPrimaryKey
	,DTKL.IsPrimaryKey
	,DTKL.ComputedValueDefinition
	,DTKL.IsForeignKeyed
	,DTKL.ForeignKeySchema
	,DTKL.ForeignKeyTable
	,DTKL.ForeignKeyColumn
	,DTKL.ForeignKeyOnDelete
	,DTKL.ModifiedAt
	,DTKL.IsRequired
	,DTKL.Description
	,D.DimensionGuid
	,CAST(COALESCE(KLS.IsCustom, 0) AS BIT) AS IsCustom
	,CAST(COALESCE(KLS.IsUsed, 1) AS BIT) AS IsUsed
	,CAST(COALESCE(KLS.IsMarkedForDeletion, 0) AS BIT) AS IsMarkedForDeletion
FROM [dbo].[ScoreDataTableKeyLink] DTKL
INNER JOIN [dbo].[ScoreDimension] D ON D.DefaultKeyGUID = DTKL.KeyGUID
LEFT JOIN [dbo].[ScoreKeyLinkSetting] KLS ON DTKL.DataTableGUID = KLS.DataTableGUID AND DTKL.KeyGUID = KLS.KeyGUID
GO


---------------------------------------------

-- dbo.viewScoreDataTable_StrataSchema
CREATE   VIEW viewScoreDataTable_StrataSchema
AS 
	SELECT 
		 DT.DataTableGUID
		,DT.FriendlyName
		,DT.Description
		,DT.SQLSchemaName
		,DT.SQLObjectName
		,DT.SQLTableAlias
		,DT.IsWrittenToDB
		,DT.DisplayFormatAttributeGUID
		,DT.DataTableID
		,DT.SQLTableAliasUnique
		,DT.IsCompositeMappingTable
		,DT.FrameworkID
		,DT.ModifiedAt
		,DT.IsWrittenIfZero
		,DT.GlobalID
		,DT.IsCompositeBoundsTable
		,DT.DisplayFormatAttributeDimensionGUID
		,DT.IsClientFriendly
		,DT.OverrideLoadBySQLSchemaName
		,DT.OverrideLoadBySQLObjectName
		,CAST(COALESCE(dts.IsRequired, 1) AS BIT) IsRequired
		,CAST(COALESCE(dts.IsUsed, 1) AS BIT) IsUsed
	FROM 
	[dbo].[ScoreDataTable] dt
	LEFT JOIN [dbo].[ScoreDatatableSetting] dts ON dts.DataTableGUID = dt.DataTableGUID
GO


---------------------------------------------

-- dbo.viewScoreDimension
CREATE view [dbo].[viewScoreDimension] 
as  
	select    
		sd.DefaultHierarchyGUID,    
		sd.DefaultKeyGUID,   
		sd.DefaultLookupKeyGUID,   
		sd.HelpTextAttributeGUID,
		sd.PrimaryGroupGUID,   
		sd.DimensionGUID,   
		sd.FriendlyName,   
		sd.IsSecured,   
		sd.PermissionSetID,   
		sd.SQLObjectName,   
		sd.SQLSchemaName,   
		sd.SQLTableAlias,   
		sd.DefaultMemberGUID,   
		sd.IsSysAdminOnly,   
		sd.IsAllowMemberDelete,   
		sd.IsAllowMemberAdd,   
		sd.IsSharingSecurity,   
		sd.IsStock,   
		sd.IsSensitivityRiskHidden,
		sd.Description,
		sd.PHIDisclaimer,
		sd.CopyrightDisclaimer,
		sd.DateModified,   
		sd.PickerType,   
		sd.DimensionVersion,   
		sd.IsGeneratingWrapperView,   
		sd.GlobalID,   
		sd.DimensionEditorMode,
		sd.IsSecuredSetupOnly,
		sd.IsClientFriendly,
		sd.IsEditable,
		sd.IsCustomAttributeAllowed,
		sd.IsCustom,	
		sd.ParentDimensionGUID,
		sd.IsStandard,
		sd.StandardCodesLastUpdated,
		sd.StandardCodesVersion,
		sd.IsDisablingHistoryTriggers,
		ISNULL(cast(case when object_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)) is not null then 1 else 0 end as bit), cast(0 as bit)) as [IsBackingObjectExist]   ,
		ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'IsTable') as bit), cast(0 as bit)) as [IsTable]    ,
		ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'IsView') as bit), cast(0 as bit)) as [IsView]    ,
		ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasUpdateTrigger') as bit), cast(0 as bit)) as [HasUpdateTrigger]   ,
		ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasInsertTrigger') as bit), CAST(0 as bit)) as [HasInsertTrigger]   ,
		ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasDeleteTrigger') as bit), CAST(0 as bit)) as [HasDeleteTrigger]   ,
		ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasInsteadOfTrigger') as bit), CAST(0 as bit)) as HasInsteadOfTrigger   ,
		coalesce(OBJECT_DEFINITION(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName))), '') as [ObjectDefinition]   ,
		case when exists (SELECT 1 FROM ScoreCompositeLink l WHERE sd.DefaultKeyGUID = l.Key1GUID and l.IsPlaceholder = 1) then CAST(1 as bit) else CAST(0 as bit) end as IsUsedAsPlaceholder   ,
		(select max(datemodified) from (select datemodified from ScoreDimension where DimensionGUID = sd.dimensionguid    union all select datemodified from ScoreAttribute where DimensionGUID = sd.dimensionguid    union all select datemodified from ScoreDimensionGroup where DimensionGUID = sd.dimensionguid    union all select datemodified from ScoreHierarchy where DimensionGUID = sd.dimensionguid     union all select datemodified from ScoreHierarchyAttributeLink shal      where shal.HierarchyGUID in (select HierarchyGUID from ScoreHierarchy where DimensionGUID = sd.dimensionguid)) x)   as LastModifiedIncludingChildren  
		,ISNULL(case when EXISTS (select 1 from PlanType PT (readuncommitted) where PT.DimensionGUID = sd.DimensionGUID) then cast(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as [IsPlanDimension]
		,case when exists (SELECT 1 FROM SecureList emf (readuncommitted) where emf.SyncedScoreDimensionGUID = sd.DimensionGUID) then CAST(1 as bit) else CAST(0 as bit) end as IsEMFSyncEnabled
	from    
		ScoreDimension sd
GO


---------------------------------------------

-- dbo.viewScoreDimensionDependency
CREATE view dbo.viewScoreDimensionDependency
as
	select distinct
		A.DimensionGUID as ParentDimensionGUID,
		D.FriendlyName as ParentDimensionName,
		FK.DimensionGUID as ChildDimensionGUID,
		FKD.FriendlyName as ChildDimensionName
	from
		viewScoreAttribute A
		inner join ScoreDimension D on D.DimensionGUID = A.DimensionGUID
		inner join viewScoreAttribute FK on FK.ForeignKeyGUID = A.AttributeGUID
		inner join ScoreDimension FKD with (readuncommitted) on FKD.DimensionGUID = FK.DimensionGUID
	where
		A.DimensionGUID != FK.DimensionGUID
		and FKD.DimensionVersion = 3
GO


---------------------------------------------

-- dbo.viewScoreDimensionDisclaimer
create view [dbo].[viewScoreDimensionDisclaimer]
as
	select
		DimensionGUID,
		GlobalID as DimensionName,
		PHIDisclaimer,
		CopyrightDisclaimer
	from
		ScoreDimension
	where
		PHIDisclaimer != '' or CopyrightDisclaimer != ''
GO


---------------------------------------------

-- dbo.viewScoreDimensionGroups
CREATE view [dbo].[viewScoreDimensionGroups]
AS
select 
	G.*
	,ISNULL(cast(case when object_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)) is not null then 1 else 0 end as bit), cast(0 as bit)) as [IsBackingObjectExist]
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'IsTable') as bit), cast(0 as bit)) as [IsTable] 
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'IsView') as bit), cast(0 as bit)) as [IsView] 
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'HasUpdateTrigger') as bit), cast(0 as bit)) as [HasUpdateTrigger]
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'HasInsertTrigger') as bit), CAST(0 as bit)) as [HasInsertTrigger]
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'HaGeleteTrigger') as bit), CAST(0 as bit)) as [HaGeleteTrigger]
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'HasInsteadOfTrigger') as bit), CAST(0 as bit)) as HasInsteadOfTrigger
	,coalesce(OBJECT_DEFINITION(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName))), '') as [ObjectDefinition]
from ScoreDimensionGroup G
	inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID
GO


---------------------------------------------

-- dbo.viewScoreDimensionHistory
CREATE view dbo.viewScoreDimensionHistory
AS
select 
	HL.DimensionHistoryLineID
	,ISNULL(UP.UserName, case when HI.MODIFIERUSERGUID = dbo.GetSuperUserGUID() then 'Strata' else '' end) as [UserName]
	,ISNULL(UP.NameLast + ', ' + UP.NameFirst, case when HI.MODIFIERUSERGUID = dbo.GetSuperUserGUID() then 'Strata' else '' end) as [User]
	,HI.DateTimeStamp
	,HL.TableName
	,HL.MemberGUID
	,HL.BeforeValues
	,HL.AfterValues
from ScoreDimensionHistoryLine HL
	inner join HistoryItem HI on HI.HISTORYITEMGUID = HL.HistoryItemGUID
	left join UserProfile UP on UP.UserGUID = HI.MODIFIERUSERGUID
GO


---------------------------------------------

-- dbo.viewScoreDimension_StrataSchema
CREATE   VIEW dbo.viewScoreDimension_StrataSchema AS
SELECT 
	D.*
	,G.SchemaName AS GroupSchemaName
	,G.ObjectName as GroupObjectName
	,COALESCE(GPARENT.SchemaName, G.SchemaName) SourceTableSchema
	,COALESCE(GPARENT.ObjectName, G.ObjectName) SourceTableName
FROM [dbo].[ScoreDimension] D
INNER JOIN [dbo].[ScoreDimensionGroup] G ON G.DimensionGroupGUID = D.PrimaryGroupGUID
LEFT JOIN [dbo].[ScoreDimension] DPARENT ON DPARENT.DimensionGUID = D.ParentDimensionGUID
LEFT JOIN [dbo].[ScoreDimensionGroup] GPARENT ON GPARENT.DimensionGroupGUID = DPARENT.PrimaryGroupGUID
GO


---------------------------------------------

-- dbo.viewScoreDimensions
CREATE view [dbo].[viewScoreDimensions]
as
select 
	sd.DefaultHierarchyGUID, 
	sd.DefaultKeyGUID,
	sd.DefaultLookupKeyGUID,
	sd.PrimaryGroupGUID,
	sd.DimensionGUID,
	sd.FriendlyName,
	sd.IsSecured,
	sd.PermissionSetID,
	sd.SQLObjectName,
	sd.SQLSchemaName,
	sd.SQLTableAlias,
	sd.DefaultMemberGUID,
	sd.IsSysAdminOnly,
	sd.IsAllowMemberDelete,
	sd.IsAllowMemberAdd,
	sd.IsStock,
	sd.Description,
	sd.DateModified,
	ISNULL(cast(case when object_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)) is not null then 1 else 0 end as bit), cast(0 as bit)) as [IsBackingObjectExist]
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'IsTable') as bit), cast(0 as bit)) as [IsTable] 
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'IsView') as bit), cast(0 as bit)) as [IsView] 
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasUpdateTrigger') as bit), cast(0 as bit)) as [HasUpdateTrigger]
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasInsertTrigger') as bit), CAST(0 as bit)) as [HasInsertTrigger]
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasDeleteTrigger') as bit), CAST(0 as bit)) as [HasDeleteTrigger]
	,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasInsteadOfTrigger') as bit), CAST(0 as bit)) as HasInsteadOfTrigger
	,coalesce(OBJECT_DEFINITION(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName))), '') as [ObjectDefinition]
from 
	ScoreDimension sd
GO


---------------------------------------------

-- dbo.viewScoreHierarchy
CREATE view [dbo].[viewScoreHierarchy] as 
select top 100 percent 
	sh.HierarchyGUID, 
	sh.FriendlyName as HierarchyName, 
	sh.PathAlias, 
	sh.DateModified,
	shal.SortOrder, 
	sa.AttributeGUID, 
	sa.FriendlyName,
	sh.DimensionGUID, 
	sd.FriendlyName as DimensionName
from
	ScoreHierarchy sh
	inner join ScoreDImension sd on sd.DimensionGUID = sh.DimensionGUID
	inner join ScoreHierarchyAttributeLink shal on sh.HierarchyGUID = shal.HierarchyGUID
	inner join ScoreAttribute sa on shal.AttributeGUID = sa.AttributeGUID
order by sd.FriendlyName, sh.FriendlyName, shal.SortOrder
GO


---------------------------------------------

-- dbo.viewScoreHierarchyAttributeLink
CREATE view [dbo].[viewScoreHierarchyAttributeLink]
AS
select 
	L.HierarchyAttributeLinkGUID,
	L.HierarchyGUID,
	L.DisplayAttributeGUID,
	L.SortOrder,
	L.IsDependentOnChild,
	L.AttributeGUID,
	D.FriendlyName as [DisplayAttributeName],
	D.SQLColumnName as [DisplayAttributeColumnName],
	A.SQLColumnName,
	A.ColumnType,
	A.IsNullable,
	A.IsRequired,
	A.IsComputed,
	A.IsCopiedWithPlan,
	A.IsIdentity,
	A.IdentityIncrement,
	A.IdentitySeed,
	A.Scale,
	A.Precision,
	A.DefaultValueDefinition,
	A.MaxLength
from ScoreHierarchyAttributeLink L
	inner join viewScoreAttributeCore30 A on L.AttributeGUID = A.AttributeGUID
	inner join ScoreAttribute D on D.AttributeGUID = L.DisplayAttributeGUID
GO


---------------------------------------------

-- dbo.viewScoreHierarchyAttributeLinkCore30
CREATE view [dbo].[viewScoreHierarchyAttributeLinkCore30]
AS
select 
	L.HierarchyAttributeLinkGUID,
	L.HierarchyGUID,
	L.DisplayAttributeGUID,
	L.SortOrder,
	L.IsDependentOnChild,
	L.AttributeGUID,
	L.DateModified,
	L.IsAttributeFiltered,
	L.FilterAttributeGUID,
	L.FilterString,
	D.FriendlyName as [DisplayAttributeName],
	D.SQLColumnName as [DisplayAttributeColumnName],
	A.SQLColumnName as [ColumnName],
	A.FriendlyName,
	A.DimensionGUID,
	A.DimensionGroupGUID,
	A.ColumnType,
	A.SecuredLootGroupPrefix,
	A.IsSecuredLootGroupID,
	A.IsSecuredLootID,
	A.ForeignKeyGUID,
	A.DefaultSortAttributeGUID,
	A.IsRequired,
	A.IsHidden,
	A.IsKey,
	A.IsWrittenToDB,
	A.IsCustomNumberFormat,
	A.CustomNumberFormat,
	A.IsComputed,
	A.IsCopiedWithPlan,
	A.IsNullable,
	A.IsIdentity,
	A.IdentityIncrement,
	A.IdentitySeed,
	A.Scale,
	A.Precision,
	A.DefaultValueDefinition,
	A.ComputedValueDefinition,
	A.MaxLength,
	A.DimensionSQLObjectExpression,
	A.DimensionSQLTableAlias,
	A.IsDimensionSecured,
	A.IsDimensionSecuredSetupOnly,
	A.DimensionName,
	A.IsForeignKeyed,
	A.ForeignKeySchema,
	A.ForeignKeyTable,
	A.ForeignKeyColumn,
	A.ForeignKeyOnDelete,
	A.AttributeType,
	A.MetaXML,
	A.IsFKAutoFilter
	
from ScoreHierarchyAttributeLink L
	inner join viewScoreAttributeCore30 A on L.AttributeGUID = A.AttributeGUID
	inner join ScoreAttribute D on D.AttributeGUID = L.DisplayAttributeGUID
GO


---------------------------------------------

-- dbo.viewScoreHierarchyCore30
CREATE view [dbo].[viewScoreHierarchyCore30] as 
select 
	sh.HierarchyGUID,
	sh.FriendlyName,
	sh.HierarchyID,
	sh.DateModified,
	sh.DimensionGUID,
	sh.PathAlias,
	sd.FriendlyName as DimensionName,
	Replace(sh.PathAlias + cast(sh.HierarchyID as nvarchar(11)), ' ','') as [UniquePathAlias],
	sh.GlobalID,
	sh.IsMR
from
	ScoreHierarchy sh
	inner join ScoreDImension sd on sd.DimensionGUID = sh.DimensionGUID
GO


---------------------------------------------

-- dbo.viewScoreHierarchyRoleLink
create view dbo.viewScoreHierarchyRoleLink
as
select
	d.DimensionGUID,
	d.FriendlyName as DimensionName,
	d.GlobalID as DimensionGlobalID,
	h.HierarchyGUID,
	h.FriendlyName as HierarchyName,
	r.RoleID,
	r.Name as RoleName,
	al.SortOrder
from
	[dbo].[ScoreHierarchy] h with (readuncommitted)
	inner join [dbo].[ScoreHierarchyAttributeLink] al with (readuncommitted) on al.HierarchyGUID = h.HierarchyGUID
	inner join [dbo].[viewScoreAttribute] a on a.AttributeGUID = al.AttributeGUID
	inner join [dbo].[viewFE2FormField] ff on ff.AttributeGUID = a.AttributeGUID
	inner join [dbo].[UserRole] r with (readuncommitted) on ff.ComputedFieldConfig like '%<UserRoleGUID>' + cast(r.UserRoleGUID as nvarchar(36)) + '</UserRoleGUID>%'
	inner join [dbo].[ScoreDimension] d with (readuncommitted) on d.DimensionGUID = h.DimensionGUID
where
	ff.ComputedFieldClassName = 'RoleAssignment'
GO


---------------------------------------------

-- dbo.viewScoreInvalidAttributes
CREATE view [dbo].[viewScoreInvalidAttributes]
AS
select 
	D.FriendlyName as [Dimension] 
	,G.SchemaName as [Schema]
	,G.ObjectName as [Table]
	,A.FriendlyName as [Attribute]
	,A.SQLColumnName as [ColumnName]
	,'Column not found.' as [Description]
from ScoreDimension D
	inner join ScoreDimensionGroup G on G.DimensionGUID = D.DimensionGUID
	inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID
	left join viewSysColumns C 
		on C.ColumnName = A.SQLColumnName
		and C.ObjectID = OBJECT_ID(dbo.GetSQLTableExpression(D.SQLSchemaName, D.SQLObjectName))
where 
	C.ColumnID is null
GO


---------------------------------------------

-- dbo.viewScoreMeasure
CREATE VIEW [dbo].[viewScoreMeasure]
AS
SELECT
	dt.SQLTableAlias,
	dt.IsWrittenIfZero,
	m.*
FROM 
	dbo.ScoreMeasure AS m 
	INNER JOIN dbo.ScoreDataTable AS dt ON m.DataTableGUID = dt.DataTableGUID
GO


---------------------------------------------

-- dbo.viewScoreMeasureSchemaInfo
create view viewScoreMeasureSchemaInfo as
select
	m.MeasureGUID,
	col.*
from
	ScoreMeasure m
	INNER JOIN dbo.ScoreDataTable AS dt ON m.DataTableGUID = dt.DataTableGUID

	--should be inner?  should it use something more specialized?
	INNER JOIN viewSysColumns col on 
		col.SchemaName = dt.SQLSchemaName
		and col.ObjectName = dt.SQLObjectName
		and col.ColumnName = m.SQLColumnName
GO


---------------------------------------------

-- dbo.viewScoreMeasure_StrataSchema
CREATE   VIEW dbo.viewScoreMeasure_StrataSchema
AS
	SELECT
		 M.MeasureGUID
		,M.FriendlyName
		,M.DataTableGUID
		,M.IsReadFromDB
		,M.IsWrittenToDB
		,M.SQLColumnName
		,M.DisplayFormat
		,M.HasMin
		,M.Min
		,M.HasMax
		,M.Max
		,M.HasMinLength
		,M.MinLength
		,M.DefaultValue
		,M.AggType
		,M.SpecialMeasureIndex
		,M.SpecialFormulaSQLColumnName
		,M.SpecialCommentSQLColumnName
		,M.HasRestrictedValues
		,M.RestrictedValues
		,M.ObjectID
		,M.ColumnID
		,M.SchemaName
		,M.ObjectName
		,M.ColumnName
		,M.ObjectType
		,M.MaxLength
		,M.IsComputed
		,M.IsNullable
		,M.Scale
		,M.Precision
		,M.IsIdentity
		,M.ColumnTypeValue
		,M.IdentityIncrement
		,M.IdentitySeed
		,M.DefaultValueDefinition
		,M.IsPartOfUniqueIndex
		,M.IsUniqueIndex
		,M.IsPartOfPrimaryKey
		,M.IsPrimaryKey
		,M.ComputedValueDefinition
		,M.IsForeignKeyed
		,M.ForeignKeySchema
		,M.ForeignKeyTable
		,M.ForeignKeyColumn
		,M.ForeignKeyOnDelete
		,M.ModifiedAt
		,M.IsHidden
		,M.GlobalID
		,M.IsRequired
		,M.Description
		,M.DisplayFolder
		,CAST(COALESCE(MS.IsCustom, 0) AS BIT) AS IsCustom
		,CAST(COALESCE(MS.IsUsed, 1) AS BIT) AS IsUsed
		,CAST(COALESCE(MS.IsMarkedForDeletion, 0) AS BIT) AS IsMarkedForDeletion
	FROM [dbo].[ScoreMeasure] M
	LEFT JOIN [dbo].[ScoreMeasureSetting] MS ON MS.MeasureGUID = M.MeasureGUID
GO


---------------------------------------------

-- dbo.viewScoreOrphanedLootTriggers
CREATE VIEW [dbo].[viewScoreOrphanedLootTriggers]
AS
select S.Name as [Schema], O.[Name] as [Object], TRG.Name as [Trigger] from sys.triggers TRG
	inner join sys.objects O on  O.object_id = TRG.parent_id
	inner join sys.schemas S on S.schema_id = O.schema_id
where TRG.name like 'trg_ScoreDimension_%_LootRefresh_%'
and SUBSTRING(TRG.Name, 20, 32) not in (select Replace(cast(DimensionGUID as nvarchar(36)),'-','') from ScoreDimension)
GO


---------------------------------------------

-- dbo.viewScorePlaceholderSection
CREATE view [dbo].[viewScorePlaceholderSection]
AS

select distinct
	SC.CompositeGUID as CompositeGUID,
	SG1.DimensionGUID as DIMENSIONGUID,
	SD1.FriendlyName as DIMENSIONNAME,
	SD1.SQLSchemaName as DIMENSIONSCHEMANAME,
	SD1.SQLObjectName as DIMENSIONOBJECTNAME,
	SG2.DimensionGUID as FILLINDIMGUID,
	SD2.FriendlyName as FILLINDIMNAME,
	SD2.SQLObjectName as FILLINOBJECTNAME,
	SD2.SQLSchemaName as FILLINSCHEMANAME,
	SCL.IsFixedIndex As IsFixedIndex
from dbo.ScoreComposite SC
	inner join dbo.ScoreDataTable DT1 on DT1.DataTableGUID = SC.DataTableGUID1
	inner join dbo.ScoreDataTable DT2 on DT2.DataTableGUID = SC.DataTableGUID2
	inner join dbo.ScoreCompositeLink SCL on SCL.CompositeGUID = SC.CompositeGUID
	inner join dbo.ScoreAttribute SA1 on SA1.AttributeGUID = SCL.Key1GUID
	inner join dbo.ScoreAttribute SA2 on SA2.AttributeGUID = SCL.Key2GUID
	inner join dbo.ScoreDimensionGroup SG1 on SG1.DimensionGroupGUID = SA1.DimensionGroupGUID
	inner join dbo.ScoreDimensionGroup SG2 on SG2.DimensionGroupGUID = SA2.DimensionGroupGUID
	inner join dbo.ScoreDimension SD1 on SD1.DimensionGUID = SG1.DimensionGUID
	inner join dbo.ScoreDimension SD2 on SD2.DimensionGUID = SG2.DimensionGUID
where SCL.IsPlaceholder = 1
GO


---------------------------------------------

-- dbo.viewScoreSecurityTriggers
CREATE view [dbo].[viewScoreSecurityTriggers]
AS
select 
	T.Name,
	SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80) as Definition,
	Substring(SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), 78,1) as [IsDebugOnly],
	Substring(SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), 80,1) as [IsUsingVersionColumn],
	D.FriendlyName as [SourceDimension],
	D.DimensionGUID as [SourceDimensionGUID],
	dbo.GetSQLTableExpression(D.SQLSchemaName, D.sqlobjectname) as [SourceExpression],
	DT.FriendlyName as [TargetDimension],
	DT.DimensionGUID as [TargetDimensionGUID],
	dbo.GetSQLTableExpression(DT.SQLSchemaName, DT.SQLObjectName) as [TargetExpression],
	case when
		SUM( case when(C.ColumnName = 'Version' and C.ColumnTypeValue = 189) then 1 else 0 end) = 1 then 1
		else 0
	end as [TargetHasVersionColumn]
		
from ScoreDimension D
	inner join ViewSysTriggers T on T.SchemaName = D.SQLSchemaName and T.ObjectName = D.SQLObjectName
	inner join ScoreDimension DT on REPLACE(DT.DimensionGUID,'-','') = SUBSTRING(T.Name, 20, 32)
	inner join viewSysObjects O on O.SchemaName = DT.SQLSchemaName and O.Objectname = DT.SQLObjectName
	inner join viewSysColumns C on C.SchemaName = O.SchemaName and C.ObjectName = O.Objectname
GROUP BY
	T.Name,
	SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80),
	Substring(SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), 78,1),
	Substring(SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), 80,1),
	D.FriendlyName,
	D.DimensionGUID,
	dbo.GetSQLTableExpression(D.SQLSchemaName, D.sqlobjectname),
	DT.FriendlyName,
	DT.DimensionGUID,
	dbo.GetSQLTableExpression(DT.SQLSchemaName, DT.SQLObjectName)
GO


---------------------------------------------

-- dbo.viewScoreTableEditorColumn
CREATE view viewScoreTableEditorColumn
as
	SELECT 
		[TableEditorColumnGUID]
		,[TableEditorConfigGUID]
		,[KeyGUID]
		,[Type]
		,[PixelWidth]
		,[DisplayOrder]
		,cast([MetaData] as nvarchar(max)) as MetaData
		,[DisplayName]
		,[DefaultMemberType]
		,[IsTextWrap]
		,[IsSortedByDefault]
		,[DefaultSortDirectionValue]
		,[DefaultSortIndex]
		,[TableEditorColumnGroupGUID]
		,[IsRequired]
		,[IsLocked]
		,[IsNonFilterable]
	FROM 
		[ScoreTableEditorColumn]
GO


---------------------------------------------

-- dbo.viewSecurableEntities
CREATE VIEW [dbo].[viewSecurableEntities]
AS
SELECT     PlanGUID AS ENTITYGUID, dbo.ZeroGUID() as ParentEntityGUID, dbo.GetPlanName(PlanGUID) AS NAME, 0 AS ENTITYTYPE, DateCreated
FROM         dbo.XPlan
UNION ALL
SELECT     F.FolderGuid AS ENTITYGUID, (CASE WHEN (ISDELETEDFOLDER = 1 AND BASEDONFOLDERGUID != '00000000-0000-0000-0000-000000000000') 
                      THEN BASEDONFOLDERGUID ELSE PARENTFOLDERGUID END) AS PARENTENTITYGUID, F.Name, 1 AS ENTITYTYPE, F.DateCreated
FROM         dbo.Folder AS F INNER JOIN
                      dbo.FolderSet AS FS ON F.FolderSetGUID = FS.FolderSetGUID
WHERE     (NOT (FS.Type IN (0, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)))
UNION ALL
SELECT     ListGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTENTITYGUID, Name, 2 AS ENTITYTYPE, GETDATE() AS Expr2
FROM         dbo.SecureList
WHERE     (ListType = 0) AND (IsSecured = 1)
UNION ALL
SELECT     ListMemberGUID AS ENTITYGUID, CASE WHEN (PARENTLISTMEMBERGUID = '00000000-0000-0000-0000-000000000000') 
                      THEN LISTGUID ELSE PARENTLISTMEMBERGUID END AS PARENTENTITYGUID, Name, 2 AS ENTITYTYPE, GETDATE() AS DATECREATED
FROM         dbo.SecureListMember
WHERE     (ListGUID IN
                          (SELECT     ListGUID
                            FROM          dbo.SecureList AS SecureList_1
                            WHERE      (IsSecured = 1)))
UNION ALL
SELECT     ReportGUID AS ENTITYGUID, FolderGUID AS PARENTGUID, Name, 3 AS SECURABLEENTITYTYPE, DateCreated
FROM         dbo.REReport
UNION ALL
SELECT     PlanTypeGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 4 AS SECURABLEENTITYTYPE, GETDATE() 
                      AS Expr1
FROM         dbo.PlanType
UNION ALL
SELECT     ForumGUID AS ENTITYGUID, EntityGUID AS PARENTGUID, Name, 5 AS SECURABLEENTITYTYPE, GETDATE() AS DATECREATED
FROM         dbo.MsgForum
UNION ALL
SELECT     TopicGUID AS ENTITYGUID, ForumGUID AS PARENTGUID, Name, 6 AS SECURABLEENTITYTYPE, GETDATE() AS DATECREATED
FROM         dbo.MsgTopic
UNION ALL
SELECT     SYSTEMSECTIONGUID AS ENTITYGUID, ParentGUID, Name, 7 AS SECURABLEENTITYTYPE, GETDATE() AS DATECREATED
FROM         dbo.SystemSection
UNION ALL
SELECT     FORMFIELDGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS Expr1, Name, 8 AS SECURABLEENTITYTYPE, GETDATE() 
                      AS DATECREATED
FROM         dbo.FE2FormField
UNION ALL
SELECT     PoolGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 10 AS SECURABLEENTITYTYPE, GETDATE() 
                      AS DATECREATED
FROM         dbo.OMZPool
UNION ALL
SELECT     ListInsertionPointGUID AS ENTITYGUID, ParentListMemberGUID AS PARENTGUID, Name, 11 AS SECURABLEENTITYTYPE, GETDATE() 
                      AS DATECREATED
FROM         dbo.SecureListInsertionPoint
UNION ALL
SELECT     ActionGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Description, 12 AS SECURABLEENTITYTYPE, GETDATE() 
                      AS DATECREATED
FROM         dbo.CustomAction
UNION ALL
SELECT     UserGroupGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name AS NAME, 13 AS SECURABLEENTITYTYPE, 
                      GETDATE() AS DATECREATED
FROM         dbo.UserGroup
UNION ALL
SELECT     WorkflowMapGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 14 AS SECURABLEENTITYTYPE, GETDATE() 
                      AS DATECREATED
FROM         dbo.WFWorkflowMap
UNION ALL
SELECT     IRCChatGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 15 as SECURABLEENTITYTYPE, getdate()
FROM         dbo.IRCChat
UNION ALL
SELECT     DesktopTemplateGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 16 AS SECURABLEENTITYTYPE, GETDATE() 
                      AS DATECREATED
FROM         dbo.DesktopTemplate
UNION ALL
SELECT     DimensionGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, FriendlyName, 19 as SECURABLEENTITYTYPE, getdate()
FROM         dbo.ScoreDimension
UNION ALL
SELECT     WorkflowStepGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 21 as SECURABLEENTITYTYPE, getdate()
FROM         dbo.WFWorkflowStep
UNION ALL
SELECT     DataViewGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 22 as SECURABLEENTITYTYPE, getdate()
FROM         dbo.DataView
UNION ALL
SELECT     ParameterSetGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 23 as SECURABLEENTITYTYPE, getdate()
FROM         dbo.REParameterSet
UNION ALL
SELECT     CubeGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 24 as SECURABLEENTITYTYPE, getdate()
FROM         dbo.EMFCubeStub
UNION ALL
SELECT TableEditorConfigGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, FriendlyName, 26 AS SECURABLEENTITYTYPE, GETDATE()
FROM dbo.ScoreTableEditorConfig
UNION ALL
SELECT ConfigID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 39 AS SECURABLEENTITYTYPE, GETDATE() FROM dbo.IntConfig
GO


---------------------------------------------

-- dbo.viewSecurableIdentity
--==========================================================================================

 
 CREATE VIEW [dbo].[viewSecurableIdentity]
AS
	SELECT     USERGUID AS IDENTITYGUID, NAMELAST + ', ' + NAMEFIRST AS NAME, 0 AS SECURABLEIDENTITYTYPE, IsDisabled
FROM         dbo.UserProfile
UNION ALL
SELECT     USERGROUPGUID AS IDENTITYGUID, NAME, 1 AS SECURABLEIDENTITYTYPE, 0 AS IsDisabled
FROM         dbo.UserGroup
WHERE     (TYPE = 0)
UNION ALL
SELECT     USERROLEGUID AS IDENTITYGUID, NAME, 2 AS SECURABLEIDENTITYTYPE, 0 AS IsDisabled
FROM         dbo.UserRole
GO


---------------------------------------------

-- dbo.viewSecureListMembersFlat
create view viewSecureListMembersFlat as
select 
	slm.ListGUID,
	slm.ListMemberGUID ,
	slmp1.ListMemberGUID as Parent1,
	slmp2.ListMemberGUID as Parent2,
	slmp3.ListMemberGUID as Parent3,
	slmp4.ListMemberGUID as Parent4,
	slmp5.ListMemberGUID as Parent5,
	slmp6.ListMemberGUID as Parent6,
	slmp7.ListMemberGUID as Parent7,
	slmp8.ListMemberGUID as Parent8,
	slmp9.ListMemberGUID as Parent9,
	slmp10.ListMemberGUID as Parent10,
	slmp11.ListMemberGUID as Parent11,
	slmp12.ListMemberGUID as Parent12
from 
	SecureListMember slm
	left join SecureListMember slmp1 on slm.ParentListMemberGUID = slmp1.ListMemberGUID
	left join SecureListMember slmp2 on slmp1.ParentListMemberGUID = slmp2.ListMemberGUID
	left join SecureListMember slmp3 on slmp2.ParentListMemberGUID = slmp3.ListMemberGUID
	left join SecureListMember slmp4 on slmp3.ParentListMemberGUID = slmp4.ListMemberGUID
	left join SecureListMember slmp5 on slmp4.ParentListMemberGUID = slmp5.ListMemberGUID
	left join SecureListMember slmp6 on slmp5.ParentListMemberGUID = slmp6.ListMemberGUID
	left join SecureListMember slmp7 on slmp6.ParentListMemberGUID = slmp7.ListMemberGUID
	left join SecureListMember slmp8 on slmp7.ParentListMemberGUID = slmp8.ListMemberGUID
	left join SecureListMember slmp9 on slmp8.ParentListMemberGUID = slmp9.ListMemberGUID
	left join SecureListMember slmp10 on slmp9.ParentListMemberGUID = slmp10.ListMemberGUID
	left join SecureListMember slmp11 on slmp10.ParentListMemberGUID = slmp11.ListMemberGUID
	left join SecureListMember slmp12 on slmp11.ParentListMemberGUID = slmp12.ListMemberGUID
GO


---------------------------------------------

-- dbo.viewSecureListParent
CREATE view viewSecureListParent as
SELECT
	SL.ListGUID,
	CASE WHEN SL.ListType = 1 THEN FF.FormFieldGUID
			ELSE '00000000-0000-0000-0000-000000000000'
	END as ParentEntityGUID
FROM
	SecureList SL
	LEFT JOIN FE2FormField FF ON FF.ListSourceConfig like '%' + cast(SL.ListGUID as nvarchar(36)) + '%'
GO


---------------------------------------------

-- dbo.viewSysAllObjects
CREATE VIEW [dbo].[viewSysAllObjects]
AS
select OBJ.object_id as [ObjectID], S.name as [SchemaName], OBJ.name as [ObjectName], OBJ.type_desc
 from sys.all_objects OBJ
	inner join sys.schemas S on S.schema_id = OBJ.schema_id
GO


---------------------------------------------

-- dbo.viewSysChangeTrackingTables
CREATE VIEW dbo.viewSysChangeTrackingTables
AS

SELECT
	s.Name AS SchemaName,
	t.Name AS TableName,
	p.rows AS ApproximateRowCount
FROM sys.change_tracking_tables ct
INNER JOIN sys.tables t ON ct.object_id = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN sys.partitions p ON t.object_id = p.object_id 
GROUP BY t.Name, s.Name, p.Rows
GO


---------------------------------------------

-- dbo.viewSysColumns
CREATE VIEW [dbo].[viewSysColumns]
AS
select 
    O.object_id as ObjectID,
	COL.Column_id as ColumnID,
	S.name as SchemaName,
	O.Name as ObjectName,
	COL.name as ColumnName,
	case when O.type_desc = 'VIEW' then 2 when O.type_desc = 'USER_TABLE' then 1 else 0 end as ObjectType,
	COL.max_length as MaxLength, 
	COL.is_computed as IsComputed,
	ISNULL(cast(case when COL.is_nullable is not null then COL.is_nullable else 0 end  as bit),0) as IsNullable,
	COL.scale as Scale,
	COL.Precision as Precision,
	COL.is_identity as IsIdentity,
	COL.system_type_id as ColumnTypeValue,
	cast(ISNULL(IDENT.increment_value, -1) as int) as IdentityIncrement,
	cast(ISNULL(IDENT.seed_value, -1) as int) as IdentitySeed,
	--'' as ComputedValueDefinition,
	case when DEF.definition is not null then DEF.definition else '' end as DefaultValueDefinition,
	--'' as DefaultValueDefinition,
	
	CAST(0 as bit) as IsPartOfUniqueIndex,
	CAST(0 as bit) as IsUniqueIndex,
	CAST(0 as bit) as IsPartOfPrimaryKey,
	CAST(0 as bit) as IsPrimaryKey,
	--case when COL.is_identity = 1 then cast(IDENT.increment_value as int) else -1 end as IdentityIncrement,
	--case when COL.is_identity = 1 then cast(IDENT.seed_value as int) else -1 end as IdentitySeed,
	case when COMPUTED.Definition is not null then COMPUTED.definition else '' end as ComputedValueDefinition
	
	--isnull(case when idx.is_unique_count > 0 then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as IsPartOfUniqueIndex,
	--isnull(case when idx.is_unique_count = 1 then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as IsUniqueIndex,
	--isnull(case when idx.is_unique_count > 0 then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as IsPartOfPrimaryKey,
	--isnull(case when idx.is_unique_count = 1 then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as IsPrimaryKey
	
	--fk stuff
	, CAST(0 as bit) as IsForeignKeyed
	,'' as ForeignKeySchema
	,'' as ForeignKeyTable
	,'' as ForeignKeyColumn
	,'' as ForeignKeyOnDelete
	--,isnull(case when fkc.column_id is not null then CAST(1 as bit) else CAST(0 as bit) end,cast(0 as bit)) as IsForeignKeyed,
	--ISNULL(fks.name,'') as ForeignKeySchema,
	--ISNULL(fkt.name,'') as ForeignKeyTable,
	--ISNULL(fkc.name,'') as ForeignKeyColumn,
	--ISNULL(case when fkdef.delete_referential_action_desc = 'NO_ACTION' then null else fkdef.delete_referential_action_desc end,'') as ForeignKeyOnDelete
from sys.columns COL
	inner join sys.objects O on O.object_id = COL.object_id
	inner join sys.schemas S on O.schema_id = S.schema_id
	left join sys.identity_columns IDENT on IDENT.column_id = COL.column_id and IDENT.object_id = O.object_id
	left join sys.computed_columns COMPUTED on COMPUTED.column_id = COL.column_id and COMPUTED.object_id = O.object_id
	left join sys.default_constraints DEF on DEF.parent_object_id = O.object_id and DEF.parent_column_id = COL.column_id
	
	--m2m
	--LEFT join (
	--	select
	--		IND_COL.object_id,
	--		IND_COL.column_id,
	--		sum(CASE WHEN IND.is_unique = 1 then 1 else 0 end) as is_unique_count,
	--		sum(CASE WHEN IND.is_primary_key = 1 then 1 else 0 end) as is_primary_key_count
	--	from
	--		sys.index_columns IND_COL 
	--		inner join sys.indexes IND on IND.object_id = IND_COL.object_id and IND.index_id = IND_COL.index_id
	--	group by
	--		IND_COL.object_id,
	--		IND_COL.column_id		
	--) idx on idx.column_id = COL.column_id and idx.object_id = O.object_id
	
	
	--FK stuff
	--left join sys.foreign_key_columns fk on COL.column_id = fk.parent_column_id and COL.object_id = fk.parent_object_id
	--left join sys.columns fkc on fk.referenced_column_id = fkc.column_id and fk.referenced_object_id = fkc.object_id
	--left join sys.tables fkt on fkc.object_id = fkt.object_id
	--left join sys.schemas fks on fkt.schema_id = fks.schema_id
	--left join sys.foreign_keys fkdef on fk.constraint_object_id = fkdef.object_id
--where
--	--replace(replace(replace('[{0}].[{1}].[{2}]','{0}', s.name),'{1}', o.name),'{2}', col.name) = '[dbo].[zzviewModelTemplateMapping_GJFModeling].[IsUserMapped]'
--	--s.name + '-' + o.name + '-' + col.name = 'dbo-zzviewModelTemplateMapping_GJFModeling-IsUserMapped'
--	s.name = 'dbo'
--	and o.name = 'zzviewModelTemplateMapping_GJFModeling'
--	and col.name = 'IsUserMapped'
	
--GROUP BY
--	dbo.IntToGUID(O.object_id), O.object_id, COL.object_id, COL.Column_ID, S.name, O.name, O.type_desc, COL.name, COL.max_length, COL.is_computed, COL.is_nullable, COL.scale,COL.precision, COL.is_identity, 
--	COL.system_type_id
GO


---------------------------------------------

-- dbo.viewSysForeignKeys
CREATE VIEW [dbo].[viewSysForeignKeys]
AS
SELECT 
	FK_Schema = FK.TABLE_SCHEMA,
    FK_Table  = FK.TABLE_NAME, 
    FK_Column = CU.COLUMN_NAME, 
    PK_Schema = PK.TABLE_SCHEMA,
    PK_Table  = PK.TABLE_NAME, 
    PK_Column = PT.COLUMN_NAME, 
    Constraint_Name = C.CONSTRAINT_NAME 
FROM 
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C 
    INNER JOIN 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK 
        ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
    INNER JOIN 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK 
        ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME 
    INNER JOIN 
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU 
        ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME 
    INNER JOIN 
    ( 
        SELECT 
            i1.TABLE_NAME, i2.COLUMN_NAME 
        FROM 
            INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 
            INNER JOIN 
            INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 
            ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
            WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' 
    ) PT 
    ON PT.TABLE_NAME = PK.TABLE_NAME
GO


---------------------------------------------

-- dbo.viewSysFunctionParameters
CREATE VIEW [dbo].[viewSysFunctionParameters]
AS
select 
	S.name as [SchemaName],
	F.name as [ObjectName],
	F.is_ms_shipped as [IsMSShipped],
	F.create_date as [CreationDate], 
	case when F.type = 'FN' then 'Scalar' when f.type='TF' then 'TableValued' end as [FunctionType],
	PM.name as [ParameterName],
	PM.max_length as [MaxLength],
	PM.precision as [Precision],
	PM.scale as [Scale],
	PM.is_output as [IsOutput],
	PM.system_type_id as [DataType]
from sys.all_objects F
	inner join sys.schemas S on S.schema_id = F.schema_id
	inner join sys.parameters PM on PM.object_id = F.object_id
where F.type = 'FN' or F.type = 'TF'
GO


---------------------------------------------

-- dbo.viewSysIndexColumns
CREATE VIEW [dbo].[viewSysIndexColumns]
AS
select S.name as SchemaName, O.name as ObjectName, 
    COL.name as ColumnName,
    IND.index_id as IndexID,
    INDC.is_included_column as IsIncludedColumn,
    INDC.index_column_id as ColumnOrder,
	INDC.is_descending_key as IsDescending,
	COL.max_length as MaxLength, 
	COL.is_computed as IsComputed,
	COL.is_nullable as IsNullable,
	COL.scale as Scale,
	COL.Precision as Precision,
	COL.is_identity as IsIdentity,
	COL.system_type_id as ColumnType,
	case when COL.is_identity = 1 then cast(IDENT.increment_value as int) else -1 end as IncrementValue,
	case when COL.is_identity = 1 then cast(IDENT.seed_value as int) else -1 end as SeedValue,
	case when COMPUTED.Definition is not null then COMPUTED.definition else '' end as ComputedDefinition,
	case when DEF.definition is not null then DEF.definition else '' end as DefaultValue
	from sys.indexes IND
	inner join sys.objects O on O.object_id = IND.object_id
	inner join sys.schemas S on S.schema_id = O.schema_id
	inner join sys.index_columns INDC on INDC.index_id = IND.index_id and INDC.object_id = IND.object_id
	inner join sys.columns COL on COL.column_id = INDC.column_id and COL.object_id = INDC.object_id
	left join sys.identity_columns IDENT on IDENT.column_id = COL.column_id and IDENT.object_id = O.object_id
	left join sys.computed_columns COMPUTED on COMPUTED.column_id = COL.column_id and COMPUTED.object_id = O.object_id
	left join sys.default_constraints DEF on DEF.parent_object_id = O.object_id and DEF.parent_column_id = COL.column_id
GO


---------------------------------------------

-- dbo.viewSysIndexDefinitions
--Forward
create view dbo.viewSysIndexDefinitions
as
	WITH indexCTE AS
	(
		SELECT DISTINCT 
			i.index_id, i.name, i.object_id, i.is_primary_key
		FROM 
			sys.indexes i 
			INNER JOIN sys.index_columns ic ON i.index_id = ic.index_id AND i.object_id = ic.object_id
	), 
	indexCTE2 AS
	(
		SELECT 
			cte.name as IndexName, 
			OBJECT_NAME(cte.object_ID) as ObjectName,
			s.name as SchemaName,
			CASE 
				cte.index_id 
				WHEN 1 THEN 'CLUSTERED'
				ELSE 'NONCLUSTERED'
				END AS IndexType, 
			(
				SELECT DISTINCT c.name + ','
				FROM 
					sys.columns c 
					INNER JOIN sys.index_columns ic on c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 0
				WHERE
					cte.OBJECT_ID = ic.object_id 
					AND cte.index_id = ic.index_id 
				FOR XML PATH('')) as ixcols,
			ISNULL((
				SELECT DISTINCT c.name + ','
				FROM 
					sys.columns c 
					INNER JOIN sys.index_columns ic ON c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 1
				WHERE
					cte.OBJECT_ID = ic.object_id 
					AND cte.index_id = ic.index_id 
				FOR XML PATH('')), '') as includedcols,
			cte.is_primary_key as IsPrimaryKey
		FROM 
			indexCTE cte
			inner join sys.tables t on t.object_id = cte.object_id
			inner join sys.schemas s on s.schema_id = t.schema_id
	) 
	SELECT 
		SchemaName,
		ObjectName,
		IndexName,
		IsPrimaryKey,
		'CREATE ' + IndexType + ' INDEX ' + IndexName + ' ON ' + SchemaName + '.' + ObjectName + '(' + SUBSTRING(ixcols, 1, LEN(ixcols)-1) + CASE LEN(includedcols) WHEN 0 THEN ')' ELSE ') INCLUDE (' + SUBSTRING(includedcols, 1, LEN(includedcols)-1) + ')' END as IndexScript
	FROM 
	   indexCTE2
GO


---------------------------------------------

-- dbo.viewSysIndexes
CREATE VIEW [dbo].[viewSysIndexes]
AS
select 
	S.name as [SchemaName], 
	O.name as [ObjectName], 
	IND.index_id as [IndexID],
	IND.name as [Name],
	IND.type_desc as [Description],
	IND.is_unique as [IsUnique],
	IND.is_primary_key as [IsPrimaryKey]
from sys.indexes IND
	inner join sys.objects O on O.object_id = IND.object_id
	inner join sys.schemas S on S.schema_id = O.schema_id
GO


---------------------------------------------

-- dbo.viewSysObjects
CREATE VIEW [dbo].[viewSysObjects]
AS
select
	S.name + '.' + O.name as SQLObjectExpression,
	S.name as SchemaName,
	O.name as ObjectName,
	isnull(case when O.type_desc = 'VIEW' then CAST(1 as bit) else CAST(0 as bit) end, CAST(1 as bit)) as IsView
from sys.objects O
	inner join sys.schemas S on S.schema_id = O.schema_id
where O.type_desc = 'USER_TABLE' OR O.type_desc = 'VIEW'
GO


---------------------------------------------

-- dbo.viewSysProcParameters
CREATE VIEW [dbo].[viewSysProcParameters]
AS
SELECT S.NAME AS [SchemaName]
	,P.NAME AS [ObjectName]
	,dbo.StripNewLine(SUBSTRING(SUBSTRING(M.DEFINITION, PATINDEX('%CREATE PROC%', M.DEFINITION), LEN(M.DEFINITION)), 1, PATINDEX('%[^a-Z]AS%', SUBSTRING(M.DEFINITION, PATINDEX('%CREATE PROC%', M.DEFINITION), LEN(M.DEFINITION))) - 1)) AS [Comments]
	,SUBSTRING(M.DEFINITION, CHARINDEX('CREATE PROC', M.DEFINITION), LEN(M.DEFINITION)) AS [Definition]
	,P.is_ms_shipped AS [IsMSShipped]
	,P.create_date AS [CreationDate]
	,PM.NAME AS [ParameterName]
	,PM.max_length AS [MaxLength]
	,PM.precision AS [Precision]
	,PM.scale AS [Scale]
	,PM.is_output AS [IsOutput]
	,PM.system_type_id AS [DataType]
	,PM.user_type_id AS [UserType]
FROM sys.procedures P
INNER JOIN sys.parameters PM ON P.object_id = PM.object_id
INNER JOIN sys.schemas S ON S.schema_id = P.schema_id
INNER JOIN sys.sql_modules M ON M.object_id = P.object_id
GO


---------------------------------------------

-- dbo.viewSysProcWithParameters
CREATE VIEW [dbo].[viewSysProcWithParameters]
AS
SELECT P.SchemaName
	,P.ObjectName
	,ISNULL(PM.Comments, '') AS [Comments]
	,ISNULL(PM.DEFINITION, SUBSTRING(M.DEFINITION, CHARINDEX('CREATE PROC', M.DEFINITION), LEN(M.DEFINITION))) + '' AS [Definition]
	,ISNULL(PM.IsMSShipped, 0) AS [IsMSShipped]
	,ISNULL(PM.CreationDate, GETDATE()) AS [CreationDate]
	,ISNULL(PM.ParameterName, '') AS [ParameterName]
	,ISNULL(PM.MaxLength, 0) AS [MaxLength]
	,ISNULL(PM.Precision, 0) AS [Precision]
	,ISNULL(PM.Scale, 0) AS [Scale]
	,ISNULL(PM.DataType, 0) AS [DataType]
	,ISNULL(PM.UserType, 0) AS [UserType]
	,ISNULL(PM.IsOutput, 0) AS [IsOutput]
	,ISNULL(SUBSTRING(PM.ParameterName, 2, Len(ParameterName)), '') AS [ArgumentName]
FROM viewSysProcedures P
INNER JOIN sys.sql_modules M ON M.object_id = P.object_id
LEFT JOIN viewsysprocparameters PM ON P.ObjectName = PM.ObjectName
	AND p.SchemaName = PM.SchemaName
GO


---------------------------------------------

-- dbo.viewSysProcedures
CREATE VIEW [dbo].[viewSysProcedures]
AS
select S.name as [SchemaName], PR.name as [ObjectName], PR.object_id
 from sys.procedures PR
	inner join sys.schemas S on S.schema_id = PR.schema_id
GO


---------------------------------------------

-- dbo.viewSysViewBaseTables
CREATE view [dbo].[viewSysViewBaseTables]
AS


WITH TBLS (ViewSchema, ViewName, TableSchema, TableName, TableType, [Level])
AS
(
    select 
		U.VIEW_SCHEMA 
		,U.VIEW_NAME 
		,U.TABLE_SCHEMA 
		,U.TABLE_NAME
		,T.TABLE_TYPE
		,0		
	from INFORMATION_SCHEMA.VIEW_TABLE_USAGE U
		inner join INFORMATION_SCHEMA.TABLES T on T.TABLE_CATALOG = U.TABLE_CATALOG and T.TABLE_SCHEMA = U.TABLE_SCHEMA and T.TABLE_NAME = U.TABLE_NAME
	where (U.VIEW_NAME <> U.TABLE_NAME or (U.VIEW_SCHEMA <> U.TABLE_SCHEMA and U.VIEW_NAME = U.TABLE_NAME))
    UNION ALL
    select 
		ANCHOR.ViewSchema
		,ANCHOR.ViewName
		,REC.TABLE_SCHEMA
		,REC.TABLE_NAME
		,T.TABLE_TYPE
		,[Level] + 1 
	from INFORMATION_SCHEMA.VIEW_TABLE_USAGE REC
		inner join TBLS ANCHOR on ANCHOR.TableName = REC.VIEW_NAME and ANCHOR.TableSchema = REC.VIEW_SCHEMA 
		inner join INFORMATION_SCHEMA.TABLES T on T.TABLE_CATALOG = REC.TABLE_CATALOG and T.TABLE_SCHEMA = REC.TABLE_SCHEMA and T.TABLE_NAME = REC.TABLE_NAME
		where (REC.VIEW_NAME <> REC.TABLE_NAME or (REC.VIEW_SCHEMA <> REC.TABLE_SCHEMA and REC.VIEW_NAME = REC.TABLE_NAME))
)		
SELECT   
  ViewSchema, ViewName, TableSchema, TableName, TableType, MIN(LEVEL) as [Level]
FROM TBLS 
 group by ViewSchema, ViewName, TableSchema, TableName, TableType
GO


---------------------------------------------

-- dbo.viewSystemCenterStep
create view dbo.viewSystemCenterStep
as
select
	s.Name as Solution,
	m.Name as Module,
	c.Name as Category,
	sc.Name as Section,
	s.*
from
	SystemCenterStep s
	inner join SystemCenterSection sc on sc.SectionGUID = s.SectionGUID
	inner join SystemCenterCategory c on c.CategoryGUID = sc.CategoryGUID
	inner join SystemCenterModule m on m.ModuleGUID = c.ModuleGUID
	inner join SystemCenterSolution sl on sl.SolutionGUID = m.SolutionGUID
GO


---------------------------------------------

-- dbo.viewSystemSectionFlat
CREATE view [dbo].[viewSystemSectionFlat] as
		select 
			ss1.SYSTEMSECTIONGUID as ss1, 
			ss2.SYSTEMSECTIONGUID as ss2, 
			ss3.SYSTEMSECTIONGUID as ss3, 
			ss4.SYSTEMSECTIONGUID as ss4, 
			ss5.SYSTEMSECTIONGUID as ss5, 
			ss6.SYSTEMSECTIONGUID as ss6
		from 
			SystemSection ss1
			left join SystemSection ss2 on ss1.ParentGUID = ss2.SYSTEMSECTIONGUID
			left join SystemSection ss3 on ss2.ParentGUID = ss3.SYSTEMSECTIONGUID
			left join SystemSection ss4 on ss3.ParentGUID = ss4.SYSTEMSECTIONGUID
			left join SystemSection ss5 on ss4.ParentGUID = ss5.SYSTEMSECTIONGUID
			left join SystemSection ss6 on ss5.ParentGUID = ss6.SYSTEMSECTIONGUID
GO


---------------------------------------------

-- dbo.viewTemplateSectionCounts
CREATE VIEW [dbo].[viewTemplateSectionCounts]
AS
WITH 
actualFillinCountByMainTemplate AS (
    SELECT
        COALESCE(SEP.[ParentModelTemplateGUID], P.[ModelTemplateGUID]) AS [ModelTemplateGUID],
        SF.[ModelGUID],
        SF.[PlaceholderSectionMemberGUID],
        COUNT(SF.[FillinGUID]) AS [Total]
    FROM [dbo].[ScoreFillin] AS SF
        INNER JOIN [dbo].[XPlan] AS P
            ON P.[PlanGUID] = SF.[ModelGUID]
        LEFT JOIN [dbo].[MEScoreExpansionProfile] AS SEP
            ON SEP.[ChildModelTemplateGUID] = P.[ModelTemplateGUID]   
    GROUP BY COALESCE(SEP.[ParentModelTemplateGUID], P.[ModelTemplateGUID]), SF.[ModelGUID], SF.[PlaceholderSectionMemberGUID]
)
SELECT
    TS.[TemplateGUID] AS [TemplateGUID],
    PH.[FriendlyName] AS [SectionName],
    TS.[SettingID],
    COALESCE(MAX(FC.[Total]), 0) AS [ActualMaxNumberOfFillins],
    COALESCE(MAX(TS.[Value]), 0) AS [ActualSectionCount]
FROM [dbo].[TemplateSettings] AS TS 
    INNER JOIN [dbo].[MEPHSection] AS PH
        ON TS.[TemplateGUID] = PH.[ModelTemplateGUID] AND PH.[FriendlyName] = SUBSTRING(TS.[SettingID], 18, LEN(TS.[SettingID]))
    LEFT JOIN actualFillinCountByMainTemplate AS FC
        ON FC.[PlaceholderSectionMemberGUID] = PH.[PHSectionMemberGUID] AND FC.[ModelTemplateGUID] = TS.[TemplateGUID]
WHERE 1=1
    AND TS.[SettingID] LIKE 'Section Counts%'
GROUP BY TS.[TemplateGUID], PH.[FriendlyName], TS.[SettingID]
GO


---------------------------------------------

-- dbo.viewTemplateSectionCountsWithRecommended
CREATE VIEW [dbo].[viewTemplateSectionCountsWithRecommended]
AS
SELECT
    SC.[TemplateGUID],
    SC.[SectionName],
    SC.[SettingID],
    SC.[ActualMaxNumberOfFillins],
    SC.[ActualSectionCount],
    SC.[ActualMaxNumberOfFillins] + 10 AS [RecommendedSectionCount]
FROM [dbo].[viewTemplateSectionCounts] AS SC
GO


---------------------------------------------

-- dbo.viewUpgradeDate
--Forward
create view viewUpgradeDate
as
	select 
		[Version], 
		MIN(LogDate) UpgradeDate
	from 
		UpgradeLog
	group by
		[Version]
GO


---------------------------------------------

-- dbo.viewUserLimit_UnassignedUsers
CREATE view viewUserLimit_UnassignedUsers as
select * 
from 
      UserProfile (Nolock)
where
      UserGUID not in (select UserGUID from UserTag)
GO


---------------------------------------------

-- dbo.viewUserLoginHistory
CREATE VIEW [dbo].[viewUserLoginHistory] AS
	SELECT up.UserGUID, up.namefirst + ' ' + up.namelast AS Name, MAX(loginstamp) AS LastLogin, MIN(loginstamp) AS FirstLogin, COUNT(*) AS NumLogins 
	FROM loginhistory lh (READUNCOMMITTED) INNER JOIN userprofile up (READUNCOMMITTED)
	ON lh.userguid = up.userguid
	GROUP BY up.UserGUID, up.namefirst + ' ' + up.namelast
GO


---------------------------------------------

-- dbo.viewWFChangeHistory
CREATE view [dbo].[viewWFChangeHistory]  as 
select WFM.Name as WORKFLOWNAME, U.UserName as MODIFIER, H.*  from HistoryItem H 
inner join WFWorkFlowMap WFM on H.OBJECTGUID = WFM.WorkFlowMapGUID
left join UserProfile U on H.ModifierUserGUID = U.UserGUID
GO


---------------------------------------------

-- dbo.viewWFEntity
CREATE VIEW [dbo].[viewWFEntity]
  WITH SCHEMABINDING
  AS
    SELECT
      PlanGUID AS EntityGUID,
      Name     AS EntityName,
      PlanTypeGUID,
      CachedLootID,
      AuthorUserGUID
    FROM [dbo].[XPlan]
    WHERE PlanTypeGUID <> '2898A6EB-3CAE-47D9-AF28-FC959F1E3955' -- Substitution Plan Type GUID
      AND IsDeletedPlan = 0
    UNION ALL
    SELECT
      MemberGUID                             AS EntityGUID,
      COALESCE(xplan.Name, NameCalc)         AS EntityName,
      '2898A6EB-3CAE-47D9-AF28-FC959F1E3955' AS PlanTypeGUID, -- Substitution Plan Type GUID
      'P|' + CONVERT(VARCHAR, [LootID])      AS CachedLootID,
      AuthorGUID                             AS AuthorUserGUID
    FROM [cap].[DimSubstitution] substitution
      LEFT JOIN [dbo].[XPlan] xplan ON xplan.PlanGUID = substitution.MemberGUID
    WHERE xplan.IsDeletedPlan = 0 OR xplan.IsDeletedPlan IS NULL
GO


---------------------------------------------

-- dbo.viewWFMissingReviewerPermissions
--Forward
CREATE view [dbo].[viewWFMissingReviewerPermissions]
as
	--permissions for plan type's permission set
	select distinct
		S.WorkflowMapGUID,
		PS.PermissionSetID,
		UR.RoleID,
		0 as [Weight],
		null as ReadValue,
		null as WriteValue,
		null as SecureValue,
		null as CreateValue,
		null as DeleteValue
	from
		WFReviewerAssignment RA
		inner join WFWorkflowStep S on S.WorkflowStepGUID = RA.WorkflowStepGUID
		inner join UserRole UR on UR.UserRoleGUID = RA.IdentityGUID
		inner join PlanTypeWorkflowMapLink L on L.WorkflowMapGUID = S.WorkflowMapGUID
		inner join PlanType PT on PT.PlanTypeGUID = L.PlanTypeGUID
		inner join ScoreDimension D on D.DimensionGUID = PT.DimensionGUID and D.IsSecured = 1
		inner join S3PermissionSet PS on PS.PermissionSetID = D.PermissionSetID
	where
		not exists(select 1 from S3Permission P where P.PermissionSetID = PS.PermissionSetID and P.RoleID = UR.RoleID)
		and PS.IsLocked = 0
	union all
	--permission for any parent dimensions of plan dimension
	select distinct
		S.WorkflowMapGUID,
		PS.PermissionSetID,
		UR.RoleID,
		0 as [Weight],
		null as ReadValue,
		null as WriteValue,
		null as SecureValue,
		null as CreateValue,
		null as DeleteValue
	from
		WFReviewerAssignment RA
		inner join WFWorkflowStep S on S.WorkflowStepGUID = RA.WorkflowStepGUID
		inner join UserRole UR on UR.UserRoleGUID = RA.IdentityGUID
		inner join PlanTypeWorkflowMapLink L on L.WorkflowMapGUID = S.WorkflowMapGUID
		inner join PlanType PT on PT.PlanTypeGUID = L.PlanTypeGUID
		inner join ScoreDimension D on D.DimensionGUID = PT.DimensionGUID and D.IsSecured = 1
		inner join viewScoreAttribute A on A.DimensionGUID = D.DimensionGUID and A.IsSecuredLootGroupID = 1
		inner join viewScoreAttribute FKA on FKA.AttributeGUID = A.ForeignKeyGUID
		inner join ScoreDimension FKD on FKD.DimensionGUID = FKA.DimensionGUID and FKD.IsSecured = 1
		inner join S3PermissionSet PS on PS.PermissionSetID = FKD.PermissionSetID and PS.PermissionSetID != D.PermissionSetID
	where
		not exists(select 1 from S3Permission P where P.PermissionSetID = PS.PermissionSetID and P.RoleID = UR.RoleID)
		and PS.IsLocked = 0
GO


---------------------------------------------

-- dbo.viewWFObjectsByFolder
CREATE view [dbo].[viewWFObjectsByFolder]
as
	--workflows
	select WF.WorkflowMapGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFWorkflowMap WF
	union all
	--phases
	select P.ProcessGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from  WFProcess P inner join WFWorkflowMap WF on WF.WorkflowMapGUID = P.WORKFLOWMAPGUID
	union all
	--steps
	select S.WorkflowStepGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from  WFWorkflowStep S inner join WFWorkflowMap WF on  WF.WorkflowMapGUID = S.WORKFLOWMAPGUID
	union all
	--process-step links
	select L.PROCESSSTEPLINKGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFProcessStepLink L inner join WFWorkflowMap WF on WF.WorkflowMapGUID = L.WORKFLOWMAPGUID
	union all
	--transitions
	select T.TRANSITIONGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFTransition T inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WORKFLOWMAPGUID
	union all
	--step reviewers
	select RA.REVIEWERASSIGNMENTGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFReviewerAssignment RA inner join WFWorkflowStep S on S.WorkflowStepGUID = RA.WORKFLOWSTEPGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID
	union all
	--step review values
	select RVT.STEPREVIEWVALUETYPELINKGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFStepReviewValueTypeLink RVT inner join WFWorkflowStep S on S.WorkflowStepGUID = RVT.WORKFLOWSTEPGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID
	union all
	--step events
	select EP.EVENTPLANGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFEventPlan EP inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID
	union all
	--transition events
	select EP.EVENTPLANGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFEventPlan EP inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID
	union all
	--step event statements
	select EPS.EventPlanStatementGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFEventPlanStatement EPS inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID
	union all
	--transition event statements
	select EPS.EventPlanStatementGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFEventPlanStatement EPS inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID
	union all
	--exit conditionsets
	select CS.ConditionSetGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFConditionSet CS inner join WFTransition T on T.CONDITIONSETGUID = CS.CONDITIONSETGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WORKFLOWMAPGUID
	union all
	--qualification conditionsets
	select CS.ConditionSetGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFConditionSet CS inner join WFWorkflowStep S on S.QualifyConditionSetGUID = CS.CONDITIONSETGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID
	union all
	--step event conditionsets
	select CS.ConditionSetGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFConditionSet CS inner join WFEventPlanStatement EPS on EPS.StatementGUID = CS.CONDITIONSETGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID
	union all
	--transition event conditionsets
	select CS.ConditionSetGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFConditionSet CS inner join WFEventPlanStatement EPS on EPS.StatementGUID = CS.CONDITIONSETGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID
	union all
	--exit conditions
	select C.ConditionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFCondition C inner join WFConditionSet CS on CS.CONDITIONSETGUID = C.ConditionSetGUID inner join WFTransition T on T.CONDITIONSETGUID = CS.CONDITIONSETGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WORKFLOWMAPGUID
	union all
	--qualification conditions
	select C.ConditionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFCondition C inner join WFConditionSet CS on CS.CONDITIONSETGUID = C.ConditionSetGUID inner join WFWorkflowStep S on S.QualifyConditionSetGUID = CS.CONDITIONSETGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID
	union all
	--step event conditions
	select C.ConditionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFCondition C inner join WFConditionSet CS on CS.CONDITIONSETGUID = C.ConditionSetGUID inner join WFEventPlanStatement EPS on EPS.StatementGUID = CS.CONDITIONSETGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID
	union all
	--transition event conditions
	select C.ConditionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFCondition C inner join WFConditionSet CS on CS.CONDITIONSETGUID = C.ConditionSetGUID inner join WFEventPlanStatement EPS on EPS.StatementGUID = CS.CONDITIONSETGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID
	union all
	--step event actions
	select CA.ActionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from CustomAction CA inner join WFEventPlanStatement EPS on EPS.StatementGUID = CA.ActionGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID where CA.ActionType = 1
	union all
	--transition event actions
	select CA.ActionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from CustomAction CA inner join WFEventPlanStatement EPS on EPS.StatementGUID = CA.ActionGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID where CA.ActionType = 1
GO


---------------------------------------------

-- dbo.viewWFOverdueReviewLogToday
create view dbo.viewWFOverdueReviewLogToday
as
select * from [dbo].[WFOverdueReviewLog] where DateTimeStamp >= getdate() - 1
GO


---------------------------------------------

-- dbo.viewWFOverdueReviews
CREATE view [dbo].[viewWFOverdueReviews]
as
	select distinct
		R.PlanGUID,
		R.UserGUID,
		R.WorkflowStepGUID,
		S.WorkflowMapGUID
	from
		viewWFReviewerAssignment R
		inner join WFToken T (readuncommitted) on T.WorkflowStepGUID = R.WorkflowStepGUID and T.EntityGUID = R.PlanGUID
		inner join WFWorkflowStep S (readuncommitted) on S.WorkflowStepGUID = R.WorkflowStepGUID
		inner join dbo.viewWFEntity E on E.EntityGUID = R.PlanGUID
	where
		S.ReminderDaysThreshold > 0
		and S.ReminderDaysThreshold <= (select DATEDIFF(day, MAX(H.DateTimeStamp), GETDATE()) from WFHistory H (readuncommitted) where H.HistoryType = 1 and H.EntityGUID = R.PlanGUID and H.WorkflowStepGUID = R.WorkflowStepGUID)
		and not exists(select 1 from [dbo].[WFReviewValue] rv (readuncommitted) where rv.WorkflowStepGUID = S.WorkflowStepGUID and rv.IdentityGUID = R.UserGUID and rv.EntityGUID = E.EntityGUID)
GO


---------------------------------------------

-- dbo.viewWFReviewerAssignment
CREATE view [dbo].[viewWFReviewerAssignment]
as
	--NOTE: results may not be distinct, so this is best used within an exists clause

	select
		E.EntityGUID as PlanGUID,
		RA.WorkflowStepGUID,
		isnull(RD.DelegateUserGUID, UP.UserGUID) as UserGUID
	from
		viewWFEntity E (readuncommitted)
		inner join S3Loot L (readuncommitted) on L.LootID = E.CachedLootID
		inner join WFToken T (readuncommitted) on T.ENTITYGUID = E.EntityGUID
		inner join WFWorkflowStep WFS (readuncommitted) on WFS.WorkflowMapGUID = T.WorkflowMapGUID
		inner join WFReviewerAssignment RA (readuncommitted) on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID
			
		inner join S3IdentityLink sIL (readuncommitted) on sIL.GroupingGUID = RA.IdentityGUID
			
		inner join UserProfile UP (readuncommitted) on UP.UserGUID = sIL.MemberGUID
		left join WFReviewerDelegate RD (readuncommitted) on RD.WorkflowStepGUID = RA.WorkflowStepGUID and RD.EntityGUID = E.EntityGUID and RD.ReviewerUserGUID = UP.UserGUID
			
	union all
		
	select
		E.EntityGUID as PlanGUID,
		RA.WorkflowStepGUID,
		isnull(RD.DelegateUserGUID, UP.UserGUID) as UserGUID
	from
		viewWFEntity E (readuncommitted)
		inner join S3Loot L (readuncommitted) on L.LootID = E.CachedLootID
		inner join WFToken T (readuncommitted) on T.ENTITYGUID = E.EntityGUID
		inner join WFWorkflowStep WFS (readuncommitted) on WFS.WorkflowMapGUID = T.WorkflowMapGUID
		inner join WFReviewerAssignment RA (readuncommitted) on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID
	
		inner join S3LootGroup sLG (readuncommitted) on sLG.LootID = L.LootID
		inner join UserRole sR (readuncommitted) on sR.UserRoleGUID = RA.IdentityGUID
		inner join S3RoleAssignment sRA (readuncommitted) on sRA.LootGroupID = sLG.LootGroupID and sR.RoleID = sRA.RoleID
	
		inner join UserProfile UP (readuncommitted) on UP.UserGUID = sRA.IdentityGUID
		left join WFReviewerDelegate RD (readuncommitted) on RD.WorkflowStepGUID = RA.WorkflowStepGUID and RD.EntityGUID = E.EntityGUID and RD.ReviewerUserGUID = UP.UserGUID
	
	union all
		
	select
		E.EntityGUID as PlanGUID,
		RA.WorkflowStepGUID,
		isnull(RD.DelegateUserGUID, UP.UserGUID) as UserGUID
	from
		viewWFEntity E (readuncommitted)
		inner join S3Loot L (readuncommitted) on L.LootID = E.CachedLootID
		inner join WFToken T (readuncommitted) on T.ENTITYGUID = E.EntityGUID
		inner join WFWorkflowStep WFS (readuncommitted) on WFS.WorkflowMapGUID = T.WorkflowMapGUID
		inner join WFReviewerAssignment RA (readuncommitted) on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID
	
		inner join S3LootGroup sLG (readuncommitted) on sLG.LootID = L.LootID
		inner join UserRole sR (readuncommitted) on sR.UserRoleGUID = RA.IdentityGUID
		inner join S3RoleAssignment sRA (readuncommitted) on sRA.LootGroupID = sLG.LootGroupID and sR.RoleID = sRA.RoleID
		inner join S3IdentityLink sIL (readuncommitted) on sIL.GroupingGUID = sRA.IdentityGUID
	
		inner join UserProfile UP (readuncommitted) on UP.UserGUID = sIL.MemberGUID
		left join WFReviewerDelegate RD (readuncommitted) on RD.WorkflowStepGUID = RA.WorkflowStepGUID and RD.EntityGUID = E.EntityGUID and RD.ReviewerUserGUID = UP.UserGUID
GO


---------------------------------------------

-- dbo.viewWFReviewerAssignmentIndexedAll
CREATE view [dbo].[viewWFReviewerAssignmentIndexedAll]
as
	--NOTE: results may not be distinct, so this is best used within an exists clause

	SELECT 
		OBJ.PlanGUID,
		OBJ.WorkflowStepGUID,
		OBJ.UserGUID
	FROM
		dbo.viewWFReviewerAssignmentIndexedByGroup OBJ (readuncommitted)
	               
	union    
	                
	SELECT 
		OBJ.PlanGUID,
		OBJ.WorkflowStepGUID,
		OBJ.UserGUID
	FROM
	   dbo.viewWFReviewerAssignmentIndexedByRole OBJ (readuncommitted)
	                                   
	union
	                    
	SELECT 
		OBJ.PlanGUID,
		OBJ.WorkflowStepGUID,
		OBJ.UserGUID
	FROM
		dbo.viewWFReviewerAssignmentIndexedByRoleGroup OBJ (readuncommitted)
GO


---------------------------------------------

-- dbo.viewWFReviewerAssignmentIndexedByGroup
CREATE view [dbo].[viewWFReviewerAssignmentIndexedByGroup]
as
	select
		RA.PlanGUID,
		RA.WorkflowStepGUID,
		coalesce(D.DelegateUserGUID, RA.UserGUID) as UserGUID
	from
		viewWFReviewerAssignmentNoDelegatesByGroup RA with (noexpand)
		left join WFReviewerDelegate D (readuncommitted) on D.ReviewerUserGUID = RA.UserGUID and D.WorkflowStepGUID = RA.WorkflowStepGUID and D.EntityGUID = RA.PlanGUID
GO


---------------------------------------------

-- dbo.viewWFReviewerAssignmentIndexedByRole
CREATE view [dbo].[viewWFReviewerAssignmentIndexedByRole]
as
	select
		RA.PlanGUID,
		RA.WorkflowStepGUID,
		coalesce(D.DelegateUserGUID, RA.UserGUID) as UserGUID
	from
		viewWFReviewerAssignmentNoDelegatesByRole RA with (noexpand)
		left join WFReviewerDelegate D (readuncommitted) on D.ReviewerUserGUID = RA.UserGUID and D.WorkflowStepGUID = RA.WorkflowStepGUID and D.EntityGUID = RA.PlanGUID
GO


---------------------------------------------

-- dbo.viewWFReviewerAssignmentIndexedByRoleGroup
--Author: gforeman
--Branch: Firefly
--Forward
create view [dbo].[viewWFReviewerAssignmentIndexedByRoleGroup]
as
	select
		RA.PlanGUID,
		RA.WorkflowStepGUID,
		coalesce(D.DelegateUserGUID, RA.UserGUID) as UserGUID
	from
		viewWFReviewerAssignmentNoDelegatesByRoleGroup RA with (noexpand)
		left join WFReviewerDelegate D (readuncommitted) on D.ReviewerUserGUID = RA.UserGUID and D.WorkflowStepGUID = RA.WorkflowStepGUID and D.EntityGUID = RA.PlanGUID
GO


---------------------------------------------

-- dbo.viewWFReviewerAssignmentNoDelegatesByGroup
CREATE view [dbo].[viewWFReviewerAssignmentNoDelegatesByGroup] with schemabinding
as
	--NOTE: results may not be distinct, so this is best used within an exists clause

	select
		T.EntityGUID as PlanGUID,
		WFS.WorkflowStepGUID,
		sIL.MemberGUID as UserGUID,
		COUNT_BIG(*) as Cnt
	from
		dbo.WFToken T
		inner join dbo.WFWorkflowStep WFS on WFS.WorkflowMapGUID = T.WorkflowMapGUID
		inner join dbo.WFReviewerAssignment RA on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID
		inner join dbo.S3IdentityLink sIL on sIL.GroupingGUID = RA.IdentityGUID
	group by
		T.EntityGUID,
		WFS.WorkflowStepGUID,
		sIL.MemberGUID
GO


---------------------------------------------

-- dbo.viewWFReviewerAssignmentNoDelegatesByRole
CREATE view [dbo].[viewWFReviewerAssignmentNoDelegatesByRole] with schemabinding
as
	--NOTE: results may not be distinct, so this is best used within an exists clause

	select
		P.PlanGUID,
		WFS.WorkflowStepGUID,
		sRA.IdentityGUID as UserGUID,
		COUNT_BIG(*) as Cnt
	from
		dbo.XPlan P
		inner join dbo.WFToken T on T.ENTITYGUID = P.PlanGUID
		inner join dbo.WFWorkflowStep WFS on WFS.WorkflowMapGUID = T.WorkflowMapGUID
		inner join dbo.WFReviewerAssignment RA on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID
		inner join dbo.S3LootGroup sLG on sLG.LootID = P.CachedLootID
		inner join dbo.UserRole sR on sR.UserRoleGUID = RA.IdentityGUID
		inner join dbo.S3RoleAssignment sRA on sRA.LootGroupID = sLG.LootGroupID and sR.RoleID = sRA.RoleID
	group by
		P.PlanGUID,
		WFS.WorkflowStepGUID,
		sRA.IdentityGUID
GO


---------------------------------------------

-- dbo.viewWFReviewerAssignmentNoDelegatesByRoleGroup
CREATE view [dbo].[viewWFReviewerAssignmentNoDelegatesByRoleGroup] with schemabinding
as
	--NOTE: results may not be distinct, so this is best used within an exists clause
	--Includes only reviewers that are assigned to a group that is in a role that is the direct reviewer

	select
		P.PlanGUID,
		WFS.WorkflowStepGUID,
		sIL.MemberGUID as UserGUID,
		COUNT_BIG(*) as Cnt
	from
		dbo.XPlan P
		inner join dbo.WFToken T on T.ENTITYGUID = P.PlanGUID
		inner join dbo.WFWorkflowStep WFS on WFS.WorkflowMapGUID = T.WorkflowMapGUID
		inner join dbo.WFReviewerAssignment RA on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID
		inner join dbo.S3LootGroup sLG on sLG.LootID = P.CachedLootID
		inner join dbo.UserRole sR on sR.UserRoleGUID = RA.IdentityGUID
		inner join dbo.S3RoleAssignment sRA on sRA.LootGroupID = sLG.LootGroupID and sR.RoleID = sRA.RoleID
		inner join dbo.S3IdentityLink sIL on sIL.GroupingGUID = sRA.IdentityGUID
	group by
		P.PlanGUID,
		WFS.WorkflowStepGUID,
		sIL.MemberGUID
GO


---------------------------------------------

-- dbo.viewWFSetup
CREATE view [dbo].[viewWFSetup]  as 
SELECT 
	PT.PlanTypeGUID,
	PT.Name AS PTName,
	WM.WorkflowMapGUID,
	WM.Name AS WMName,
	P.ProcessGUID,
	P.Name AS PName,
	WS.WorkflowStepGUID,
	WS.Name AS WSName,
	P.DisplayOrder as PDisplayOrder,
	WS.DisplayOrder as WSDisplayOrder
FROM 
	PlanType PT
	INNER JOIN PlanTypeWorkflowMapLink L ON PT.PlanTypeGUID = L.PlanTypeGUID
	INNER JOIN WFWorkflowMap WM ON WM.WorkflowMapGUID = L.WorkflowMapGUID
	INNER JOIN WFWorkflowStep WS ON WS.WorkflowMapGUID = WM.WorkflowMapGUID
	LEFT JOIN WFProcessStepLink PSL ON PSL.WorkflowStepGUID = WS.WorkflowStepGUID
	LEFT JOIN WFProcess P ON P.ProcessGUID = PSL.ProcessGUID
--ORDER BY
--	PT.Name, WM.Name, P.DisplayOrder, WS.DisplayOrder
GO


---------------------------------------------

-- dbo.viewWFWorkflowStepCore30
CREATE view dbo.viewWFWorkflowStepCore30
as
	select 
		isnull(m.Name, 'Step Templates') as WorkflowMapName,
		s.* 
	from 
		dbo.WFWorkflowStep s
		left join dbo.WFWorkflowMap m on m.WorkflowMapGUID = s.WorkflowMapGUID
GO


---------------------------------------------

-- dbo.viewXPlanWithLocks
CREATE view [dbo].[viewXPlanWithLocks]
as
	select 
		isnull(
        case 
            when L.LockGUID is not null or P.IsFinancialsLocked = 1 or P.IsSuspended = 1 then cast(1 as bit) 
            else cast(0 as bit) end,
        cast(0 as bit)) as IsLocked,

		case 
            when L.LockGUID is not null then 'Locked for edit by ' + L.UserName + ' (' + cast(L.DateLocked as nvarchar(max)) + ')'
            when P.IsFinancialsLocked = 1 then 'This plan has been finalized and is no longer editable' 
            when P.IsSuspended = 1 then 'Budget suspended by ' + P.SuspendedByUserName + ' (' + cast(P.DateSuspended as nvarchar(max)) + ')'
            else '' end as LockReason,
		P.*
	from
		dbo.XPlan P with (readuncommitted)
		left join Lock L with (readuncommitted) on L.ItemGUID = P.PlanGUID and L.LockGroup = 'PlanLock'
        inner join EMFModelTemplate MT on P.ModelTemplateGUID = MT.ModelTemplateGUID
GO


---------------------------------------------

---------------------------------------------
--  PROCEDURES
---------------------------------------------

-- dbo.ConvertIntToBigIntByColumnNameNoCompression
CREATE PROCEDURE [dbo].[ConvertIntToBigIntByColumnNameNoCompression] (@sourceSchema nvarchar(100), @sourceTable nvarchar(200), @columnName nvarchar(200), @debug bit=0, @expectedType nvarchar(100)='bigint')
        AS
   SET NOCOUNT ON
   
   DECLARE @runTime datetime=getdate()
   DECLARE @cmd nvarchar(max)
   DECLARE @targetTable nvarchar(200)
   DECLARE @objectId int
   DECLARE @name nvarchar(max)
   DECLARE @definition nvarchar(4000)
   DECLARE @colName nvarchar(100)
   DECLARE @conName nvarchar(100)
   DECLARE @compressionDesc nvarchar(20)
   DECLARE @indexId int
   DECLARE @conType nvarchar(5)
   DECLARE @indexType nvarchar(50)
   DECLARE @uniqueness nvarchar(50)
   DECLARE @indexName nvarchar(100)
   DECLARE @suffix nvarchar(50)
   DECLARE @mergedSource nvarchar(100)
   DECLARE @fullSourceName sysname
   DECLARE @dataType nvarchar(200)   
	
	SELECT @dataType = DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_NAME = @sourceTable and COLUMN_NAME = @columnName and TABLE_SCHEMA = @sourceSchema
   	
	IF (dbo.TableExists(@sourceSchema, @sourceTable) = 0 or @dataType = @expectedType) 
	BEGIN
		RETURN
	END
	
	IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'identityCompression')) 
	BEGIN
		EXEC ('CREATE SCHEMA [identityCompression] AUTHORIZATION [dbo]')
	END
    
----create suffix in the format of _YYYYMMDD for backup table
    SELECT @fullSourceName=@sourceSchema+'.'+@sourceTable
    SELECT @suffix=REPLACE(convert(nvarchar,GETDATE(),102),'.','')+'_'+REPLACE(LEFT(CONVERT(varchar,CONVERT(time,GETDATE(),8)),8),':','')
    SELECT @objectId=object_id FROM sys.objects WHERE schema_id=schema_id(@sourceSchema) AND name=@sourceTable
    SELECT @targetTable='identityCompression.['+@sourceTable+'_'+REPLACE(CONVERT(nvarchar(max),NEWID()),'-','_')+']'
    SELECT @mergedSource='['+@sourceSchema+'].['+@sourceTable+']'
/*  Create table Compress table (if required) Create default constraints */
--  create the new target table
       
              DECLARE @def nvarchar(max)
              DECLARE c1 CURSOR FOR
                      SELECT '['+c.name+']' 
                           + CASE 
                             WHEN c.is_computed=0 THEN CASE WHEN c.name!=@columnName then '   ['+t.name+']' else '   ['+@expectedType+']' end
                                  + CASE 
                                    WHEN c.is_identity=1 THEN '   identity('+CONVERT(varchar,ident_seed(@mergedSource))  +','+CONVERT(varchar,ident_incr(@mergedSource))+')' 
                                    ELSE '' 
                                     END
                                  + CASE 
                                    WHEN t.name LIKE 'n%char' AND c.max_length = -1 THEN '(max)'
                                    WHEN t.name LIKE 'n%char' THEN '  ('+CONVERT(varchar,c.max_length/2)+')'
                                    WHEN t.name LIKE '%char%' THEN  '  ('+CONVERT(varchar,c.max_length)+')'
                                    WHEN t.name IN ('numeric','decimal') THEN '('+CONVERT(varchar,c.precision)+','+CONVERT(varchar,c.scale)+')' 
                                    ELSE '' 
                                     END
                                  + CASE
									WHEN cc.is_persisted=1 THEN ' PERSISTED'
									ELSE ''
									 END
								  + CASE 
                                    WHEN c.is_nullable=1 THEN ' NULL' 
                                    ELSE ' NOT NULL' 
                                     END
                             ELSE ' as '
                                  + cc.definition
								  + CASE
									WHEN cc.is_persisted=1 THEN ' PERSISTED'
									ELSE ''
									 END
								  + CASE
									WHEN cc.is_persisted=1 AND c.is_nullable=0 THEN ' NOT NULL'
									ELSE ''
									 END
                              END
                       FROM sys.columns c
                            INNER JOIN sys.types t 
                            ON t.system_type_id = c.system_type_id 
                               AND t.user_type_id = c.user_type_id
                 
                            LEFT JOIN sys.computed_columns cc 
                            ON cc.object_id = c.object_id 
                               AND cc.name = c.name
                      WHERE c.object_id = @objectId
                      ORDER BY c.column_id
                 OPEN c1
                FETCH c1 INTO @def
               SELECT @cmd = 'create table ' + @targetTable + '(' + @def
                FETCH c1 INTO @def
                WHILE @@FETCH_STATUS = 0
                BEGIN
                      SELECT @cmd = @cmd + ',' + @def
                       FETCH c1 INTO @def
                  END
               SELECT @cmd = @cmd + ')'
                CLOSE c1
           DEALLOCATE c1
                PRINT @cmd
                   IF @debug = 0
                 EXEC (@cmd)    
      
--  select the compression type of the table
    SELECT TOP 1 @compressionDesc = [data_compression_desc]
      FROM sys.partitions
     WHERE object_id=@objectId
    SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' rebuild partition = all with (data_compression = ' + @compressionDesc + ')'
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
--duplicate defaults for the target table from the source
 
   DECLARE c1 CURSOR FOR
           SELECT con.name, con.definition, col.name
             FROM sys.default_constraints con
                  INNER JOIN sys.columns col
                  ON con.parent_column_id = col.column_id
                     AND col.object_id = con.parent_object_id
            WHERE con.parent_object_id = @objectId
              AND con.type = 'D'
      OPEN c1
     FETCH c1 INTO @name, @definition, @colName
     WHILE @@FETCH_STATUS=0
     BEGIN 
           SELECT @cmd = 'SP_RENAME '''+@sourceSchema+'.'+@name+''','''+@name+'_'+@suffix+''''
           PRINT @cmd
           IF @debug = 0
               EXEC (@cmd)
           SELECT @cmd = 'ALTER TABLE '+@targetTable+' ADD CONSTRAINT ['+@name+'] DEFAULT '+@definition+' FOR ['+@colName+']'
            BEGIN TRY
                  PRINT @cmd
                     IF @debug = 0
                   EXEC (@cmd)
              END TRY
            BEGIN CATCH
                  PRINT 'Error: ' + @cmd
              END CATCH
            FETCH c1 INTO @name, @definition, @colName
       END
     CLOSE c1
DEALLOCATE c1
--Check if source table has an identity column
   
   DECLARE @isIdentity bit
   DECLARE @colList nvarchar(max)
   DECLARE @srcList nvarchar(max)
        IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = @objectId AND is_identity = 1) 
    SELECT @isIdentity=1 
      ELSE 
    SELECT @isIdentity = 0
--Create list of columns in the source/target tables.  Omit timestamp columns
   
   DECLARE c2 CURSOR FOR 
           SELECT DISTINCT '['+c.name+']'
             FROM sys.columns c
                  LEFT JOIN sys.systypes t
                  ON t.xtype = c.system_type_id
            WHERE c.object_id=@objectId
              AND t.name != 'timestamp'
              AND c.is_computed=0
              --AND c.is_identity=0
            ORDER BY '['+c.name+']'
      OPEN c2
     FETCH c2 INTO @colName
    SELECT @colList = @colName
    SELECT @srcList = 'src.' + @colName
     FETCH c2 INTO @colName
     WHILE @@FETCH_STATUS = 0
     BEGIN
           SELECT @colList=@colList+','+@colName
           SELECT @srcList=@srcList+',src.'+@colName
            FETCH c2 INTO @colName
       END
     CLOSE c2
DEALLOCATE c2
---- PRINT @colList
--Populate the target table.
	select @cmd=''

	if @isIdentity=1 
	begin
		select @cmd='set identity_insert '+@targetTable+' on; '
		--exec (@cmd)
	end
   
    SELECT @cmd = @cmd+'INSERT ' + @targetTable + ' WITH (tablock) (' + @colList + ') SELECT ' + @colList + ' FROM [' + @sourceSchema + '].[' + @sourceTable + '] src ;' 
     --PRINT @cmd
     --IF @debug=0
      --EXEC (@cmd)

	if @isIdentity=1 
	begin
		select @cmd=@cmd+'; set identity_insert '+@targetTable+' off'
		--exec (@cmd)
	end

	PRINT @cmd
     IF @debug=0
      EXEC (@cmd)
--Replicate the primary and unique keys for the target table
 
   DECLARE c1 CURSOR FOR      
           SELECT c.name, c.unique_index_id, c.type, i.type_desc
             FROM sys.key_constraints c
                  INNER JOIN sys.indexes i
                  ON i.object_id = c.parent_object_id
                     AND i.index_id=c.unique_index_id
            WHERE c.type IN ('PK','UQ')
              AND c.parent_object_id=@objectId
      OPEN c1
     FETCH c1 INTO @conName, @indexId, @conType, @indexType
     WHILE @@FETCH_STATUS=0
     BEGIN
              PRINT @conName +' ' + convert(varchar,@indexId)+' '+@conType
              DECLARE c2 CURSOR FOR      
                      SELECT '[' + c.name + ']'
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id=ic.column_id
                                AND ic.is_included_column=0
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
                       --ORDER BY ic.index_column_id 
                       ORDER BY ic.key_ordinal
                 OPEN c2
             --SELECT @objectId,@indexId
                FETCH c2 INTO @colName
              PRINT @colName
               SELECT @colList = @colName
                FETCH c2 INTO @colName
                WHILE @@FETCH_STATUS = 0
                BEGIN
                      SELECT @colList = @colList + ',' + @colName
                      FETCH c2 INTO @colName
                  END
                CLOSE c2
           DEALLOCATE c2
                   IF @conType='PK'
               SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' primary key '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')'
                   IF @conType='UQ'
               SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' unique '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')'
                PRINT @cmd
                   IF @debug=0
                 EXEC (@cmd)
                FETCH c1 INTO @conName,@indexId,@conType,@indexType
       END
     CLOSE c1
DEALLOCATE c1
--Create check constraints
   
   DECLARE c1 CURSOR FOR      
           SELECT [name],[definition]
             FROM sys.check_constraints
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName,@definition
     WHILE @@FETCH_STATUS = 0
     BEGIN
		   SELECT @cmd = 'SP_RENAME '''+@sourceSchema+'.'+@conName+''','''+@conName+'_'+@suffix+''''
           PRINT @cmd
           IF @debug = 0
               EXEC (@cmd)

           SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT ' + @conName + ' check ' + @definition
               IF @debug = 0
             EXEC (@cmd)
            FETCH c1 INTO @conName, @definition
       END
     CLOSE c1
DEALLOCATE c1
----Create indexes
   
   DECLARE @incList nvarchar(max)
   DECLARE @incName nvarchar(100)
   DECLARE @ascDesc nvarchar(10)
   DECLARE c1 CURSOR FOR 
           SELECT name, index_id, type_desc, 
                  CASE 
                  WHEN is_unique=1 THEN 'UNIQUE' 
                  ELSE '' 
                  END 
             FROM sys.indexes i
            WHERE i.object_id = @ObjectId
              AND NOT EXISTS 
                  (SELECT 1 
                     FROM sys.key_constraints kc 
                    WHERE kc.parent_object_id = i.object_id 
                      AND i.index_id = kc.unique_index_id)
      OPEN c1
     FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness
     WHILE @@FETCH_STATUS = 0
     BEGIN
              DECLARE c2 CURSOR FOR      
                      SELECT '[' + c.name + ']' , 
                             CASE 
                             WHEN ic.is_descending_key = 1 THEN 'DESC' 
                             ELSE 'ASC' 
                             END
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id = ic.column_id
                                AND ic.is_included_column = 0
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
                       --ORDER BY ic.index_column_id
                       ORDER BY ic.key_ordinal
                         
                 OPEN c2
                FETCH c2 INTO @colName,@ascDesc
               SELECT @colList = @colName + ' ' + @ascDesc
                FETCH c2 INTO @colName, @ascDesc
                WHILE @@FETCH_STATUS=0
                BEGIN
                      SELECT @colList = @colList + ',' + @colName + ' ' + @ascDesc
                       FETCH c2 INTO @colName, @ascDesc
                  END    
                CLOSE c2
           DEALLOCATE c2
               SELECT @colName = ''
              DECLARE c2 CURSOR FOR 
                      SELECT '[' + c.name + ']'
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id = ic.column_id
                                AND ic.is_included_column = 1
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
                       --ORDER BY ic.index_column_id
                       ORDER BY ic.key_ordinal
                           
                 OPEN c2
                FETCH c2 INTO @colName
               SELECT @incList = @colName
                FETCH c2 INTO @colName
                WHILE @@FETCH_STATUS=0
                BEGIN
                      SELECT @incList = @incList + ',' + @colName
                      FETCH c2 INTO @colName
                  END
                CLOSE c2
           DEALLOCATE c2
              PRINT @indexName +' : ' + @colList + ' : '+@inclist
               SELECT @cmd = 'CREATE ' + @uniqueness + ' ' + @indexType+
                      +' INDEX [' + @indexName + '] ON ' + @targetTable + ' (' + @colList + ')'
                      +  CASE
                         WHEN @incList = '' THEN '' 
                         ELSE ' include (' + @incList + ')' 
                         END
                      +' WITH (data_compression=' + @compressionDesc + ')'
                PRINT @cmd
                   IF @debug = 0
                 EXEC (@cmd)
                FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness
       END 
     CLOSE c1
DEALLOCATE c1
----Create foreign keys
  
   DECLARE @refColName nvarchar(max)
   DECLARE @refColList nvarchar(max)
   DECLARE @refTable nvarchar(100)
   DECLARE @onDelete nvarchar(50)
   DECLARE @onUpdate nvarchar(50)
   
   DECLARE c1 CURSOR FOR 
           SELECT name, delete_referential_action_desc, update_referential_action_desc 
             FROM sys.foreign_keys 
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName, @onDelete, @onUpdate
     WHILE @@fetch_status = 0
     BEGIN   
              DECLARE c2 CURSOR FOR
                      SELECT pc.name, rc.name, '[' + schema_name(t.schema_id) + '].[' + t.name + ']'
                        FROM sys.foreign_key_columns fkc
                             INNER JOIN sys.foreign_keys fk
                             ON fkc.constraint_object_id = fk.object_id
                             INNER JOIN sys.columns pc
                             ON pc.column_id = fkc.parent_column_id
                                AND pc.object_id = @objectId
                             INNER JOIN sys.columns rc
                             ON rc.column_id = fkc.referenced_column_id
                                AND rc.object_id = fkc.referenced_object_id
                             INNER JOIN sys.tables t
                             ON t.object_id = fkc.referenced_object_id
                       WHERE fk.parent_object_id=@objectId
                         AND fk.name = @conName
                       ORDER BY fkc.constraint_column_id
                                
                 OPEN c2
                FETCH c2 INTO @colName, @refColName, @refTable
               SELECT @colList = @colName
               SELECT @refColList = @refColName
                FETCH c2 INTO @colName, @refColName, @refTable
                WHILE @@FETCH_STATUS = 0
                BEGIN   
                      SELECT @colList = ',' + @colName
                      SELECT @refColList = ',' + @refColName
                       FETCH c2 INTO @colName,@refColName,@refTable
                  END    
                CLOSE c2
           DEALLOCATE c2
               SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT [' + @conName + '] FOREIGN KEY (' + @colList + ') REFERENCES ' + @refTable + '(' + @refColList + ') '
                      +  CASE
                         WHEN @onDelete != 'NO_ACTION' THEN 'on delete ' + @onDelete 
                         ELSE '' 
                          END
                      +  CASE 
                         WHEN @onUpdate != 'NO_ACTION' THEN ' on update ' + @onUpdate 
                         ELSE '' 
                          END
                PRINT @cmd
                   IF @debug=0
                 EXEC (@cmd)
                FETCH c1 INTO @conName, @onDelete, @onUpdate
       END
     CLOSE c1
DEALLOCATE c1
--  Rename the primary key and drop foreign keys in the source table
   DECLARE c1 CURSOR FOR 
           SELECT name, type 
             FROM sys.key_constraints 
            WHERE parent_object_id = @objectId
            UNION ALL 
           SELECT name,type 
             FROM sys.foreign_keys 
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName, @conType
     WHILE @@FETCH_STATUS = 0
     BEGIN 
               IF @conType = 'F'
           SELECT @cmd = 'ALTER TABLE [' + @sourceSchema + '].[' + @sourceTable + '] DROP CONSTRAINT [' + @conName + ']'
             ELSE
           SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '.' + @conName + ''',' + '''' + @conName + '_' + @suffix + ''''
            PRINT @cmd
               IF @debug = 0
             EXEC (@cmd)
            FETCH c1 INTO @conName,@conType
       END
     CLOSE c1
DEALLOCATE c1
-- Turn on change tracking if required
    IF EXISTS (SELECT 1 FROM sys.change_tracking_tables WHERE OBJECT_ID=@objectId)
    BEGIN
        SELECT @cmd='ALTER TABLE '+@targetTable+' enable Change_tracking'
        exec (@cmd)
    END
-- Replace the source table with the target table.  Move the source table to the bak schema and append @suffix
    SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '''' + ',''' + @sourceTable + '_' + @suffix + ''''
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'sp_rename ''' + REPLACE(REPLACE(@targetTable,'[',''),']','') + ''',''' + @sourceTable + ''''
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'ALTER SCHEMA [' + @sourceSchema + '] TRANSFER [identityCompression].[' + @sourceTable + ']'
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'ALTER SCHEMA [BAK] TRANSFER [' + @sourceSchema + '].[' + @sourceTable + '_' + @suffix + ']'
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
--  Create triggers here
   DECLARE @triggerDef varchar(MAX) = ''
   DECLARE @triggerName varchar(MAX) = ''
   DECLARE @triggerDisabled bit = 0
   DECLARE @triggerSql varchar(MAX) = ''

   SELECT m.definition, obj.name, t.is_disabled
   into #tmpTriggers
           FROM sys.sql_modules m
           INNER JOIN sys.objects obj on obj.object_id = m.object_id
		   INNER JOIN sys.triggers t on t.object_id = m.object_id
           WHERE obj.type = 'TR' and obj.parent_object_id = OBJECT_ID('[BAK].[' + @sourceTable + '_' + @suffix + ']')

   DECLARE c1 CURSOR FOR
           SELECT definition, name, is_disabled
           FROM #tmpTriggers
      OPEN c1
     FETCH c1 INTO @triggerDef, @triggerName, @triggerDisabled
     WHILE @@FETCH_STATUS = 0
     BEGIN
		   --There is no renaming trigger so a drop and create is necessary to put the original trigger on the bak table
		   SET @triggerSql = 'DROP TRIGGER IF EXISTS [BAK].[' + @triggerName + ']'
		   PRINT @triggerSql
		   IF @debug = 0
		    EXEC (@triggerSql)

		   --create the trigger replacing the orig table name with bak name
		   SET @triggerSql = REPLACE(@triggerDef, @triggerName, @triggerName + '_' + @suffix)
		   SET @triggerSql = REPLACE(@triggerSql, '[' + @sourceSchema + ']','[bak]')
		   SET @triggerSql = REPLACE(@triggerSql, '[' + @sourceTable, '[' + @sourceTable + '_' + @suffix)
		   SET @triggerSql = REPLACE(@triggerSql, @sourceSchema + '.' + @sourceTable, 'bak.' + @sourcetable + '_' + @suffix)
		   PRINT @triggerSql
		   IF @debug = 0
		    EXEC (@triggerSql)		   
			
			--create trigger on new table
		   PRINT @triggerDef
		   IF @debug = 0
			EXEC (@triggerDef)           
			--disable trigger if it was previously disabled
		   IF (@triggerDisabled <> 0)
		   BEGIN
				SET @triggerSql = 'DISABLE TRIGGER [' + @sourceSchema + '].[' + @triggerName + '] on [' + @sourceSchema + '].[' + @sourceTable + ']'
			   PRINT @triggerSql
			   IF @debug = 0
				EXEC (@triggerSql)
		   END
           FETCH c1 INTO @triggerDef, @triggerName, @triggerDisabled
       END
     CLOSE c1
DEALLOCATE c1	  
--Update replication table if required
    IF EXISTS (SELECT 1 FROM dbo.ReplicationTable WHERE TableName=@fullSourceName)
    BEGIN
        UPDATE  dbo.ReplicationTable set LastRefreshChangeTrackingVersion = null
        WHERE TableName = @fullSourceName
    END
GO


---------------------------------------------

-- dbo.CopyData
CREATE PROCEDURE [dbo].[CopyData] (@sourceSchema nvarchar(100), @sourceTable nvarchar(200), @whereClause nvarchar(2000), @debug bit=0, @identityCompression bit=0)
	    AS
	   SET NOCOUNT ON
   DECLARE @cmd nvarchar(max)
   DECLARE @targetTable nvarchar(200)
   DECLARE @objectId int
   DECLARE @name nvarchar(100)
   DECLARE @definition nvarchar(4000)
   DECLARE @colName nvarchar(100)
   DECLARE @conName nvarchar(100)
   DECLARE @compressionDesc nvarchar(20)
   DECLARE @indexId int
   DECLARE @conType nvarchar(5)
   DECLARE @indexType nvarchar(50)
   DECLARE @uniqueness nvarchar(50)
   DECLARE @indexName nvarchar(100)
   DECLARE @suffix nvarchar(50)
   DECLARE @mergedSource nvarchar(100)

----create suffix in the format of _YYYYMMDD for backup table

    SELECT @suffix=REPLACE(convert(nvarchar,GETDATE(),102),'.','')+'_'+REPLACE(LEFT(CONVERT(varchar,CONVERT(time,GETDATE(),8)),8),':','')
    SELECT @objectId=object_id FROM sys.objects WHERE schema_id=schema_id(@sourceSchema) AND name=@sourceTable
    SELECT @targetTable='data.['+@sourceTable+'_'+REPLACE(CONVERT(nvarchar(max),NEWID()),'-','_')+']'
    SELECT @mergedSource='['+@sourceSchema+'].['+@sourceTable+']'

/*  Create table Compress table (if required) Create default constraints */
--  create the new target table

	    IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id=@objectId AND is_computed=1)
	 BEGIN 
              DECLARE @def nvarchar(max)
			  DECLARE c1 CURSOR FOR
					  SELECT '['+c.name+']' 
						   + CASE 
							 WHEN c.is_computed=0 THEN '   ['+t.name+']'
								  +	CASE 
									WHEN c.is_identity=1 THEN '   identity('+CONVERT(varchar,ident_seed(@mergedSource))  +','+CONVERT(varchar,ident_incr(@mergedSource))+')' 
									ELSE '' 
									 END
								  +	CASE 
									WHEN t.name	LIKE 'n%char' AND c.max_length = -1 THEN '(max)'
									WHEN t.name LIKE 'n%char' THEN '  ('+CONVERT(varchar,c.max_length/2)+')'
									WHEN t.name LIKE '%char%' THEN  '  ('+CONVERT(varchar,c.max_length)+')'
									WHEN t.name IN ('numeric','decimal') THEN '('+CONVERT(varchar,c.precision)+','+CONVERT(varchar,c.scale)+')' 
									ELSE '' 
									 END
								  +	CASE 
									WHEN c.is_nullable=1 THEN ' NULL' 
									ELSE ' NOT NULL' 
									 END
							 ELSE ' as '
								  + cc.definition
							  END
					   FROM sys.columns c
						    INNER JOIN sys.types t 
						    ON t.system_type_id = c.system_type_id 
							   AND t.user_type_id = c.user_type_id
				 
						    LEFT JOIN sys.computed_columns cc 
						    ON cc.object_id = c.object_id 
							   AND cc.name = c.name
					  WHERE c.object_id = @objectId
					  ORDER BY c.column_id

				 OPEN c1
				FETCH c1 INTO @def
			   SELECT @cmd = 'create table ' + @targetTable + '(' + @def
				FETCH c1 INTO @def
				WHILE @@FETCH_STATUS = 0
				BEGIN
					  SELECT @cmd = @cmd + ',' + @def
					   FETCH c1 INTO @def
				  END
			   SELECT @cmd = @cmd + ')'
			    CLOSE c1
           DEALLOCATE c1
			    PRINT @cmd
				   IF @debug = 0
			     EXEC (@cmd)	
	   END
	  ELSE
     BEGIN 
           SELECT @cmd='SELECT * INTO '+@targetTable+' FROM ['+@sourceSchema+'].['+@sourceTable +'] WHERE 1=2'
            PRINT @cmd
			   IF @debug=0
             EXEC (@cmd)
	   END

--  select the compression type of the table

    SELECT TOP 1 @compressionDesc = [data_compression_desc]
	  FROM sys.partitions
     WHERE object_id=@objectId
    SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' rebuild partition = all with (data_compression = ' + @compressionDesc + ')'
     PRINT @cmd
	    IF @debug = 0
	  EXEC (@cmd)

--duplicate defaults for the target table from the source

   DECLARE c1 CURSOR FOR
		   SELECT con.name, con.definition, col.name
		     FROM sys.default_constraints con
				  INNER JOIN sys.columns col
				  ON con.parent_column_id = col.column_id
				     AND col.object_id = con.parent_object_id
		    WHERE con.parent_object_id = @objectId
			  AND con.type = 'D'
      OPEN c1
     FETCH c1 INTO @name, @definition, @colName
     WHILE @@FETCH_STATUS=0
     BEGIN 
           SELECT @cmd = 'ALTER TABLE '+@targetTable+' ADD DEFAULT '+@definition+' FOR ['+@colName+']'
		    BEGIN TRY
			      PRINT @cmd
				     IF @debug = 0
				   EXEC (@cmd)
			  END TRY
			BEGIN CATCH
				  PRINT 'Error: ' + @cmd
			  END CATCH
			FETCH c1 INTO @name, @definition, @colName
	   END
	 CLOSE c1
DEALLOCATE c1

--Check if source table has an identity column

   DECLARE @isIdentity bit
   DECLARE @colList nvarchar(max)
   DECLARE @srcList nvarchar(max)
        IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = @objectId AND is_identity = 1) 
    SELECT @isIdentity=1 
	  ELSE 
	SELECT @isIdentity = 0

--Create list of columns in the source/target tables.  Omit timestamp columns and identity column if @identityCompression=1

   DECLARE c2 CURSOR FOR 
		   SELECT DISTINCT '['+c.name+']'
			 FROM sys.columns c
				  LEFT JOIN sys.systypes t
				  ON t.xtype = c.system_type_id
			WHERE c.object_id=@objectId
			  AND t.name != 'timestamp'
			  AND c.is_computed=0
			  AND (c.is_identity=0 or @identityCompression=0)
			ORDER BY '['+c.name+']'
      OPEN c2
	 FETCH c2 INTO @colName
	SELECT @colList = @colName
	SELECT @srcList = 'src.' + @colName
	 FETCH c2 INTO @colName
	 WHILE @@FETCH_STATUS = 0
	 BEGIN
		   SELECT @colList=@colList+','+@colName
		   SELECT @srcList=@srcList+',src.'+@colName
		    FETCH c2 INTO @colName
	   END
	 CLOSE c2
DEALLOCATE c2

---- PRINT @colList
--Populate the target table.

        IF @identityCompression = 0
	 BEGIN
		   SELECT @cmd = CASE 
					     WHEN @isIdentity = 1 THEN 'SET identity_insert ' + @targetTable + ' ON;' 
						 ELSE '' 
						  END
		   SELECT @cmd = @cmd + 'INSERT ' + @targetTable + ' WITH (tablock) (' + @colList + ') SELECT ' + @srcList + ' FROM [' + @sourceSchema + '].[' + @sourceTable + '] src ' + @whereClause + ';'
		   SELECT @cmd = @cmd 
		               + CASE 
					     WHEN @isIdentity = 1 THEN 'SET identity_insert ' + @targetTable + ' OFF;' 
						 ELSE '' 
						  END
	   END
	  ELSE
	 BEGIN
		   SELECT @cmd = 'INSERT ' + @targetTable + ' WITH (tablock) (' + @colList + ') SELECT ' + @colList + ' FROM [' + @sourceSchema + '].[' + @sourceTable + '] src ' + @whereClause + ';'
	   END
     PRINT @cmd
        IF @debug=0
      EXEC (@cmd)

--Replicate the primary and unique keys for the target table

   DECLARE c1 CURSOR FOR      
           SELECT c.name, c.unique_index_id, c.type, i.type_desc
             FROM sys.key_constraints c
                  INNER JOIN sys.indexes i
                  ON i.object_id = c.parent_object_id
                     AND i.index_id=c.unique_index_id
            WHERE c.type IN ('PK','UQ')
              AND c.parent_object_id=@objectId
      OPEN c1
     FETCH c1 INTO @conName, @indexId, @conType, @indexType
     WHILE @@FETCH_STATUS=0
     BEGIN
              --PRINT @conName +' ' + convert(varchar,@indexId)+' '+@conType
              DECLARE c2 CURSOR FOR      
		              SELECT '[' + c.name + ']'
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id=ic.column_id
                                AND ic.is_included_column=0
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
					   ORDER BY ic.index_column_id
                 OPEN c2
             --SELECT @objectId,@indexId
                FETCH c2 INTO @colName
              --PRINT @colName
               SELECT @colList = @colName
                FETCH c2 INTO @colName
                WHILE @@FETCH_STATUS = 0
                BEGIN
                      SELECT @colList = @colList + ',' + @colName
                      FETCH c2 INTO @colName
                  END
                CLOSE c2
           DEALLOCATE c2
                   IF @conType='PK'
               SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' primary key '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')'
                   IF @conType='UQ'
               SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' unique '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')'
                PRINT @cmd
                   IF @debug=0
                 EXEC (@cmd)
                FETCH c1 INTO @conName,@indexId,@conType,@indexType
       END
     CLOSE c1
DEALLOCATE c1

--Create check constraints

   DECLARE c1 CURSOR FOR      
           SELECT [name],[definition]
             FROM sys.check_constraints
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName,@definition
     WHILE @@FETCH_STATUS = 0
     BEGIN
           SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT ' + @conName + ' check ' + @definition
               IF @debug = 0
             EXEC (@cmd)
            FETCH c1 INTO @conName, @definition
       END
     CLOSE c1
DEALLOCATE c1

----Create indexes

   DECLARE @incList nvarchar(max)
   DECLARE @incName nvarchar(100)
   DECLARE @ascDesc nvarchar(10)
   DECLARE c1 CURSOR FOR 
           SELECT name, index_id, type_desc, 
		          CASE 
				  WHEN is_unique=1 THEN 'UNIQUE' 
				  ELSE 'NONUNIQUE' 
				  END 
             FROM sys.indexes i
            WHERE i.object_id = @ObjectId
              AND NOT EXISTS 
			      (SELECT 1 
				     FROM sys.key_constraints kc 
					WHERE kc.parent_object_id = i.object_id 
					  AND i.index_id = kc.unique_index_id)

      OPEN c1
     FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness
     WHILE @@FETCH_STATUS = 0
     BEGIN
              DECLARE c2 CURSOR FOR      
                      SELECT '[' + c.name + ']' , 
                             CASE 
                             WHEN ic.is_descending_key = 1 THEN 'DESC' 
                             ELSE 'ASC' 
                             END
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id = ic.column_id
                                AND ic.is_included_column = 0
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
                       ORDER BY ic.index_column_id
                         
                 OPEN c2
                FETCH c2 INTO @colName,@ascDesc
               SELECT @colList = @colName + ' ' + @ascDesc
                FETCH c2 INTO @colName, @ascDesc
                WHILE @@FETCH_STATUS=0
                BEGIN
                      SELECT @colList = @colList + ',' + @colName + ' ' + @ascDesc
                       FETCH c2 INTO @colName, @ascDesc
                  END    
                CLOSE c2
           DEALLOCATE c2
               SELECT @colName = ''
              DECLARE c2 CURSOR FOR 
                      SELECT '[' + c.name + ']'
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id = ic.column_id
                                AND ic.is_included_column = 1
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
                       ORDER BY ic.index_column_id
                           
                 OPEN c2
                FETCH c2 INTO @colName
               SELECT @incList = @colName
                FETCH c2 INTO @colName
                WHILE @@FETCH_STATUS=0
                BEGIN
                      SELECT @incList = @incList + ',' + @colName
                      FETCH c2 INTO @colName
                  END
                CLOSE c2
           DEALLOCATE c2
              --PRINT @indexName +' : ' + @colList + ' : '+@inclist
               SELECT @cmd = 'CREATE ' + @indexType+
                      +' INDEX [' + @indexName + '] ON ' + @targetTable + ' (' + @colList + ')'
                      +  CASE
                         WHEN @incList = '' THEN '' 
                         ELSE ' include (' + @incList + ')' 
                         END
                      +' WITH (data_compression=' + @compressionDesc + ')'
                PRINT @cmd
                   IF @debug = 0
                 EXEC (@cmd)
                FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness
       END 
     CLOSE c1
DEALLOCATE c1

----Create foreign keys

   DECLARE @refColName nvarchar(max)
   DECLARE @refColList nvarchar(max)
   DECLARE @refTable nvarchar(100)
   DECLARE @onDelete nvarchar(50)
   DECLARE @onUpdate nvarchar(50)
   
   DECLARE c1 CURSOR FOR 
           SELECT name, delete_referential_action_desc, update_referential_action_desc 
             FROM sys.foreign_keys 
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName, @onDelete, @onUpdate
     WHILE @@fetch_status = 0
     BEGIN   
              DECLARE c2 CURSOR FOR
                      SELECT pc.name, rc.name, '[' + schema_name(t.schema_id) + '].[' + t.name + ']'
                        FROM sys.foreign_key_columns fkc
                             INNER JOIN sys.foreign_keys fk
                             ON fkc.constraint_object_id = fk.object_id
                             INNER JOIN sys.columns pc
                             ON pc.column_id = fkc.parent_column_id
                                AND pc.object_id = @objectId
                             INNER JOIN sys.columns rc
                             ON rc.column_id = fkc.referenced_column_id
                                AND rc.object_id = fkc.referenced_object_id
                             INNER JOIN sys.tables t
                             ON t.object_id = fkc.referenced_object_id
                       WHERE fk.parent_object_id=@objectId
                         AND fk.name = @conName
                       ORDER BY fkc.constraint_column_id
                                
                 OPEN c2
                FETCH c2 INTO @colName, @refColName, @refTable
               SELECT @colList = @colName
               SELECT @refColList = @refColName
                FETCH c2 INTO @colName, @refColName, @refTable
                WHILE @@FETCH_STATUS = 0
                BEGIN   
                      SELECT @colList = ',' + @colName
                      SELECT @refColList = ',' + @refColName
                       FETCH c2 INTO @colName,@refColName,@refTable
                  END    
                CLOSE c2
           DEALLOCATE c2
               SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT [' + @conName + '] FOREIGN KEY (' + @colList + ') REFERENCES ' + @refTable + '(' + @refColList + ') '
                      +  CASE
                         WHEN @onDelete != 'NO_ACTION' THEN 'on delete ' + @onDelete 
                         ELSE '' 
                          END
                      +  CASE 
                         WHEN @onUpdate != 'NO_ACTION' THEN 'on update ' + @onUpdate 
                         ELSE '' 
                          END
                PRINT @cmd
                   IF @debug = 0
                 EXEC (@cmd)
                FETCH c1 INTO @conName, @onDelete, @onUpdate
       END
     CLOSE c1
DEALLOCATE c1

--  Rename the primary key and drop foreign keys in the source table

   DECLARE c1 CURSOR FOR 
           SELECT name, type 
             FROM sys.key_constraints 
            WHERE parent_object_id = @objectId
            UNION ALL 
           SELECT name,type 
             FROM sys.foreign_keys 
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName, @conType
     WHILE @@FETCH_STATUS = 0
     BEGIN 
               IF @conType = 'F'
           SELECT @cmd = 'ALTER TABLE [' + @sourceSchema + '].[' + @sourceTable + '] DROP CONSTRAINT [' + @conName + ']'
             ELSE
           SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '.' + @conName + ''',' + '''' + @conName + '_' + @suffix + ''''
            PRINT @cmd
               IF @debug = 0
             EXEC (@cmd)
            FETCH c1 INTO @conName,@conType
       END
     CLOSE c1
DEALLOCATE c1

--  Create CopyDataBAK schema

        IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'CopyDataBAK')
     BEGIN 
           SELECT @cmd = 'CREATE SCHEMA CopyDataBAK'
            PRINT @cmd
               IF @debug = 0
             EXEC ('CREATE SCHEMA CopyDataBAK')
       END

-- Replace the source table with the target table.  Move the source table to the bak schema and append @suffix

    SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '''' + ',''' + @sourceTable + '_' + @suffix + ''''
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'sp_rename ''' + REPLACE(REPLACE(@targetTable,'[',''),']','') + ''',''' + @sourceTable + ''''
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'ALTER SCHEMA [' + @sourceSchema + '] TRANSFER [data].[' + @sourceTable + ']'
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'ALTER SCHEMA [CopyDataBAK] TRANSFER [' + @sourceSchema + '].[' + @sourceTable + '_' + @suffix + ']'
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
GO


---------------------------------------------

-- dbo.GetScoreDataTableColumnValidationResults
CREATE PROCEDURE dbo.GetScoreDataTableColumnValidationResults
(
	@SchemaList VARCHAR(MAX),-- = 'clientdss,dss'
	@IgnoreColumnList VARCHAR(MAX)-- = 'TransactionID,RowID,Version'
)
AS
BEGIN

	SELECT s.name AS [Schema]
			,t.name AS [Table]
			,c.COLUMN_NAME AS [Column]
			,CONVERT(BIT, CASE WHEN c.IS_NULLABLE = 'YES' THEN 1 ELSE 0 END) AS Nullable
			,CONVERT(BIT, CASE WHEN c.COLUMN_DEFAULT IS NULL THEN 1 ELSE 0 END) AS HasDefault		
	FROM sys.tables t
	INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
	INNER JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_NAME = t.name AND c.TABLE_SCHEMA = s.name
	INNER JOIN [dbo].[ConvertCSValuesToTable](@SchemaList, ',') schemasToCheck ON schemasToCheck.val = s.name
	INNER JOIN dbo.ScoreDataTable dt ON dt.SQLObjectName = t.name AND dt.SQLSchemaName = s.name
	LEFT JOIN [dbo].[ConvertCSValuesToTable](@IgnoreColumnList, ',') ignore ON ignore.val = c.COLUMN_NAME
	WHERE (c.IS_NULLABLE = 'YES' OR c.COLUMN_DEFAULT IS NULL)
			AND ignore.pos IS NULL
END
GO


---------------------------------------------

-- dbo.GetScoreViewValidationResults
CREATE PROCEDURE dbo.GetScoreViewValidationResults
(
	@SchemaList VARCHAR(MAX)-- = 'clientdss,dss'
)
AS
BEGIN
	DECLARE @checkSchema NVARCHAR(500)
	DECLARE @checkObject NVARCHAR(500)
	DECLARE @checkColumn NVARCHAR(500)
	DECLARE @checkSQL NVARCHAR(500)
	DECLARE @DimensionName NVARCHAR(500)
	DECLARE @devnull INT

	DECLARE @ErrorLog TABLE (
		Dimension NVARCHAR(500)
		,Error NVARCHAR(500)
		,[Table] NVARCHAR(500)
		,[Column] NVARCHAR(500)
		,[Schema] VARCHAR(MAX)
		)

	DECLARE c_schemacheck CURSOR FAST_FORWARD FOR

	SELECT
		sd.FriendlyName
		,sd.SQLSchemaName
		,sd.SQLObjectName
		,sa.SQLColumnName
	FROM
		ScoreDimension sd
		INNER JOIN ScoreDimensionGroup sdg ON sd.DimensionGUID=sdg.DimensionGUID
		INNER JOIN ScoreAttribute sa ON sdg.DimensionGroupGUID=sa.DimensionGroupGUID
		INNER JOIN [dbo].[ConvertCSValuesToTable](@SchemaList, ',') schemasToCheck ON schemasToCheck.val = sd.SQLSchemaName
	ORDER BY
		sd.FriendlyName
		,sd.SQLSchemaName
		,sd.SQLObjectName
		,sa.SQLColumnName
	;
	
	OPEN c_schemacheck;

	FETCH NEXT FROM c_schemacheck INTO @DimensionName, @checkSchema, @checkObject, @checkColumn

	WHILE @@FETCH_STATUS=0
		BEGIN
			--SET @checkSQL='DECLARE @devnull INT; SELECT TOP 1 @devnull=COUNT([' + @checkColumn + ']) FROM [' + @checkSchema + '].[' + @checkObject + '] OPTION(FAST 1)'
			SET @checkSQL='DECLARE @devnull INT; SELECT TOP 0 @devnull=COUNT([' + @checkColumn + ']) FROM [' + @checkSchema + '].[' + @checkObject + '] (READUNCOMMITTED)'
			--PRINT @checkSQL
		
			BEGIN TRY
				exec sp_executesql @checkSQL
			END TRY
			BEGIN CATCH
				INSERT INTO @ErrorLog (Dimension,Error,[Table],[Column],[Schema]) VALUES (@DimensionName,ERROR_MESSAGE(),@checkObject,@checkColumn, @checkSchema)
				--PRINT ERROR_MESSAGE() + '   SELECT [' + @checkColumn + '] FROM [' + @checkSchema + '].[' + @checkObject + ']'
			END CATCH
		
		
			FETCH NEXT FROM c_schemacheck INTO @DimensionName, @checkSchema, @checkObject, @checkColumn
		END

	CLOSE c_schemacheck;
	DEALLOCATE c_schemacheck;

	SELECT
		Dimension
		,Error
		,[Table]
		,[Column]
		,[Schema]
	FROM @ErrorLog

END
GO


---------------------------------------------

-- dbo.IdentityCompression
CREATE   PROCEDURE [dbo].[IdentityCompression] (@sourceSchema nvarchar(100), @sourceTable nvarchar(200), @debug bit=0)
	    AS
   SET NOCOUNT ON
   
   declare @checkCmd nvarchar(1000)
   declare @resultsTable table (TableIsVetted int)
   select @checkCmd='if exists (select 1 from ['+setting+'].SQLAdministration.dbo.IdentityCompressionVetted where SchemaName='''+
   @sourceSchema + ''' and TableName='''+@sourceTable+''') select 1 else select 0' from dbsetting where name='SMC_PRIMARY_SERVER'
   
   begin try
	insert @resultsTable exec (@checkCmd)
   end try
   begin catch
	print 'Could not locate SQLAdministration.dbo.IdentityCompressionVetted on SMC_PRIMARY_SERVER'
   end catch
  
   if not exists (select 1 from @resultsTable where TableIsVetted=1)
   begin
		PRINT 'Table '+@sourceSchema+'.'+@sourceTable+ ' is not vetted for use with this stored procedure.'
		RETURN 0
   end 
  
  /*
   IF NOT EXISTS (SELECT 1 FROM IdentityCompressionVetted WHERE SchemaName=@sourceSchema and TableName=@sourceTable) 
   BEGIN
      PRINT 'Table '+@sourceSchema+'.'+@sourceTable+ ' is not vetted for use with this stored procedure.'
	  RETURN 0
   END
   */

   DECLARE @runTime datetime=getdate()
   DECLARE @cmd nvarchar(max)
   DECLARE @targetTable nvarchar(200)
   DECLARE @objectId int
   DECLARE @name nvarchar(100)
   DECLARE @definition nvarchar(4000)
   DECLARE @colName nvarchar(100)
   DECLARE @conName nvarchar(100)
   DECLARE @compressionDesc nvarchar(20)
   DECLARE @indexId int
   DECLARE @conType nvarchar(5)
   DECLARE @indexType nvarchar(50)
   DECLARE @uniqueness nvarchar(50)
   DECLARE @indexName nvarchar(100)
   DECLARE @suffix nvarchar(50)
   DECLARE @mergedSource nvarchar(100)
   DECLARE @fullSourceName sysname
	

----create suffix in the format of _YYYYMMDD for backup table
	SELECT @fullSourceName=@sourceSchema+'.'+@sourceTable
    SELECT @suffix=REPLACE(convert(nvarchar,GETDATE(),102),'.','')+'_'+REPLACE(LEFT(CONVERT(varchar,CONVERT(time,GETDATE(),8)),8),':','')
    SELECT @objectId=object_id FROM sys.objects WHERE schema_id=schema_id(@sourceSchema) AND name=@sourceTable
    SELECT @targetTable='data.['+@sourceTable+'_'+REPLACE(CONVERT(nvarchar(max),NEWID()),'-','_')+']'
    SELECT @mergedSource='['+@sourceSchema+'].['+@sourceTable+']'

/*  Create table Compress table (if required) Create default constraints */
--  create the new target table

	INSERT IdentityCompressionLog select @runTime,@sourceSchema,@sourceTable,1

	    IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id=@objectId AND is_computed=1)
	 BEGIN 
              DECLARE @def nvarchar(max)
			  DECLARE c1 CURSOR FOR
					  SELECT '['+c.name+']' 
						   + CASE 
							 WHEN c.is_computed=0 THEN '   ['+t.name+']'
								  +	CASE 
									WHEN c.is_identity=1 THEN '   identity('+CONVERT(varchar,ident_seed(@mergedSource))  +','+CONVERT(varchar,ident_incr(@mergedSource))+')' 
									ELSE '' 
									 END
								  +	CASE 
									WHEN t.name	LIKE 'n%char' AND c.max_length = -1 THEN '(max)'
									WHEN t.name LIKE 'n%char' THEN '  ('+CONVERT(varchar,c.max_length/2)+')'
									WHEN t.name LIKE '%char%' THEN  '  ('+CONVERT(varchar,c.max_length)+')'
									WHEN t.name IN ('numeric','decimal') THEN '('+CONVERT(varchar,c.precision)+','+CONVERT(varchar,c.scale)+')' 
									ELSE '' 
									 END
								  +	CASE 
									WHEN c.is_nullable=1 THEN ' NULL' 
									ELSE ' NOT NULL' 
									 END
							 ELSE ' as '
								  + cc.definition
							  END
					   FROM sys.columns c
						    INNER JOIN sys.types t 
						    ON t.system_type_id = c.system_type_id 
							   AND t.user_type_id = c.user_type_id
				 
						    LEFT JOIN sys.computed_columns cc 
						    ON cc.object_id = c.object_id 
							   AND cc.name = c.name
					  WHERE c.object_id = @objectId
					  ORDER BY c.column_id

				 OPEN c1
				FETCH c1 INTO @def
			   SELECT @cmd = 'create table ' + @targetTable + '(' + @def
				FETCH c1 INTO @def
				WHILE @@FETCH_STATUS = 0
				BEGIN
					  SELECT @cmd = @cmd + ',' + @def
					   FETCH c1 INTO @def
				  END
			   SELECT @cmd = @cmd + ')'
			    CLOSE c1
           DEALLOCATE c1
			    PRINT @cmd
				   IF @debug = 0
			     EXEC (@cmd)	
	   END
	  ELSE
     BEGIN 
           SELECT @cmd='SELECT * INTO '+@targetTable+' FROM ['+@sourceSchema+'].['+@sourceTable +'] WHERE 1=2'
            PRINT @cmd
			   IF @debug=0
             EXEC (@cmd)
	   END

--  select the compression type of the table
	UPDATE IdentityCompressionLog SET status=2 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable

    SELECT TOP 1 @compressionDesc = [data_compression_desc]
	  FROM sys.partitions
     WHERE object_id=@objectId
    SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' rebuild partition = all with (data_compression = ' + @compressionDesc + ')'
     PRINT @cmd
	    IF @debug = 0
	  EXEC (@cmd)

--duplicate defaults for the target table from the source
  UPDATE IdentityCompressionLog SET status=3 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
   DECLARE c1 CURSOR FOR
		   SELECT con.name, con.definition, col.name
		     FROM sys.default_constraints con
				  INNER JOIN sys.columns col
				  ON con.parent_column_id = col.column_id
				     AND col.object_id = con.parent_object_id
		    WHERE con.parent_object_id = @objectId
			  AND con.type = 'D'
      OPEN c1
     FETCH c1 INTO @name, @definition, @colName
     WHILE @@FETCH_STATUS=0
     BEGIN 
		   SELECT @cmd = 'SP_RENAME '''+@sourceSchema+'.'+@name+''','''+@name+'_'+@suffix+''''
		   PRINT @cmd
		   IF @debug = 0
		       EXEC (@cmd)
           SELECT @cmd = 'ALTER TABLE '+@targetTable+' ADD CONSTRAINT ['+@name+'] DEFAULT '+@definition+' FOR ['+@colName+']'
		    BEGIN TRY
			      PRINT @cmd
				     IF @debug = 0
				   EXEC (@cmd)
			  END TRY
			BEGIN CATCH
				  PRINT 'Error: ' + @cmd
			  END CATCH
			FETCH c1 INTO @name, @definition, @colName
	   END
	 CLOSE c1
DEALLOCATE c1

--Check if source table has an identity column
   UPDATE IdentityCompressionLog SET status=4 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
   DECLARE @isIdentity bit
   DECLARE @colList nvarchar(max)
   DECLARE @srcList nvarchar(max)
        IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = @objectId AND is_identity = 1) 
    SELECT @isIdentity=1 
	  ELSE 
	SELECT @isIdentity = 0

--Create list of columns in the source/target tables.  Omit timestamp columns and identity column
   UPDATE IdentityCompressionLog SET status=5 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
   DECLARE c2 CURSOR FOR 
		   SELECT DISTINCT '['+c.name+']'
			 FROM sys.columns c
				  LEFT JOIN sys.systypes t
				  ON t.xtype = c.system_type_id
			WHERE c.object_id=@objectId
			  AND t.name != 'timestamp'
			  AND c.is_computed=0
			  AND c.is_identity=0
			ORDER BY '['+c.name+']'
      OPEN c2
	 FETCH c2 INTO @colName
	SELECT @colList = @colName
	SELECT @srcList = 'src.' + @colName
	 FETCH c2 INTO @colName
	 WHILE @@FETCH_STATUS = 0
	 BEGIN
		   SELECT @colList=@colList+','+@colName
		   SELECT @srcList=@srcList+',src.'+@colName
		    FETCH c2 INTO @colName
	   END
	 CLOSE c2
DEALLOCATE c2

---- PRINT @colList
--Populate the target table.
    UPDATE IdentityCompressionLog SET status=6 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable

    SELECT @cmd = 'INSERT ' + @targetTable + ' WITH (tablock) (' + @colList + ') SELECT ' + @colList + ' FROM [' + @sourceSchema + '].[' + @sourceTable + '] src ;' 

     PRINT @cmd
     IF @debug=0
      EXEC (@cmd)

--Replicate the primary and unique keys for the target table
   UPDATE IdentityCompressionLog SET status=7 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
   DECLARE c1 CURSOR FOR      
           SELECT c.name, c.unique_index_id, c.type, i.type_desc
             FROM sys.key_constraints c
                  INNER JOIN sys.indexes i
                  ON i.object_id = c.parent_object_id
                     AND i.index_id=c.unique_index_id
            WHERE c.type IN ('PK','UQ')
              AND c.parent_object_id=@objectId
      OPEN c1
     FETCH c1 INTO @conName, @indexId, @conType, @indexType
     WHILE @@FETCH_STATUS=0
     BEGIN
              PRINT @conName +' ' + convert(varchar,@indexId)+' '+@conType
              DECLARE c2 CURSOR FOR      
		              SELECT '[' + c.name + ']'
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id=ic.column_id
                                AND ic.is_included_column=0
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
					   --ORDER BY ic.index_column_id 
					   ORDER BY ic.key_ordinal
                 OPEN c2
             --SELECT @objectId,@indexId
                FETCH c2 INTO @colName
              PRINT @colName
               SELECT @colList = @colName
                FETCH c2 INTO @colName
                WHILE @@FETCH_STATUS = 0
                BEGIN
                      SELECT @colList = @colList + ',' + @colName
                      FETCH c2 INTO @colName
                  END
                CLOSE c2
           DEALLOCATE c2
                   IF @conType='PK'
               SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' primary key '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')'
                   IF @conType='UQ'
               SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' unique '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')'
                PRINT @cmd
                   IF @debug=0
                 EXEC (@cmd)
                FETCH c1 INTO @conName,@indexId,@conType,@indexType
       END
     CLOSE c1
DEALLOCATE c1

--Create check constraints
   UPDATE IdentityCompressionLog SET status=8 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
   DECLARE c1 CURSOR FOR      
           SELECT [name],[definition]
             FROM sys.check_constraints
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName,@definition
     WHILE @@FETCH_STATUS = 0
     BEGIN
           SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT ' + @conName + ' check ' + @definition
               IF @debug = 0
             EXEC (@cmd)
            FETCH c1 INTO @conName, @definition
       END
     CLOSE c1
DEALLOCATE c1

----Create indexes
   UPDATE IdentityCompressionLog SET status=9 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
   DECLARE @incList nvarchar(max)
   DECLARE @incName nvarchar(100)
   DECLARE @ascDesc nvarchar(10)
   DECLARE c1 CURSOR FOR 
           SELECT name, index_id, type_desc, 
		          CASE 
				  WHEN is_unique=1 THEN 'UNIQUE' 
				  ELSE '' 
				  END 
             FROM sys.indexes i
            WHERE i.object_id = @ObjectId
              AND NOT EXISTS 
			      (SELECT 1 
				     FROM sys.key_constraints kc 
					WHERE kc.parent_object_id = i.object_id 
					  AND i.index_id = kc.unique_index_id)

      OPEN c1
     FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness
     WHILE @@FETCH_STATUS = 0
     BEGIN
              DECLARE c2 CURSOR FOR      
                      SELECT '[' + c.name + ']' , 
                             CASE 
                             WHEN ic.is_descending_key = 1 THEN 'DESC' 
                             ELSE 'ASC' 
                             END
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id = ic.column_id
                                AND ic.is_included_column = 0
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
                       --ORDER BY ic.index_column_id
					   ORDER BY ic.key_ordinal
                         
                 OPEN c2
                FETCH c2 INTO @colName,@ascDesc
               SELECT @colList = @colName + ' ' + @ascDesc
                FETCH c2 INTO @colName, @ascDesc
                WHILE @@FETCH_STATUS=0
                BEGIN
                      SELECT @colList = @colList + ',' + @colName + ' ' + @ascDesc
                       FETCH c2 INTO @colName, @ascDesc
                  END    
                CLOSE c2
           DEALLOCATE c2
               SELECT @colName = ''
              DECLARE c2 CURSOR FOR 
                      SELECT '[' + c.name + ']'
                        FROM sys.index_columns ic
                             INNER JOIN sys.columns c
                             ON ic.object_id = c.object_id
                                AND c.column_id = ic.column_id
                                AND ic.is_included_column = 1
                       WHERE ic.object_id = @objectId
                         AND ic.index_id = @indexId 
                       --ORDER BY ic.index_column_id
					   ORDER BY ic.key_ordinal
                           
                 OPEN c2
                FETCH c2 INTO @colName
               SELECT @incList = @colName
                FETCH c2 INTO @colName
                WHILE @@FETCH_STATUS=0
                BEGIN
                      SELECT @incList = @incList + ',' + @colName
                      FETCH c2 INTO @colName
                  END
                CLOSE c2
           DEALLOCATE c2
              PRINT @indexName +' : ' + @colList + ' : '+@inclist
               SELECT @cmd = 'CREATE ' + @uniqueness + ' ' + @indexType+
                      +' INDEX [' + @indexName + '] ON ' + @targetTable + ' (' + @colList + ')'
                      +  CASE
                         WHEN @incList = '' THEN '' 
                         ELSE ' include (' + @incList + ')' 
                         END
                      +' WITH (data_compression=' + @compressionDesc + ')'
                PRINT @cmd
                   IF @debug = 0
                 EXEC (@cmd)
                FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness
       END 
     CLOSE c1
DEALLOCATE c1

----Create foreign keys
   UPDATE IdentityCompressionLog SET status=10 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
   DECLARE @refColName nvarchar(max)
   DECLARE @refColList nvarchar(max)
   DECLARE @refTable nvarchar(100)
   DECLARE @onDelete nvarchar(50)
   DECLARE @onUpdate nvarchar(50)
   
   DECLARE c1 CURSOR FOR 
           SELECT name, delete_referential_action_desc, update_referential_action_desc 
             FROM sys.foreign_keys 
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName, @onDelete, @onUpdate
     WHILE @@fetch_status = 0
     BEGIN   
              DECLARE c2 CURSOR FOR
                      SELECT pc.name, rc.name, '[' + schema_name(t.schema_id) + '].[' + t.name + ']'
                        FROM sys.foreign_key_columns fkc
                             INNER JOIN sys.foreign_keys fk
                             ON fkc.constraint_object_id = fk.object_id
                             INNER JOIN sys.columns pc
                             ON pc.column_id = fkc.parent_column_id
                                AND pc.object_id = @objectId
                             INNER JOIN sys.columns rc
                             ON rc.column_id = fkc.referenced_column_id
                                AND rc.object_id = fkc.referenced_object_id
                             INNER JOIN sys.tables t
                             ON t.object_id = fkc.referenced_object_id
                       WHERE fk.parent_object_id=@objectId
                         AND fk.name = @conName
                       ORDER BY fkc.constraint_column_id
                                
                 OPEN c2
                FETCH c2 INTO @colName, @refColName, @refTable
               SELECT @colList = @colName
               SELECT @refColList = @refColName
                FETCH c2 INTO @colName, @refColName, @refTable
                WHILE @@FETCH_STATUS = 0
                BEGIN   
                      SELECT @colList = ',' + @colName
                      SELECT @refColList = ',' + @refColName
                       FETCH c2 INTO @colName,@refColName,@refTable
                  END    
                CLOSE c2
           DEALLOCATE c2
               SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT [' + @conName + '] FOREIGN KEY (' + @colList + ') REFERENCES ' + @refTable + '(' + @refColList + ') '
                      +  CASE
                         WHEN @onDelete != 'NO_ACTION' THEN 'on delete ' + @onDelete 
                         ELSE '' 
                          END
                      +  CASE 
                         WHEN @onUpdate != 'NO_ACTION' THEN 'on update ' + @onUpdate 
                         ELSE '' 
                          END
                PRINT @cmd
                   IF @debug=0
                 EXEC (@cmd)
                FETCH c1 INTO @conName, @onDelete, @onUpdate
       END
     CLOSE c1
DEALLOCATE c1

--  Rename the primary key and drop foreign keys in the source table
UPDATE IdentityCompressionLog SET status=11 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
   DECLARE c1 CURSOR FOR 
           SELECT name, type 
             FROM sys.key_constraints 
            WHERE parent_object_id = @objectId
            UNION ALL 
           SELECT name,type 
             FROM sys.foreign_keys 
            WHERE parent_object_id = @objectId
      OPEN c1
     FETCH c1 INTO @conName, @conType
     WHILE @@FETCH_STATUS = 0
     BEGIN 
               IF @conType = 'F'
           SELECT @cmd = 'ALTER TABLE [' + @sourceSchema + '].[' + @sourceTable + '] DROP CONSTRAINT [' + @conName + ']'
             ELSE
           SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '.' + @conName + ''',' + '''' + @conName + '_' + @suffix + ''''
            PRINT @cmd
               IF @debug = 0
             EXEC (@cmd)
            FETCH c1 INTO @conName,@conType
       END
     CLOSE c1
DEALLOCATE c1

-- Turn on change tracking if required
UPDATE IdentityCompressionLog SET status=12 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
	IF EXISTS (SELECT 1 FROM sys.change_tracking_tables WHERE OBJECT_ID=@objectId)
	BEGIN
		SELECT @cmd='ALTER TABLE '+@targetTable+' enable Change_tracking'
		exec (@cmd)
	END




-- Replace the source table with the target table.  Move the source table to the bak schema and append @suffix
UPDATE IdentityCompressionLog SET status=13 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
    SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '''' + ',''' + @sourceTable + '_' + @suffix + ''''
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'sp_rename ''' + REPLACE(REPLACE(@targetTable,'[',''),']','') + ''',''' + @sourceTable + ''''
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'ALTER SCHEMA [' + @sourceSchema + '] TRANSFER [data].[' + @sourceTable + ']'
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)
    SELECT @cmd = 'ALTER SCHEMA [BAK] TRANSFER [' + @sourceSchema + '].[' + @sourceTable + '_' + @suffix + ']'
     PRINT @cmd
        IF @debug = 0
      EXEC (@cmd)

--Update replication table if required
	UPDATE IdentityCompressionLog SET status=14 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
	IF EXISTS (SELECT 1 FROM dbo.ReplicationTable WHERE TableName=@fullSourceName)
	BEGIN
		UPDATE  dbo.ReplicationTable set LastRefreshChangeTrackingVersion = null
		WHERE TableName = @fullSourceName
	END

UPDATE IdentityCompressionLog SET status=0 WHERE runTime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable
GO


---------------------------------------------

-- dbo.IntAddSimpleSecurityForActions
create proc dbo.IntAddSimpleSecurityForActions
AS
BEGIN
	declare @everyone uniqueidentifier = '00000000-0000-0000-0000-000000000001';
	declare @count int;
	select @count = COUNT(PermissionGuid) from S3SimplePermission P where P.LootID = '18F307C3-C344-424F-A38E-1F7ABCD295A5' and P.IdentityGUID = @everyone;
	if (@count = 0) begin
		insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
			VALUES ('18F307C3-C344-424F-A38E-1F7ABCD295A5', @everyone, 1,1,1);
	end
	set @count = 0;
	select @count = COUNT(PermissionGuid) from S3SimplePermission P where P.LootID = '38CF0A6C-FBA8-44F9-A707-B8BAA2234EEB' and P.IdentityGUID = @everyone;
	if (@count = 0) begin
		insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
			VALUES ('38CF0A6C-FBA8-44F9-A707-B8BAA2234EEB', @everyone, 1,1,1);
	end
	set @count = 0;
	select @count = COUNT(PermissionGuid) from S3SimplePermission P where P.LootID = 'BA71645B-30B9-4ED1-A43B-89EFC06931B9' and P.IdentityGUID = @everyone;
	if (@count = 0) begin
		insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
			VALUES ('BA71645B-30B9-4ED1-A43B-89EFC06931B9', @everyone, 1,1,1);
	end
	set @count = 0;
	select @count = COUNT(PermissionGuid) from S3SimplePermission P where P.LootID = '74DAD74D-3F8C-4C31-A5FD-972EC0868A50' and P.IdentityGUID = @everyone;
	if (@count = 0) begin
		insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
			VALUES ('74DAD74D-3F8C-4C31-A5FD-972EC0868A50', @everyone, 1,1,1);
	end
END
GO


---------------------------------------------

-- dbo.dt_addtosourcecontrol
create proc dbo.dt_addtosourcecontrol
    @vchSourceSafeINI varchar(255) = '',
    @vchProjectName   varchar(255) ='',
    @vchComment       varchar(255) ='',
    @vchLoginName     varchar(255) ='',
    @vchPassword      varchar(255) =''

as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId = 0

declare @iStreamObjectId int
select @iStreamObjectId = 0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

declare @vchDatabaseName varchar(255)
select @vchDatabaseName = db_name()

declare @iReturnValue int
select @iReturnValue = 0

declare @iPropertyObjectId int
declare @vchParentId varchar(255)

declare @iObjectCount int
select @iObjectCount = 0

    exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 GOTO E_OAError


    /* Create Project in SS */
    exec @iReturn = sp_OAMethod @iObjectId,
                                'AddProjectToSourceSafe',
                                NULL,
                                @vchSourceSafeINI,
                                @vchProjectName output,
                                @@SERVERNAME,
                                @vchDatabaseName,
                                @vchLoginName,
                                @vchPassword,
                                @vchComment


    if @iReturn <> 0 GOTO E_OAError

    exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT

    if @iReturn <> 0 GOTO E_OAError

    /* Set Database Properties */

    begin tran SetProperties

    /* add high level object */

    exec @iPropertyObjectId = dbo.dt_adduserobject_vcs 'VCSProjectID'

    select @vchParentId = CONVERT(varchar(255),@iPropertyObjectId)

    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSProjectID', @vchParentId , NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSProject' , @vchProjectName , NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSourceSafeINI' , @vchSourceSafeINI , NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSQLServer', @@SERVERNAME, NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName, NULL

    if @@error <> 0 GOTO E_General_Error

    commit tran SetProperties

    declare cursorProcNames cursor for
        select convert(varchar(255), name) from sysobjects where type = 'P' and name not like 'dt_%'
    open cursorProcNames

    while 1 = 1
    begin
        declare @vchProcName varchar(255)
        fetch next from cursorProcNames into @vchProcName
        if @@fetch_status <> 0
            break

        select colid, text into #ProcLines
        from syscomments
        where id = object_id(@vchProcName)
        order by colid

        declare @iCurProcLine int
        declare @iProcLines int
        select @iCurProcLine = 1
        select @iProcLines = (select count(*) from #ProcLines)
        while @iCurProcLine <= @iProcLines
        begin
            declare @pos int
            select @pos = 1
            declare @iCurLineSize int
            select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine))
            while @pos <= @iCurLineSize
            begin
                declare @vchProcLinePiece varchar(255)
                select @vchProcLinePiece = convert(varchar(255),
                    substring((select text from #ProcLines where colid = @iCurProcLine),
                              @pos, 255 ))
                exec @iReturn = sp_OAMethod @iStreamObjectId, 'AddStream', @iReturnValue OUT, @vchProcLinePiece
                if @iReturn <> 0 GOTO E_OAError
                select @pos = @pos + 255
            end
            select @iCurProcLine = @iCurProcLine + 1
        end
        drop table #ProcLines

        exec @iReturn = sp_OAMethod @iObjectId,
                                    'CheckIn_StoredProcedure',
                                    NULL,
                                    @sProjectName = @vchProjectName,
                                    @sSourceSafeINI = @vchSourceSafeINI,
                                    @sServerName = @@SERVERNAME,
                                    @sDatabaseName = @vchDatabaseName,
                                    @sObjectName = @vchProcName,
                                    @sComment = @vchComment,
                                    @sLoginName = @vchLoginName,
                                    @sPassword = @vchPassword,
                                    @iVCSFlags = 0,
                                    @iActionFlag = 0,
                                    @sStream = ''

        if @iReturn = 0 select @iObjectCount = @iObjectCount + 1

    end

CleanUp:
	close cursorProcNames
	deallocate cursorProcNames
    select @vchProjectName
    select @iObjectCount
    return

E_General_Error:
    /* this is an all or nothing.  No specific error messages */
    goto CleanUp

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    goto CleanUp
GO


---------------------------------------------

-- dbo.dt_addtosourcecontrol_u
create proc dbo.dt_addtosourcecontrol_u
    @vchSourceSafeINI nvarchar(255) = '',
    @vchProjectName   nvarchar(255) ='',
    @vchComment       nvarchar(255) ='',
    @vchLoginName     nvarchar(255) ='',
    @vchPassword      nvarchar(255) =''

as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId = 0

declare @iStreamObjectId int
select @iStreamObjectId = 0

declare @VSSGUID nvarchar(100)
select @VSSGUID = N'SQLVersionControl.VCS_SQL'

declare @vchDatabaseName varchar(255)
select @vchDatabaseName = db_name()

declare @iReturnValue int
select @iReturnValue = 0

declare @iPropertyObjectId int
declare @vchParentId nvarchar(255)

declare @iObjectCount int
select @iObjectCount = 0

    exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 GOTO E_OAError


    /* Create Project in SS */
    exec @iReturn = sp_OAMethod @iObjectId,
                                'AddProjectToSourceSafe',
                                NULL,
                                @vchSourceSafeINI,
                                @vchProjectName output,
                                @@SERVERNAME,
                                @vchDatabaseName,
                                @vchLoginName,
                                @vchPassword,
                                @vchComment


    if @iReturn <> 0 GOTO E_OAError

    exec @iReturn = sp_OAGetProperty @iObjectId, N'GetStreamObject', @iStreamObjectId OUT

    if @iReturn <> 0 GOTO E_OAError

    /* Set Database Properties */

    begin tran SetProperties

    /* add high level object */

    exec @iPropertyObjectId = dbo.dt_adduserobject_vcs 'VCSProjectID'

    select @vchParentId = CONVERT(nvarchar(255),@iPropertyObjectId)

    exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSProjectID', @vchParentId , NULL
    exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSProject' , @vchProjectName , NULL
    exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSSourceSafeINI' , @vchSourceSafeINI , NULL
    exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSSQLServer', @@SERVERNAME, NULL
    exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName, NULL

    if @@error <> 0 GOTO E_General_Error

    commit tran SetProperties

    declare cursorProcNames cursor for
        select convert(nvarchar(255), name) from sysobjects where type = N'P' and name not like N'dt_%'
    open cursorProcNames

    while 1 = 1
    begin
        declare @vchProcName nvarchar(255)
        fetch next from cursorProcNames into @vchProcName
        if @@fetch_status <> 0
            break

        select colid, text into #ProcLines
        from syscomments
        where id = object_id(@vchProcName)
        order by colid

        declare @iCurProcLine int
        declare @iProcLines int
        select @iCurProcLine = 1
        select @iProcLines = (select count(*) from #ProcLines)
        while @iCurProcLine <= @iProcLines
        begin
            declare @pos int
            select @pos = 1
            declare @iCurLineSize int
            select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine))
            while @pos <= @iCurLineSize
            begin
                declare @vchProcLinePiece nvarchar(255)
                select @vchProcLinePiece = convert(nvarchar(255),
                    substring((select text from #ProcLines where colid = @iCurProcLine),
                              @pos, 255 ))
                exec @iReturn = sp_OAMethod @iStreamObjectId, N'AddStream', @iReturnValue OUT, @vchProcLinePiece
                if @iReturn <> 0 GOTO E_OAError
                select @pos = @pos + 255
            end
            select @iCurProcLine = @iCurProcLine + 1
        end
        drop table #ProcLines

        exec @iReturn = sp_OAMethod @iObjectId,
                                    'CheckIn_StoredProcedure',
                                    NULL,
                                    @sProjectName = @vchProjectName,
                                    @sSourceSafeINI = @vchSourceSafeINI,
                                    @sServerName = @@SERVERNAME,
                                    @sDatabaseName = @vchDatabaseName,
                                    @sObjectName = @vchProcName,
                                    @sComment = @vchComment,
                                    @sLoginName = @vchLoginName,
                                    @sPassword = @vchPassword,
                                    @iVCSFlags = 0,
                                    @iActionFlag = 0,
                                    @sStream = ''

        if @iReturn = 0 select @iObjectCount = @iObjectCount + 1

    end

CleanUp:
	close cursorProcNames
	deallocate cursorProcNames
    select @vchProjectName
    select @iObjectCount
    return

E_General_Error:
    /* this is an all or nothing.  No specific error messages */
    goto CleanUp

E_OAError:
    exec dbo.dt_displayoaerror_u @iObjectId, @iReturn
    goto CleanUp
GO


---------------------------------------------

-- dbo.dt_adduserobject
/*
**	Add an object to the dtproperties table
*/
create procedure dbo.dt_adduserobject
as
	set nocount on
	/*
	** Create the user object if it does not exist already
	*/
	begin transaction
		insert dbo.dtproperties (property) VALUES ('DtgSchemaOBJECT')
		update dbo.dtproperties set objectid=@@identity 
			where id=@@identity and property='DtgSchemaOBJECT'
	commit
	return @@identity
GO


---------------------------------------------

-- dbo.dt_adduserobject_vcs
create procedure dbo.dt_adduserobject_vcs
    @vchProperty varchar(64)

as

set nocount on

declare @iReturn int
    /*
    ** Create the user object if it does not exist already
    */
    begin transaction
        select @iReturn = objectid from dbo.dtproperties where property = @vchProperty
        if @iReturn IS NULL
        begin
            insert dbo.dtproperties (property) VALUES (@vchProperty)
            update dbo.dtproperties set objectid=@@identity
                    where id=@@identity and property=@vchProperty
            select @iReturn = @@identity
        end
    commit
    return @iReturn
GO


---------------------------------------------

-- dbo.dt_checkinobject
create proc dbo.dt_checkinobject
    @chObjectType  char(4),
    @vchObjectName varchar(255),
    @vchComment    varchar(255)='',
    @vchLoginName  varchar(255),
    @vchPassword   varchar(255)='',
    @iVCSFlags     int = 0,
    @iActionFlag   int = 0,   /* 0 => AddFile, 1 => CheckIn */
    @txStream1     Text = '', /* There is a bug that if items are NULL they do not pass to OLE servers */
    @txStream2     Text = '',
    @txStream3     Text = ''


as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId = 0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'


declare @iPropertyObjectId int
select @iPropertyObjectId  = 0

    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   varchar(255)
    declare @vchSourceSafeINI varchar(255)
    declare @vchServerName    varchar(255)
    declare @vchDatabaseName  varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        if @iActionFlag = 1
        begin
            /* Procedure Can have up to three streams
            Drop Stream, Create Stream, GRANT stream */

            begin tran compile_all

            /* try to compile the streams */
            exec (@txStream1)
            if @@error <> 0 GOTO E_Compile_Fail

            exec (@txStream2)
            if @@error <> 0 GOTO E_Compile_Fail

            exec (@txStream3)
            if @@error <> 0 GOTO E_Compile_Fail
        end

        exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
        if @iReturn <> 0 GOTO E_OAError

        if @iActionFlag = 1
        begin
            exec @iReturn = sp_OAMethod @iObjectId,
                                        'CheckIn_StoredProcedure',
                                        NULL,
                                        @sProjectName = @vchProjectName,
                                        @sSourceSafeINI = @vchSourceSafeINI,
                                        @sServerName = @vchServerName,
                                        @sDatabaseName = @vchDatabaseName,
                                        @sObjectName = @vchObjectName,
                                        @sComment = @vchComment,
                                        @sLoginName = @vchLoginName,
                                        @sPassword = @vchPassword,
                                        @iVCSFlags = @iVCSFlags,
                                        @iActionFlag = @iActionFlag,
                                        @sStream = @txStream2
        end
        else
        begin
            declare @iStreamObjectId int
            declare @iReturnValue int

            exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT
            if @iReturn <> 0 GOTO E_OAError

            select colid, text into #ProcLines
            from syscomments
            where id = object_id(@vchObjectName)
            order by colid

            declare @iCurProcLine int
            declare @iProcLines int
            select @iCurProcLine = 1
            select @iProcLines = (select count(*) from #ProcLines)
            while @iCurProcLine <= @iProcLines
            begin
                declare @pos int
                select @pos = 1
                declare @iCurLineSize int
                select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine))
                while @pos <= @iCurLineSize
                begin
                    declare @vchProcLinePiece varchar(255)
                    select @vchProcLinePiece = convert(varchar(255),
                        substring((select text from #ProcLines where colid = @iCurProcLine),
                                  @pos, 255 ))
                    exec @iReturn = sp_OAMethod @iStreamObjectId, 'AddStream', @iReturnValue OUT, @vchProcLinePiece
                    if @iReturn <> 0 GOTO E_OAError
                    select @pos = @pos + 255
                end
                select @iCurProcLine = @iCurProcLine + 1
            end
            drop table #ProcLines

            exec @iReturn = sp_OAMethod @iObjectId,
                                        'CheckIn_StoredProcedure',
                                        NULL,
                                        @sProjectName = @vchProjectName,
                                        @sSourceSafeINI = @vchSourceSafeINI,
                                        @sServerName = @vchServerName,
                                        @sDatabaseName = @vchDatabaseName,
                                        @sObjectName = @vchObjectName,
                                        @sComment = @vchComment,
                                        @sLoginName = @vchLoginName,
                                        @sPassword = @vchPassword,
                                        @iVCSFlags = @iVCSFlags,
                                        @iActionFlag = @iActionFlag,
                                        @sStream = ''
        end

        if @iReturn <> 0 GOTO E_OAError

        if @iActionFlag = 1
        begin
            commit tran compile_all
            if @@error <> 0 GOTO E_Compile_Fail
        end

    end

CleanUp:
    return

E_Compile_Fail:
    declare @lerror int
    select @lerror = @@error
    rollback tran compile_all
    RAISERROR (@lerror,16,-1)
    goto CleanUp

E_OAError:
    if @iActionFlag = 1 rollback tran compile_all
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    goto CleanUp
GO


---------------------------------------------

-- dbo.dt_checkinobject_u
create proc dbo.dt_checkinobject_u
    @chObjectType  char(4),
    @vchObjectName nvarchar(255),
    @vchComment    nvarchar(255)='',
    @vchLoginName  nvarchar(255),
    @vchPassword   nvarchar(255)='',
    @iVCSFlags     int = 0,
    @iActionFlag   int = 0,   /* 0 => AddFile, 1 => CheckIn */
    @txStream1     Text = '', /* There is a bug that if items are NULL they do not pass to OLE servers */
    @txStream2     Text = '',
    @txStream3     Text = ''


as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId = 0

declare @VSSGUID nvarchar(100)
select @VSSGUID = N'SQLVersionControl.VCS_SQL'


declare @iPropertyObjectId int
select @iPropertyObjectId  = 0

    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   nvarchar(255)
    declare @vchSourceSafeINI nvarchar(255)
    declare @vchServerName    nvarchar(255)
    declare @vchDatabaseName  nvarchar(255)
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        if @iActionFlag = 1
        begin
            /* Procedure Can have up to three streams
            Drop Stream, Create Stream, GRANT stream */

            begin tran compile_all

            /* try to compile the streams */
            exec (@txStream1)
            if @@error <> 0 GOTO E_Compile_Fail

            exec (@txStream2)
            if @@error <> 0 GOTO E_Compile_Fail

            exec (@txStream3)
            if @@error <> 0 GOTO E_Compile_Fail
        end

        exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
        if @iReturn <> 0 GOTO E_OAError

        if @iActionFlag = 1
        begin
            exec @iReturn = sp_OAMethod @iObjectId,
                                        N'CheckIn_StoredProcedure',
                                        NULL,
                                        @sProjectName = @vchProjectName,
                                        @sSourceSafeINI = @vchSourceSafeINI,
                                        @sServerName = @vchServerName,
                                        @sDatabaseName = @vchDatabaseName,
                                        @sObjectName = @vchObjectName,
                                        @sComment = @vchComment,
                                        @sLoginName = @vchLoginName,
                                        @sPassword = @vchPassword,
                                        @iVCSFlags = @iVCSFlags,
                                        @iActionFlag = @iActionFlag,
                                        @sStream = @txStream2
        end
        else
        begin
            declare @iStreamObjectId int
            declare @iReturnValue int

            exec @iReturn = sp_OAGetProperty @iObjectId, N'GetStreamObject', @iStreamObjectId OUT
            if @iReturn <> 0 GOTO E_OAError

            select colid, text into #ProcLines
            from syscomments
            where id = object_id(@vchObjectName)
            order by colid

            declare @iCurProcLine int
            declare @iProcLines int
            select @iCurProcLine = 1
            select @iProcLines = (select count(*) from #ProcLines)
            while @iCurProcLine <= @iProcLines
            begin
                declare @pos int
                select @pos = 1
                declare @iCurLineSize int
                select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine))
                while @pos <= @iCurLineSize
                begin
                    declare @vchProcLinePiece nvarchar(255)
                    select @vchProcLinePiece = convert(nvarchar(255),
                        substring((select text from #ProcLines where colid = @iCurProcLine),
                                  @pos, 255 ))
                    exec @iReturn = sp_OAMethod @iStreamObjectId, N'AddStream', @iReturnValue OUT, @vchProcLinePiece
                    if @iReturn <> 0 GOTO E_OAError
                    select @pos = @pos + 255
                end
                select @iCurProcLine = @iCurProcLine + 1
            end
            drop table #ProcLines

            exec @iReturn = sp_OAMethod @iObjectId,
                                        N'CheckIn_StoredProcedure',
                                        NULL,
                                        @sProjectName = @vchProjectName,
                                        @sSourceSafeINI = @vchSourceSafeINI,
                                        @sServerName = @vchServerName,
                                        @sDatabaseName = @vchDatabaseName,
                                        @sObjectName = @vchObjectName,
                                        @sComment = @vchComment,
                                        @sLoginName = @vchLoginName,
                                        @sPassword = @vchPassword,
                                        @iVCSFlags = @iVCSFlags,
                                        @iActionFlag = @iActionFlag,
                                        @sStream = ''
        end

        if @iReturn <> 0 GOTO E_OAError

        if @iActionFlag = 1
        begin
            commit tran compile_all
            if @@error <> 0 GOTO E_Compile_Fail
        end

    end

CleanUp:
    return

E_Compile_Fail:
    declare @lerror int
    select @lerror = @@error
    rollback tran compile_all
    RAISERROR (@lerror,16,-1)
    goto CleanUp

E_OAError:
    if @iActionFlag = 1 rollback tran compile_all
    exec dbo.dt_displayoaerror_u @iObjectId, @iReturn
    goto CleanUp
GO


---------------------------------------------

-- dbo.dt_checkoutobject
create proc dbo.dt_checkoutobject
    @chObjectType  char(4),
    @vchObjectName varchar(255),
    @vchComment    varchar(255),
    @vchLoginName  varchar(255),
    @vchPassword   varchar(255),
    @iVCSFlags     int = 0,
    @iActionFlag   int = 0/* 0 => Checkout, 1 => GetLatest, 2 => UndoCheckOut */

as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId =0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

declare @iReturnValue int
select @iReturnValue = 0

declare @vchTempText varchar(255)

/* this is for our strings */
declare @iStreamObjectId int
select @iStreamObjectId = 0

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   varchar(255)
    declare @vchSourceSafeINI varchar(255)
    declare @vchServerName    varchar(255)
    declare @vchDatabaseName  varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        /* Procedure Can have up to three streams
           Drop Stream, Create Stream, GRANT stream */

        exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = sp_OAMethod @iObjectId,
                                    'CheckOut_StoredProcedure',
                                    NULL,
                                    @sProjectName = @vchProjectName,
                                    @sSourceSafeINI = @vchSourceSafeINI,
                                    @sObjectName = @vchObjectName,
                                    @sServerName = @vchServerName,
                                    @sDatabaseName = @vchDatabaseName,
                                    @sComment = @vchComment,
                                    @sLoginName = @vchLoginName,
                                    @sPassword = @vchPassword,
                                    @iVCSFlags = @iVCSFlags,
                                    @iActionFlag = @iActionFlag

        if @iReturn <> 0 GOTO E_OAError


        exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        create table #commenttext (id int identity, sourcecode varchar(255))


        select @vchTempText = 'STUB'
        while @vchTempText IS NOT NULL
        begin
            exec @iReturn = sp_OAMethod @iStreamObjectId, 'GetStream', @iReturnValue OUT, @vchTempText OUT
            if @iReturn <> 0 GOTO E_OAError

            if (@vchTempText IS NOT NULL) insert into #commenttext (sourcecode) select @vchTempText
        end

        select 'VCS'=sourcecode from #commenttext order by id
        select 'SQL'=text from syscomments where id = object_id(@vchObjectName) order by colid

    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    GOTO CleanUp
GO


---------------------------------------------

-- dbo.dt_checkoutobject_u
create proc dbo.dt_checkoutobject_u
    @chObjectType  char(4),
    @vchObjectName nvarchar(255),
    @vchComment    nvarchar(255),
    @vchLoginName  nvarchar(255),
    @vchPassword   nvarchar(255),
    @iVCSFlags     int = 0,
    @iActionFlag   int = 0/* 0 => Checkout, 1 => GetLatest, 2 => UndoCheckOut */

as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId =0

declare @VSSGUID nvarchar(100)
select @VSSGUID = N'SQLVersionControl.VCS_SQL'

declare @iReturnValue int
select @iReturnValue = 0

declare @vchTempText nvarchar(255)

/* this is for our strings */
declare @iStreamObjectId int
select @iStreamObjectId = 0

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   nvarchar(255)
    declare @vchSourceSafeINI nvarchar(255)
    declare @vchServerName    nvarchar(255)
    declare @vchDatabaseName  nvarchar(255)
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        /* Procedure Can have up to three streams
           Drop Stream, Create Stream, GRANT stream */

        exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = sp_OAMethod @iObjectId,
                                    N'CheckOut_StoredProcedure',
                                    NULL,
                                    @sProjectName = @vchProjectName,
                                    @sSourceSafeINI = @vchSourceSafeINI,
                                    @sObjectName = @vchObjectName,
                                    @sServerName = @vchServerName,
                                    @sDatabaseName = @vchDatabaseName,
                                    @sComment = @vchComment,
                                    @sLoginName = @vchLoginName,
                                    @sPassword = @vchPassword,
                                    @iVCSFlags = @iVCSFlags,
                                    @iActionFlag = @iActionFlag

        if @iReturn <> 0 GOTO E_OAError


        exec @iReturn = sp_OAGetProperty @iObjectId, N'GetStreamObject', @iStreamObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        create table #commenttext (id int identity, sourcecode nvarchar(255))


        select @vchTempText = N'STUB'
        while @vchTempText IS NOT NULL
        begin
            exec @iReturn = sp_OAMethod @iStreamObjectId, N'GetStream', @iReturnValue OUT, @vchTempText OUT
            if @iReturn <> 0 GOTO E_OAError

            if (@vchTempText IS NOT NULL) insert into #commenttext (sourcecode) select @vchTempText
        end

        select N'VCS'=sourcecode from #commenttext order by id
        select N'SQL'=text from syscomments where id = object_id(@vchObjectName) order by colid

    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror_u @iObjectId, @iReturn
    GOTO CleanUp
GO


---------------------------------------------

-- dbo.dt_displayoaerror
CREATE PROCEDURE dbo.dt_displayoaerror
    @iObject int,
    @iresult int
as

set nocount on

declare @vchOutput      varchar(255)
declare @hr             int
declare @vchSource      varchar(255)
declare @vchDescription varchar(255)

    exec @hr = sp_OAGetErrorInfo @iObject, @vchSource OUT, @vchDescription OUT

    select @vchOutput = @vchSource + ': ' + @vchDescription
    raiserror (@vchOutput,16,-1)

    return
GO


---------------------------------------------

-- dbo.dt_displayoaerror_u
CREATE PROCEDURE dbo.dt_displayoaerror_u
    @iObject int,
    @iresult int
as

set nocount on

declare @vchOutput      nvarchar(255)
declare @hr             int
declare @vchSource      nvarchar(255)
declare @vchDescription nvarchar(255)

    exec @hr = sp_OAGetErrorInfo @iObject, @vchSource OUT, @vchDescription OUT

    select @vchOutput = @vchSource + ': ' + @vchDescription
    raiserror (@vchOutput,16,-1)

    return
GO


---------------------------------------------

-- dbo.dt_droppropertiesbyid
/*
**	Drop one or all the associated properties of an object or an attribute 
**
**	dt_dropproperties objid, null or '' -- drop all properties of the object itself
**	dt_dropproperties objid, property -- drop the property
*/
create procedure dbo.dt_droppropertiesbyid
	@id int,
	@property varchar(64)
as
	set nocount on

	if (@property is null) or (@property = '')
		delete from dbo.dtproperties where objectid=@id
	else
		delete from dbo.dtproperties 
			where objectid=@id and property=@property
GO


---------------------------------------------

-- dbo.dt_dropuserobjectbyid
/*
**	Drop an object from the dbo.dtproperties table
*/
create procedure dbo.dt_dropuserobjectbyid
	@id int
as
	set nocount on
	delete from dbo.dtproperties where objectid=@id
GO


---------------------------------------------

-- dbo.dt_generateansiname
/* 
**	Generate an ansi name that is unique in the dtproperties.value column 
*/ 
create procedure dbo.dt_generateansiname(@name varchar(255) output) 
as 
	declare @prologue varchar(20) 
	declare @indexstring varchar(20) 
	declare @index integer 
 
	set @prologue = 'MSDT-A-' 
	set @index = 1 
 
	while 1 = 1 
	begin 
		set @indexstring = cast(@index as varchar(20)) 
		set @name = @prologue + @indexstring 
		if not exists (select value from dtproperties where value = @name) 
			break 
		 
		set @index = @index + 1 
 
		if (@index = 10000) 
			goto TooMany 
	end 
 
Leave: 
 
	return 
 
TooMany: 
 
	set @name = 'DIAGRAM' 
	goto Leave
GO


---------------------------------------------

-- dbo.dt_getobjwithprop
/*
**	Retrieve the owner object(s) of a given property
*/
create procedure dbo.dt_getobjwithprop
	@property varchar(30),
	@value varchar(255)
as
	set nocount on

	if (@property is null) or (@property = '')
	begin
		raiserror('Must specify a property name.',-1,-1)
		return (1)
	end

	if (@value is null)
		select objectid id from dbo.dtproperties
			where property=@property

	else
		select objectid id from dbo.dtproperties
			where property=@property and value=@value
GO


---------------------------------------------

-- dbo.dt_getobjwithprop_u
/*
**	Retrieve the owner object(s) of a given property
*/
create procedure dbo.dt_getobjwithprop_u
	@property varchar(30),
	@uvalue nvarchar(255)
as
	set nocount on

	if (@property is null) or (@property = '')
	begin
		raiserror('Must specify a property name.',-1,-1)
		return (1)
	end

	if (@uvalue is null)
		select objectid id from dbo.dtproperties
			where property=@property

	else
		select objectid id from dbo.dtproperties
			where property=@property and uvalue=@uvalue
GO


---------------------------------------------

-- dbo.dt_getpropertiesbyid
/*
**	Retrieve properties by id's
**
**	dt_getproperties objid, null or '' -- retrieve all properties of the object itself
**	dt_getproperties objid, property -- retrieve the property specified
*/
create procedure dbo.dt_getpropertiesbyid
	@id int,
	@property varchar(64)
as
	set nocount on

	if (@property is null) or (@property = '')
		select property, version, value, lvalue
			from dbo.dtproperties
			where  @id=objectid
	else
		select property, version, value, lvalue
			from dbo.dtproperties
			where  @id=objectid and @property=property
GO


---------------------------------------------

-- dbo.dt_getpropertiesbyid_u
/*
**	Retrieve properties by id's
**
**	dt_getproperties objid, null or '' -- retrieve all properties of the object itself
**	dt_getproperties objid, property -- retrieve the property specified
*/
create procedure dbo.dt_getpropertiesbyid_u
	@id int,
	@property varchar(64)
as
	set nocount on

	if (@property is null) or (@property = '')
		select property, version, uvalue, lvalue
			from dbo.dtproperties
			where  @id=objectid
	else
		select property, version, uvalue, lvalue
			from dbo.dtproperties
			where  @id=objectid and @property=property
GO


---------------------------------------------

-- dbo.dt_getpropertiesbyid_vcs
create procedure dbo.dt_getpropertiesbyid_vcs
    @id       int,
    @property varchar(64),
    @value    varchar(255) = NULL OUT

as

    set nocount on

    select @value = (
        select value
                from dbo.dtproperties
                where @id=objectid and @property=property
                )
GO


---------------------------------------------

-- dbo.dt_getpropertiesbyid_vcs_u
create procedure dbo.dt_getpropertiesbyid_vcs_u
    @id       int,
    @property varchar(64),
    @value    nvarchar(255) = NULL OUT

as

    set nocount on

    select @value = (
        select uvalue
                from dbo.dtproperties
                where @id=objectid and @property=property
                )
GO


---------------------------------------------

-- dbo.dt_isundersourcecontrol
create proc dbo.dt_isundersourcecontrol
    @vchLoginName varchar(255) = '',
    @vchPassword  varchar(255) = '',
    @iWhoToo      int = 0 /* 0 => Just check project; 1 => get list of objs */

as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId = 0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

declare @iReturnValue int
select @iReturnValue = 0

declare @iStreamObjectId int
select @iStreamObjectId   = 0

declare @vchTempText varchar(255)

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   varchar(255)
    declare @vchSourceSafeINI varchar(255)
    declare @vchServerName    varchar(255)
    declare @vchDatabaseName  varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if (@vchProjectName IS NULL) or (@vchSourceSafeINI  IS NULL) or (@vchServerName IS NULL) or (@vchDatabaseName IS NULL)
    begin
        RAISERROR('Not Under Source Control',16,-1)
        return
    end

    if @iWhoToo = 1
    begin

        /* Get List of Procs in the project */
        exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = sp_OAMethod @iObjectId,
                                    'GetListOfObjects',
                                    NULL,
                                    @vchProjectName,
                                    @vchSourceSafeINI,
                                    @vchServerName,
                                    @vchDatabaseName,
                                    @vchLoginName,
                                    @vchPassword

        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        create table #ObjectList (id int identity, vchObjectlist varchar(255))

        select @vchTempText = 'STUB'
        while @vchTempText IS NOT NULL
        begin
            exec @iReturn = sp_OAMethod @iStreamObjectId, 'GetStream', @iReturnValue OUT, @vchTempText OUT
            if @iReturn <> 0 GOTO E_OAError

            if (@vchTempText IS NOT NULL) insert into #ObjectList (vchObjectlist ) select @vchTempText
        end

        select vchObjectlist from #ObjectList order by id
    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    goto CleanUp
GO


---------------------------------------------

-- dbo.dt_isundersourcecontrol_u
create proc dbo.dt_isundersourcecontrol_u
    @vchLoginName nvarchar(255) = '',
    @vchPassword  nvarchar(255) = '',
    @iWhoToo      int = 0 /* 0 => Just check project; 1 => get list of objs */

as

	set nocount on

	declare @iReturn int
	declare @iObjectId int
	select @iObjectId = 0

	declare @VSSGUID nvarchar(100)
	select @VSSGUID = N'SQLVersionControl.VCS_SQL'

	declare @iReturnValue int
	select @iReturnValue = 0

	declare @iStreamObjectId int
	select @iStreamObjectId   = 0

	declare @vchTempText nvarchar(255)

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   nvarchar(255)
    declare @vchSourceSafeINI nvarchar(255)
    declare @vchServerName    nvarchar(255)
    declare @vchDatabaseName  nvarchar(255)
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if (@vchProjectName IS NULL) or (@vchSourceSafeINI  IS NULL) or (@vchServerName IS NULL) or (@vchDatabaseName IS NULL)
    begin
        RAISERROR(N'Not Under Source Control',16,-1)
        return
    end

    if @iWhoToo = 1
    begin

        /* Get List of Procs in the project */
        exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = sp_OAMethod @iObjectId,
                                    N'GetListOfObjects',
                                    NULL,
                                    @vchProjectName,
                                    @vchSourceSafeINI,
                                    @vchServerName,
                                    @vchDatabaseName,
                                    @vchLoginName,
                                    @vchPassword

        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = sp_OAGetProperty @iObjectId, N'GetStreamObject', @iStreamObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        create table #ObjectList (id int identity, vchObjectlist nvarchar(255))

        select @vchTempText = N'STUB'
        while @vchTempText IS NOT NULL
        begin
            exec @iReturn = sp_OAMethod @iStreamObjectId, N'GetStream', @iReturnValue OUT, @vchTempText OUT
            if @iReturn <> 0 GOTO E_OAError

            if (@vchTempText IS NOT NULL) insert into #ObjectList (vchObjectlist ) select @vchTempText
        end

        select vchObjectlist from #ObjectList order by id
    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror_u @iObjectId, @iReturn
    goto CleanUp
GO


---------------------------------------------

-- dbo.dt_removefromsourcecontrol
create procedure dbo.dt_removefromsourcecontrol

as

    set nocount on

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    exec dbo.dt_droppropertiesbyid @iPropertyObjectId, null

    /* -1 is returned by dt_droppopertiesbyid */
    if @@error <> 0 and @@error <> -1 return 1

    return 0
GO


---------------------------------------------

-- dbo.dt_setpropertybyid
/*
**	If the property already exists, reset the value; otherwise add property
**		id -- the id in sysobjects of the object
**		property -- the name of the property
**		value -- the text value of the property
**		lvalue -- the binary value of the property (image)
*/
create procedure dbo.dt_setpropertybyid
	@id int,
	@property varchar(64),
	@value varchar(255),
	@lvalue image
as
	set nocount on
	declare @uvalue nvarchar(255) 
	set @uvalue = convert(nvarchar(255), @value) 
	if exists (select * from dbo.dtproperties 
			where objectid=@id and property=@property)
	begin
		--
		-- bump the version count for this row as we update it
		--
		update dbo.dtproperties set value=@value, uvalue=@uvalue, lvalue=@lvalue, version=version+1
			where objectid=@id and property=@property
	end
	else
	begin
		--
		-- version count is auto-set to 0 on initial insert
		--
		insert dbo.dtproperties (property, objectid, value, uvalue, lvalue)
			values (@property, @id, @value, @uvalue, @lvalue)
	end
GO


---------------------------------------------

-- dbo.dt_setpropertybyid_u
/*
**	If the property already exists, reset the value; otherwise add property
**		id -- the id in sysobjects of the object
**		property -- the name of the property
**		uvalue -- the text value of the property
**		lvalue -- the binary value of the property (image)
*/
create procedure dbo.dt_setpropertybyid_u
	@id int,
	@property varchar(64),
	@uvalue nvarchar(255),
	@lvalue image
as
	set nocount on
	-- 
	-- If we are writing the name property, find the ansi equivalent. 
	-- If there is no lossless translation, generate an ansi name. 
	-- 
	declare @avalue varchar(255) 
	set @avalue = null 
	if (@uvalue is not null) 
	begin 
		if (convert(nvarchar(255), convert(varchar(255), @uvalue)) = @uvalue) 
		begin 
			set @avalue = convert(varchar(255), @uvalue) 
		end 
		else 
		begin 
			if 'DtgSchemaNAME' = @property 
			begin 
				exec dbo.dt_generateansiname @avalue output 
			end 
		end 
	end 
	if exists (select * from dbo.dtproperties 
			where objectid=@id and property=@property)
	begin
		--
		-- bump the version count for this row as we update it
		--
		update dbo.dtproperties set value=@avalue, uvalue=@uvalue, lvalue=@lvalue, version=version+1
			where objectid=@id and property=@property
	end
	else
	begin
		--
		-- version count is auto-set to 0 on initial insert
		--
		insert dbo.dtproperties (property, objectid, value, uvalue, lvalue)
			values (@property, @id, @avalue, @uvalue, @lvalue)
	end
GO


---------------------------------------------

-- dbo.dt_validateloginparams
create proc dbo.dt_validateloginparams
    @vchLoginName  varchar(255),
    @vchPassword   varchar(255)
as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId =0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchSourceSafeINI varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT

    exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 GOTO E_OAError

    exec @iReturn = sp_OAMethod @iObjectId,
                                'ValidateLoginParams',
                                NULL,
                                @sSourceSafeINI = @vchSourceSafeINI,
                                @sLoginName = @vchLoginName,
                                @sPassword = @vchPassword
    if @iReturn <> 0 GOTO E_OAError

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    GOTO CleanUp
GO


---------------------------------------------

-- dbo.dt_validateloginparams_u
create proc dbo.dt_validateloginparams_u
    @vchLoginName  nvarchar(255),
    @vchPassword   nvarchar(255)
as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId =0

declare @VSSGUID nvarchar(100)
select @VSSGUID = N'SQLVersionControl.VCS_SQL'

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchSourceSafeINI nvarchar(255)
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT

    exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 GOTO E_OAError

    exec @iReturn = sp_OAMethod @iObjectId,
                                N'ValidateLoginParams',
                                NULL,
                                @sSourceSafeINI = @vchSourceSafeINI,
                                @sLoginName = @vchLoginName,
                                @sPassword = @vchPassword
    if @iReturn <> 0 GOTO E_OAError

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror_u @iObjectId, @iReturn
    GOTO CleanUp
GO


---------------------------------------------

-- dbo.dt_vcsenabled
create proc dbo.dt_vcsenabled

as

set nocount on

declare @iObjectId int
select @iObjectId = 0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

    declare @iReturn int
    exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 raiserror('', 16, -1) /* Can't Load Helper DLLC */
GO


---------------------------------------------

-- dbo.dt_verstamp006
/*
**	This procedure returns the version number of the stored
**    procedures used by the Microsoft Visual Database Tools.
**    Current version is 7.0.00.
*/
create procedure dbo.dt_verstamp006
as
	select 7000
GO


---------------------------------------------

-- dbo.dt_verstamp007
/*
**	This procedure returns the version number of the stored
**    procedures used by the the Microsoft Visual Database Tools.
**	Version is 7.0.05.
*/
create procedure dbo.dt_verstamp007
as
	select 7005
GO


---------------------------------------------

-- dbo.dt_whocheckedout
create proc dbo.dt_whocheckedout
        @chObjectType  char(4),
        @vchObjectName varchar(255),
        @vchLoginName  varchar(255),
        @vchPassword   varchar(255)

as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId =0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

    declare @iPropertyObjectId int

    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   varchar(255)
    declare @vchSourceSafeINI varchar(255)
    declare @vchServerName    varchar(255)
    declare @vchDatabaseName  varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        declare @vchReturnValue varchar(255)
        select @vchReturnValue = ''

        exec @iReturn = sp_OAMethod @iObjectId,
                                    'WhoCheckedOut',
                                    @vchReturnValue OUT,
                                    @sProjectName = @vchProjectName,
                                    @sSourceSafeINI = @vchSourceSafeINI,
                                    @sObjectName = @vchObjectName,
                                    @sServerName = @vchServerName,
                                    @sDatabaseName = @vchDatabaseName,
                                    @sLoginName = @vchLoginName,
                                    @sPassword = @vchPassword

        if @iReturn <> 0 GOTO E_OAError

        select @vchReturnValue

    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    GOTO CleanUp
GO


---------------------------------------------

-- dbo.dt_whocheckedout_u
create proc dbo.dt_whocheckedout_u
        @chObjectType  char(4),
        @vchObjectName nvarchar(255),
        @vchLoginName  nvarchar(255),
        @vchPassword   nvarchar(255)

as

set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId =0

declare @VSSGUID nvarchar(100)
select @VSSGUID = N'SQLVersionControl.VCS_SQL'

    declare @iPropertyObjectId int

    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   nvarchar(255)
    declare @vchSourceSafeINI nvarchar(255)
    declare @vchServerName    nvarchar(255)
    declare @vchDatabaseName  nvarchar(255)
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        declare @vchReturnValue nvarchar(255)
        select @vchReturnValue = ''

        exec @iReturn = sp_OAMethod @iObjectId,
                                    N'WhoCheckedOut',
                                    @vchReturnValue OUT,
                                    @sProjectName = @vchProjectName,
                                    @sSourceSafeINI = @vchSourceSafeINI,
                                    @sObjectName = @vchObjectName,
                                    @sServerName = @vchServerName,
                                    @sDatabaseName = @vchDatabaseName,
                                    @sLoginName = @vchLoginName,
                                    @sPassword = @vchPassword

        if @iReturn <> 0 GOTO E_OAError

        select @vchReturnValue

    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror_u @iObjectId, @iReturn
    GOTO CleanUp
GO


---------------------------------------------

-- dbo.procActionLogSummarize
create proc procActionLogSummarize as
insert into actionloghistory (Year, Month, Day, Action, SubAction, SumDuration, AvgDuration, MinDuration, MaxDuration, StdevDuration, Count)
select Year, Month, Day, Action, SubAction, SumDuration, AvgDuration, MinDuration, MaxDuration, StdevDuration, Count
from viewactionlogsummary

truncate table actionlog
GO


---------------------------------------------

-- dbo.procAddIdentityColumnToTable
--NOTE: This procedure may fail if there's already an Identity Column in the table.
CREATE proc [dbo].[procAddIdentityColumnToTable](
	@SchemaName NVARCHAR(128),
	@TableName NVARCHAR(MAX),
	@ColumnName NVARCHAR(128),
	 @DebugMode bit = 0, @Seed NVARCHAR(128) = '1', @Increment nvarchar(128) = '1')

AS
BEGIN

DECLARE @sql varchar(max)

IF dbo.tableColumnExists(@SchemaName, @TableName, @ColumnName)=0 BEGIN
	SET @SQL = 	'ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName))
	SET @SQL = @SQL + ' ADD ' + @ColumnName
	SET @SQL = @SQL + ' ' + 'int'
	SET @SQL = @SQL + ' NOT NULL CONSTRAINT DF_' + replace(@TableName,' ','_') + '_' + @ColumnName
	SET @SQL = @SQL + ' IDENTITY(' + @Seed + ',' + @Increment + ');'
	SET @SQL = @SQL + ' ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName))
	SET @SQL = @SQL + ' ADD PRIMARY KEY (' + @ColumnName + ');'
	IF @DebugMode = 0 BEGIN
		EXEC (@SQL)
		PRINT @ColumnName + ' added to ' + @TableName
	END ELSE BEGIN
		PRINT @SQL
	END
	
END


END
GO


---------------------------------------------

-- dbo.procAddPlansDimensionToAllModelDataConfigs
CREATE proc [dbo].[procAddPlansDimensionToAllModelDataConfigs] 
	@override bit = 0
as

declare @cnt int
select @cnt  = count(*) from emfsubtable
if @cnt = 0 or @override = 1 begin
	insert into emfmodeldataconfigdimensionlink (modeldataconfigguid, dimensionguid)
	select mdc.modeldataconfigguid,  (select listguid from securelist where listtype =2) from emfmodeldataconfig mdc left join emfmodeldataconfigdimensionlink  mdcdl on mdc.modeldataconfigguid = mdcdl.modeldataconfigguid and mdcdl.dimensionguid = (select listguid from securelist where listtype =2) 
	where mdcdl.modeldataconfigguid is null

	update  emfmodeldataconfigdimensionlink  set ismodelkey =1
end
GO


---------------------------------------------

-- dbo.procAddTableDeleteVersionRows
CREATE proc procAddTableDeleteVersionRows
as


	insert into tabledeleteversion(tablename) 	select 'UserUserGroupLink' where 0 = (select count(*) from tabledeleteversion where tablename = 'UserUserGroupLink')
GO


---------------------------------------------

-- dbo.procAddWorkerToActiveController
CREATE    PROCEDURE [dbo].[procAddWorkerToActiveController]
@ControllerID as uniqueidentifier,
@WorkerID as uniqueidentifier
 AS

IF ((select count(*) from [dbo].[ActiveControllers] where ControllerID=@ControllerID AND WorkerID=@WorkerID) = 0)
BEGIN
	INSERT INTO [dbo].[ActiveControllers] (ControllerID,WorkerID,[TimeStamp]) VALUES (@ControllerID, @WorkerID, getdate())
END
GO


---------------------------------------------

-- dbo.procAdjustTemplateSectionCounts
CREATE PROCEDURE [dbo].[procAdjustTemplateSectionCounts] (@templateGUID UNIQUEIDENTIFIER)
AS
BEGIN

    IF EXISTS(SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID)
    BEGIN
        -- child profiles do not have their own settings (main template should be used instead)
        RETURN; -- do nothing
    END

	;WITH newSectionCounts AS (
	    SELECT
	        TSC.[TemplateGUID],
	        TSC.[SettingID],
	        CASE
                WHEN (RM.[RecommendedMaxCount] IS NOT NULL) AND ((RM.[RecommendedMaxCount] - TSC.[ActualMaxNumberOfFillins]) BETWEEN 0 AND 10) -- 10 is placeholder
                    THEN
                        RM.[RecommendedMaxCount] -- user recommended max section count because fill-ins can fit into it and won't force profile creation
	            WHEN ((TSC.[ActualSectionCount] - TSC.[ActualMaxNumberOfFillins]) BETWEEN 0 AND 10) -- 10 is placeholder
	                THEN
	                    TSC.[ActualSectionCount] -- use existing section count because fill-ins can fit into the placeholder
                ELSE
	                TSC.[RecommendedSectionCount] -- use recommended section count because the difference is too high
	        END AS [NewSectionCountToUse]

	    FROM [dbo].[viewTemplateSectionCountsWithRecommended] AS TSC
            INNER JOIN [dbo].[EMFModelTemplate] AS MT
                ON TSC.[TemplateGUID] = MT.[ModelTemplateGUID]
            LEFT JOIN [dbo].[MEScoreExpansionRecommendedMaxCount] AS RM
                ON RM.[SectionName] = TSC.[SectionName] AND MT.[Name] = 'OB Departmental Budget' -- only 'OB Departmental Budget' supports expansion profiles
	)        
	UPDATE TS
	SET TS.[Value] = SC.[NewSectionCountToUse]
	FROM [dbo].[TemplateSettings] AS TS
	INNER JOIN newSectionCounts AS SC
	    ON SC.[TemplateGUID] = TS.[TemplateGUID] AND SC.[SettingID] = TS.[SettingID]
	WHERE 1=1
	    AND TS.[TemplateGUID] = @templateGUID
	    AND TS.[Value] <> SC.[NewSectionCountToUse];

END
GO


---------------------------------------------

-- dbo.procBackupTable
CREATE PROCEDURE [dbo].[procBackupTable]
	@tablename [nvarchar](400),
	@schema [nvarchar](400),
	@where [nvarchar](max) = ''
AS
declare @dbname nvarchar(400) = DB_Name()
declare @username nvarchar(400) = replace(system_user, 'sdt\', '')
declare @count int
declare @BackupName nvarchar(max) = @dbname + '_' + @tablename + '_' + replace(convert(nvarchar(10), getdate(), 102), '.', '') + '_' + @username

begin try
--Check for dupe backup names
select @count = COUNT(*) from TempTableBackups.sys.tables where name like '%' + @BackupName + '%'
set @BackupName = @BackupName + '_' + right('0' + CAST((@count+1) as nvarchar(10)), 2)
 
    --Create bak table
    print @BackupName
    declare @sql nvarchar(max) = 'select * into TempTableBackups.[dbo].[' + @BackupName + '] from ' + @schema + '.' + @tablename
	if (@where != '') set @sql = @sql + ' where ' + @where
    exec (@sql)
end try
begin catch
    print 'Error: ' + error_message()
end catch
GO


---------------------------------------------

-- dbo.procBatchDeleteOnTable
CREATE PROCEDURE [dbo].[procBatchDeleteOnTable]
(
	@FromClause NVARCHAR(MAX),
	@WhereClause NVARCHAR(MAX),
	@BaseTableAlias NVARCHAR(10) = '',
	@BatchSize INT = 100000,
	@IsDebugStatement BIT = 0
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @msg NVARCHAR(200);

	IF (@FromClause LIKE '%join%' AND @BaseTableAlias = '')
		BEGIN
			SET @msg = N'@FromClause with JOINs requires a @BaseTableAlias value.';
			RAISERROR(@msg, 0, 1) WITH NOWAIT;
			RETURN;
		END

	DECLARE @sql NVARCHAR(MAX);

	SET @sql = N'
	WHILE (1=1)
		BEGIN
			DELETE TOP ('+CAST(@BatchSize AS VARCHAR)+') '+@BaseTableAlias+'
			FROM '+@FromClause+' WHERE '+@WhereClause+';

			IF (@@ROWCOUNT = 0) BREAK;
		END';

	IF @IsDebugStatement = 1 SET @sql = 'PRINT ''' + @sql + '''';

	EXEC (@sql);

END
GO


---------------------------------------------

-- dbo.procCallRestApi
CREATE PROCEDURE [dbo].[procCallRestApi]
    @url VARCHAR(2083),
    @method VARCHAR(10) = 'get',
	@body VARCHAR(MAX) = NULL,
	@authorization VARCHAR(100) = NULL,
    @responseText VARCHAR(8000) OUTPUT,
    @statusCode INT OUTPUT,
    @statusText VARCHAR(1000) OUTPUT
AS
BEGIN
    DECLARE @object AS INT;
    DECLARE @error AS INT;
    DECLARE @MessageError VARCHAR(255);
    DECLARE @MessageErrorNumber VARCHAR(255);

	SET @statusCode = -1;
	SET @statusText = 'Unexpected error';
	SET @responseText = 'Unexpected error';
	SET @MessageError = 'Unexpected error';

    EXEC @error = sys.sp_OACreate 'MSXML2.ServerXMLHttp', @object OUT;
    IF @error <> 0
    BEGIN
        SET @MessageError = 'sp_OACreate MSXML2.ServerXMLHttp failed';
        GOTO fini;
    END;

    EXEC @error = sys.sp_OAMethod @object, 'open', NULL, @method, @url, false;
    IF @error <> 0
    BEGIN
        SET @MessageError = 'sp_OAMethod Open failed';
        GOTO fini;
    END;

	EXEC @error = sp_OAMethod
		@object,
		'setRequestHeader',
		NULL,
		'Content-Type',
		'application/json';
	IF @error <> 0
	BEGIN
		SET @MessageError = 'sp_OAMethod setRequestHeader failed';
		GOTO fini;
	END;
	
	-- *HACK* to get around the CSRF filter. We will remove this once we change the location of the endpoint
    EXEC @error = sp_OAMethod @object, 'setRequestHeader', NULL, 'CSRF', ' ';
    IF @error <> 0
    BEGIN
        SET @MessageError = 'sp_OAMethod setRequestHeader failed';
        GOTO fini;
    END;

	IF @authorization IS NOT NULL
	BEGIN
		EXEC @error = sp_OAMethod @object, 'setRequestHeader', NULL, 'Authorization', @authorization;
		IF @error <> 0
		BEGIN
			SET @MessageError = 'sp_OAMethod setRequestHeader failed';
			GOTO fini;
		END;
	END;

	EXEC @error = sys.sp_OAMethod @object, 'send', NULL, @body;
    IF @error <> 0
    BEGIN
        SET @MessageError = 'sp_OAMethod Send failed';
        GOTO fini;
    END;

    EXEC @error = sys.sp_OAGetProperty @object, 'status', @statusCode OUT;
    IF @error <> 0
    BEGIN
        SET @MessageError = 'sp_OAGetProperty read status failed';
        GOTO fini;
    END;

    EXEC @error = sys.sp_OAGetProperty @object, 'StatusText', @statusText OUT;
    IF @error <> 0
    BEGIN
        SET @MessageError = 'sp_OAGetProperty statusText failed';
        GOTO fini;
    END;

    EXEC @error = sys.sp_OAGetProperty
        @object,
        'responseText',
        @responseText OUT;
    IF @error <> 0
    BEGIN
        SET @MessageError = 'sp_OAGetProperty responseText failed';
        GOTO fini;
    END;

    EXEC sys.sp_OADestroy @object;

    PRINT @statusText + ' ' + CAST(@statusCode AS VARCHAR(MAX)) + ' ' + @responseText;

    RETURN;

    fini:
    PRINT @MessageError;
    DECLARE @src VARCHAR(1000);
    DECLARE @desc VARCHAR(1000);
    EXEC @error = sys.sp_OAGetErrorInfo @object, @src OUT, @desc OUT;

	IF @error <> 0
	BEGIN
	    SELECT
        CONVERT(VARBINARY(4), @error) [error],
        @src [Source],
        @desc [Description];
	END;

    
    EXEC sp_OADestroy @object;

	SET @MessageErrorNumber = 'Error : ' + CAST(@error AS VARCHAR) + ' - ' + @MessageError;
    
	SELECT @MessageErrorNumber
    --RAISERROR(@MessageErrorNumber, 16, 1);

    RETURN;

END;
GO


---------------------------------------------

-- dbo.procCapEMFSetYearFillins
CREATE proc dbo.procCapEMFSetYearFillins
	@PLANGUID UniqueIdentifier
	,@PHSectionGUID UniqueIdentifier
	,@TargetFirstMemberGUID uniqueidentifier
	,@NumMembers int
as

declare @FirstMemberGUID uniqueidentifier
set @FirstMemberGUID = dbo.GetModelFirstFillInSection(@planguid, @phsectionguid)


if @FirstMemberGUID = '00000000-0000-0000-0000-000000000000' begin
	exec procEMFFillInAddToEndSection @phsectionguid, @targetfirstmemberguid, @planguid
	set @firstmemberguid = @targetfirstmemberguid
end 

DECLARE @OFFSET Int

SELECT @OFFSET = tfm.DisplayOrder - fm.DisplayOrder
FROM
	SecureListMember fm 
	inner join SecureListMember tfm on fm.ListMemberGUID = @FirstMemberGUID and tfm.ListMemberGUID = @TargetFirstMemberGUID
	
if @OFFSET is null return

DECLARE @ONEGUID UniqueIdentifier
SET @ONEGUID = '11111111-1111-1111-1111-111111111111'

declare @PHDimGUID uniqueidentifier
SELECT @PHDimGUID = listguid from SecureListMember where ListMemberGUID = @PHSectionGUID

if @PHDimGUID is null return

declare @fidimguid uniqueidentifier
select @fidimguid = fillindimensionguid from SecureList where ListGUID = @PHDimGUID

if @fidimguid is null return

declare @higuid uniqueidentifier

declare @cnt int
exec procLogObjectHistory @PlanGUID, 'Changing base fill-in', 0, @higuid output

--FIX FILLINS
UPDATE EMFFillIn SET FilledInMemberGUID = dbo.GetSecureListOffsetMember(FilledInMemberGUID,@offset)
WHERE 
	ModelGUID = @PlanGUID 
	AND PlaceholderMemberGUID IN (SELECT ListMemberGUID FROM SecureListMember WHERE ParentListMemberGUID = @PHSectionGUID)

--DELETE FILLINS PUSHED OFF THE END of possible members
DELETE FROM EMFFillIn WHERE 
	MODELGUID = @PLANGUID 
	and FilledInMemberGUID = @ONEGUID

--DELETE FILLINS PUSHED OFF THE END of # of members
DELETE FROM EMFFillIn WHERE ModelGUID = @PlanGUID AND FilledInMemberGUID IN (SELECT GUID FROM dbo.getFillinMembersPastMaxIndex(@PLANGUID, @PHDimGUID, @NumMembers))

--add FILLINS to equal # of members
exec procEMFFillInAdd @planguid, @PHDimGUID, @NumMembers

declare @sql varchar(max)
declare @mdTableName varchar(max)

declare @phDimColumnName varchar(max)
set @phDimColumnName = 'G' + REPLACE(cast(@phdimguid as varchar(36)),'-','_')

set @sql = '
declare @msg varchar(max)
declare @cnt int
declare @planguid uniqueidentifier
set @planguid = ''' + cast(@planguid as varchar(36))+ '''

declare @fidimguid uniqueidentifier
set @fidimguid = ''' + cast(@fidimguid as varchar(36))+ '''

declare @PHSectionGUID uniqueidentifier
set @PHSectionGUID = ''' + cast(@PHSectionGUID as varchar(36))+ '''

declare @oneguid uniqueidentifier
set @oneguid = ''11111111-1111-1111-1111-111111111111''

declare @higuid uniqueidentifier
set @higuid = ''' + cast(@higuid as varchar(36)) + '''

UPDATE zzemfmodeldata_{mdcguidfriendly}
SET 
   zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = dbo.GetSecureListOffsetMember(zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ',' + cast(@offset as varchar(4)) + ')
    ,HISTORYITEMGUID = @higuid
WHERE 
	MODELGUID = @planguid
	--ONLY Update data who was previously assigned to a member that was filling in the section we are updating, altho this could cause a duplicate issue
	AND zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' 
		IN ( SELECT FI.FilledInMemberGUID FROM EMFFillIn FI WHERE FI.PlaceholderMemberGUID 
				IN (SELECT ListMemberGUID FROM SecureListMember WHERE ParentListMemberGUID = @PHSectionGUID))

DELETE FROM zzemfmodeldata_{mdcguidfriendly} WHERE VALUE = 0 AND MODELGUID = @PLANGUID and zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = @ONEGUID
DELETE FROM zzemfmodeldata_{mdcguidfriendly} WHERE MODELGUID = @PLANGUID and (zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = @ONEGUID
	OR (
			not zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' in (select filledinmemberguid from emffillin where modelguid = @planguid)  --orphan cause not filled in
			and
			not zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = ''00000000-0000-0000-0000-000000000000'' --not orphaned because emptyguid is ok
		)
	)
		
set @cnt = @@rowcount
if @cnt > 0 begin
  set @msg = ''Cleared orphaned nonzero cells from {mdcname} while changing Year configuration''
  exec procLogObjectHistory @PlanGUID, @msg, @cnt, @higuid
end

'


declare @mtguid uniqueidentifier
select @mtguid = modeltemplateguid from XPlan where PlanGUID = @PLANGUID

--FOR EACH MD TABLE USED BY THIS PLAN
declare @where varchar(max)
set @where = 'where modeldataconfigguid in (select modeldataconfigguid from viewEMFModelTemplateMDCs where modeltemplateguid = ''' + cast(@mtguid as varchar(36)) + ''')
					and modeldataconfigguid in (select modeldataconfigguid from emfmodeldataconfigdimensionlink where dimensionguid = ''' + cast(@PHDimGUID as varchar(36)) + ''')
'

exec procEMFRunForManyStructures @sql, @where, 1
GO


---------------------------------------------

-- dbo.procChangeDBSetting
--Author: gforeman
--Branch: EarwigJFS
--Forward
CREATE procedure [dbo].[procChangeDBSetting]
@settingname as nvarchar(128),
@value as nvarchar(4000)
as
if (select count(*) from dbsetting where name = @settingname) = 1 begin
	update dbsetting set setting = @value, LastModifiedDate = getdate() where name = @settingname
end else begin
	insert into dbsetting (name, setting, LastModifiedDate) select rtrim(ltrim(@settingname)), @value, getdate()
end
GO


---------------------------------------------

-- dbo.procCheckDimensionMemberIntegrity
CREATE PROCEDURE [dbo].[procCheckDimensionMemberIntegrity]
   @moreinfo as bit = 0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @LEVEL int
	SET @LEVEL = 0

	CREATE TABLE #LISTMEMBERVALIDATION (LISTMEMBERGUID uniqueidentifier, PARENTLISTMEMBERGUID uniqueidentifier, OUTLINELEVEL int, LISTGUID uniqueidentifier)
	CREATE TABLE #INVALIDLISTINFO (LISTGUID uniqueidentifier)

	INSERT #LISTMEMBERVALIDATION
	SELECT
		LISTMEMBERGUID,
		PARENTLISTMEMBERGUID,
		OUTLINELEVEL,
		LISTGUID
	FROM
		SecureListMember
	WHERE
		PARENTLISTMEMBERGUID = '00000000-0000-0000-0000-000000000000'

	INSERT #INVALIDLISTINFO SELECT DISTINCT LISTGUID FROM #LISTMEMBERVALIDATION WHERE OUTLINELEVEL != @LEVEL AND LISTGUID NOT IN(SELECT LISTGUID FROM #INVALIDLISTINFO)

	WHILE((SELECT COUNT(*) FROM #LISTMEMBERVALIDATION) > 0) BEGIN
		SET @LEVEL = @LEVEL + 1	

		INSERT #LISTMEMBERVALIDATION
		SELECT
			LISTMEMBERGUID,
			PARENTLISTMEMBERGUID,
			OUTLINELEVEL,
			LISTGUID
		FROM
			SecureListMember
		WHERE
			PARENTLISTMEMBERGUID IN (SELECT LISTMEMBERGUID FROM #LISTMEMBERVALIDATION)

		DELETE FROM #LISTMEMBERVALIDATION WHERE PARENTLISTMEMBERGUID NOT IN(SELECT LISTMEMBERGUID FROM #LISTMEMBERVALIDATION)

		INSERT #INVALIDLISTINFO SELECT DISTINCT LISTGUID FROM #LISTMEMBERVALIDATION WHERE OUTLINELEVEL != @LEVEL AND LISTGUID NOT IN(SELECT LISTGUID FROM #INVALIDLISTINFO)
	END

	IF (@moreinfo = 1) BEGIN
		SELECT I.*, L.NAME FROM #INVALIDLISTINFO I LEFT JOIN SecureList L ON I.LISTGUID = L.LISTGUID
	END ELSE BEGIN
		SELECT COUNT(*) FROM #INVALIDLISTINFO
	END

	DROP TABLE #INVALIDLISTINFO
	DROP TABLE #LISTMEMBERVALIDATION
END
GO


---------------------------------------------

-- dbo.procCleanNamespace
CREATE procedure [dbo].[procCleanNamespace] 

as
set nocount on

declare @tablename varchar(max)
declare @columnName varchar(max)

--set @tablename = 'DesktopContent'
--set @columnName = 'ContentFullName'
--exec procCleanNamespaceSingle @tablename,@columnName, ' Strata.X.Controls,',' Strata.Jazz.UI,'
GO


---------------------------------------------

-- dbo.procCleanNamespaceSingle
CREATE proc [dbo].[procCleanNamespaceSingle]
	@tablename varchar(max)
	,@columnname varchar(max)
	,@original varchar(max)
	,@new varchar(max)
as
	set nocount on
	
	declare @sql varchar(max)
	set @sql = '
	update 
		' + @tablename + ' 
	set 
		' + @columnname + ' = REPLACE(cast(' + @columnname + ' as nvarchar(max)),''' + @original + ''',''' + @new + ''') 
	where 
		cast(' + @columnname + ' as nvarchar(max)) <> REPLACE(cast(' + @columnname + ' as nvarchar(max)),''' + @original + ''',''' + @new + ''')
	'
	
	declare @cnt int
	exec( @sql)
	set @cnt = @@ROWCOUNT
	if @cnt > 0 begin
		print cast(@cnt as varchar(max)) + ' changes in ' + @tablename + '.' + @columnname + ' from ' + @original + ' to ' + @new
	end
GO


---------------------------------------------

-- dbo.procCleanOrphanFolderItems
CREATE procedure [dbo].[procCleanOrphanFolderItems] 

as

update REReport
set FolderGUID = (select rootfolderguid from FolderSet where Type=4)
where FolderGUID not in (select FolderGUID from REReport)
GO


---------------------------------------------

-- dbo.procCleanOrphanFolders
CREATE procedure [dbo].[procCleanOrphanFolders] 

as
delete from folder where parentfolderguid not in (select folderguid from folder) and parentfolderguid <> '00000000-0000-0000-0000-000000000000'
GO


---------------------------------------------

-- dbo.procCleanOrphanListMembers
CREATE procedure [dbo].[procCleanOrphanListMembers] 

as
delete from securelistmember where parentlistmemberguid not in (select listmemberguid from securelistmember) and parentlistmemberguid <> '00000000-0000-0000-0000-000000000000'
GO


---------------------------------------------

-- dbo.procClearCachedReportsByName
-- =============================================
-- Author:		Derek Daniel
-- Create date: 20070501
-- Description:	Delete cached reports that contain the word "historical".
--              In Eisenhower production, the "historical" reports are used in the template
--              to bring in actual data.  Long term, this will need to be refined to
--              clear cached reports only for specific cubes when those cubes are refreshed
--              with new data.  (see change request 11786)
-- =============================================
CREATE PROCEDURE [dbo].[procClearCachedReportsByName] 
	-- Add the parameters for the stored procedure here
	@reportNameContains as nvarchar(256)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
DELETE 
FROM RECachedReport
WHERE     CACHEDREPORTGUID IN
(
SELECT     cached.CACHEDREPORTGUID
FROM          RECachedReport cached
INNER JOIN REReport rer
ON cached.REPORTGUID = rer.REPORTGUID
WHERE      (rer.NAME LIKE @reportNameContains)
)

END
GO


---------------------------------------------

-- dbo.procClearChangeTrackingFile
create proc dbo.procClearChangeTrackingFile
	@ModelTemplateGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
AS BEGIN

delete from [dbo].[DataPathFile_ModelTemplate]
where FullPath like '%' + cast(@ModelTemplateGUID as nvarchar(50)) + '%'
and FullPath like '%.ChangeTracking.csv'

END
GO


---------------------------------------------

-- dbo.procClearDataIntSectionObjects
--Forward

create procedure dbo.procClearDataIntSectionObjects(
   @SectionID uniqueidentifier
)
AS
BEGIN	

	declare @name varchar(max);
	select @name = Name from dbo.IntDataInterfaceSection where DataInterfaceSectionID = @SectionID

	declare @importTable varchar(max);
	declare @rejectTable varchar(max);
	select @importTable = dbo.GetDataIntSectionAcceptedTableName(@SectionID);
	select @rejectTable = dbo.GetDataIntSectionRejectedTableName(@SectionID);

	declare @importView varchar(max);
	declare @rejectView varchar(max);
	select @importView = dbo.GetDataIntSectionAcceptedViewName(@name, @SectionID);
	select @rejectView = dbo.GetDataIntSectionRejectedViewName(@name, @SectionID);


	declare @schema sysname;
	declare @object sysname;
	declare @isview bit;

	declare crsCursor CURSOR LOCAL FAST_FORWARD FOR
		select SchemaName, ObjectName, 0 as [IsView] from ViewSysTables where SchemaName = dbo.DataIntegrationSchema()
				 and ((ObjectName = @importTable) or (ObjectName = @rejectTable))
		union all
		select SchemaName, ObjectName, 1 as [IsView] from ViewSysViews where SchemaName = dbo.DataIntegrationSchema() 
				and ((ObjectName = @importView) or (ObjectName = @rejectView))

	open crsCursor;

	FETCH NEXT FROM crsCursor into @schema, @object, @isview
	WHILE (@@FETCH_STATUS = 0) 
		BEGIN
			
			if (@isview = 1) begin
				print 'Dropping View: [' + @schema + '].[' + @object + ']';
				exec procSysDropView @schema, @object;
			end
			else begin
				print 'Dropping Table: [' + @schema + '].[' + @object + ']';
				exec procSysDropTable @schema, @object;
			end
			
			FETCH NEXT FROM crsCursor into @schema, @object, @isview
		END
	close crsCursor;
	DEALLOCATE crsCursor;
END

RETURN
GO


---------------------------------------------

-- dbo.procClearDataIntSectionObjectsAll
CREATE procedure [dbo].[procClearDataIntSectionObjectsAll](
   @IsDebugOnly bit = 1
)
AS
BEGIN	

	declare @schema sysname;
	declare @object sysname;
	declare @isview bit;

	declare crsCursor CURSOR LOCAL FAST_FORWARD FOR
		select SchemaName, ObjectName, 0 as [IsView] from ViewSysTables where SchemaName = dbo.DataIntegrationSchema()
		union all
		select SchemaName, ObjectName, 1 as [IsView] from ViewSysViews where SchemaName = dbo.DataIntegrationSchema() 

	open crsCursor;

	FETCH NEXT FROM crsCursor into @schema, @object, @isview
	WHILE (@@FETCH_STATUS = 0) 
		BEGIN
			
			if (@isview = 1) begin
				print 'Dropping View: [' + @schema + '].[' + @object + ']';
				if (@IsDebugOnly = 0) begin
				    exec procSysDropView @schema, @object;
				end
			end
			else begin
				print 'Dropping Table: [' + @schema + '].[' + @object + ']';
				if (@IsDebugOnly = 0) begin
					exec procSysDropTable @schema, @object;
				end
			end
			
			FETCH NEXT FROM crsCursor into @schema, @object, @isview
		END
	close crsCursor;
	DEALLOCATE crsCursor;
END
GO


---------------------------------------------

-- dbo.procCollapseTasks
CREATE    PROCEDURE [dbo].[procCollapseTasks]
@TaskGUID as uniqueidentifier,
@AssemblyQualifiedName as nvarchar(1024),
@CollapsibleID as nvarchar(MAX),
@DBConnectionGUID as uniqueidentifier
 AS

delete from tetask 
where 
	taskguid <> @taskguid 
	and [status] <> 1 
	and iscollapsible = 1 
	and Assemblyqualifiedname = @AssemblyQualifiedName 
	and collapsibleid = @CollapsibleID 
	and collapsibleid <> '' 
	and DBConnectionGUID = @DBConnectionGUID
	--dont collapse grouping tasks
	and GroupingID = ''
GO


---------------------------------------------

-- dbo.procConvertCSGuidsToTempTable
CREATE PROCEDURE procConvertCSGuidsToTempTable 
                    (@list      text,
                     @delimiter char(1) = N',')
AS
SET NOCOUNT ON

 CREATE TABLE #CSGUIDTABLE (listpos int IDENTITY(1, 1) NOT NULL,
                             guid     uniqueidentifier) 

      DECLARE @pos      int,
              @textpos  int,
              @chunklen smallint,
              @tmpstr   nvarchar(4000),
              @leftover nvarchar(4000),
              @tmpval   uniqueidentifier

      SET @textpos = 1
      SET @leftover = ''
      WHILE @textpos <= datalength(@list) / 2
      BEGIN
         SET @chunklen = 4000 - datalength(@leftover) / 2
         SET @tmpstr = @leftover + substring(@list, @textpos, @chunklen)
         SET @textpos = @textpos + @chunklen

         SET @pos = charindex(@delimiter, @tmpstr)

         WHILE @pos > 0
         BEGIN
            SET @tmpval = cast(ltrim(rtrim(left(@tmpstr, @pos - 1))) as uniqueidentifier)

            INSERT #CSGUIDTABLE (guid) VALUES (@tmpval)
            SET @tmpstr = substring(@tmpstr, @pos + 1, len(@tmpstr))
            SET @pos = charindex(@delimiter, @tmpstr)
         END

         SET @leftover = @tmpstr
      END

      INSERT #CSGUIDTABLE(guid) VALUES (cast(ltrim(rtrim(@leftover)) as uniqueidentifier))
GO


---------------------------------------------

-- dbo.procConvertColumnTypeWithFKReferencingTable
CREATE PROCEDURE [dbo].[procConvertColumnTypeWithFKReferencingTable]
    @Schema NVARCHAR(100), -- ex. dss
    @TableName NVARCHAR(200), -- ex. DimCPT
    @ColumnName NVARCHAR(200), -- ex.CPTID
    @Type NVARCHAR(100), -- ex. 'smallint', 'int', 'bigint',
    @Debug BIT = 0 -- Set to false by default.
AS
BEGIN
SET NOCOUNT ON;
DECLARE @TimeStamp VARCHAR(30) = CONVERT(VARCHAR, GETDATE(), 121),
@ProcName VARCHAR(100) = OBJECT_NAME(@@PROCID),
@Count INT = 0, @SQL NVARCHAR(4000),
@FKName NVARCHAR(4000), 
@FKSchema NVARCHAR(4000),
@FKTableName NVARCHAR(4000),
@FKColumnName NVARCHAR(4000),
@DeleteText NVARCHAR(15),
@UpdateText NVARCHAR(15),
@IDColumnName NVARCHAR(4000),
@FullTableName NVARCHAR (4000) = @Schema + '.' + @TableName,
@FKIsDisabled BIT;
RAISERROR('%s: Starting %s', 0, 1, @TimeStamp, @ProcName) WITH NOWAIT;
SELECT @IDColumnName = name 
    FROM sys.columns
    WHERE object_id = OBJECT_ID(@FullTableName)
    AND is_identity = 1;
SET @Count = @@ROWCOUNT;
IF (@Count != 0)
BEGIN
SELECT
    fk.name FKName,
    OBJECT_SCHEMA_NAME(fk.parent_object_id) FKSchema,
    OBJECT_NAME(fk.parent_object_id) FKTableName,
    COL_NAME(fc.parent_object_id, fc.parent_column_id) AS FKColumnName,
    CASE (fk.delete_referential_action)
        WHEN 1 THEN 'CASCADE'
        WHEN 2 THEN 'SET NULL'
        WHEN 3 THEN 'SET DEFAULT'
        ELSE 'NO ACTION'
    END DeleteAction,
    CASE (fk.update_referential_action)
    WHEN 1 THEN 'CASCADE'
        WHEN 2 THEN 'SET NULL'
        WHEN 3 THEN 'SET DEFAULT'
        ELSE 'NO ACTION'
    END UpdateAction,
    CASE
        WHEN fk.is_disabled = 1 OR fk.is_not_trusted = 1 THEN 1 
        ELSE 0
    END AS FKIsDisabled
INTO #ForeignKeys
FROM sys.foreign_keys AS fk
INNER JOIN sys.foreign_key_columns AS fc
    ON fk.object_id = fc.constraint_object_id
WHERE OBJECT_SCHEMA_NAME(fk.referenced_object_id) = @Schema
    AND OBJECT_NAME(fk.referenced_object_id) = @TableName
    AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = @IDColumnName;
    
SET @Count = @@ROWCOUNT;
END
IF (@Count != 0)
BEGIN
-- Drop FK Constraints
    SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
    RAISERROR('%s: Found %d foreign key references.', 0, 1, @TimeStamp, @Count) WITH NOWAIT;
    DECLARE Drop_FK_Cursor CURSOR FOR
    SELECT FKName, FKSchema, FKTableName
    FROM #ForeignKeys
    ORDER BY FKName;
    OPEN Drop_FK_Cursor;
    FETCH NEXT FROM Drop_FK_Cursor INTO @FKName, @FKSchema, @FKTableName;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- Drop FK constraint
        SET @SQL = 'ALTER TABLE [' + @FKSchema + '].[' + @FKTableName + '] DROP CONSTRAINT [' + @FKName + ']';
        SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
        RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT;
        IF (@Debug = 0)
        EXEC sp_executesql @SQL;
        FETCH NEXT FROM Drop_FK_Cursor INTO @FKName, @FKSchema, @FKTableName;
    END
    CLOSE Drop_FK_Cursor;
    DEALLOCATE Drop_FK_Cursor;
END
SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
RAISERROR('%s: Changing PK type to %s.', 0, 1, @TimeStamp, @Type) WITH NOWAIT;
-- Change parent table type
SET @SQL = 'EXEC dbo.ConvertIntToBigIntByColumnNameNoCompression @sourceSchema=''' + @Schema + ''', @sourceTable=''' + @TableName + ''', @columnName=''' + @ColumnName + ''', @expectedType=''' + @Type + ''';'
SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT;
IF (@Debug = 0)
EXEC sp_executesql @SQL;
IF (@Count != 0)
BEGIN
    SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
    RAISERROR('%s: Recreating foreign keys.', 0, 1, @TimeStamp) WITH NOWAIT;
    -- Recreate foreign key constraints with ON DELETE and ON UPDATE actions
    DECLARE Create_FK_Cursor CURSOR FOR
    SELECT FKName, FKSchema, FKTableName, FKColumnName, DeleteAction, UpdateAction, FKIsDisabled
    FROM #ForeignKeys
    ORDER BY FKName;
    OPEN Create_FK_Cursor;
    FETCH NEXT FROM Create_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName, @DeleteText, @UpdateText, @FKIsDisabled;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- Recreate FK constraint with the specific ON DELETE and ON UPDATE actions
        SET @SQL = 'ALTER TABLE [' + @FKSchema + '].[' + @FKTableName + ']' + CASE (@FKIsDisabled) WHEN 1 THEN ' WITH NOCHECK' ELSE '' END + ' ADD CONSTRAINT [' + @FKName + '] FOREIGN KEY (' + @FKColumnName + ') REFERENCES [' + @Schema + '].[' + @TableName 
        + ']([' + @IDColumnName + ']) ON DELETE ' + @DeleteText + ' ON UPDATE ' + @UpdateText;
        SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
        RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT;
        IF (@Debug = 0)
        EXEC sp_executesql @SQL;
        FETCH NEXT FROM Create_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName, @DeleteText, @UpdateText, @FKIsDisabled;
    END
    CLOSE Create_FK_Cursor;
    DEALLOCATE Create_FK_Cursor;
END
END
GO


---------------------------------------------

-- dbo.procConvertFKReferencingTablePKToReferencedTableType
CREATE PROCEDURE dbo.procConvertFKReferencingTablePKToReferencedTableType
    @Schema NVARCHAR(100), -- ex. dss
    @TableName NVARCHAR(200), -- ex. DimCPT
    @ColumnName NVARCHAR(200), -- ex.CPTID
    @Type NVARCHAR(100), -- ex. 'smallint', 'int', 'bigint',
    @Debug BIT = 0 -- Set to false by default.
AS
BEGIN
SET NOCOUNT ON;

DECLARE @TimeStamp VARCHAR(30) = CONVERT(VARCHAR, GETDATE(), 121),
@ProcName VARCHAR(100) = OBJECT_NAME(@@PROCID),
@Count INT = 0, @SQL NVARCHAR(4000),
@FKName NVARCHAR(4000), 
@FKSchema NVARCHAR(4000),
@FKTableName NVARCHAR(4000),
@FKColumnName NVARCHAR(4000),
@DeleteText NVARCHAR(15),
@UpdateText NVARCHAR(15);

RAISERROR('%s: Starting %s', 0, 1, @TimeStamp, @ProcName) WITH NOWAIT;

SELECT
    fk.name FKName,
    OBJECT_SCHEMA_NAME(fk.parent_object_id) FKSchema,
    OBJECT_NAME(fk.parent_object_id) FKTableName,
    COL_NAME(fc.parent_object_id, fc.parent_column_id) AS FKColumnName,
    CASE (fk.delete_referential_action)
        WHEN 1 THEN 'CASCADE'
        WHEN 2 THEN 'SET NULL'
        WHEN 3 THEN 'SET DEFAULT'
        ELSE 'NO ACTION'
    END DeleteAction,
    CASE (fk.update_referential_action)
    WHEN 1 THEN 'CASCADE'
        WHEN 2 THEN 'SET NULL'
        WHEN 3 THEN 'SET DEFAULT'
        ELSE 'NO ACTION'
    END UpdateAction
INTO #ForeignKeys
FROM sys.foreign_keys AS fk
INNER JOIN sys.foreign_key_columns AS fc
    ON fk.object_id = fc.constraint_object_id
WHERE OBJECT_SCHEMA_NAME(fk.referenced_object_id) = @Schema
    AND OBJECT_NAME(fk.referenced_object_id) = @TableName
    AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = @ColumnName;

SET @Count = @@ROWCOUNT;

IF (@Count != 0)
BEGIN
-- Drop FK Constraints, alter column type.
    SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
    RAISERROR('%s: Found %d foreign key references.', 0, 1, @TimeStamp, @Count) WITH NOWAIT;

    DECLARE Drop_FK_Cursor CURSOR FOR
    SELECT FKName, FKSchema, FKTableName, FKColumnName
    FROM #ForeignKeys
    ORDER BY FKName;

    OPEN Drop_FK_Cursor;
    FETCH NEXT FROM Drop_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- Drop FK constraint
        SET @SQL = 'ALTER TABLE [' + @FKSchema + '].[' + @FKTableName + '] DROP CONSTRAINT [' + @FKName + ']';
        SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
        RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT;

        IF (@Debug = 0)
        EXEC sp_executesql @SQL;

        -- Alter column type
		SET @SQL = 'EXEC dbo.ConvertIntToBigIntByColumnNameNoCompression @sourceSchema=''' + @FKSchema + ''', @sourceTable=''' + @FKTableName + ''', @columnName=''' + @FKColumnName + ''', @expectedType=''' + @Type + ''';'

        IF (@Debug = 0)
        EXEC sp_executesql @SQL;

        FETCH NEXT FROM Drop_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName;
    END

    CLOSE Drop_FK_Cursor;
    DEALLOCATE Drop_FK_Cursor;
END

SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
RAISERROR('%s: Changing PK type to %s.', 0, 1, @TimeStamp, @Type) WITH NOWAIT;
-- Change PK type
SET @SQL = 'EXEC dbo.ConvertIntToBigIntByColumnNameNoCompression @sourceSchema=''' + @Schema + ''', @sourceTable=''' + @TableName + ''', @columnName=''' + @ColumnName + ''', @expectedType=''' + @Type + ''';'
SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT;

IF (@Debug = 0)
EXEC sp_executesql @SQL;

IF (@Count != 0)
BEGIN
    SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
    RAISERROR('%s: Recreating foreign keys.', 0, 1, @TimeStamp) WITH NOWAIT;
    -- Recreate foreign key constraints with ON DELETE and ON UPDATE actions
    DECLARE Create_FK_Cursor CURSOR FOR
    SELECT FKName, FKSchema, FKTableName, FKColumnName, DeleteAction, UpdateAction
    FROM #ForeignKeys
    ORDER BY FKName;

    OPEN Create_FK_Cursor;
    FETCH NEXT FROM Create_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName, @DeleteText, @UpdateText;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- Recreate FK constraint with the specific ON DELETE and ON UPDATE actions
        SET @SQL = 'ALTER TABLE [' + @FKSchema + '].[' + @FKTableName + '] ADD CONSTRAINT [' + @FKName + '] FOREIGN KEY (' + @FKColumnName + ') REFERENCES [' + @Schema + '].[' + @TableName + ']([' + @ColumnName + ']) ON DELETE ' + @DeleteText + ' ON UPDATE ' + @UpdateText;
        SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121);
        RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT;

        IF (@Debug = 0)
        EXEC sp_executesql @SQL;

        FETCH NEXT FROM Create_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName, @DeleteText, @UpdateText;
    END

    CLOSE Create_FK_Cursor;
    DEALLOCATE Create_FK_Cursor;
END

END
GO


---------------------------------------------

-- dbo.procConvertSecureListMemberValues
-- =============================================
-- Author:      
-- Create date: 
-- Description:   <This stored procedure handles converting secure list member values from text to numeric and vice versus. ,,>
-- =============================================
CREATE PROCEDURE [dbo].[procConvertSecureListMemberValues]
@listguid uniqueidentifier,
@valueindex int,
@sourceType int,
@targetType int
AS
BEGIN
   -- SET NOCOUNT ON added to prevent extra result sets from
   -- interfering with SELECT statements.
   SET NOCOUNT ON;
--set @listguid = 'F7CDA86B-F23E-40A1-B081-0B46772591A7'
--set @valueindex = 0
--set @sourceType = 0
--set @targettype = 1

If (@sourceType<>0 AND @sourceType<>1)
BEGIN
Print 'Error: SourceType can only be 0 or 1:  Text = 0 or Numeric = 1'
RETURN
END

If (@targetType<>0 AND @targetType<>1)
BEGIN
Print 'Error: targetType can only be 0 or 1:  Text = 0 or Numeric = 1'
RETURN
END

If  (@sourceType = @targetType)
BEGIN
Print 'Error: sourcetype and targettype shouldn''t be the same. '
RETURN
END


If (@sourceType = 0) 
BEGIN
UPDATE dbo.[SecureListMemberValue]
SET
VALUEFLOAT = (
CASE ISNUMERIC(VALUETEXT)
WHEN 1 THEN Cast(VALUETEXT AS float)
ELSE 0
END
),
VALUETEXT = '',
[TYPE] = @targetType
Where LISTGUID = @listguid and VALUEINDEX = @valueindex and [TYPE] = @sourceType
END

If (@sourceType = 1)
BEGIN
   UPDATE dbo.SecureListMemberValue 
   SET
VALUETEXT = VALUEFLOAT,
   VALUEFLOAT = 0,
[TYPE] = @targetType
   Where LISTGUID = @listguid and VALUEINDEX = @valueindex and TYPE = @sourceType
END

  

END
GO


---------------------------------------------

-- dbo.procCopyFrameworkDatabaseObjects
create procedure [dbo].[procCopyFrameworkDatabaseObjects]
(
	@FrameworkSchema nvarchar(128),
	@TargetDatabase nvarchar(512),
	@IsIncludeMembers bit,
	@IsDebugOnly bit = 0
)
AS

DECLARE @Guid uniqueidentifier
DECLARE @Name nvarchar(128)

--Step 1:
-- COPY ALL COMPOSITES
declare crsComposite CURSOR FAST_FORWARD FOR
	select C.CompositeGUID, C.FriendlyName from dbo.ScoreComposite C
		left join dbo.ScoreDataTable D1 on D1.DataTableGuid = C.DataTableGUID1
		left join dbo.ScoreDataTable D2 on D2.DataTableGuid = C.DatatableGUID2
	WHERE D1.SqlSchemaName = @FrameworkSchema OR D2.SqlSchemaName = @FrameworkSchema
open crsComposite;

FETCH NEXT FROM crsComposite into @Guid, @Name
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		exec dbo.procScoreCopyComposite @Guid, @TargetDatabase, @IsIncludeMembers,@IsDebugOnly
		FETCH NEXT FROM crsComposite into @Guid, @Name
	END
close crsComposite;
DEALLOCATE crsComposite;


--Step 2:
-- COPY ALL DATATABLES (in case we missed any)
declare crsDataTable CURSOR FAST_FORWARD FOR
	select DataTableGUID, FriendlyName from dbo.ScoreDataTable
		where SQLSchemaName = @FrameworkSchema
open crsDataTable;

FETCH NEXT FROM crsDataTable into @Guid, @Name
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		exec dbo.procScoreCopyDataTable @Guid, @TargetDatabase, @IsIncludeMembers,@IsDebugOnly
		FETCH NEXT FROM crsDataTable into @Guid, @Name
	END
close crsDataTable;
DEALLOCATE crsDataTable;

--Step 3:
-- COPY ALL DIMENSIONS (In case we missed any)
declare crsDimension CURSOR FAST_FORWARD FOR
	select DimensionGUID, FriendlyName from dbo.ScoreDimension
		where SQLSchemaName = @FrameworkSchema
open crsDimension;

FETCH NEXT FROM crsDimension into @Guid, @Name
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		exec dbo.procScoreCopyDimension @Guid, @TargetDatabase, @IsIncludeMembers,@IsDebugOnly
		FETCH NEXT FROM crsDimension into @Guid, @Name
	END
close crsDimension;
DEALLOCATE crsDimension;
GO


---------------------------------------------

-- dbo.procCopySimpleSecurity
CREATE proc [dbo].[procCopySimpleSecurity]
	@SourceEntityGUID uniqueidentifier,
	@TargetEntityGUID uniqueidentifier,
	@CleanTargetEntitySecurity bit = 0
as

if @CleanTargetEntitySecurity = 1
	delete from S3SimplePermission where LootID = @TargetEntityGUID
else
	delete from S3SimplePermission where LootID = @TargetEntityGUID
		and IdentityGUID in (
			select IdentityGUID from S3SimplePermission where LootID = @SourceEntityGUID
		)

insert into S3SimplePermission
	(LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
select
	@TargetEntityGUID,
	ACL.IdentityGUID,
	ACL.ReadValue,
	ACL.WriteValue,
	ACL.SecureValue
from
	S3SimplePermission ACL
where
	ACL.LootID = @SourceEntityGUID
GO


---------------------------------------------

-- dbo.procCreateTask
CREATE PROCEDURE [dbo].[procCreateTask] 
	@taskTypeName VARCHAR(1000),
	@contextXML NVARCHAR(MAX),
	@userName VARCHAR(100) = 'Strata',
	@statusCode INT OUTPUT,
	@taskSource VARCHAR(500) = 'HangfireController'
AS
BEGIN

	DECLARE @baseUrl VARCHAR(200);
	SELECT @baseUrl = dbo.GetHangfireApiEndpoint();

	DECLARE @url AS VARCHAR(2083) = @baseUrl + '/Jobs';

	DECLARE @databaseGUID UNIQUEIDENTIFIER;
	/* Old block
	EXEC dbo.procSMCGetDatabaseGUID @ReturnVal = @DatabaseGUID OUTPUT;
	IF (@databaseGUID IS NULL)
	BEGIN
		RAISERROR('Unable to determine SMC Database GUID, check to ensure your SMC database settings are correct.', 18, 0);
		RETURN;
	END;
	*/

	-- New block
	if exists (select 1 from DBSetting where name = 'dbguid_cache')
		select @databaseGUID=setting from DBSetting where name = 'dbguid_cache'
	else
	begin
		EXEC dbo.procSMCGetDatabaseGUID @ReturnVal = @databaseGUID OUTPUT;
		IF (@databaseGUID IS NULL)
		BEGIN
			RAISERROR('Unable to determine SMC Database GUID, check to ensure your SMC database settings are correct.', 18, 0);
			RETURN;
		END
		else
			exec dbo.procChangeDBSetting 'dbguid_cache', @databaseGUID;
	end
	
	-- end new block

	DECLARE @auth VARCHAR(100) = 'Hangfire ' + CAST(@databaseGUID AS VARCHAR(36));

	DECLARE @body AS VARCHAR(MAX);

	SET @body = 
	(

		SELECT @taskTypeName AS TaskName
				, @databaseGUID AS DatabaseGuid
				, '10101010-1111-0000-1111-101010101010' AS UserGuid
				, @userName AS UserName
				, @contextXML AS ContextData
				, @taskSource AS TaskSource
		FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
	);

	
	DECLARE @statusText NVARCHAR(1000);
	DECLARE @responseText VARCHAR(1000);
	EXEC dbo.procCallRestApi
		@url = @url,
		@method = 'POST',
		@body = @body,
		@authorization = @auth,
		@responseText = @responseText OUTPUT,
		@statusCode = @statusCode OUTPUT,
		@statusText = @statusText OUTPUT;

END;
GO


---------------------------------------------

-- dbo.procCreateTokenForUser
CREATE PROC [dbo].[procCreateTokenForUser]
	@username VARCHAR(MAX)
AS
	DECLARE @userguid UNIQUEIDENTIFIER
	SELECT @userguid = userguid FROM userprofile WHERE username = @username

	DECLARE @cnt INT
	SELECT @cnt = COUNT(*) FROM CurrentUser WHERE tokenguid = @userguid

	IF @cnt = 0 BEGIN
		INSERT INTO CurrentUser (tokenguid, userguid, ipaddress, loginstamputc, lastactionstamputc, username)
		VALUES (@userguid, @userguid, '127.0.0.1', GETUTCDATE(), '2020-01-01', @username)
	END
	PRINT @userguid
GO


---------------------------------------------

-- dbo.procCreatezzFactTableIndex
CREATE PROCEDURE [dbo].[procCreatezzFactTableIndex]  
@zzTableName nvarchar(256)
AS
DECLARE @sql nvarchar(1204)
SET @sql ='
 IF EXISTS (SELECT name FROM sys.indexes WHERE name = ''HistoryItemGUID''
 AND object_id = (SELECT object_id(''' + @zzTableName + ''') ) )
 BEGIN
  CREATE NONCLUSTERED INDEX [HistoryItemGUID] ON ' + @zzTableName + '
  (
  [HISTORYITEMGUID] ASC
  )
  WITH DROP_EXISTING 
 END
 ELSE
 BEGIN
  CREATE NONCLUSTERED INDEX [HistoryItemGUID] ON ' + @zzTableName + '
  (
  [HISTORYITEMGUID] ASC
  )
 END
'
EXEC sp_executesql @sql
GO


---------------------------------------------

-- dbo.procCustomScriptGet
CREATE proc [dbo].[procCustomScriptGet]
	@customScriptGUID uniqueidentifier,
	@encode bit = 0
as
	declare @script nvarchar(max)
	select @script = ScriptText from CustomScript where CustomScriptGUID = @customScriptGUID
	if(@encode = 1) begin
		select @script = REPLACE(@script, '''', '''''')
	end
	
	if(LEN(@script) > 4000) begin
	    print '*********************************************************************************************************************'
		print 'WARNING: SCRIPT LENGTH EXCEEDS 4000 CHARACTERS - PRINT OUT CONTAINS EXTRA LINE BREAKS THAT MAY BREAK THE SCRIPT'
		print '*********************************************************************************************************************'
		print ''
	end
	
	declare @pos int
	set @pos = 0
	while(@pos < len(@script)) begin
		print substring(@script, @pos, @pos + 4000)
		set @pos = @pos + 4000
	end
GO


---------------------------------------------

-- dbo.procCustomScriptSet
create proc procCustomScriptSet
	@customScriptGUID uniqueidentifier,
	@scriptText nvarchar(max)
as
	update CustomScript set ScriptText = @scriptText where CustomScriptGUID = @customScriptGUID
GO


---------------------------------------------

-- dbo.procDIRefreshClientField
CREATE PROCEDURE [dbo].[procDIRefreshClientField]
(
    @ConfigID uniqueidentifier
)
AS
begin
	update isfd
	set isfd.ClientField = dbo.intGetTransformationSourceField(isfd.SourceColumnId)
	from IntDataInterfaceField f1
	join IntDataInterfaceSection dis on dis.DataInterfaceSectionID=f1.DataInterfaceSectionID
	join IntDataInterface dif on dis.DataInterfaceID=dif.DataInterfaceID
	join IntConfig ic on ic.DataInterfaceID=dif.DataInterfaceID and ic.IsHidden = 0
	join IntTransformation it on it.ConfigID=ic.ConfigID
	cross apply intGetTransformationSourceFileList(it.TransformationID) tsfl
	join IntSourceFile isf on isf.SourceFileID = tsfl.SourceFileID
	join IntDataInterfaceMap idm on f1.DataInterfaceFieldID=idm.DataInterfaceFieldID
	join IntSourceField isfd on isfd.DataSourceID=it.TransformationID and idm.SourceColumnID=isfd.SourceColumnID
	where f1.IsHidden = 0 and ic.ConfigID=@ConfigID
end
GO


---------------------------------------------

-- dbo.procDashboardInvalidateCacheByAttributeGUID
/*************************************************************
** Change History
**************************************************************
** CID		Date			Author		WI				Description
** 1      2022-01-28  	HV      	JAZZ-29025	Fiscal Time Period - Count from Current Month
*************************************************************/
CREATE PROCEDURE [dbo].[procDashboardInvalidateCacheByAttributeGUID]
  @attributeGUID uniqueidentifier
AS

DELETE c FROM dbo.DashboardWidgetCache c
INNER JOIN (
	SELECT DISTINCT w.DashboardWidgetGUID
	FROM dbo.DashboardWidget w 
		INNER JOIN dbo.DataView dv on dv.dataviewguid = w.datasourceguid
		INNER JOIN dbo.RESqlReportRegisteredDimension rd ON rd.DataViewGUID=dv.DataViewGUID 
		INNER JOIN dbo.RESQLReportRegisteredAttribute a ON rd.RegisteredDimensionGUID = a.RegisteredDimensionGUID
	WHERE a.AttributeGuid = @attributeGuid) t
ON t.DashboardWidgetGUID = c.DashboardWidgetGUID
GO


---------------------------------------------

-- dbo.procDashboardInvalidateCacheByFrameworkID
CREATE PROC dbo.procDashboardInvalidateCacheByFrameworkID
	@frameworkId int
AS

delete from DashboardWidgetCache
where DesktopTemplateGUID in (
		select DesktopTemplateGUID 
		from DashboardWidget w 
			 inner join dataview dv on dv.dataviewguid = w.datasourceguid
			 inner join fw.DimFramework f on dv.FrameworkGUID = f.MemberGUID
		where f.FrameworkID = @frameworkId)
GO


---------------------------------------------

-- dbo.procDashboardInvalidateCacheByReportGUID
CREATE PROC dbo.procDashboardInvalidateCacheByReportGUID 
	@reportGUID uniqueidentifier
AS

-- remove all cache for dashboards that contain this report
delete from DashboardWidgetCache 
where DesktopTemplateGUID in (
	select DesktopTemplateGUID 
	from DashboardWidget 
	where WidgetJSON like '%' + cast(@reportGUID as nvarchar(36)) + '%'
)
GO


---------------------------------------------

-- dbo.procDashboardInvalidateCacheForCube
CREATE PROC dbo.procDashboardInvalidateCacheForCube
	
AS
	delete from DashboardWidgetCache 
	where DesktopTemplateGUID in (
		select DesktopTemplateGUID 
		from DashboardWidget w inner join EMFCubeStub c on w.DataSourceGUID = c.CubeGUID)
GO


---------------------------------------------

-- dbo.procDataPathCopyFile
--select * from datapathfile

CREATE proc [dbo].[procDataPathCopyFile]
	@originalFileGUID uniqueidentifier,
	@newfullpath varchar(max)
as
 
delete from DataPathFile where FullPath = @newfullpath
insert into DataPathFile(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile where FileGUID = @originalFileguid
	
delete from DataPathFile_History where FullPath = @newfullpath
insert into DataPathFile_History(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile_History where FileGUID = @originalFileguid

delete from DataPathFile_Improv where FullPath = @newfullpath
insert into DataPathFile_Improv(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile_Improv where FileGUID = @originalFileguid

delete from DataPathFile_ModelTemplate where FullPath = @newfullpath
insert into DataPathFile_ModelTemplate(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile_ModelTemplate where FileGUID = @originalFileguid

delete from DataPathFile_Reporting where FullPath = @newfullpath
insert into DataPathFile_Reporting(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile_Reporting where FileGUID = @originalFileguid
GO


---------------------------------------------

-- dbo.procDataPathDeleteStale
CREATE proc [dbo].[procDataPathDeleteStale] as


delete dpf
from
	DataPathFile_Improv dpf
where
	FullPath like 'ImprovWorkbook%'
	and not exists (
		select 1 
		from
			XPlan obj
		where
			cast(obj.PlanGUID as varchar(36)) = SUBSTRING(dpf.FullPath,LEN('ImprovWorkbook')+1,36)
		)
		
		

delete dpf
from
	DataPathFile_History dpf
where
	FullPath like 'History\%'
	and not exists (
		select 1 
		from
			HistoryItem hi
		where
			cast(hi.HISTORYITEMGUID as varchar(36)) = SUBSTRING(dpf.FullPath,LEN('History\')+1,36)
		)
		
delete dpf
from
	DataPathFile_ModelTemplate dpf
where
	FullPath like 'ModelTemplateHistory\%'
	and not exists (
		select 1 
		from
			EMFModelTemplate mt
		where
			cast(mt.ModelTemplateGUID as varchar(36)) = SUBSTRING(dpf.FullPath,LEN('ModelTemplateHistory\')+1,36)
		)
		
		
delete dpf
from
	DataPathFile_ModelTemplate dpf
where
	FullPath like 'ModelTemplates\%'
	and not exists (
		select 1 
		from
			EMFModelTemplate mt
		where
			cast(mt.ModelTemplateGUID as varchar(36)) = SUBSTRING(dpf.FullPath,LEN('ModelTemplates\')+1,36)
		)
GO


---------------------------------------------

-- dbo.procDataPathObtainLock
CREATE procedure [dbo].[procDataPathObtainLock] (
     @FullPath varchar(max),
     @MaxLockSeconds int = 30, -- by default, you can only hold a lock for 30 seconds before stolen
	 @OwnerID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
)
AS
BEGIN

declare @ObtainedLocked bit;

if(@FullPath like 'History%') begin
	update DataPathFile_History WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE(), LockOwner = @OwnerID 
	where 
		(FullPath = @FullPath AND IsLocked = 0)
		OR
		(FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds)
		OR
		(FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking
end else begin
	if(@FullPath like 'Improv%') begin
		update DataPathFile_Improv WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE() , LockOwner = @OwnerID
		where 
			(FullPath = @FullPath AND IsLocked = 0)
			OR
			(FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds)
			OR
			(FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking
	end else begin
		if(@FullPath like 'ModelTemplate%') begin
			update DataPathFile_ModelTemplate WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE() , LockOwner = @OwnerID
			where 
				(FullPath = @FullPath AND IsLocked = 0)
				OR
				(FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds)
				OR
				(FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking
		end else begin
			if(@FullPath like 'Reporting%') begin
				update DataPathFile_Reporting WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE(), LockOwner = @OwnerID
				where 
					(FullPath = @FullPath AND IsLocked = 0)
					OR
					(FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds)
					OR
					(FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking
			end else begin
				update DataPathFile WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE(), LockOwner = @OwnerID 
				where 
					(FullPath = @FullPath AND IsLocked = 0)
					OR
					(FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds)
					OR
					(FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking
			end
		end
	end
end

declare @RowsAffected int;
select @RowsAffected = @@ROWCOUNT;

if (@RowsAffected = 1)
begin
	set @ObtainedLocked = 1
end
else
begin
	set @ObtainedLocked = 0
end
select @ObtainedLocked;

END
GO


---------------------------------------------

-- dbo.procDataPathReleaseLock
CREATE procedure [dbo].[procDataPathReleaseLock] (
	@FullPath varchar(max)
)
AS
BEGIN
	update DataPathFile WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1;
	if(@FullPath like 'History%') begin update DataPathFile_History WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1 end;
	if(@FullPath like 'Improv%') begin update DataPathFile_Improv WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1 end;
	if(@FullPath like 'ModelTemplate%') begin update DataPathFile_ModelTemplate WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1 end;
	if(@FullPath like 'Reporting%') begin update DataPathFile_Reporting WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1 end;
END
GO


---------------------------------------------

-- dbo.procDeactivateInactiveUsers
CREATE PROC [dbo].[procDeactivateInactiveUsers]
AS
	SET NOCOUNT ON
	
	IF (EXISTS(SELECT 1 FROM [dbo].[DBSetting] WHERE Name = 'SECURITY_USERDEACTIVATEDAYS' AND Setting != '-1')) 
	BEGIN
		DECLARE @expiredays INT
		SELECT @expiredays = CAST(Setting AS INT) FROM [dbo].[DBSetting] WHERE Name = 'SECURITY_USERDEACTIVATEDAYS'
		
		UPDATE u SET u.IsDisabled = 1
		FROM [dbo].[UserProfile] u
		WHERE @expiredays < DATEDIFF(day, ISNULL((SELECT MAX(LoginStamp) FROM [dbo].[LoginHistory] h WHERE h.UserGUID = u.UserGUID), u.LastChangedPasswordUtc AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time'), GETDATE())
	END
GO


---------------------------------------------

-- dbo.procDeleteUpdatedClinicalIndicatorEncounters
CREATE PROCEDURE [dbo].[procDeleteUpdatedClinicalIndicatorEncounters]
	@transactionguid uniqueidentifier
AS

CREATE TABLE #ClinicalIndicatorEncounters (EncounterID bigint primary key NOT NULL DEFAULT (0))

INSERT INTO #ClinicalIndicatorEncounters (EncounterID)
SELECT EncounterID 
FROM [clientdss].[FactPatientEncounterSummary]
WHERE HistoryItemGUID = @transactionguid

CREATE TABLE #Deleted (RowID int);

WHILE (1 = 1)
BEGIN

	DELETE top (5000) dss.FactPatientEncounterClinicalIndicator
		OUTPUT deleted.RowID into #Deleted
	FROM dss.FactPatientEncounterClinicalIndicator
	WHERE EncounterID IN (SELECT CIE.EncounterID FROM #ClinicalIndicatorEncounters CIE)

	if ((SELECT COUNT(*) FROM #Deleted) = 0)
	BEGIN
		BREAK;
	END

	delete from #Deleted;

END--ENDWHILE

DROP TABLE #Deleted;



RETURN
GO


---------------------------------------------

-- dbo.procDemoAssignRandomAuthor
create proc procDemoAssignRandomAuthor
	@lootgroupid nvarchar(128)
as

declare @randomUserGUID uniqueidentifier
declare @authorRoleID smallint
select @authorRoleID = roleid from userrole where type = 1

select top 1 @randomuserGUID= userguid from userprofile 
where authid = ''
and namelast not like 'zstrata%'
order by newid()

exec dbo.[procS3ClearAssignmentByLootGroupRole] @lootgroupid, @authorRoleID
exec dbo.procS3AssignIdentityToSpecialRole @randomUserGUID, 1, @lootgroupid
GO


---------------------------------------------

-- dbo.procDepreciate
CREATE proc procDepreciate 
	@amount money
	,@amountYear int
	,@usefulLife int
	,@inserviceYear int
	,@inserviceMonth int
as

create table #out (year int, amount money)

if @inserviceYear < @amountYear set @inserviceYear = @amountYear

declare @resultYear int
set @resultYear = @inserviceYear

while @resultYear <= @inserviceYear + @usefulLife begin
	insert into #out (year, amount)
	values (@resultYear, dbo.GetDepreciationPart(@amount,@amountYear,@usefulLife, @inserviceYear, @inserviceMonth, @resultYear))
	
	set @resultYear = @resultYear + 1
end

select * from #out
GO


---------------------------------------------

-- dbo.procDirectoryAddEntry
CREATE PROCEDURE dbo.procDirectoryAddEntry 
(
@planGUID AS UNIQUEIDENTIFIER,
@planTypeGUID AS UNIQUEIDENTIFIER,
@schemaName AS NVARCHAR(64) = 'data'
)
AS 
	--this procedure is obsolete given FE20, but still exists for backwards compatibility
	RETURN
GO


---------------------------------------------

-- dbo.procDirectoryCacheClean
CREATE proc procDirectoryCacheClean
	@clean bit = 0
as
	declare @name varchar(128)

	--old cache tables
	declare crsCache cursor for select name from sys.tables where name like 'DirectoryCache%'
	open crsCache
	fetch next from crsCache into @name
	while(@@FETCH_STATUS = 0) begin
		if(@clean = 0) begin
			print 'data.' + @name
		end else begin
			declare @sql varchar(4000)
			set @sql = 'drop table data.' + @name
			exec(@sql)
		end

		fetch next from crsCache into @name
	end
	close crsCache
	deallocate crsCache
	
	--old cache views
	declare crsView cursor for select name from sys.views where name like 'viewDirectoryCache_%'
	open crsView
	fetch next from crsView into @name
	while(@@FETCH_STATUS = 0) begin
		if((select count(*) from PlanType where replace(replace(replace(replace(REPLACE(Name, ' ', ''), '.', ''), '(', ''), ')', ''), '-', '') = REPLACE(@name, 'viewDirectoryCache_', '')) = 0) begin
			if(@clean = 0) begin
				print 'data.' + @name
			end else begin
				declare @sql2 varchar(4000)
				set @sql2 = 'drop view data.' + @name
				exec(@sql2)
			end
		end

		fetch next from crsView into @name
	end
	close crsView
	deallocate crsView
GO


---------------------------------------------

-- dbo.procDirectoryRefreshField
CREATE PROCEDURE [dbo].[procDirectoryRefreshField]
	@planTypeGUID as uniqueidentifier,
	@formFieldGUID uniqueidentifier,
	@isForRebuild bit = 0,
	@debug bit = 0,
	@entityexpression nvarchar(max) = ''
AS
	--this procedure is obsolete given FE20, but still exists for backwards compatibility
	RETURN
GO


---------------------------------------------

-- dbo.procDirectoryRefreshFieldAll
CREATE PROCEDURE [dbo].[procDirectoryRefreshFieldAll]
	@planTypeGUID as uniqueidentifier,
	@isForRebuild bit = 0,
	@debug bit = 0,
	@entityexpression nvarchar(max) = ''
AS
	--this procedure is obsolete given FE20, but still exists for backwards compatibility
	RETURN
GO


---------------------------------------------

-- dbo.procDropCLRAssembly
CREATE PROCEDURE dbo.procDropCLRAssembly 
	 @asmname NVARCHAR(1000)
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	
	--First we need to drop all the Wrapper objects that are dependent on the Assembly which include CLR { Aggregates, Scalars, Stored Procedures, Table Value Functions & Triggers }
	DECLARE @d_sql NVARCHAR(MAX);
	DECLARE @drop_type VARCHAR(100)


	-- CURSOR VARIABLES --

	DECLARE @wname NVARCHAR(1000);
	DECLARE @wtype NVARCHAR(1000);

	-- CURSOR VARIABLES (END) --

	DECLARE dCursor CURSOR FAST_FORWARD FOR
	SELECT '[' + ss.name + '].[' + o.name + ']'  AS wraper_name, o.type
	FROM sys.assembly_modules am
	JOIN sys.objects o ON am.object_id = o.object_id
	JOIN sys.assemblies sas ON sas.assembly_id = am.assembly_id
	JOIN sys.schemas ss ON ss.schema_id = o.schema_id
	WHERE sas.name = @asmname

	OPEN dCursor

	FETCH NEXT FROM dCursor INTO @wname, @wtype

	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		SET @drop_type = '';
		
		IF @wtype IN ('PC', 'P')
			SELECT @drop_type = 'PROCEDURE'

		IF @wtype IN ('FN', 'FS', 'FT', 'IF', 'TF')
			SELECT @drop_type = 'FUNCTION'
	    
		IF @wtype = 'AF'
			SELECT @drop_type = 'AGGREGATE'
	    
		IF @wtype = 'U'
			SELECT @drop_type = 'TABLE'
	    
		IF @wtype = 'V'
			SELECT @drop_type = 'VIEW'
			
		IF @drop_type <> ''
		BEGIN
			SET @d_sql = 'DROP '+ @drop_type + ' ' + @wname 
			EXEC(@d_sql);
		END

		FETCH NEXT FROM dCursor INTO @wname, @wtype
	END

	CLOSE dCursor
	DEALLOCATE dCursor

	--Finally drop the Assembly
	SET @d_sql = N'IF  EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = ''' + @asmname + ''' AND is_user_defined = 1) DROP ASSEMBLY ['+ @asmname  +']'
				   
	EXEC(@d_sql)
	
END
GO


---------------------------------------------

-- dbo.procDropIndexesByQuery
create proc [dbo].procDropIndexesByQuery
	@tablename	sysname,
	@query nvarchar(max)
as

-- name:   sp_drop_constraints
-- author: douglas bass
-- date:   06/19/2000

-- sp_drop_constraints will drop all constraints on the specified table, 
-- including CHECK, FOREIGN KEY, PRIMARY KEY, UNIQUE, and DEFAULT constraints.  
-- Compile it in your master database and use it from any user database.

set nocount on

declare @constname	sysname,
	@cmd		varchar(1024)

declare curs_constraints cursor LOCAL FAST_FORWARD for
	select 	name
	from 	sys.indexes 
	where 	
		type = 2
		and object_id = object_id(@tablename)
		and name like @query 
		
open curs_constraints

fetch next from curs_constraints into @constname
while (@@fetch_status = 0)
begin
	select @cmd = 'DROP INDEX ' + @tablename + '.' + @constname
	--print @cmd
	exec(@cmd)
	fetch next from curs_constraints into @constname
end

close curs_constraints
deallocate curs_constraints

return 0
GO


---------------------------------------------

-- dbo.procDropzzFactTableIndex
CREATE PROCEDURE [dbo].[procDropzzFactTableIndex] 
@zzTableName nvarchar(256)
AS
DECLARE @sql nvarchar(1204)
SET @sql ='
 IF EXISTS (SELECT name FROM sys.indexes WHERE name = ''HistoryItemGUID''
 AND object_id = (SELECT object_id(''' + @zzTableName + ''') ) )
 BEGIN
  DROP INDEX [HistoryItemGUID] ON ' + @zzTableName + ' WITH (ONLINE = OFF)
 END
'
Exec sp_executesql @sql
GO


---------------------------------------------

-- dbo.procEMFBlastFormulas
CREATE proc procEMFBlastFormulas
	@modelguid uniqueidentifier
	,@measureguid uniqueidentifier
as

/*
exec procEMFBlastFormulas '00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000000'
*/

declare @mtguid uniqueidentifier
select @mtguid = modeltemplateguid from xplan where planguid = @modelguid

declare @mdcguid uniqueidentifier
declare @zztable varchar(max)
declare @sql varchar(max)

DECLARE mdc CURSOR LOCAL FAST_FORWARD
FOR 
	select  
		distinct
		case when parentmodeldataconfigguid = '00000000-0000-0000-0000-000000000000' then st.modeldataconfigguid
		else parentmodeldataconfigguid
		end as ModelDataConfigGUID
	from 
		emfmodeltemplatelinksource ls
		left join emfsubtable st on ls.parentsubtableguid = st.subtableguid
		inner join emfmodeldatalink mls on ls.linksourceguid = mls.linksourceguid
	where 
		modeltemplateguid = @mtguid
		and mls.modelguid = mls.parentmodelguid  --only self linked are valid
		
OPEN mdc
FETCH NEXT FROM mdc INTO @mdcguid
WHILE @@FETCH_STATUS = 0
BEGIN
	
	set @zztable = 'zzEMFModelData_' + replace(cast(@mdcguid as varchar(36)),'-','_')
	
	set @sql = 'UPDATE ' + @zztable + ' SET Formula = cast(Value as money), StringValue = cast(value as money) WHERE MeasureGUID = ''' + cast(@measureguid as varchar(36)) + ''' AND (formula <> cast(value as money) or stringvalue <> cast(value as money)) AND ModelGUID = ''' + cast(@modelguid as varchar(36)) + ''''
	
	exec(@sql)

	FETCH NEXT FROM mdc INTO @mdcguid
END
CLOSE mdc
DEALLOCATE mdc
GO


---------------------------------------------

-- dbo.procEMFClearOrphanedPlaceholderLabelMappings
create proc procEMFClearOrphanedPlaceholderLabelMappings as 
delete plm from EMFModelTemplatePlaceholderLabelMapping plm
where not plm.PlaceholderMemberGUID in (select listmemberguid from SecureListMember slm where slm.ListGUID = plm.PlaceholderDimensionGUID)
GO


---------------------------------------------

-- dbo.procEMFCreatePlanEmptyFillins
create proc procEMFCreatePlanEmptyFillins as 
insert into emffillin (modelguid, placeholdermemberguid, filledinmemberguid,issetbyuser)
select planguid, '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', 1 from xplan 
where not exists
(select 1 from emffillin where emffillin.modelguid = planguid and placeholdermemberguid = '00000000-0000-0000-0000-000000000000' and filledinmemberguid = '00000000-0000-0000-0000-000000000000')
GO


---------------------------------------------

-- dbo.procEMFFillInAdd
--CREATE FUNCTION [dbo].[GetFillinMembersMissing] 
--   (@modelGUID uniqueidentifier, @placeholderDimensionGUID uniqueidentifier, @maxIndex int)
--RETURNS 
--	@fillInMemberGUIDS TABLE  ( guid uniqueidentifier)
--AS
--BEGIN
CREATE proc [dbo].[procEMFFillInAdd]
	@modelGUID uniqueidentifier
	,@placeholderDimensionGUID as uniqueidentifier --ph
	,@maxIndex int
as

/*
	test 2
	set @placeholderDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77'
	set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC'

	declare @maxIndex int
	set @maxIndex = 4
	--declare @minIndex int
*/
--delete fillins past index @maxIndex
	declare @firstMemberGUID uniqueidentifier
	select @firstMemberGUID = dbo.getModelFirstFillIn(@modelGUID, @placeholderDimensionGUID)
	
	--get out of here if we dont have a base fillin, we cant know where to start
	-- starting at the beginning is kind of dangerous
	if @firstMemberGUID = '00000000-0000-0000-0000-000000000000' return
	
		select 
			--modelguid,dbo.getplanname(modelguid),
			row_number() over (order by slm.sortorderfullpath) as RowNum, 
			listmemberguid
		into #members
		from
			securelistmember slm 
		where
			exists(
				select 1 
				from 
					securelistmember slm2
				where 
					slm2.listguid = slm.listguid
					and slm2.parentlistmemberguid = slm.parentlistmemberguid
					and slm2.listmemberguid = @firstMemberGUID
				)
		
		declare @firstRowNum int
		select @firstRowNum = rownum from #members where listmemberguid = @firstmemberguid
		
		
		DECLARE fillins CURSOR LOCAL FAST_FORWARD FOR 		
			select
				listmemberguid as FillInGUID
			from 
				#members
			where
				rownum between  @firstRowNum and (@firstRowNum + @maxIndex -1)
				and not exists (
					select 1
					from
						emffillin
					where
						filledinmemberguid = listmemberguid
						and modelguid = @modelguid
						)
			order by rownum
			
		declare @fillInMemberGUID uniqueidentifier
		
		OPEN fillins
		FETCH NEXT FROM fillins INTO @fillInMemberGUID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			--exec procEMFFillInSetByIndex @PHDimensionGUID, @ParentPHMemberGUID, @index, @FillInGUID, @ModelGUID
			print @fillInMemberGUID
			exec procEMFFillInAddToEnd @PlaceholderDimensionGUID, @FillInMemberGUID, @ModelGUID
			
			FETCH NEXT FROM fillins INTO @fillInMemberGUID
		END
		
		CLOSE fillins
		deallocate fillins
		
	
	
		
		--exec procEMFFillInAddToEnd


		drop table #members
		
			--PlaceholderMemberGUID in 
			--	(	select listmemberguid 
			--		from securelist 
			--		where listguid = @placeholderDimensionGUID
			--	)
			--and ModelGUID = @modelGUID
		--) FillIns
--	WHERE
--		RowNum > @MaxIndex 
		
		
	

--   RETURN 
--END 
--GO
GO


---------------------------------------------

-- dbo.procEMFFillInAddToEnd
CREATE proc [dbo].[procEMFFillInAddToEnd]
	 @PlaceholderDimensionGUID uniqueidentifier
	--,@PlaceholderParentMemberGUID uniqueidentifier  isnt going to be used on a PH dimension with multi sections yet
	,@FillInMemberGUID uniqueidentifier
	,@ModelGUID uniqueidentifier
as

/*
declare @PHDimGUID uniqueidentifier
declare @PlaceholderIndex int
declare @FillInMemberGUID uniqueidentifier
declare @ModelGUID uniqueidentifier

set @modelguid = '7594B42B-AF3D-43B6-8A56-6CA6F84F836B' --scott 2.0 1
set @PHDimGUID = '1A220CA5-182D-4EA8-AE70-1E6C1E7F8D2D' --staff ph
set @placeholderindex = 2  
set @fillinmemberguid = '37D0CF18-435E-4CEC-9C6F-1D56C6276883' --staff: tushar
*/

declare @placeholdermemberguid uniqueidentifier
declare @placeholderindex int


select @placeholderIndex = dbo.GetModelLastFillInIndex(@ModelGUID,@PlaceholderDimensionGUID)   --next index

set @placeholderIndex= @placeholderIndex + 1

select
	@placeholdermemberguid = placeholdermemberguid
from
	(
	select 
		row_number() over (order by PH.SortOrder) - 1 as PlaceholderIndex, --zero based
		PH.PlaceholderMemberGUID 
	from
		viewplaceholders PH
	where
		PH.PlaceholderDimensionGUID = @PlaceholderDimensionGUID
		--and PH.PlaceholderParentMemberGUID = @PlaceholderParentMemberGUID
	) phnum
where
	PlaceholderIndex  = @placeholderindex


if @placeholdermemberguid is null return

exec procEMFFillInSet @modelguid, @placeholdermemberguid, @fillinmemberguid
GO


---------------------------------------------

-- dbo.procEMFFillInAddToEndSection
CREATE proc [dbo].[procEMFFillInAddToEndSection]
	@SectionGUID uniqueidentifier  --isnt going to be used on a PH dimension with multi sections yet
	,@FillInMemberGUID uniqueidentifier
	,@ModelGUID uniqueidentifier
as

/*
declare @PHDimGUID uniqueidentifier
declare @PlaceholderIndex int
declare @FillInMemberGUID uniqueidentifier
declare @ModelGUID uniqueidentifier

set @modelguid = '7594B42B-AF3D-43B6-8A56-6CA6F84F836B' --scott 2.0 1
set @PHDimGUID = '1A220CA5-182D-4EA8-AE70-1E6C1E7F8D2D' --staff ph
set @placeholderindex = 2  
set @fillinmemberguid = '37D0CF18-435E-4CEC-9C6F-1D56C6276883' --staff: tushar
*/

declare @placeholdermemberguid uniqueidentifier
declare @placeholderindex int


select @placeholderIndex = dbo.GetModelLastFillInIndexSection(@ModelGUID,@SectionGUID)   --next index

set @placeholderIndex= @placeholderIndex + 1

select
	@placeholdermemberguid = placeholdermemberguid
from
	(
	select 
		row_number() over (order by PH.SortOrder) - 1 as PlaceholderIndex, --zero based
		PH.PlaceholderMemberGUID 
	from
		viewplaceholders PH
	where
		PH.PlaceholderParentMemberGUID = @SectionGUID
		
		--and PH.PlaceholderParentMemberGUID = @PlaceholderParentMemberGUID
	) phnum
where
	PlaceholderIndex  = @placeholderindex


if @placeholdermemberguid is null return

exec procEMFFillInSet @modelguid, @placeholdermemberguid, @fillinmemberguid
GO


---------------------------------------------

-- dbo.procEMFFillInCopy
create proc procEMFFillInCopy
	@oldmodelguid uniqueidentifier,
	@newmodelguid uniqueidentifier
as
insert into emffillin(modelguid, placeholdermemberguid, filledinmemberguid, issetbyuser)
select
	@newmodelguid, placeholdermemberguid, filledinmemberguid, issetbyuser
from
	emffillin
where 
	modelguid = @oldmodelguid
	and not exists(select 1 from emffillin fi2 where fi2.modelguid = @newmodelguid and fi2.placeholdermemberguid = emffillin.placeholdermemberguid)
GO


---------------------------------------------

-- dbo.procEMFFillInSet
CREATE proc [dbo].[procEMFFillInSet]
	@planguid uniqueidentifier,
	@PlaceholderMemberGUID uniqueidentifier,
	@FilledInMemberGUID uniqueidentifier
as

if exists (select 1 from emffillin where ModelGUID = @planguid and placeholdermemberguid = @placeholdermemberguid)  begin
	update EMFFillIn 
	SET FilledInMemberGUID = @FilledInMemberGUID 
	WHERE
		ModelGUID = @planguid
		and PlaceholderMemberGUID = @PlaceholderMemberGUID

end else begin 

	INSERT INTO EMFFillIn (ModelGUID, PlaceHolderMemberGUID, FilledInMemberGUID)
	VALUES (@PlanGUID, @PlaceHolderMemberGUID, @FilledInMemberGUID)

end
GO


---------------------------------------------

-- dbo.procEMFFillInSetByIndex
CREATE proc [dbo].[procEMFFillInSetByIndex]
	 @PlaceholderDimensionGUID uniqueidentifier
	,@PlaceholderParentMemberGUID uniqueidentifier
	,@PlaceholderIndex int
	,@FillInMemberGUID uniqueidentifier
	,@ModelGUID uniqueidentifier
as

/*
declare @PHDimGUID uniqueidentifier
declare @PlaceholderIndex int
declare @FillInMemberGUID uniqueidentifier
declare @ModelGUID uniqueidentifier

set @modelguid = '7594B42B-AF3D-43B6-8A56-6CA6F84F836B' --scott 2.0 1
set @PHDimGUID = '1A220CA5-182D-4EA8-AE70-1E6C1E7F8D2D' --staff ph
set @placeholderindex = 2  
set @fillinmemberguid = '37D0CF18-435E-4CEC-9C6F-1D56C6276883' --staff: tushar
*/

declare @placeholdermemberguid uniqueidentifier

select
	@placeholdermemberguid = placeholdermemberguid
from
	(
	select 
		row_number() over (order by PH.SortOrder) - 1 as PlaceholderIndex, --zero based
		PH.PlaceholderMemberGUID 
	from
		viewplaceholders PH
	where
		PH.PlaceholderDimensionGUID = @PlaceholderDimensionGUID
		and PH.PlaceholderParentMemberGUID = @PlaceholderParentMemberGUID
	) phnum
where
	PlaceholderIndex  = @placeholderindex

if @placeholdermemberguid is null return

exec procEMFFillInSet @modelguid, @placeholdermemberguid, @fillinmemberguid
GO


---------------------------------------------

-- dbo.procEMFFillInSetByTemplate
CREATE proc [dbo].[procEMFFillInSetByTemplate]
	@modelguid uniqueidentifier
	,@placeholderdimensionGUID uniqueidentifier
	,@fitname varchar(max)
	,@isClearingOld bit = 1
as

declare @desc varchar(max)
declare @instanceGUID uniqueidentifier
set @instanceGUID = NEWID()

begin try
	begin transaction

		declare @fillInDimensionGUID uniqueidentifier
		select @fillInDimensionGUID = fillInDimensionGUID from securelist where listguid = @placeholderdimensionGUID

		if @fillinDimensionguid is null 
		BEGIN
			ROLLBACK TRANSACTION
			set @desc = '[procEMFFillInSetByTemplate] Failed'
			exec procLogScript @desc, null
			RETURN
	    END
			--SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist

		if @isClearingOld = 1 begin
			delete from EMFFillIn where
				modelguid = @modelguid
				and placeholderMemberGUID in (select listmemberguid from securelistmember where listguid = @placeholderDimensionGUID)
		end
			
			
		insert into EMFFillInSetManyStaging (InstanceGUID,PHDimensionGUID,ModelGUID,ParentPHMemberGUID,FillInGUID,SortOrder)		
		select 
			@instanceGUID,
			@placeholderdimensionguid as PHDimensionGUID, 
			@modelguid as ModelGUID,
			phsection.listmemberguid as ParentPHMemberGUID,
			slmv.listmemberguid as FillInGUID,
			coalesce(slmvdo.valuetext,slm.sortorderfullpath) as SortOrder
			
		from
			securelistmember slm
			inner join securelistmembervalue slmv on slm.listmemberguid = slmv.listmemberguid
			inner join securelistmember phsection on 
				slmv.valuetext = phsection.name
				and phsection.listguid = @placeholderDimensionGUID
			left join securelistproperty slpdo on slm.listguid = slpdo.listguid and slpdo.name = 'Default Order'
			left join securelistmembervalue slmvdo on slm.listguid = slmvdo.listguid and slmvdo.valueindex = slpdo.propertyindex and slmvdo.listmemberguid = slm.listmemberguid
		where
			slmv.listguid = @fillInDimensionGUID
			and	
			exists (
				select 1 
				from 
					securelistproperty slp
				where 
					slp.propertytype= 9
					and slp.listguid = slmv.listguid
					and slmv.valueindex = slp.propertyindex
					and slp.name = @fitname
				)
		
		exec procEMFFillInSetMany @instanceguid	
		
		delete from EMFFillInSetManyStaging where InstanceGUID = @instanceGUID

		set @desc = '[procEMFFillInSetByTemplate] Succeeded, InstanceGUID=' + cast(@instanceGUID as varchar(36))
		exec procLogScript @desc, null
	
	COMMIT TRANSACTION
END TRY

BEGIN CATCH
	ROLLBACK TRANSACTION
	set @desc = '[procEMFFillInSetByTemplate] Failed, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + ': ' + error_message()
	exec procLogScript @desc, null
	exec procSysRethrowError
END CATCH
GO


---------------------------------------------

-- dbo.procEMFFillInSetMany
CREATE proc [dbo].[procEMFFillInSetMany]
	@InstanceGUID uniqueidentifier
as

declare @desc varchar(max)

BEGIN TRY
	BEGIN TRANSACTION

	declare @PHDimensionGUID uniqueidentifier
	declare @modelguid uniqueidentifier
	declare @parentPHMemberGUID uniqueidentifier
	declare @fillInGUID uniqueidentifier
	declare @index int
	
	SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist
	FROM EMFFillInSetManyStaging
	WHERE InstanceGUID = @InstanceGUID

	--clears out ALL (even those set by users) fillins for all combos of Plan-PlaceholderSection that are trying to be mass set
	DELETE FROM EMFFillIn 
	where 
		exists
			(
				select 1 --listmemberguid 
				from 
					#fillinsdist fid
					inner join securelistmember slm on fid.parentphmemberguid = slm.parentlistmemberguid
				where 
					fid.modelguid = emffillin.modelguid
					and emffillin.placeholdermemberguid = slm.listmemberguid
			)
		--and issetbyuser = 0
		
			
	DECLARE fillins CURSOR LOCAL FAST_FORWARD
		FOR SELECT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, Row_Number() over (partition by modelguid, parentphmemberguid order by SORTORDER asc) -1 FROM #fillinsDist
		WHERE 
			NOT MODELGUID IS NULL 
			AND NOT PARENTPHMEMBERGUID is null
			AND NOT FILLINGUID is null
	OPEN fillins
	FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index
	WHILE @@FETCH_STATUS = 0
	BEGIN
		exec procEMFFillInSetByIndex @PHDimensionGUID, @ParentPHMemberGUID, @index, @FillInGUID, @ModelGUID

		FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index
	END
	
	CLOSE fillins
	deallocate fillins
	drop table #fillinsDist
	
	set @desc = '[procEMFFillInSetMany] Succeeded, InstanceGUID=' + cast(@instanceGUID as varchar(36))
	exec procLogScript @desc, null
	
	COMMIT TRANSACTION
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
	
	set @desc = '[procEMFFillInSetMany] Failed, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + ': ' + error_message()
	exec procLogScript @desc, null
	
	exec procSysRethrowError
END CATCH
GO


---------------------------------------------

-- dbo.procEMFFillInSetManyClearThoseBeingSet
CREATE proc [dbo].[procEMFFillInSetManyClearThoseBeingSet]
	@InstanceGUID uniqueidentifier
as
declare @desc varchar(36)
begin try
	begin transaction
	declare @PHDimensionGUID uniqueidentifier
	declare @modelguid uniqueidentifier
	declare @parentPHMemberGUID uniqueidentifier
	declare @fillInGUID uniqueidentifier
	declare @index int
	
	SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist
	FROM EMFFillInSetManyStaging
	WHERE InstanceGUID = @InstanceGUID


	--clears out ALL (even those set by users) fillins for all combos of Plan-PlaceholderSection that are trying to be mass set
	DELETE FROM EMFFillIn 
	where 
		exists
			(
				select 1 --listmemberguid 
				from 
					#fillinsdist fid
					--inner join securelistmember slm on fid.parentphmemberguid = slm.parentlistmemberguid
				where 
					fid.modelguid = emffillin.modelguid
					and emffillin.filledinmemberguid = fid.fillinguid
			)
		and (not FillInGUID = '00000000-0000-0000-0000-000000000000' and not PlaceholderMemberGUID =  '00000000-0000-0000-0000-000000000000')
		--and issetbyuser = 0
		
			
	DECLARE fillins CURSOR LOCAL FAST_FORWARD
		FOR SELECT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, Row_Number() over (partition by modelguid, parentphmemberguid order by SORTORDER asc) -1 FROM #fillinsDist
		WHERE 
			NOT MODELGUID IS NULL 
			AND NOT PARENTPHMEMBERGUID is null
			AND NOT FILLINGUID is null
	OPEN fillins
	FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index
	WHILE @@FETCH_STATUS = 0
	BEGIN
		exec procEMFFillInSetByIndex @PHDimensionGUID, @ParentPHMemberGUID, @index, @FillInGUID, @ModelGUID

		FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index
	END
	
	CLOSE fillins
	deallocate fillins
	drop table #fillinsDist
	
	set @desc = '[procEMFFillInSetManyClearThoseBeingSet] Succeeded, InstanceGUID=' + cast(@instanceGUID as varchar(36))
	exec procLogScript @desc, null
	
	COMMIT TRANSACTION
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
	
	set @desc = '[procEMFFillInSetManyClearThoseBeingSet] Failed, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + ': ' + error_message()
	exec procLogScript @desc, null
	
	exec procSysRethrowError
END CATCH
GO


---------------------------------------------

-- dbo.procEMFFillInSetManyClearThoseBeingSet_ReorderAtEnd
CREATE proc [dbo].[procEMFFillInSetManyClearThoseBeingSet_ReorderAtEnd]
	@InstanceGUID uniqueidentifier
as
declare @desc varchar(max)

begin try
	begin transaction

	declare @PHDimensionGUID uniqueidentifier
	declare @modelguid uniqueidentifier
	declare @parentPHMemberGUID uniqueidentifier
	declare @fillInGUID uniqueidentifier
	declare @index int
	
	SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist
	FROM EMFFillInSetManyStaging
	WHERE InstanceGUID = @InstanceGUID


	--clears out ALL (even those set by users) fillins for all combos of Plan-PlaceholderSection that are trying to be mass set
	delete FROM EMFFillIn 
	where 
		exists
			(
				select 1 --listmemberguid 
				from 
					#fillinsdist fid
					--inner join securelistmember slm on fid.parentphmemberguid = slm.parentlistmemberguid
				where 
					fid.modelguid = emffillin.modelguid
					and emffillin.filledinmemberguid = fid.fillinguid
			)
		and (not FillInGUID = '00000000-0000-0000-0000-000000000000' and not PlaceholderMemberGUID =  '00000000-0000-0000-0000-000000000000')
		--and issetbyuser = 0

----If Any Remaining for Plan-Section Combos are out of order after removal - reorder--
	Update viewemffillinsoutoforder set placeholdermemberguid = sortedphmemberguid 
	where 
		exists
			(select 1 
			 from
			 #fillinsdist fid
			 where
				fid.modelguid = viewemffillinsoutoforder.modelguid
				and viewemffillinsoutoforder.placeholdersectionguid = fid.PARENTPHMEMBERGUID
			 )
			 					
	DECLARE fillins CURSOR LOCAL FAST_FORWARD
		FOR SELECT PARENTPHMEMBERGUID, FILLINGUID,MODELGUID FROM #fillinsDist
		WHERE 
			NOT MODELGUID IS NULL 
			AND NOT PARENTPHMEMBERGUID is null
			AND NOT FILLINGUID is null
	OPEN fillins
	FETCH NEXT FROM fillins INTO @parentPHMemberGUID, @fillInGUID, @ModelGUID
	--FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index
	WHILE @@FETCH_STATUS = 0
	BEGIN
		                            
		exec procEMFFillInAddToEndSection @parentPHMemberGUID, @fillInGUID, @ModelGUID
		--exec procEMFFillInSetByIndex @PHDimensionGUID, @ParentPHMemberGUID, @index, @FillInGUID, @ModelGUID
	
		FETCH NEXT FROM fillins INTO @parentPHMemberGUID, @fillInGUID, @ModelGUID
	
	END
	
	CLOSE fillins
	deallocate fillins
	
	--Reorder Based on Dimension Sort After All Added To End of Section--
	Update viewemffillinsoutoforder set placeholdermemberguid = sortedphmemberguid 
	where 
		exists
			(select 1 
			 from
			 #fillinsdist fid
			 where
				fid.modelguid = viewemffillinsoutoforder.modelguid
				and viewemffillinsoutoforder.placeholdersectionguid = fid.PARENTPHMEMBERGUID
			 )

	drop table #fillinsDist
	
	set @desc = '[procEMFFillInSetManyClearThoseBeingSet_ReorderAtEnd] Succeeded, InstanceGUID=' + cast(@instanceGUID as varchar(36))
	exec procLogScript @desc, null
	
	COMMIT TRANSACTION
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
	
	set @desc = '[procEMFFillInSetManyClearThoseBeingSet_ReorderAtEnd] Failed, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + ': ' + error_message()
	exec procLogScript @desc, null
	
	exec procSysRethrowError
END CATCH
GO


---------------------------------------------

-- dbo.procEMFFillInSetManyNoClear
CREATE proc [dbo].[procEMFFillInSetManyNoClear]
	@InstanceGUID uniqueidentifier
as

/*
declare @PHDimGUID uniqueidentifier
declare @PlaceholderIndex int
declare @FillInMemberGUID uniqueidentifier
declare @ModelGUID uniqueidentifier

set @modelguid = '7594B42B-AF3D-43B6-8A56-6CA6F84F836B' --scott 2.0 1
set @PHDimGUID = '1A220CA5-182D-4EA8-AE70-1E6C1E7F8D2D' --staff ph
set @placeholderindex = 2  
set @fillinmemberguid = '37D0CF18-435E-4CEC-9C6F-1D56C6276883' --staff: tushar
*/

	declare @PHDimensionGUID uniqueidentifier
	declare @modelguid uniqueidentifier
	declare @parentPHMemberGUID uniqueidentifier
	declare @fillInGUID uniqueidentifier
	declare @index int
	
	SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist
	FROM EMFFillInSetManyStaging
	WHERE InstanceGUID = @InstanceGUID

	--clears out ALL (even those set by users) fillins for all combos of Plan-PlaceholderSection that are trying to be mass set
	--DELETE FROM EMFFillIn 
	--where 
	--	exists
	--		(
	--			select 1 --listmemberguid 
	--			from 
	--				#fillinsdist fid
	--				inner join securelistmember slm on fid.parentphmemberguid = slm.parentlistmemberguid
	--			where 
	--				fid.modelguid = emffillin.modelguid
	--				and emffillin.placeholdermemberguid = slm.listmemberguid
	--		)
		--and issetbyuser = 0
		
			
	DECLARE fillins CURSOR LOCAL FAST_FORWARD
		FOR SELECT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, Row_Number() over (partition by modelguid, parentphmemberguid order by SORTORDER asc) -1 FROM #fillinsDist
		WHERE 
			NOT MODELGUID IS NULL 
			AND NOT PARENTPHMEMBERGUID is null
			AND NOT FILLINGUID is null
			AND NOT EXISTS (
				SELECT 1 
				FROM EMFFillIn exFI
					inner join securelistmember phslm on exfi.placeholdermemberguid = phslm.listmemberguid
				WHERE exFI.modelguid  = #fillinsDist.modelguid
						and exFI.filledinmemberguid = #fillinsDist.fillinguid
						and phslm.parentlistmemberguid = #fillinsDist.parentphmemberguid	
				)
			
	OPEN fillins
	FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index
	WHILE @@FETCH_STATUS = 0
	BEGIN
		exec procEMFFillInAddtoendsection  @ParentPHMemberGUID, @FillInGUID, @ModelGUID

		FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index
	END
	
	CLOSE fillins
	deallocate fillins
	drop table #fillinsDist
--select
--	@placeholdermemberguid = placeholdermemberguid
--from
--	(
--	select 
--		row_number() over (order by PH.SortOrder) - 1 as PlaceholderIndex, --zero based
--		PH.PlaceholderMemberGUID 
--	from
--		viewplaceholders PH
--	where
--		PH.PlaceholderDimensionGUID = @PlaceholderDimensionGUID
--		and PH.PlaceholderParentMemberGUID = @PlaceholderParentMemberGUID
--	) phnum
--where
--	PlaceholderIndex  = @placeholderindex

--if @placeholdermemberguid is null return

--exec procEMFFillInSet @modelguid, @placeholdermemberguid, @fillinmemberguid


--GO
GO


---------------------------------------------

-- dbo.procEMFGetModelDependencyTreesByModel
CREATE procedure [dbo].[procEMFGetModelDependencyTreesByModel](
	@ModelGUID uniqueidentifier
)
AS
BEGIN
	

DECLARE @submodelGUID uniqueidentifier;

DECLARE @ModelTree TABLE ( ModelGUID uniqueidentifier, [Level]  int)

insert into @ModelTree  select * from dbo.GetModelDependencyTree(@modelGUID, 100);
select * from @ModelTree --select for dataset

DECLARE mCursor CURSOR FAST_FORWARD FOR
	select ModelGUID from @ModelTree
	
open mCursor

FETCH NEXT FROM mCursor into @submodelGUID
WHILE(@@FETCH_STATUS = 0)
BEGIN
	if (@submodelGUID <> @ModelGUID)
		select * from dbo.GetModelDependencyTree(@submodelGUID, 100);
	
	FETCH NEXT FROM mCursor into @submodelGUID;
END
close mCursor;
DEALLOCATE mCursor;

	
END
GO


---------------------------------------------

-- dbo.procEMFGetModelDependencyTreesByModelList
CREATE Procedure [dbo].[procEMFGetModelDependencyTreesByModelList]
(
	@ModelGUIDCSV nvarchar(max)
)
AS

declare crsCursor CURSOR FAST_FORWARD FOR
	select PlanGUID from XPlan 
		where PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@ModelGUIDCSV, ',')) and IsDeletedPlan = 0
	
open crsCursor;

DECLARE @UsedModels TABLE
(
	ModelGUID uniqueidentifier primary key
)
DECLARE @modelGUID uniqueidentifier
DECLARE @submodelGUID uniqueidentifier;

declare @ModelTree TABLE ( ModelGUID uniqueidentifier, [Level]  int)
		
		
FETCH NEXT FROM crsCursor into @modelGUID
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		
		insert into @ModelTree  select * from dbo.GetModelDependencyTree(@modelGUID, 100);
		if (not exists (select 1 from @UsedModels where ModelGUID = @modelGUID))
		BEGIN
			select * from @ModelTree --select for dataset
			insert into @UsedModels (ModelGUID) VALUES (@modelGUID);
			
			DECLARE mCursor CURSOR FAST_FORWARD FOR
			select ModelGUID from @ModelTree
			
			open mCursor
			
			FETCH NEXT FROM mCursor into @submodelGUID
			WHILE(@@FETCH_STATUS = 0)
			BEGIN
				if (not exists (select 1 from @UsedModels where ModelGUID = @submodelGUID))
				BEGIN
					select * from dbo.GetModelDependencyTree(@submodelGUID, 100);
					insert into @UsedModels (ModelGUID) values (@submodelGUID);
				END
				
				FETCH NEXT FROM mCursor into @submodelGUID;
			END
			close mCursor;
			DEALLOCATE mCursor;
			
			delete from @ModelTree
		END --if not exists	
		
		FETCH NEXT FROM crsCursor into @modelGUID
	END --while
close crsCursor;
DEALLOCATE crsCursor;
GO


---------------------------------------------

-- dbo.procEMFGetModelDependencyTreesByModelTemplate
--Author: gforeman
--Branch: Earwig
--Forward
CREATE Procedure [dbo].[procEMFGetModelDependencyTreesByModelTemplate]
(
	@ModelTemplateGUID uniqueidentifier
)
AS

declare crsCursor CURSOR FAST_FORWARD FOR
	select PlanGUID from XPlan 
		where ModelTemplateGUID = @ModelTemplateGUID and IsDeletedPlan = 0
	
open crsCursor;

DECLARE @UsedModels TABLE
(
	ModelGUID uniqueidentifier primary key
)
DECLARE @modelGUID uniqueidentifier
DECLARE @submodelGUID uniqueidentifier;

declare @ModelTree TABLE ( ModelGUID uniqueidentifier, [Level]  int)
		
		
FETCH NEXT FROM crsCursor into @modelGUID
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		
		insert into @ModelTree  select * from dbo.GetModelDependencyTree(@modelGUID, 100);
		if (not exists (select 1 from @UsedModels where ModelGUID = @modelGUID))
		BEGIN
			select * from @ModelTree --select for dataset
			insert into @UsedModels (ModelGUID) VALUES (@modelGUID);
			
			DECLARE mCursor CURSOR FAST_FORWARD FOR
			select ModelGUID from @ModelTree
			
			open mCursor
			
			FETCH NEXT FROM mCursor into @submodelGUID
			WHILE(@@FETCH_STATUS = 0)
			BEGIN
				if (not exists (select 1 from @UsedModels where ModelGUID = @submodelGUID))
				BEGIN
					select * from dbo.GetModelDependencyTree(@submodelGUID, 100);
					insert into @UsedModels (ModelGUID) values (@submodelGUID);
				END
				
				FETCH NEXT FROM mCursor into @submodelGUID;
			END
			close mCursor;
			DEALLOCATE mCursor;
			
			delete from @ModelTree
		END --if not exists	
		
		FETCH NEXT FROM crsCursor into @modelGUID
	END --while
close crsCursor;
DEALLOCATE crsCursor;
GO


---------------------------------------------

-- dbo.procEMFImprovInsertCopy
CREATE proc [dbo].[procEMFImprovInsertCopy]
	@sourceplanguid uniqueidentifier
	,@newplanguid uniqueidentifier
as

declare @sourceFileGuid uniqueidentifier
select @sourceFileGuid =FileGUID  from DataPathFile_Improv where FullPath = 'ImprovWorkbook' + CAST(@sourceplanguid as varchar(36)) +'.xlsx'

declare @fullpath varchar(max)
if not @sourceFileGuid is null begin
	set @fullpath = 'ImprovWorkbook' + CAST(@newplanguid as varchar(36)) +'.xlsx'
	exec dbo.procDataPathCopyFile  @sourceFileGuid, @fullpath
end

delete from MEImprovData where ModelGUID = @newplanguid
insert into MEImprovData(ModelGUID, WorksheetGUID, Row, Col, Formula, CellValue, OriginalComment)
select @newplanguid, WorksheetGUID, Row, Col, Formula, CellValue, OriginalComment
from
	MEImprovData
where
	modelguid = @sourceplanguid
GO


---------------------------------------------

-- dbo.procEMFListCacheCleanup
CREATE proc [dbo].[procEMFListCacheCleanup]
	@isDeleting bit = 0
as
	declare @tblsql nvarchar(4000)
	declare @tablename nvarchar(100)
	declare crsTables cursor for
		select 
			t.name
		from 
			sys.tables t
			left join SecureList l on cast(l.ListGUID as nvarchar(36)) = replace(RIGHT(t.name, 36), '_', '-')
		where 
			t.name like 'zzlist%'
			and l.ListGUID is null
		
	open crsTables
	fetch next from crsTables into @tablename

	while(@@FETCH_STATUS = 0) begin
		set @tblsql = 'drop table ' + @tablename
		exec(@tblsql)

		fetch next from crsTables into @tablename
	end

	close crsTables
	deallocate crsTables

	declare @viewsql nvarchar(4000)
	declare @viewname nvarchar(100)
	declare crsViews cursor for
		select 
			v.name
		from 
			sys.views v
			left join SecureList l on replace(l.Name, ' ', '') = replace(replace(v.name, 'zzviewlist_', ''), 'zzviewlistexport_', '')
		where 
			v.name like 'zzviewlist%'
			and l.ListGUID is null
		
	open crsViews
	fetch next from crsViews into @viewname

	while(@@FETCH_STATUS = 0) begin
		if(@isDeleting = 1) begin
			set @viewsql = 'drop view ' + @viewname
			exec(@viewsql)
		end else begin
			print @viewname
		end
		
		fetch next from crsViews into @viewname
	end

	close crsViews
	deallocate crsViews
GO


---------------------------------------------

-- dbo.procEMFMDCViewCleanup
CREATE proc [dbo].[procEMFMDCViewCleanup]
	@isDeleting bit = 0
as
	declare @viewsql nvarchar(4000)
	declare @viewname nvarchar(100)
	declare crsViews cursor for
		select 
			v.name
		from 
			sys.views v
			left join EMFModelDataConfig mdc on replace(replace(replace(replace(replace(replace(replace(mdc.Name, ' ', ''), '-', ''), '&', ''), '(', ''), ')', ''), '/', ''), '\', '') in(replace(v.Name, 'zzviewModelTemplateMapping_', ''), replace(v.Name, 'zzviewModelTemplateMappingBasic_', ''), replace(v.Name, 'zzviewModelData_', ''), replace(v.Name, 'zzviewModelDataInner_', ''), replace(v.Name, 'zzviewModelDataBasic_', ''))
		where 
			v.name like 'zzviewModel%'
			and mdc.ModelDataConfigGUID is null
		
	open crsViews
	fetch next from crsViews into @viewname

	while(@@FETCH_STATUS = 0) begin
		if(@isDeleting = 1) begin
			set @viewsql = 'drop view ' + @viewname
			exec(@viewsql)
		end else begin
			print @viewname
		end

		fetch next from crsViews into @viewname
	end

	close crsViews
	deallocate crsViews
GO


---------------------------------------------

-- dbo.procEMFMissingPHMembersCreate
CREATE proc [dbo].[procEMFMissingPHMembersCreate]
	@sourcedb nvarchar(100)
as
	declare @sql nvarchar(max)
	
	set @sql='
		insert into [dbo].[SecureListMember] ([ListMemberGUID],[ListGUID],[ParentListMemberGUID],[Name],[Description],[FullPath],[DisplayOrder],[OutlineLevel],[OperatorType],[IsIDLocked],[IsNameLocked],[IsDeleteLocked],[IsNewChildLocked],[IsParentAssociationLocked],[IsEditAttributeLocked],[ListMemberID],[SortOrderFullPath],[FillInConfigGUID],[FillInDimensionGUID],[DateCreated],[DateModified],[LootIDOverride]) 
		select LM.[ListMemberGUID],LM.[ListGUID],LM.[ParentListMemberGUID],LM.[Name],LM.[Description],LM.[FullPath],LM.[DisplayOrder],LM.[OutlineLevel],LM.[OperatorType],LM.[IsIDLocked],LM.[IsNameLocked],LM.[IsDeleteLocked],LM.[IsNewChildLocked],LM.[IsParentAssociationLocked],LM.[IsEditAttributeLocked],LM.[ListMemberID],LM.[SortOrderFullPath],LM.[FillInConfigGUID],LM.[FillInDimensionGUID],LM.[DateCreated],LM.[DateModified],LM.[LootIDOverride] 
		from
			' + @sourcedb + '.dbo.SecureListMember LM
			inner join ' + @sourcedb + '.dbo.SecureList L on L.ListGUID = LM.ListGUID
			left join SecureListMember ME on ME.Name = LM.Name and ME.ListGUID = LM.ListGUID
		where
			ME.ListMemberGUID is null
			and L.Name like ''%ph'''
			
	exec(@sql)
GO


---------------------------------------------

-- dbo.procEMFModelTemplateMappingEnsureIndexes
create proc procEMFModelTemplateMappingEnsureIndexes
as
	declare @mdcguid uniqueidentifier
	declare @sql nvarchar(max)
	declare crsScripts cursor for 
		select 
			MDC.ModelDataConfigGUID,
			'CREATE CLUSTERED INDEX [idx_zzEMFModelTemplateMapping_' + replace(CAST(MDC.ModelDataConfigGUID as nvarchar(36)), '-', '_') + '_ByTemplate] ON [dbo].[zzEMFModelTemplateMapping_' + replace(CAST(MDC.ModelDataConfigGUID as nvarchar(36)), '-', '_')  + '] 
			(
				[MODELTEMPLATEGUID] ASC
			)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]' as IdxCreateSQL
		from 
			EMFModelDataConfig MDC
		where
			not exists(select 1 from sys.indexes idx where idx.name = 'idx_zzEMFModelTemplateMapping_' + replace(CAST(MDC.ModelDataConfigGUID as nvarchar(36)), '-', '_') + '_ByTemplate')

	open crsScripts
	fetch next from crsScripts into @mdcguid, @sql
			
	while (@@FETCH_STATUS = 0) begin
		print @mdcguid
		exec(@sql)
		fetch next from crsScripts into @mdcguid, @sql
	end

	close crsScripts
	deallocate crsScripts
GO


---------------------------------------------

-- dbo.procEMFRemoveTemplateMappings
CREATE proc [dbo].[procEMFRemoveTemplateMappings]
	@modeltemplateguid uniqueidentifier,
	@includeprofiles bit = 1
as
	--EMF mapping tables
	declare @execsql varchar(max)
	set @execsql = '
	delete from zzemfmodeltemplatemapping_{mdcguidfriendly} where modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + '''
	'
	declare @structurefiltersql varchar(max)
	set @structurefiltersql = '
	WHERE 
		ModelDataConfigGUID IN (
		select 
			isnull(st.modeldataconfigguid, ls.parentmodeldataconfigguid)
		from 
			emfmodeltemplatelinksource ls
			left join emfsubtable st on ls.parentsubtableguid = st.subtableguid
		where
			modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + '''
			)'
	exec dbo.procEMFRunForManyStructures @execsql, @structurefiltersql, 1,0

	--Expansions (EMF)
	delete from EMFModelTemplateExpansion where ExpansionGUID in (select expansionguid from viewEMFModelTemplateExpansion where ModelTemplateGUID = @modeltemplateguid)
	
	--Form Field mappings (Score)
	delete from EMFModelTemplateFormFieldMapping where cellguid in (select c.cellguid from viewmecell c where c.BookGUID = @modeltemplateguid)
	
	--Placeholder Labels (EMF)
	delete from EMFModelTemplatePlaceholderLabelMapping where cellguid in (select c.cellguid from viewmecell c where c.BookGUID = @modeltemplateguid)
	
	--Form Field mappings (EMF)
	delete from EMFModelTemplateFormFieldMapping where cellguid in (select ff.CellGUID from EMFModelTemplateFormFieldMapping ff left join MEExcelCell ce on ce.ExcelCellGUID = ff.CellGUID where ce.ExcelCellGUID is null)

	--Score mapping tables
	set @execsql = '
	delete m
	from 
		{schema}.{object} m 
	where 
		exists (
			select 1 
			from 
				viewMECell c
			where
				c.CellGUID = m.CellGUID
				and c.BookGUID = ''' + cast(@modeltemplateguid as varchar(36)) + '''
			)
		or not exists (
			select 1
			from
				viewMECell c2
			where
				c2.CellGUID = m.CellGUID
		)
		'
	set @structurefiltersql = '
	where
		ScoreDataTable.DataTableGUID in (
			select DataTableGUID1 
			from ScoreComposite sc
				inner join EMFModelTemplateLinkSource ls on ls.ParentScoreCompositeTableGUID = sc.CompositeGUID
			where
				ls.ModelTemplateGUID = ''' + cast(@modeltemplateguid as varchar(36)) + '''
		) 
	'
	exec dbo.procScoreRunForManyStructures @execsql, @structurefiltersql, 1, 0

	--Placeholder Labels (Score)
	delete phl from [dbo].[MEScorePlaceholderLabel] phl where phl.CellGUID in (select cx.ExcelCellGUID from [dbo].[viewMECell] cx where cx.ModelTemplateGUID = @modeltemplateguid)
	
	--Expansions (Score)
	delete scx from MEScoreExpansion scx where scx.ExcelCellGUID in (select cx.ExcelCellGUID from [dbo].[viewMECell] cx where cx.ModelTemplateGUID = @modeltemplateguid)

	--Template Cells (Score)
	delete xc from [dbo].[MEExcelCell] xc inner join [dbo].[EMFModelTemplateWorksheet] ws on ws.WorksheetGUID = xc.ExcelSheetGUID where ws.ModelTemplateGUID = @modeltemplateguid;

	--Child Expansion Profiles
	if (@includeprofiles = 1) begin
		declare crsProfiles cursor fast_forward for select ChildModelTemplateGUID from [dbo].[MEScoreExpansionProfile] with (readuncommitted) where ParentModelTemplateGUID = @modeltemplateguid
		declare @childmtguid uniqueidentifier
		open crsProfiles
		fetch next from crsProfiles into @childmtguid
		while(@@fetch_status = 0) begin
			exec [dbo].[procEMFRemoveTemplateMappings] @childmtguid, 0
			fetch next from crsProfiles into @childmtguid
		end
		close crsProfiles
		deallocate crsProfiles
	end
GO


---------------------------------------------

-- dbo.procEMFRemoveUnfilledData
create proc procEMFRemoveUnfilledData
	@placeholderDimensionGUID uniqueidentifier
	,@isDeleting bit = 0
	,@isRunning bit = 0
as
--set @isRunning = 0
--set @isDeleting = 1
--set @placeholderDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77'


declare @dimnameFriendly varchar(128)
select @dimnameFriendly = REPLACE(name,' ','') from securelist where ListGUID = @placeholderDimensionGUID

--select * from SecureList where IsPlaceholder = 1
declare @planDimGUID uniqueidentifier
select @planDimGUID = listguid from SecureList where ListType = 2

declare @wheresql varchar(max)
set @wheresql = '
where modeldataconfigguid in (
select
	modeldataconfigguid
from
	EMFModelDataConfigDimensionLink
where
	DimensionGUID = ''' + cast(@placeholderDimensionGUID as varchar(36)) + '''
intersect
select
	modeldataconfigguid
from
	EMFModelDataConfigDimensionLink
where
	DimensionGUID = ''' + cast(@planDimGUID as varchar(36)) + '''
	)
'
	
declare @maybeBasic varchar(10)
if @isDeleting = 1 
	set @maybeBasic = 'Basic'
else
	set @maybeBasic = ''
	
declare @sql varchar(max)


if @isDeleting = 1 
	set @sql = 'delete data '
else
	set @sql = 'select 	''{mdcname}'' as MDCName, * '


set @sql = @sql + ' 
from
	zzviewModelData' + @maybebasic + '_{mdcnamefriendly} data
where
	not exists (
	select 1
	from
		EMFFillIn fi 
	where
		fi.modelguid = data.PlansGUID --modelguid
		and fi.FilledInMemberGUID = data.' + @dimnamefriendly + 'GUID -- g17FEAA4B_A2A2_4353_B081_03E3DFB5CB77
	)
'

exec procEMFRunForManyStructures @sql, @wheresql,@isRunning,0
GO


---------------------------------------------

-- dbo.procEMFRunForManyStructures
CREATE proc [dbo].[procEMFRunForManyStructures]
	@execsql varchar(max)
	,@structurefiltersql varchar(max) = ''
	,@exec bit = 0
	,@allTogether bit = 0
as

--set @execsql = '
--	select ''{mdcname}'', count(*) from zzemfmodeldata_{mdcguidfriendly}
--'
--set @structurefiltersql = '
--where name like ''lrfp%''
--'

declare @structuresql varchar(max)

set @structuresql = '
select
	modeldataconfigguid, name
from
	emfmodeldataconfig
' + @structurefiltersql

create table #mdcs (modeldataconfigguid uniqueidentifier, name nvarchar(64))

insert into #mdcs
exec (@structuresql)	

declare @mdcguid uniqueidentifier
declare @mdcguidfriendly varchar(36)
declare @mdcname nvarchar(64)
declare @mdcnamefriendly nvarchar(64)
declare @sql varchar(max)

	declare crsMDC CURSOR FOR
		select modeldataconfigguid, name 
		from #mdcs
		
	open crsMDC;
	
	set @sql = ''
	
	FETCH NEXT FROM crsMDC into @mdcguid, @mdcname
	WHILE (@@FETCH_STATUS = 0) 
		BEGIN
		
			set @mdcguidfriendly = replace(cast(@mdcguid as varchar(36)),'-','_')
			set @mdcnamefriendly = REPLACE(@mdcname,' ','')
			set @mdcnamefriendly = REPLACE(@mdcnamefriendly,'-','')
			set @mdcnamefriendly = REPLACE(@mdcnamefriendly,'.','')
			
			if @allTogether = 1 begin
				set @sql = @sql + replace(replace(replace(replace(@execsql,'{mdcguid}',cast(@mdcguid as varchar(36))), '{mdcname}',@mdcname),'{mdcguidfriendly}',@mdcguidfriendly),'{mdcnamefriendly}',@mdcnamefriendly)
			end else begin
				set @sql = replace(replace(replace(replace(@execsql,'{mdcguid}',cast(@mdcguid as varchar(36))), '{mdcname}',@mdcname),'{mdcguidfriendly}',@mdcguidfriendly),'{mdcnamefriendly}',@mdcnamefriendly)
				if @exec = 1 begin
					exec(@sql)
				end else begin
					print @sql
				end
			end

			
			

			FETCH NEXT FROM crsMDC into  @mdcguid, @mdcname
		END
	close crsMDC;
	DEALLOCATE crsMDC;

			if @allTogether = 1 begin
				if @exec = 1 begin
					exec(@sql)
				end else begin
					print @sql
				end
			end


	
drop table #mdcs
GO


---------------------------------------------

-- dbo.procEMFShowTemplateMappingCounts
CREATE proc [dbo].[procEMFShowTemplateMappingCounts]
	@modeltemplateguid uniqueidentifier
as

	
declare @wheresql varchar(max)
set @wheresql = '
where modeldataconfigguid in (
select
	ISNULL(st.MODELDATACONFIGGUID,ls.ParentModelDataConfigGUID)
from
	EMFModelTemplateLinkSource ls
	left join EMFSubtable st on ls.ParentSubtableGUID= st.SUBTABLEGUID
where
	modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + '''
	)
'

declare @sql varchar(max)
set @sql = ' 
select
	''{mdcname}'' as Name, count(*) as TotalCnt, sum(case when isusermapped = 1 then 1 else 0 end) as UserMappedCount
from
	zzEMFModelTemplateMapping_{mdcguidfriendly} map
where
	modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + '''
'

exec procEMFRunForManyStructures @sql, @wheresql,1
GO


---------------------------------------------

-- dbo.procEMFViewTemplateMappingCount
CREATE proc [dbo].[procEMFViewTemplateMappingCount]
	@modeltemplateguid uniqueidentifier
as

declare @execsql varchar(max)
set @execsql = 'declare @cnt int
	select @cnt = count(*) from zzemfmodeltemplatemapping_{mdcguidfriendly} with (readuncommitted) where modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + '''
	print ''{mdcname} '' + cast(@cnt as varchar(36))
	'

declare @structurefiltersql varchar(max)
set @structurefiltersql = ' WHERE ModelDataConfigGUID IN (
select 
	isnull(st.modeldataconfigguid, ls.parentmodeldataconfigguid)
from 
	emfmodeltemplatelinksource ls
	left join emfsubtable st on ls.parentsubtableguid = st.subtableguid
where
	modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + '''
	)'
	
exec dbo.procEMFRunForManyStructures @execsql, @structurefiltersql, 1,0
GO


---------------------------------------------

-- dbo.procEnsureColumnInTable
CREATE proc [dbo].[procEnsureColumnInTable](
	@SchemaName NVARCHAR(128),
	@TableName NVARCHAR(MAX),
	@ColumnName NVARCHAR(128),
	 @Type NVARCHAR(128), @Default nvarchar(128), @DebugMode bit = 0)

AS
BEGIN

DECLARE @sql varchar(max)

IF dbo.tableColumnExists(@SchemaName, @TableName, @ColumnName)=0 BEGIN
	SET @SQL = 	'ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName))
	SET @SQL = @SQL + ' ADD ' + @ColumnName
	SET @SQL = @SQL + ' ' + @Type
	IF LOWER(@Type) <> 'timestamp'
	begin
	  SET @SQL = @SQL + ' NOT NULL CONSTRAINT DF_' + replace(@TableName,' ','_') + '_' + @ColumnName
	  SET @SQL = @SQL + ' DEFAULT ' + @default
	end
	

	IF @DebugMode = 0 BEGIN
		EXEC (@SQL)
		PRINT @ColumnName + ' added to ' + @TableName
	END ELSE BEGIN
		PRINT @SQL
	END
	
END


END
GO


---------------------------------------------

-- dbo.procEnsureColumnInTableCopyFromOther
CREATE proc [dbo].[procEnsureColumnInTableCopyFromOther](
	@SchemaName NVARCHAR(128),
	@TableName NVARCHAR(MAX),
	@ColumnName NVARCHAR(128), 
	@Type NVARCHAR(128), @Default nvarchar(128), @OldColumnName NVARCHAR(128),  @DebugMode bit = 0)

AS
BEGIN

DECLARE @sql varchar(max)
DECLARE @sql2 varchar(max)

IF dbo.ColumnExists(@SchemaName, @TableName, @ColumnName)=0 BEGIN
	SET @SQL = 	'ALTER TABLE ' + (select [dbo].[GetSQLTableExpression] (@SchemaName, @TableName))
	SET @SQL = @SQL + ' ADD ' + @ColumnName
	SET @SQL = @SQL + ' ' + @Type
	SET @SQL = @SQL + ' NOT NULL CONSTRAINT DF_' + Replace(@TableName,' ','_') + '_' + @ColumnName
	SET @SQL = @SQL + ' DEFAULT ' + @default

	SET @SQL2 = ' UPDATE ' + (select [dbo].[GetSQLTableExpression] (@SchemaName, @TableName))
	SET @SQL2 = @SQL2 + '   SET ' + @ColumnName 
	SET @SQL2 = @SQL2 + '			= ' + @OldColumnName 
	
	IF @DebugMode = 0 BEGIN
		EXEC (@SQL)
		PRINT @ColumnName + ' added to ' + @TableName
		EXEC (@SQL2)
		PRINT @OldColumnName + ' copied to ' + @ColumnName + ' for ' + @TableName
		
	END ELSE BEGIN
		PRINT @SQL
		PRINT 'GO'
		PRINT @SQL2
	END
	
END


END
GO


---------------------------------------------

-- dbo.procEnsureColumnNotInTable
CREATE proc [dbo].[procEnsureColumnNotInTable](
	@SchemaName NVARCHAR(128),
	@TableName NVARCHAR(MAX),
	@ColumnName NVARCHAR(128), 
	@DebugMode bit = 0
)
AS
BEGIN

DECLARE @sql varchar(max)

IF dbo.ColumnExists(@SchemaName, @TableName, @ColumnName)=1 BEGIN
	SET @SQL = 	'ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName))
	SET @SQL = @SQL + ' DROP CONSTRAINT DF_' + @TableName + '_' + @ColumnName

	SET @SQL = @SQL + '
						ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName))
	SET @SQL = @SQL + ' DROP COLUMN ' + @ColumnName

	IF @DebugMode = 0 BEGIN
		EXEC (@SQL)
		PRINT @ColumnName + ' removed from ' + @TableName
	END ELSE BEGIN
		PRINT @SQL
	END
	
END


END
GO


---------------------------------------------

-- dbo.procEnsureDimensionColumnsInTable
CREATE proc [dbo].[procEnsureDimensionColumnsInTable]
	@schemaname nvarchar(128),
	@tableName nvarchar(128),
	@mdcguid uniqueidentifier,
	@debugmode bit,
	@skipmodel bit
as

DECLARE @dimensionName as nvarchar(256)
DECLARE @dimensionGUID as uniqueidentifier
DECLARE @listtype int
DECLARE @zzDIMcursor nvarchar(256)


DECLARE zzdimensions CURSOR LOCAL FAST_FORWARD
FOR SELECT SLM.LISTGUID, SLM.NAME, SLM.LISTTYPE, UPPER('G' + REPLACE(cast(SLM.LISTGUID as varchar(36)),'-','_')) FROM dbo.EMFModelDataConfigDimensionLink MDCDL JOIN SECURELIST SLM ON MDCDL.DIMENSIONGUID=SLM.LISTGUID WHERE MDCDL.MODELDATACONFIGGUID = @MDCGUID ORDER BY CASE WHEN SLM.LISTTYPE = 2 THEN 0 ELSE 1 END, CAST(SLM.LISTGUID as varchar(36)) ASC

OPEN zzdimensions
FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @listtype, @zzDIMcursor
WHILE @@FETCH_STATUS = 0
BEGIN
	--SET @zzDIMcolumnname = @zzDIMcursor --+ 'GUID'

	IF @LISTTYPE = 2 BEGIN
		IF @skipmodel = 0 BEGIN
			exec procEnsureColumnInTable @schemaname, @tableName,'MODELGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
		END
	END ELSE BEGIN
		exec procEnsureColumnInTable @schemaname, @tableName,@zzDimCursor, 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
	END


	FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @listtype, @zzDIMcursor
END
CLOSE zzdimensions
DEALLOCATE zzdimensions
GO


---------------------------------------------

-- dbo.procEnsureSchema
CREATE PROCEDURE dbo.procEnsureSchema(
	@Schema nvarchar(128)
)
AS
BEGIN

	declare @count int;
	select @count = count(*) from INFORMATION_SCHEMA.SCHEMATA where [SCHEMA_NAME] = @Schema;
	
	if (@count < 1) 
	begin
		declare @sql varchar(max);
		set @sql = 'CREATE SCHEMA [' + @Schema + '];';
		exec (@sql);
	end

END
GO


---------------------------------------------

-- dbo.procEnsureScoreDataTableSetup
CREATE proc [dbo].[procEnsureScoreDataTableSetup]
	@dataTableGUID uniqueidentifier
	,@debugMode bit = 0
as

--set @dataTableGUID = 'BDD7EF92-5335-4FD1-9E0A-E22FF8A60CC8'
--set @debugMode = 0
declare @mappingTableName nvarchar(max)
declare @SchemaName nvarchar(128)

select 
	@mappingTableName = SQLObjectName,
	@SchemaName = SQLSchemaName
from dbo.ScoreDataTable where DataTableGUID = @dataTableGUID

exec procAddIdentityColumnToTable @SchemaName, @mappingTableName,'RowID', @DebugMode, '1', '1'
exec procEnsureColumnInTable @SchemaName, @mappingTableName,'HistoryItemGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
exec procEnsureColumnInTable @SchemaName, @mappingTableName, 'Version', 'timestamp', '', @DebugMode
exec procEnsureColumnInTable @SchemaName, @mappingTableName, 'IsDeleted', 'bit', '0', @DebugMode
GO


---------------------------------------------

-- dbo.procEnsureScoreMappingTableSetup
CREATE proc [dbo].[procEnsureScoreMappingTableSetup]
	@dataTableGUID uniqueidentifier
	,@debugMode bit = 0
	,@isLegacy bit = 0
as

--set @dataTableGUID = 'BDD7EF92-5335-4FD1-9E0A-E22FF8A60CC8'
--set @debugMode = 0
declare @mappingTableName nvarchar(max)
declare @SchemaName nvarchar(128)
select 
	@mappingTableName = SQLObjectName,
	@SchemaName = SQLSchemaName
from dbo.ScoreDataTable where DataTableGUID = @dataTableGUID

exec procEnsureScoreDataTableSetup @dataTableGUID, @debugMode
exec procEnsureColumnInTable @SchemaName, @mappingTableName,'RowExpanded', 'int', '0', @DebugMode
exec procEnsureColumnInTable @SchemaName, @mappingTableName,'CellGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsUserMapped', 'bit', '1', @DebugMode
exec procEnsureColumnInTable @SchemaName, @mappingTableName,'MeasureGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode

exec procEnsureScoreMeasureExists @datatableguid,'RowExpanded',2,@debugmode
exec procEnsureScoreMeasureExists @datatableguid,'CellGUID',1,@debugmode
exec procEnsureScoreMeasureExists @datatableguid,'IsUserMapped',10,@debugmode
exec procEnsureScoreMeasureExists @datatableguid,'MeasureGUID',8,@debugmode

if @isLegacy = 1 begin
	exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsReadFromDB', 'bit', '0', @DebugMode
	exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsWrittenToDB', 'bit', '0', @DebugMode
	exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsLocked', 'bit', '0', @DebugMode
	exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsAssumptionInput', 'bit', '0', @DebugMode
	exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsAssumptionOutput', 'bit', '0', @DebugMode
	exec procEnsureColumnInTable @SchemaName, @mappingTableName,'CompositeGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
	exec procEnsureScoreMeasureExists @datatableguid,'IsWrittenToDB',3,@debugmode
	exec procEnsureScoreMeasureExists @datatableguid,'IsReadFromDB',4,@debugmode
	exec procEnsureScoreMeasureExists @datatableguid,'IsLocked',5,@debugmode
	exec procEnsureScoreMeasureExists @datatableguid,'IsAssumptionInput',6,@debugmode
	exec procEnsureScoreMeasureExists @datatableguid,'IsAssumptionOutput',7,@debugmode
	exec procEnsureScoreMeasureExists @datatableguid,'CompositeGUID',9,@debugmode
end


        --CellGUID = 1
        --RowExpanded = 2
        --IsWrittenToDB = 3
        --IsReadFromDB = 4
        --IsLocked = 5
        --IsAssumptionInput = 6
        --IsAssumptionOutput = 7
        --MeasureGUID = 8
--guid = 36
--int = 52
--bit = 104
--go
--alter proc procEnsureScoreMeasureExists
--	@dataTableGUID uniqueidentifier
--	,@columnName varchar(64)
--	,@sqlDataType int
--	,@specialMeasureIndex tinyint 
--	,@isDebug bit = 0
--as

--declare @cnt int
--select @cnt = COUNT(*) from dbo.ScoreMeasure sm where sm.DataTableGUID = @dataTableGUID and SQLColumnName = @columnName
--if @cnt = 0 begin

--	if @isDebug = 1 begin
--		select @columnName, @datatableguid,1,1,@columnName, '{0}.' + @columnName, @sqlDataType,@specialMeasureIndex
--	end else begin
--		insert into dbo.ScoreMeasure (FriendlyName,DataTableGUID,IsReadFromDB,IsWrittenToDB,SQLColumnName, SQLColumnExpression, SQLDataType, SpecialMeasureIndex)
--		select @columnName, @datatableguid,1,1,@columnName, '{0}.' + @columnName, @sqlDataType,@specialMeasureIndex
--	end
--end
GO


---------------------------------------------

-- dbo.procEnsureScoreMeasureExists
CREATE proc [dbo].[procEnsureScoreMeasureExists]
	@dataTableGUID uniqueidentifier
	,@columnName varchar(64)
	,@specialMeasureIndex tinyint 
	,@isDebug bit = 0
as

declare @cnt int
select @cnt = COUNT(*) from dbo.ScoreMeasure sm where sm.DataTableGUID = @dataTableGUID and SQLColumnName = @columnName
if @cnt = 0 begin
	--measure missing completely
	if @isDebug = 1 begin
		select @columnName, @datatableguid,1,1,@columnName, '{0}.' + @columnName, @specialMeasureIndex
	end else begin
		insert into dbo.ScoreMeasure (FriendlyName,DataTableGUID,IsReadFromDB,IsWrittenToDB,SQLColumnName,  SpecialMeasureIndex)
		select @columnName, @datatableguid,1,1,@columnName, @specialMeasureIndex
	end
end else if @cnt = 1 begin
	select @cnt = COUNT(*) from dbo.ScoreMeasure sm where sm.DataTableGUID = @dataTableGUID and SQLColumnName = @columnName and SpecialMeasureIndex = @specialMeasureIndex
	if @cnt = 0 begin
		--special measure index is wrong
		if @isDebug = 1 begin
			print 'Index not set correctly for ' + @columnname
		end else begin
			update dbo.ScoreMeasure set SpecialMeasureIndex = @specialMeasureIndex where DataTableGUID = @dataTableGUID and SQLColumnName = @columnName
		end	
	end
end
GO


---------------------------------------------

-- dbo.procEnsureUserAppModeAccessLink
CREATE proc procEnsureUserAppModeAccessLink (
	@UserGUID uniqueidentifier,
	@AccessLevel tinyint = 1
)
AS
BEGIN
if ((select COUNT(*) from UserProfileAppModeAccessLink where UserGUID = @UserGUID and AccessLevel = @AccessLevel) = 0)
	insert into UserProfileAppModeAccessLink (UserGUID, AccessLevel) VALUES (@UserGUID, @AccessLevel); 
END
GO


---------------------------------------------

-- dbo.procEnsureUserAppModeAccessLinkAllUsers
create procedure procEnsureUserAppModeAccessLinkAllUsers
AS
BEGIN

declare crsCursor CURSOR FAST_FORWARD FOR
	select UserGUID from UserProfile
	
open crsCursor;

DECLARE @guid uniqueidentifier

FETCH NEXT FROM crsCursor into @guid
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		
		exec procEnsureUserAppModeAccessLink @guid;		
		FETCH NEXT FROM crsCursor into @guid
	END
close crsCursor;
DEALLOCATE crsCursor;

END
GO


---------------------------------------------

-- dbo.procErrorPrint
-- Create procedure to retrieve error information.
create PROCEDURE procErrorPrint
AS
print '
ERRORNUMBER: ' + cast(ERROR_NUMBER() as varchar(max)) + '
ERROR_SEVERITY: ' + cast(ERROR_SEVERITY() as varchar(max)) + '
ERROR_STATE: ' + cast(ERROR_STATE() as varchar(max)) + '
ERROR_PROCEDURE: ' + cast(ERROR_PROCEDURE() as varchar(max)) + '
ERROR_LINE: ' + cast(ERROR_LINE() as varchar(max)) + '
ERROR_MESSAGE: ' + cast(ERROR_MESSAGE() as varchar(max))
GO


---------------------------------------------

-- dbo.procEventUpdate
CREATE proc procEventUpdate
	@eventname varchar(64)
as

insert into Event (EventName) 
select @eventname where not @eventname in (select eventname from Event)

if @@ROWCOUNT = 0 begin
	update 
		Event
	set 
		EventName = EventName
	where
		EventName = @eventname
end
GO


---------------------------------------------

-- dbo.procExpansionDeleteInvalidMemberSelections
CREATE PROC procExpansionDeleteInvalidMemberSelections AS 
DELETE xmem FROM
	EMFModelTemplateExpansion Ex
	INNER JOIN EMFModelTemplateExpansionLabel lab ON ex.EXPANSIONGUID = lab.EXPANSIONGUID
	INNER JOIN EMFEntityExpansionMember xmem ON xmem.EXPANSIONGUID = ex.EXPANSIONGUID
	INNER JOIN SecureListMember mem ON xmem.DIMENSIONMEMBERGUID = mem.listmemberguid
WHERE
	ex.DIMENSIONLEVEL <> mem.OUTLINELEVEL
GO


---------------------------------------------

-- dbo.procFE2UpdateFormFieldSection
CREATE PROCEDURE [dbo].[procFE2UpdateFormFieldSection](
	@FormFieldGUID As UNIQUEIDENTIFIER,
	@FormSectionGUID As UNIQUEIDENTIFIER,
	@IgnoreColumn As BIT
)
AS
BEGIN
  DECLARE
    @Row INT,
	@Col INT

  SELECT @Row=MAX(Row)
  FROM [dbo].[FE2FormField]
  WHERE FormSectionGUID = @FormSectionGUID
  
  IF @Row IS NULL
  BEGIN
    SET @Row = 0
    SET @Col = 0
  END
  ELSE IF (@IgnoreColumn = 1 OR EXISTS (SELECT 1 FROM [dbo].[FE2FormField] WHERE FormSectionGUID = @FormSectionGUID and Row=@Row and Col=1))
  BEGIN
    SET @Row += 1
    SET @Col = 0
  END
  ELSE BEGIN
    SET @Col = 1
  END

  UPDATE [dbo].[FE2FormField]
  SET Col=@Col, Row=@Row, FormSectionGUID=@FormSectionGUID
  WHERE FormFieldGUID=@FormFieldGUID AND FormSectionGUID != @FormSectionGUID

END
GO


---------------------------------------------

-- dbo.procFindPerformanceFlaws
CREATE PROCEDURE [dbo].[procFindPerformanceFlaws]
	@SchemaName NVARCHAR(10) = '', -- Provide the schema you wish to check
	@SpecificObj NVARCHAR(1000) = '' -- If you are looking for a specific object, specify it here, otherwise the entire schema will be checked
AS
BEGIN

	/*
	Script Owner: Mike Y.

	Script Notes:
	 - This is not a performant script, so ignore the amount of cursors, can always tweak it later
	 - There are false positives, will work on trying to narrow that down as we use this
	 - Will add more checks as time goes on.
	 
	Left to do:
	 - Use Search Arguments  ( will look /search for table scan at SQL level in Perf Env as a first step)
	 - Avoid using table variables, cursors or function calls that evaluate each row in where clause
	 
	Change Log:
	  07/12/2019 - Added table level checks
	*/

	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb.dbo.#objects') IS NOT NULL
	    DROP TABLE #objects
		
	IF OBJECT_ID('tempdb.dbo.#Results') IS NOT NULL
	    DROP TABLE #Results
		
	CREATE TABLE #Results (
		Name NVARCHAR(MAX),
		ObjectType NVARCHAR(MAX),
		Severity SMALLINT,
		Category NVARCHAR(MAX),
		Description NVARCHAR(MAX)
	)			
				
	SELECT * 
	INTO #objects
	FROM [sys].[objects] 
	WHERE type IN ('U', 'P', 'V') -- https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-objects-transact-sql?view=sql-server-2017
		AND schema_id = SCHEMA_ID(@SchemaName)
		AND (@SpecificObj = '' OR object_id = OBJECT_ID(@SchemaName + '.' + @SpecificObj))

	IF ((SELECT COUNT(*) FROM #objects) = 0)
	BEGIN
		SELECT @SchemaName + '.' + @SpecificObj + ' was not found in this database' AS Error
		RETURN;
	END

	-- Use table compression if it will grow over 1,000 rows
	CREATE TABLE #FactPageCompression (
		Name NVARCHAR(MAX),
		ObjectType NVARCHAR(MAX)
	)

	-- Loop through any procs
	DECLARE @ObjectId INT,
			@SchemaId INT,
			@Type NVARCHAR(MAX)
	
	DECLARE crsObjs CURSOR FAST_FORWARD FOR SELECT Object_Id, Schema_Id, Type_Desc FROM #objects WHERE Type != 'U' 
	OPEN crsObjs
	FETCH NEXT FROM crsObjs INTO @ObjectId, @SchemaId, @Type
	DECLARE @sql NVARCHAR(MAX)
	WHILE (@@fetch_status = 0) 
	BEGIN
		SELECT @sql = OBJECT_DEFINITION(@ObjectId)
		
		INSERT INTO #Results (Name, ObjectType, Category, Description, Severity)
		SELECT SCHEMA_NAME(@SchemaId) + '.' + OBJECT_NAME(@ObjectId), @Type, Category, Description, Severity FROM [dbo].[funcFindTSQLPerformanceFlaws](@sql);
			
		FETCH next FROM crsObjs INTO @ObjectId, @SchemaId, @Type
		
	END
	CLOSE crsObjs
	DEALLOCATE crsObjs

	DECLARE @TableName NVARCHAR(MAX);

	-- Table Checks 
	DECLARE crsTbls cURSOR FAST_FORWARD FOR SELECT Object_Id, Schema_Id, Type_Desc FROM #objects WHERE Type = 'U' 
	OPEN crsTbls
	FETCH NEXT FROM crsTbls INTO @ObjectId, @SchemaId, @Type
	WHILE (@@fetch_status = 0) 
	BEGIN
		SELECT @sql = OBJECT_DEFINITION(@ObjectId)
			
		IF (OBJECT_NAME(@ObjectId) LIKE ('%Fact%'))
		BEGIN
		
			IF NOT EXISTS(SELECT 1 FROM sys.partitions SP LEFT OUTER JOIN sys.indexes IX ON sp.object_id = ix.object_id and sp.index_id = ix.index_id
				WHERE sp.data_compression > 0 AND sp.object_id = @ObjectId)
			BEGIN
				INSERT INTO #FactPageCompression (Name, ObjectType) VALUES (SCHEMA_NAME(@SchemaId) + '.' + OBJECT_NAME(@ObjectId), @Type)
			END
			
		END			
		
		FETCH next FROM crsTbls INTO @ObjectId, @SchemaId, @Type
	END
	CLOSE crsTbls
	DEALLOCATE crsTbls

	-- Check for tables that need page compression
	SELECT
	      SCHEMA_NAME(sOBJ.Schema_Id) + '.' + sOBJ.name AS [Name], 
		  sOBJ.Type_Desc AS ObjectType,
		  'Table Compression' AS Category,
		  'Use Page Compression on all Tables containing over 1000 rows' AS Description
	INTO #TablesNeedingPageCompression
	FROM 
	      #objects AS sOBJ
	      INNER JOIN sys.partitions AS sPTN ON sOBJ.object_id = sPTN.object_id
	WHERE
	      sOBJ.type = 'U'
		  AND sPTN.Rows >= 1000
		  AND sPTN.data_compression = 0
		  AND SCHEMA_NAME(sOBJ.schema_id) = @SchemaName
	ORDER BY [Name]

	-- Clustered Index needed
	SELECT SCHEMA_NAME(o.Schema_Id) + '.' + o.name AS [Name], 
		o.Type_Desc AS ObjectType,
		'Clustered Index' AS Category, 
		'This table does not have a clustered index, verify if this needs a clustered index or not. This helps JOINs, WHERE operations and Order/Group By clauses' AS Description
	INTO #ClusterIndex
	FROM sys.indexes i
		INNER JOIN #objects o ON  i.object_id = o.object_id
	WHERE o.type_desc = 'USER_TABLE'
		AND i.type_desc = 'HEAP' -- determine which tables in our database are a 'heap', meaning they do not have a clustered index. https://www.mssqltips.com/sqlservertip/2510/sql-server-tables-without-a-clustered-index/
		AND SCHEMA_NAME(o.schema_id) = @SchemaName
		AND OBJECT_NAME(o.Object_ID) NOT LIKE ('%Fact%')
	ORDER BY o.name

	-- Check column size
	SELECT SCHEMA_NAME(o.Schema_Id) + '.' + TABLE_NAME as Name,
		o.Type_Desc AS ObjectType,
		'Column Size' AS Category,
		'Keep the columns short (data size), verify that the columns truly need to be MAX' AS Description
	INTO #ColumnSize
	FROM INFORMATION_SCHEMA.COLUMNS i
		INNER JOIN #objects o ON  i.TABLE_NAME = OBJECT_NAME(o.object_id)
	WHERE TABLE_SCHEMA = @SchemaName AND CHARACTER_MAXIMUM_LENGTH = -1

	-- Populate results tables
	
	-- Severity
	-- 3 - High
	-- 2 - Medium
	-- 1 - Low
	
	IF ((SELECT COUNT(*) FROM #FactPageCompression) > 0)
	BEGIN
		INSERT INTO #Results (Name, ObjectType, Category, Description, Severity)
		SELECT Name, ObjectType, 'Table Compression' AS Category, 'Use Page Compression on all Fact Tables' AS Description, 3 AS Severity FROM #FactPageCompression
	END
	
	IF ((SELECT COUNT(*) FROM #TablesNeedingPageCompression) > 0)
	BEGIN		
		INSERT INTO #Results (Name, ObjectType, Category, Description, Severity)
		SELECT Name, ObjectType, Category, Description, 2 AS Severity FROM #TablesNeedingPageCompression
	END
	
	IF ((SELECT COUNT(*) FROM #ClusterIndex) > 0)
	BEGIN
		INSERT INTO #Results (Name, ObjectType, Category, Description, Severity)
		SELECT Name, ObjectType, Category, Description, 3 AS Severity FROM #ClusterIndex
	END
	
	IF ((SELECT COUNT(*) FROM #ColumnSize) > 0)
	BEGIN
		INSERT INTO #Results (Name, ObjectType, Category, Description, Severity)
		SELECT Name, ObjectType, Category, Description, 1 AS Severity FROM #ColumnSize
	END
	
	SELECT Name, CASE WHEN Severity = 3 THEN 'High'
					  WHEN Severity = 2 THEN 'Medium'
					  WHEN Severity = 1 THEN 'Low' ELSE 'N/A' END AS Severity, 
		   ObjectType, Category, Description 
	FROM #Results 
	ORDER BY Name, Category, ObjectType
	
END
GO


---------------------------------------------

-- dbo.procFixSelfModelLinks
CREATE proc [dbo].[procFixSelfModelLinks]
	@modelguid uniqueidentifier
as

set nocount on

--delete those for wrong tempaltes or dead plans
delete 
	emfmodeldatalink 
from 
	emfmodeldatalink
where
	not exists
	(	select 1 
		from
			xplan p
			left join emfmodeltemplatelinksource ls on p.modeltemplateguid = ls.modeltemplateguid 
		where
			emfmodeldatalink.modelguid = p.planguid
			and emfmodeldatalink.linksourceguid = ls.linksourceguid
			and p.planguid = @modelguid
	)
	and modelguid = @modelguid

	
--plan other than self for one marked self
update
	emfmodeldatalink
set
	parentmodelguid = modelguid
where
	parentmodelguid <> modelguid
	and linksourceguid in (select linksourceguid from emfmodeltemplatelinksource where isself = 1)
	and modelguid = @modelguid
	
--missing for correct template
insert into emfmodeldatalink (linksourceguid, modelguid, parentmodelguid)
select 
	ls.linksourceguid, p.planguid, p.planguid
from 
	xplan p
	inner join emfmodeltemplatelinksource ls on p.modeltemplateguid = ls.modeltemplateguid and ls.isself = 1
where
	not exists(
		select 1
		from
			emfmodeldatalink mdl
		where
			mdl.modelguid = p.planguid
			and mdl.linksourceguid = ls.linksourceguid
	)
	and p.planguid = @modelguid
GO


---------------------------------------------

-- dbo.procFixSelfModelLinksAll
create proc [dbo].[procFixSelfModelLinksAll]
	@debug bit = 0
as

if @debug = 0
	set nocount on

--delete those for wrong tempaltes or dead plans
delete 
	emfmodeldatalink 
from 
	emfmodeldatalink
where
	not exists
	(	select 1 
		from
			xplan p
			left join emfmodeltemplatelinksource ls on p.modeltemplateguid = ls.modeltemplateguid 
		where
			emfmodeldatalink.modelguid = p.planguid
			and emfmodeldatalink.linksourceguid = ls.linksourceguid
	)

	
--plan other than self for one marked self
update
	emfmodeldatalink
set
	parentmodelguid = modelguid
where
	parentmodelguid <> modelguid
	and linksourceguid in (select linksourceguid from emfmodeltemplatelinksource where isself = 1)
	
--missing for correct template
insert into emfmodeldatalink (linksourceguid, modelguid, parentmodelguid)
select 
	ls.linksourceguid, p.planguid, p.planguid
from 
	xplan p
	inner join emfmodeltemplate mt on p.modeltemplateguid = mt.modeltemplateguid
	inner join emfmodeltemplatelinksource ls on mt.modeltemplateguid = ls.modeltemplateguid and ls.isself = 1
	left join emfmodeldatalink mdl on mdl.linksourceguid = ls.linksourceguid and mdl.modelguid = p.planguid 
where
	mdl.modelguid is null
GO


---------------------------------------------

-- dbo.procFixSelfModelLinksAllIncludingNonSelf
create proc [dbo].[procFixSelfModelLinksAllIncludingNonSelf]
	@debug bit = 0
as

if @debug = 0
	set nocount on

--delete those for wrong tempaltes or dead plans
delete 
	emfmodeldatalink 
from 
	emfmodeldatalink
where
	not exists
	(	select 1 
		from
			xplan p
			left join emfmodeltemplatelinksource ls on p.modeltemplateguid = ls.modeltemplateguid 
		where
			emfmodeldatalink.modelguid = p.planguid
			and emfmodeldatalink.linksourceguid = ls.linksourceguid
	)

	
--plan other than self for one marked self
update
	emfmodeldatalink
set
	parentmodelguid = modelguid
where
	parentmodelguid <> modelguid
	and linksourceguid in (select linksourceguid from emfmodeltemplatelinksource )
	
--missing for correct template
insert into emfmodeldatalink (linksourceguid, modelguid, parentmodelguid)
select 
	ls.linksourceguid, p.planguid, p.planguid
from 
	xplan p
	inner join emfmodeltemplate mt on p.modeltemplateguid = mt.modeltemplateguid
	inner join emfmodeltemplatelinksource ls on mt.modeltemplateguid = ls.modeltemplateguid
	left join emfmodeldatalink mdl on mdl.linksourceguid = ls.linksourceguid and mdl.modelguid = p.planguid 
where
	mdl.modelguid is null
GO


---------------------------------------------

-- dbo.procFixZZTables
CREATE PROCEDURE [dbo].[procFixZZTables]
	@DebugMode bit = 0
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @zzMDCGUID uniqueidentifier
	DECLARE @mdcName nvarchar(max)
	DECLARE @zzMDCtablename nvarchar(36)
--	DECLARE @zzDIMcursor nvarchar(256)
--	DECLARE @zzDIMcolumnname nvarchar(256)
	DECLARE @modelTemplateMappingTableName nvarchar(256)
	DECLARE @modelDataTableName nvarchar(256)
--	DECLARE @dimensionName as nvarchar(256)
--	DECLARE @dimensionGUID as uniqueidentifier
--	DECLARE @fixSQL as nvarchar(max)

	DECLARE zztable CURSOR LOCAL FAST_FORWARD
		FOR SELECT NAME, MODELDATACONFIGGUID FROM EMFMODELDATACONFIG
	OPEN zztable
	FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID
	WHILE @@FETCH_STATUS = 0
	BEGIN


		--SET @zztable_query = 'ALTER TABLE ' + @zztable_name + ' ADD [MAPPINGTYPE] int NOT NULL Default(0) WITH VALUES'
		--EXECUTE sp_executesql @zztable_query
		SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_')

		SET @modelTemplateMappingTableName = 'zzEMFModelTemplateMapping_' + @zzMDCtablename
		if (select count(*) from sysobjects where xtype='u' and name like @modelTemplateMappingTableName) = 0
			PRINT @modelTemplateMappingTableName + ' table is not present'
		else begin
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'MODELTEMPLATEGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'CELLGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'SOURCEGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureDimensionColumnsInTable 'dbo', @modelTemplateMappingTableName, @zzMDCGUID, @DebugMode, 1
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'MEASUREGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'WORKSHEETGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'ROW', 'int', '0', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'COL', 'int', '0', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'ISREADONLY', 'bit', '0', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'IsLocked', 'bit', '0', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'IsReadFromDB', 'bit', '1', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'IsWrittenToDB', 'bit', '1', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'IsUserMapped', 'bit', '1', @DebugMode
			exec procEnsureColumnInTableCopyFromOther 'dbo', @modelTemplateMappingTableName ,'RowDesigner', 'int', '0', 'Row', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'AssumptionType', 'int', '0', @DebugMode
			exec procEnsureColumnNotInTable 'dbo',  @modelTemplateMappingTableName, 'riskvariabletemplateguid', @DebugMode
		end


		SET @modelDataTableName = 'zzEMFModelData_' + @zzMDCtablename
		if (select count(*) from sysobjects where xtype='u' and name like @modelDataTableName) = 0
			PRINT @modelDataTableName + ' table is not present'
		else begin
			--exec procEnsureColumnInTable @modelDataTableName ,'MODELGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureDimensionColumnsInTable 'dbo',  @modelDataTableName, @zzMDCGUID, @DebugMode, 0
			exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'MEASUREGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'VALUE', 'float', '0', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'FORMULA', 'varchar(1024)', '''''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'STRINGVALUE', 'varchar(1024)', '''''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'HISTORYITEMGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'SUBTABLEROWGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'DATAROWGUID', 'uniqueidentifier', 'newid()', @DebugMode
			exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'ISACTIVE', 'bit', '1', @DebugMode
			exec procEnsureColumnNotInTable 'dbo', @modelDataTableName, 'riskvariableguid', @DebugMode

		end
		

--		DECLARE zzdimensions CURSOR LOCAL FAST_FORWARD
--		FOR SELECT SLM.LISTGUID, SLM.NAME, UPPER('G' + REPLACE(cast(SLM.LISTGUID as varchar(36)),'-','_')) FROM dbo.EMFModelDataConfigDimensionLink MDCDL JOIN SECURELIST SLM ON MDCDL.DIMENSIONGUID=SLM.LISTGUID WHERE MDCDL.MODELDATACONFIGGUID = @zzMDCGUID
--		OPEN zzdimensions
--		FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor
--		WHILE @@FETCH_STATUS = 0
--		BEGIN
--			SET @zzDIMcolumnname = @zzDIMcursor --+ 'GUID'
--			SET @fixSQL = 'DELETE FROM emfmodeldataconfigdimensionlink WHERE DIMENSIONGUID = ''' + cast(@dimensionGUID as varchar(36)) + ''' and MODELDATACONFIGGUID = ''' + cast(@zzMDCGUID as varchar(36)) + ''''
--			IF (SELECT count(*) FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype='U' AND (sysobjects.name like @modelDataTableName or sysobjects.name like @modelMappingTableName or sysobjects.name like @modelTemplateMappingTableName)and syscolumns.name like @zzDIMcolumnname) <> 3
--				--PRINT '   ' + @zzDIMcolumnname + ' is present'
--			--ELSE
--				PRINT @fixSQL + ' --' + cast(@zzMDCGUID as varchar(36)) + ' (' + @mdcName + ') - ' + @zzDIMcolumnname + ' (' + @dimensionName + ') is not present in both ModelData and ModelMapping'
--				
--
--			FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor
--		END
--		CLOSE zzdimensions
--		DEALLOCATE zzdimensions
--			
		FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID
	END
	CLOSE zztable
	DEALLOCATE zztable

END
GO


---------------------------------------------

-- dbo.procFormDataCreateMissing
CREATE proc [dbo].[procFormDataCreateMissing]
	@plantypeguid uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@isdebug bit = 0
as
	--this proc exists for backwards compatibility only
	return
GO


---------------------------------------------

-- dbo.procFormField10Delete
CREATE PROCEDURE [dbo].[procFormField10Delete]
	@FormFieldGUID uniqueidentifier
AS
BEGIN
	if((select count(*) from FEFormField where FormFieldGUID = @FormFieldGUID) = 0) begin
		return
	end

	--remove from forms
	declare @placeholder varchar(128)
	select @placeholder = '<input class=StrataFormField value="' + Name + '" GUID="' + cast(FormFieldGUID as varchar(36)) + '" strataobj="sfec:FormFieldControl">' from FEFormField where FormFieldGUID = @FormFieldGUID
	update FEFormSection set HTMLDesign = replace(HTMLDesign, @placeholder, ''), HTML = replace(HTML, @placeholder, '') where HTMLDesign like '%' + @placeholder + '%'
	
	--remove data
	delete from FEFormData where FormFieldGUID = @FormFieldGUID

	--remove form field mappings
	delete from EMFModelTemplateFormFieldMapping where FormFieldGUID = @FormFieldGUID

	--remove custom script
	delete from CustomScript where CustomScriptGUID=(select sourceguid from FEFormField where FormFieldGUID = @FormFieldGUID)
	
	--remove gridsettings
	delete from GridSetting where ColumnID='G' + replace(cast(@FormFieldGUID as varchar(36)), '-', '_')
	
	--remove field
	delete from FEFormField where FormFieldGUID = @FormFieldGUID
END
GO


---------------------------------------------

-- dbo.procFormFieldCalculationActionTask
CREATE PROC [dbo].[procFormFieldCalculationActionTask]
	@isDebugOnly bit = 0
AS
	SET NOCOUNT ON

	DECLARE @sql varchar(max);

	SET @sql = '
	DECLARE @statusCode INT;
	SET @statusCode = 0;
	EXEC [dbo].[procCreateTask]
	            @taskTypeName = ''Strata.CS.Jazz.Biz.FormEngine20.ComputedFields.ComputedFieldControllerTask, Strata.CS.Jazz.Biz'',
				@contextXML = ''<CONTEXTXML><ISREADFROMDATABASEQUEUE>1</ISREADFROMDATABASEQUEUE><SOURCE>procFormFieldCalculationActionTask</SOURCE></CONTEXTXML>'',
				@taskSource = ''procFormFieldCalculationActionTask'',
			    @statusCode = @statusCode OUTPUT;
	IF @statusCode < 200 OR @statusCode > 299
	BEGIN
		RAISERROR(''Failed to insert to Hangfire'',16,1);
	END;
	';

	IF (@isDebugOnly = 0) BEGIN
		EXEC (@sql)
	END ELSE BEGIN
		PRINT @sql
	END
GO


---------------------------------------------

-- dbo.procFormFieldCalculationRefresh
CREATE PROCEDURE [dbo].[procFormFieldCalculationRefresh]
	@formfieldguid uniqueidentifier,
	@entityexpression nvarchar(max) = '',
	@directoryrefresh bit = 0,
	@refreshmodefilter int = 0
AS
	--for backwards compatibility, refresh all fields tied to this formfieldguid
	declare @allfields nvarchar(max)
	select @allfields = dbo.StrAggr(cast(FormFieldGUID as nvarchar(36)), ',', '') from [dbo].[FE2FormField] (readuncommitted) where FormFieldGUID = @formfieldguid or OldFormFieldGUID = @formfieldguid
	
	if(len(@allfields) > 0) begin
		insert into [dbo].[FE2FormFieldRefreshRequest] (FormFieldGUIDCSV, PlanLookupSQL) values(@allfields, @entityexpression)
		exec procFormFieldCalculationActionTask
	end
GO


---------------------------------------------

-- dbo.procFormFieldCalculationRefreshAll
CREATE PROCEDURE [dbo].[procFormFieldCalculationRefreshAll]
	@plantypeguid uniqueidentifier
AS
	insert into [dbo].[FE2FormFieldRefreshRequest] (PlanTypeGUID) values(@plantypeguid)
	exec procFormFieldCalculationActionTask
GO


---------------------------------------------

-- dbo.procFormFieldCalculationRefreshAllByEntity
CREATE PROCEDURE [dbo].[procFormFieldCalculationRefreshAllByEntity]
	@entityexpression nvarchar(max),
	@isdebug bit = 0
AS
	insert into [dbo].[FE2FormFieldRefreshRequest] (PlanLookupSQL) values(@entityexpression)
	exec procFormFieldCalculationActionTask @isdebug
GO


---------------------------------------------

-- dbo.procFormFieldCalculationRefreshByPlanType
CREATE PROCEDURE [dbo].[procFormFieldCalculationRefreshByPlanType]
	@formfieldguid uniqueidentifier,
	@plantypeguid uniqueidentifier,
	@entityexpression nvarchar(max) = '',
	@createmissing bit = 1,
	@isbulk bit = 0
AS
	insert into [dbo].[FE2FormFieldRefreshRequest] (FormFieldGUIDCSV, PlanTypeGUID, PlanLookupSQL) select cast(@formfieldguid as nvarchar(36)), @plantypeguid, @entityexpression
	exec procFormFieldCalculationActionTask
GO


---------------------------------------------

-- dbo.procFormFieldCalculationRefreshMultiple
CREATE PROCEDURE [dbo].[procFormFieldCalculationRefreshMultiple]
	@formfieldguidCSV nvarchar(max),
	@entityexpression nvarchar(max) = '',
	@directoryrefresh bit = 0,
	@refreshmodefilter int = 0
AS
	if(len(@formfieldguidCSV) > 0) begin
		insert into [dbo].[FE2FormFieldRefreshRequest] (FormFieldGUIDCSV, PlanLookupSQL) values(@formfieldguidCSV, @entityexpression)
		exec procFormFieldCalculationActionTask	
	end
GO


---------------------------------------------

-- dbo.procFormFieldCalculationRefreshNoSync
CREATE proc [dbo].[procFormFieldCalculationRefreshNoSync]
	@planGUIDList nvarchar(max),
	@refreshMode int = 2
as
	--this procedure is obsolete given FE20, but still exists for backwards compatibility
	RETURN
GO


---------------------------------------------

-- dbo.procFormFieldCalculationRefreshNoSyncAll
CREATE proc [dbo].[procFormFieldCalculationRefreshNoSyncAll]
	@planTypeGUID uniqueidentifier,
	@refreshMode int = 2
as
	--this procedure is obsolete given FE20, but still exists for backwards compatibility
	RETURN
GO


---------------------------------------------

-- dbo.procFormFieldCalculationTest
create proc dbo.procFormFieldCalculationTest
	@formfieldguid uniqueidentifier
as
	declare @refreshsql nvarchar(max)
	select @refreshsql = LastRefreshSQL from [dbo].[viewFE2FormFieldComputed] where FormFieldGUID = @formfieldguid
	
	if (@refreshsql is null) begin
		print 'Field not found.'
		return
	end
	
	if (len(ltrim(rtrim(@refreshsql))) = 0) begin
		print 'Refresh SQL not found.  Please go to Admin Tools and refresh this field with test mode enabled, and then try again.'
		return
	end
	
	print @refreshsql
	exec(@refreshsql)
GO


---------------------------------------------

-- dbo.procFormHTMLPrint
create procedure procFormHTMLPrint
	@formdefguid uniqueidentifier
as
	declare @html nvarchar(max)
	declare crsSections cursor for select html from feformsection where formdefguid=@formdefguid order by parentformsectionguid, displayorder
	open crsSections
	fetch next from crsSections into @html
	while(@@fetch_status = 0) begin
		print @html
		fetch next from crsSections into @html
	end
	close crsSections
	deallocate crsSections
GO


---------------------------------------------

-- dbo.procGenerateDataMessages
CREATE PROCEDURE [dbo].[procGenerateDataMessages]
	@MAXMESSAGESPERTOPIC int,
	@IGNORETOPICGUID varchar(36) = ''
	
AS
BEGIN
	SET NOCOUNT ON

	declare @authorguid uniqueidentifier
	declare @emptyguid varchar(36)
	declare @nummessages int
	declare @count int
	declare @TOPICGUID uniqueidentifier

	set @emptyguid = '00000000-0000-0000-0000-000000000000'

	-- loop through all topics and create respective messages
	DECLARE crsTopics cursor LOCAL FAST_FORWARD FOR select topicguid from msgtopic
	OPEN crsTopics
	FETCH NEXT FROM crsTopics into @TOPICGUID

		WHILE (@@FETCH_STATUS = 0)
		BEGIN

			If (@IGNORETOPICGUID <> @TOPICGUID)
			BEGIN
				SET @nummessages = ROUND(@MAXMESSAGESPERTOPIC * rand(), 0)
				If (@nummessages = 0)
					BEGIN
						SET @nummessages = 1
					END

				PRINT cast(@nummessages as varchar) + ' messages created for topicguid = ' --+ cast(@TOPICGUID as varchar)
				
				SET @count = 1
				WHILE (@count <= @nummessages)
					BEGIN
						SELECT @authorguid = userguid from userprofile order by newid()
				
						INSERT INTO MSGMESSAGE(messageguid, topicguid, messagetypeguid, replytomsgguid, subject, body, authorguid, datecreated, datesent, hasattachments)
						SELECT top 1 newid(), @TOPICGUID, messagetypeguid, replytomsgguid, subject, body, @authorguid, dateadd(hour, @count * (24 - @count) * rand(), datecreated), datesent, hasattachments from msgmessage order by newid()
					
						SET @count = @count + 1
					END				

				PRINT @TOPICGUID
			END
			FETCH NEXT FROM crsTopics into @TOPICGUID
		END

	CLOSE crsTopics
	DEALLOCATE crsTopics

	SET NOCOUNT OFF
END
GO


---------------------------------------------

-- dbo.procGenerateDataTopics
CREATE PROCEDURE [dbo].[procGenerateDataTopics]
	@NUMTOPICS int,
	@COPYTOPICGUID varchar(36) = ''
	
AS
BEGIN
	SET NOCOUNT ON

	declare @authorguid uniqueidentifier
	declare @emptyguid varchar(36)

	set @emptyguid = '00000000-0000-0000-0000-000000000000'

	declare @i int
	set @i = 0
	while (@i < @NUMTOPICS) begin
		--copy an existing x number of times
		if (@COPYTOPICGUID <> '')
			BEGIN
				SELECT @COPYTOPICGUID = topicguid from msgtopic where topicguid = @COPYTOPICGUID
				if (@COPYTOPICGUID is not null)
					BEGIN
						SELECT @authorguid = userguid from userprofile order by newid()
						insert into msgtopic (topicguid, forumguid, authorguid, [name], description, topictype, datecreated) 
							select newid(), forumguid, @authorguid, 'Copy of ' + [name] + cast(@i as varchar), description, topictype, dateadd(day, @i + 1, datecreated) from msgtopic where topicguid = @COPYTOPICGUID
						
						PRINT 'Topic created'
					END
			END
		else
			BEGIN
				SELECT @authorguid = userguid from userprofile order by newid()
								
				--currently can only create private message topics
				insert into msgtopic (topicguid, forumguid, authorguid, [name], description, topictype, datecreated) values(newid(), @emptyguid, @authorguid, newid(), newid(), 2, getdate())
			END
		set @i = @i + 1
	end

	SET NOCOUNT OFF
END
GO


---------------------------------------------

-- dbo.procGetCompactedUserACL
CREATE PROCEDURE [dbo].[procGetCompactedUserACL]
	@UserGUID uniqueidentifier
AS
	IF (NOT EXISTS(SELECT 1 FROM UserProfile (readuncommitted) WHERE UserGUID = @UserGUID)) BEGIN RETURN END

	--everything user has access to
	CREATE TABLE #UserACL(LootGroupPrefix nvarchar(100), LootID nvarchar(128), IsFullAccess bit, IsReadable bit, IsWritable bit, IsSecurable bit, IsDeletable bit, IsCreatable bit)
	INSERT #UserACL 
		SELECT 
			LootGroupPrefix, 
			LootID, 
			CAST(0 as bit) as IsFullAccess,
			IsReadable, 
			IsWritable, 
			IsSecurable, 
			IsDeletable, 
			IsCreatable 
		FROM 
			dbo.ufn_GetS3ACLByUserGuid(@UserGUID) 

	--loot groups where the user has access to everything
	CREATE TABLE #FullAccess(LootGroupPrefix nvarchar(100), LootID nvarchar(128), IsFullAccess bit, IsReadable bit, IsWritable bit, IsSecurable bit, IsDeletable bit, IsCreatable bit)
	INSERT #FullAccess
		SELECT
			L.LootGroupPrefix,
			'' as LootID,
			CAST(1 as bit) as IsFullAccess,
			CAST(1 as bit) as IsReadable,
			CAST(1 as bit) as IsWritable,
			CAST(1 as bit) as IsSecurable,
			CAST(1 as bit) as IsDeletable,
			CAST(1 as bit) as IsCreatable
		FROM
			S3Loot L (readuncommitted)
		GROUP BY
			L.LootGroupPrefix
		HAVING
			(select COUNT(*) from #UserACL acl where acl.LootGroupPrefix = L.LootGroupPrefix and acl.IsReadable = 1 and acl.IsWritable = 1 and acl.IsCreatable = 1 and acl.IsDeletable = 1 and acl.IsSecurable = 1) >= COUNT(*)

	--compact acl based on full access
	DELETE FROM #UserACL where LootGroupPrefix in(select LootGroupPrefix from #FullAccess)

	--include items user has no access to
	INSERT #UserACL 
	SELECT
		L.LootGroupPrefix,
		L.LootID as LootID,
		CAST(0 as bit) as IsFullAccess,
		CAST(0 as bit) as IsReadable,
		CAST(0 as bit) as IsWritable,
		CAST(0 as bit) as IsSecurable,
		CAST(0 as bit) as IsDeletable,
		CAST(0 as bit) as IsCreatable
	FROM
		S3Loot L (readuncommitted)
	WHERE
		not exists (select 1 from #UserACL acl where acl.LootID = L.LootID)
		and not exists(select 1 from #FullAccess fa where fa.LootGroupPrefix = L.LootGroupPrefix)

	--return acl + full access groups
	SELECT * FROM #UserACL
	UNION ALL
	SELECT * FROM #FullAccess

	--clean up
	DROP TABLE #UserACL
	DROP TABLE #FullAccess
GO


---------------------------------------------

-- dbo.procGetDimensionAttributesToReportRelationInfo
CREATE proc [dbo].[procGetDimensionAttributesToReportRelationInfo]
as
	set nocount on
declare @departmentDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'Department')

declare @capProjectDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'CAP Project')
declare @fundingReleaseDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'CAP Funding Release')
declare @requisitionDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'CAP Requisition')
declare @substitutionSourceDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'CAP Substitution')

declare @longRangePlanDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'SP Long Range Plan')
declare @rollingForecastPlanDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'SP Rolling Forecast Plan')
declare @longRangeServiceLineDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'SP Long Range Service Line')
declare @rollingServiceLinePlanDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'SP Rolling Service Line Plan')

declare @departmentalBudgetDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'OB Departmental Budget')

declare @departmentMrDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'MR Department')

declare @attributeGuids table (AttributeGUID uniqueidentifier)

declare @departmentAttributeGuids table (AttributeGUID uniqueidentifier)
insert into @departmentAttributeGuids
select AttributeGUID from viewScoreAttribute where DimensionGUID = @departmentDimGuid

--department attributes
insert into @attributeGuids
select AttributeGUID from @departmentAttributeGuids

--department mr attributes
declare @departmentMrAttributeGuids table (AttributeGUID uniqueidentifier, DepartmentAttributeGUID uniqueidentifier)
insert into @departmentMrAttributeGuids
select distinct mr.AttributeGUID, d.AttributeGUID
from viewScoreAttribute mr 
join viewScoreAttribute d on d.DimensionGUID = @departmentDimGuid
	and d.SqlColumnName=mr.SqlColumnName
where mr.DimensionGUID = @departmentMrDimGuid

insert into @attributeGuids
select AttributeGUID from @departmentMrAttributeGuids

--ob departmental budget
declare @obAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @obAttributeGuids
select AttributeGUID, InferredAttributeGuid from viewScoreAttribute 
where DimensionGUID = @departmentalBudgetDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids)
insert into @attributeGuids
select AttributeGUID from @obAttributeGuids

--sp long Range Plan
declare @splongRangeAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @splongRangeAttributeGuids
select AttributeGUID, InferredAttributeGuid from viewScoreAttribute 
where DimensionGUID = @longRangePlanDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids)
insert into @attributeGuids
select AttributeGUID from @splongRangeAttributeGuids

--sp rolling Forecast Plan
declare @sprollingForecastAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @sprollingForecastAttributeGuids
select AttributeGUID, InferredAttributeGuid from viewScoreAttribute 
where DimensionGUID = @rollingForecastPlanDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids)
insert into @attributeGuids
select AttributeGUID from @sprollingForecastAttributeGuids

--sp long Range Service Line
declare @splongRangeServiceLineAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @splongRangeServiceLineAttributeGuids
select AttributeGUID, InferredAttributeGuid from viewScoreAttribute 
where DimensionGUID = @longRangeServiceLineDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids)
insert into @attributeGuids
select AttributeGUID from @splongRangeServiceLineAttributeGuids

--sp rolling Service Line Plan
declare @sprollingServiceLinePlanAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @sprollingServiceLinePlanAttributeGuids
select AttributeGUID, InferredAttributeGuid from viewScoreAttribute 
where DimensionGUID = @rollingServiceLinePlanDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids)
insert into @attributeGuids
select AttributeGUID from @sprollingServiceLinePlanAttributeGuids

--cap Project
declare @capProjectAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @capProjectAttributeGuids
select AttributeGUID, InferredAttributeGuid from viewScoreAttribute 
where DimensionGUID = @capProjectDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids)
insert into @attributeGuids
select AttributeGUID from @capProjectAttributeGuids

--cap funding Release
declare @capfundingReleaseAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @capfundingReleaseAttributeGuids
select attr.AttributeGUID, cattr.InferredAttributeGuid from viewScoreAttribute attr
join @capProjectAttributeGuids cattr on cattr.AttributeGUID = attr.InferredAttributeGuid
where DimensionGUID = @fundingReleaseDimGuid 
insert into @attributeGuids
select AttributeGUID from @capfundingReleaseAttributeGuids

--cap requisition
declare @caprequisitionAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @caprequisitionAttributeGuids
select  attr.AttributeGUID,  attr.InferredAttributeGuid from viewScoreAttribute attr
join @capProjectAttributeGuids cattr on cattr.AttributeGUID = attr.InferredAttributeGuid
where DimensionGUID = @requisitionDimGuid
insert into @attributeGuids
select AttributeGUID from @caprequisitionAttributeGuids

--cap substitution
declare @capsubstitutionAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier)
insert into @capsubstitutionAttributeGuids
select  attr.AttributeGUID,  attr.InferredAttributeGuid from viewScoreAttribute attr
join @capProjectAttributeGuids cattr on cattr.AttributeGUID = attr.InferredAttributeGuid
where DimensionGUID = @substitutionSourceDimGuid
insert into @attributeGuids
select AttributeGUID from @capsubstitutionAttributeGuids

-- Result table to return
declare @result table (AttributeGUID uniqueidentifier, ReportGUID uniqueidentifier, FrameworkID tinyint)

declare @frameworkInfo table (FrameworkID tinyint, FrameworkName nvarchar(100), ReportFrameworkPrefix nvarchar(5))
insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Capital Management'), 'Capital Management', 'CAP'
insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Operating Budgeting'), 'Operating Budgeting', 'OB'
insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Management Reporting'), 'Management Reporting', 'MR'
insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Strategic Planning'), 'Strategic Planning', 'SP'
insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Productivity Reporting'), 'Productivity Reporting', 'PR'
insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Decision Support'), 'Decision Support', 'DS'

-- Cursor configuration
declare @frameworkId tinyInt
declare @frameworkName nvarchar(100)
declare @prefix nvarchar(5)
declare crsFrameworks cursor fast_forward for
	select FrameworkID, FrameworkName, ReportFrameworkPrefix
	from @frameworkInfo

open crsFrameworks
fetch next from crsFrameworks into @frameworkId, @frameworkName, @prefix

while (@@fetch_status = 0) 
	begin
		insert into @result
		--ad hoc reports using the attribute for this framework
		select
			cast(ra.AttributeID as uniqueidentifier), r.ReportGUID, @frameworkId
		from 
			REClientReportSectionAttribute ra 
			inner join REClientReportSectionLink sl on sl.ClientReportSectionGUID = ra.ClientReportSectionGUID
			inner join REReport r on r.ReportGUID = sl.ReportGUID
			inner join REClientReportDataSourceLink rdsl on r.ReportGUID = rdsl.ReportGUID
			inner join DataView dv on rdsl.DataSourceGUID = dv.DataViewGUID
			inner join Folder f on f.FolderGUID = r.FolderGUID
			left join Folder pf on pf.FolderGUID = f.ParentFolderGUID
		where 
			ra.AttributeID in (select cast(AttributeGUID as nvarchar(36)) from @attributeGuids)
			and 
			(dv.Name like (@prefix + '%') 
				or (f.Name = @frameworkname or isnull(pf.Name, '') = @frameworkname))

		insert into @result
		--ad hoc reports using the attribute for this framework as filter
		select
			cast(ra.AttributeID as uniqueidentifier), r.ReportGUID, @frameworkId
		from 
			REClientReportParameter ra 
			inner join REReport r on r.ReportGUID = ra.ReportGUID
			inner join REClientReportDataSourceLink rdsl on r.ReportGUID = rdsl.ReportGUID
			inner join DataView dv on rdsl.DataSourceGUID = dv.DataViewGUID
			inner join Folder f on f.FolderGUID = r.FolderGUID
			left join Folder pf on pf.FolderGUID = f.ParentFolderGUID
		where 
			ra.AttributeID in (select cast(AttributeGUID as nvarchar(36)) from @attributeGuids)
			and 
			(dv.Name like (@prefix + '%') 
				or (f.Name = @frameworkname or isnull(pf.Name, '') = @frameworkname))

		insert into @result
		--tabular detail reports using the attribute for this framework
		select
			ra.AttributeGUID, r.ReportGUID, @frameworkId
		from 
			RESQLReportDisplayColumn dc
			inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = dc.SQLReportSetupGUID
			inner join REReport r on r.ReportGUID = rs.ReportGUID
			inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = rs.DataViewGUID
			inner join RESQLReportRegisteredAttribute ra on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID
			inner join dbo.ScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
			inner join DataView dv on rd.DataViewGUID = dv.DataViewGUID
			inner join Folder f on f.FolderGUID = r.FolderGUID
			left join Folder pf on pf.FolderGUID = f.ParentFolderGUID
		where 
			ltrim(rtrim(dc.ColumnName)) = case when ltrim(rtrim(ra.ColumnAlias)) = '' then a.SQLColumnName else ltrim(rtrim(ra.ColumnAlias)) end
			and ra.AttributeGUID in (select AttributeGUID from @attributeGuids)
			and (dv.Name like (@prefix + '%')
				or (f.Name = @frameworkname or isnull(pf.Name, '') = @frameworkname))

		fetch next from crsFrameworks into @frameworkId, @frameworkName, @prefix
	end
close crsFrameworks
deallocate crsFrameworks

declare @resultFinal table (AttributeGUID uniqueidentifier, ReportGUID uniqueidentifier, FrameworkID tinyint)

insert into @resultFinal
select distinct r.AttributeGUID, r.ReportGUID, r.FrameworkID 
from @result r
join @departmentAttributeGuids d on d.AttributeGUID=r.AttributeGUID

insert into @resultFinal
select distinct d.DepartmentAttributeGUID, r.ReportGUID, r.FrameworkID 
from @result r
join @departmentMrAttributeGuids d on d.AttributeGUID=r.AttributeGUID


insert into @resultFinal
select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @obAttributeGuids d on d.AttributeGUID=r.AttributeGUID

insert into @resultFinal
select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @splongRangeAttributeGuids d on d.AttributeGUID=r.AttributeGUID

insert into @resultFinal
select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @sprollingForecastAttributeGuids d on d.AttributeGUID=r.AttributeGUID

insert into @resultFinal
select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @splongRangeServiceLineAttributeGuids d on d.AttributeGUID=r.AttributeGUID

insert into @resultFinal
select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @sprollingServiceLinePlanAttributeGuids d on d.AttributeGUID=r.AttributeGUID

insert into @resultFinal
select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @capProjectAttributeGuids d on d.AttributeGUID=r.AttributeGUID

insert into @resultFinal
select distinct p.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @capfundingReleaseAttributeGuids d on r.AttributeGUID=d.AttributeGUID
join @capProjectAttributeGuids p on d.InferredAttributeGuid=p.AttributeGUID

insert into @resultFinal
select distinct p.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @caprequisitionAttributeGuids d on r.AttributeGUID=d.AttributeGUID
join @capProjectAttributeGuids p on d.InferredAttributeGuid=p.AttributeGUID

insert into @resultFinal
select distinct p.InferredAttributeGuid, r.ReportGUID, r.FrameworkID 
from @result r
join @capsubstitutionAttributeGuids d on r.AttributeGUID=d.AttributeGUID
join @capProjectAttributeGuids p on d.InferredAttributeGuid=p.AttributeGUID

select distinct r.AttributeGUID, r.ReportGUID, r.FrameworkID 
from @resultFinal r
order by AttributeGUID, FrameworkID
GO


---------------------------------------------

-- dbo.procGetInputDataByBatches
/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2022-08-17	HV		JAZZ-41822		PR Metrics Definition - Select Standard Metrics - Productive Hours, UOS Staffing, Productive Hours per UOS
** 2		2022-10-13	KF		JAZZ-44078		Charge Based Statistics Modals Performance Improvement
** 3		2023-10-10	KF		JAZZ-61890		Technical - Convert pi.FactMetric and pi.FactMetricDaily Rowid and dependent objects to bigint
************************************************************
*/
CREATE PROCEDURE [dbo].[procGetInputDataByBatches]
	@batchSize int = 10000,
	@columnName nvarchar(100),
	@tableAlias nvarchar(100),
	@fromClause nvarchar(max),
	@whereClause nvarchar(max),
	@declareParameters nvarchar(max) = '',
	@isDebug bit = 0
AS

DECLARE @columnNameWithAlias nvarchar(200)
set @columnNameWithAlias = @tableAlias + '.' + @columnName

DECLARE @sql nvarchar(max) = ''

IF @declareParameters IS NOT NULL AND @declareParameters != '' BEGIN
  SET @sql = @sql + 'DECLARE
' + @declareParameters + '
'
END

SET @sql = @sql + '
IF OBJECT_ID(''tempdb..#inputData'') IS NOT NULL DROP TABLE #inputData

SELECT ' + @columnNameWithAlias + ', COUNT_BIG(*) AS RecordsCount, 0 AS BatchID INTO #inputData
FROM ' + @fromClause

IF NOT( @whereClause  is null or @whereClause  = '')
BEGIN
	SET @sql = @sql + '
	WHERE ' + @whereclause
END

SET @sql = @sql + '
GROUP BY ' + @columnNameWithAlias + '

-- Split data into batches
WHILE EXISTS (SELECT TOP 1 1 FROM #inputData WHERE BatchID = 0)
BEGIN
	;WITH infoTable AS 
	(
		SELECT 
			IPP.' + @columnName + ',
			ROW_NUMBER() OVER (ORDER BY IPP.' + @columnName + ') AS RowNumber,
			SUM(RecordsCount) OVER (ORDER BY IPP.' + @columnName + ') AS Total,
			M.MaxBatchID+1 AS BatchID
		FROM #inputData IPP
		CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputData) M
		WHERE IPP.BatchID = 0
	)
	UPDATE IPP
	SET IPP.BatchID = MI.BatchID
	FROM #inputData IPP
	INNER JOIN infoTable MI ON MI.' + @columnName + ' = IPP.' + @columnName + '
	WHERE MI.Total <= ' + cast(@BatchSize as nvarchar(100)) + ' OR MI.RowNumber = 1
END

select * from #inputData'

IF @isDebug = 1
BEGIN
	PRINT (cast(@sql as ntext));
END
ElSE
BEGIN
	EXEC (@sql);
END
GO


---------------------------------------------

-- dbo.procGetNextQueuedTask
CREATE    PROCEDURE [dbo].[procGetNextQueuedTask]
		@MinPriority int = 0,
		@WhereClause varchar(MAX),
		@WorkerID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
 AS
DECLARE @sql varchar(MAX)

--SQL
SET @sql = 'BEGIN TRANSACTION;'
SET @sql = @sql + ' DECLARE @NEXTQUEUEDTASKGUID uniqueidentifier; '
SET @sql = @sql + 'SELECT TOP 1 @NEXTQUEUEDTASKGUID = t.TaskGUID FROM TETASK t WITH (updlock, rowlock, readpast) left join TEDISABLEDDATABASE ddb  on t.dbconnectionguid = ddb.disableddbconnectionguid  where ddb.disableddbconnectionguid is null and t.status <> 1 and t.status <> 4 and GETDATE() > t.NextRunTime'

IF (@WhereClause <> '') BEGIN
	SET @sql = @sql + ' and ' + @WhereClause
END
SET @sql = @sql + ' and priority >= ' + cast(@MinPriority as varchar);
--Grouping
set @sql = @sql + ' and not exists ( select 1 from TETask T0 where T0.GroupingID <> '''' and T0.GroupingID = t.GroupingID and T0.GroupingIndex < t.GroupingIndex)';
set @sql = @sql + ' order by t.priority DESC, t.creationtime;'
SET @sql = @sql + ' UPDATE TETASK WITH (updlock, rowlock, readpast) SET STATUS=1, STARTTIME = getDate(), WorkerID=''' + cast(@WorkerID as varchar(36)) + ''' where TaskGUID = @NEXTQUEUEDTASKGUID;'
SET @sql = @sql + ' SELECT * FROM TETASK WITH (updlock, rowlock, readpast) where TaskGUID = @NextQUEUEDTASKGUID;'
SET @sql = @sql + ' COMMIT TRANSACTION;'
print @sql;
exec (@sql)
GO


---------------------------------------------

-- dbo.procGetNextQueuedTaskByPriority
CREATE    PROCEDURE [dbo].[procGetNextQueuedTaskByPriority]
@Priority int
 AS

DECLARE @TEMPTABLENAME varchar(38)
DECLARE @sql varchar(MAX)

SET @TEMPTABLENAME = '#' + dbo.GetSQLColumnSafeGuid(newid())

--insert next queued item (all non-executing tasks) into temp table
SET @sql = 'BEGIN TRAN; SELECT TOP 1 t.* INTO ' + @TEMPTABLENAME + ' FROM TETASK t left join TEDISABLEDDATABASE ddb on t.dbconnectionguid = ddb.disableddbconnectionguid where ddb.disableddbconnectionguid is null and status <> 1 and priority < ' + cast(@Priority as varchar) + ' order by priority, creationtime;'

-- if one task was entered into temp table, then
--		find taskguid from temp table and update real table with new status
--		return temp table
--		drop temp table
SET @sql = @sql + ' IF (SELECT COUNT(*) FROM ' + @TEMPTABLENAME + ') > 0 BEGIN '
SET @sql = @sql + '     DECLARE @NEXTQUEUEDTASKGUID uniqueidentifier;'
SET @sql = @sql + '     SELECT @NEXTQUEUEDTASKGUID = TASKGUID FROM ' + @TEMPTABLENAME + ';'
SET @sql = @sql + '     UPDATE TETASK SET STATUS = 1, STARTTIME = getdate() WHERE TASKGUID = @NEXTQUEUEDTASKGUID; '
SET @sql = @sql + '     SELECT * FROM ' + @TEMPTABLENAME + ';'
SET @sql = @sql + ' END'
SET @sql = @sql + ' DROP TABLE ' + @TEMPTABLENAME + ';'
SET @sql = @sql + ' COMMIT TRAN; '

exec (@sql)
GO


---------------------------------------------

-- dbo.procGetQueuedTaskCount
CREATE PROCEDURE [dbo].[procGetQueuedTaskCount]		
		@WhereClause varchar(4000)
 AS
 
DECLARE @sql varchar(MAX)
SET @sql = ' select count(*) from TETask t with (updlock, rowlock, readpast) where ' + @WhereClause + ' and Status=0 and GetDate() > t.NextRunTime;'
exec(@sql);
GO


---------------------------------------------

-- dbo.procGetRelatedPlans
CREATE   PROCEDURE procGetRelatedPlans
	@PlanGUID UNIQUEIDENTIFIER
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @keyAttributeGUID UNIQUEIDENTIFIER
	DECLARE @keyColumnExpression NVARCHAR(MAX)
	DECLARE @keyTableExpression NVARCHAR(MAX)

	SELECT TOP 1
		@keyAttributeGUID = sa.AttributeGUID,
		@keyColumnExpression = sa.SQLColumnName,
		@keyTableExpression = dbo.GetSQLTableExpression(dg.SchemaName, dg.ObjectName)
	FROM XPlan p
	JOIN PlanType pt ON pt.PlanTypeGUID = p.PlanTypeGUID
	JOIN ScoreDimension d ON d.DimensionGUID = pt.DimensionGUID
	JOIN ScoreDimensionGroup dg ON dg.DimensionGUID = d.DimensionGUID
	JOIN ScoreAttribute sa ON sa.DimensionGroupGUID = dg.DimensionGroupGUID AND sa.AttributeGUID = d.DefaultKeyGUID
	WHERE p.PlanGUID = @PlanGUID

	DECLARE @planId NVARCHAR(MAX)
	DECLARE @getIdSql NVARCHAR(MAX) =
		'SELECT @planId = ' + @keyColumnExpression + ' FROM ' + @keyTableExpression + ' ' +
		'WHERE MemberGUID = ''' + CAST(@PlanGUID AS NVARCHAR(36)) + ''''

	EXEC sp_executesql @getIdSql, N'@planId NVARCHAR(MAX) OUTPUT', @planId = @planId OUTPUT

	DROP TABLE IF EXISTS #child_plan_queries

	SELECT
		NEWID() AS QueryGUID,
		dbo.GetSQLTableExpression(dg.SchemaName, dg.ObjectName) AS TableExpression,
		sa.SQLColumnName AS ColumnExpression
	INTO #child_plan_queries
	FROM PlanType pt
	JOIN ScoreDimension d ON d.DimensionGUID = pt.DimensionGUID
	JOIN ScoreDimensionGroup dg ON dg.DimensionGUID = d.DimensionGUID
	JOIN ScoreAttribute sa ON sa.DimensionGroupGUID = dg.DimensionGroupGUID
	WHERE sa.ForeignKeyGUID = @keyAttributeGUID

	DECLARE @sql NVARCHAR(MAX) = ''

	WHILE (SELECT COUNT(1) FROM #child_plan_queries) > 0
	BEGIN
		DECLARE @queryGUID UNIQUEIDENTIFIER
		DECLARE @tableExpression NVARCHAR(MAX) = ''
		DECLARE @columnExpression NVARCHAR(MAX) = ''
		DECLARE @childMemberGUID UNIQUEIDENTIFIER = dbo.GetZeroGUID()

		SELECT TOP 1 
			@queryGUID = QueryGUID,
			@tableExpression = TableExpression,
			@columnExpression = ColumnExpression
		FROM #child_plan_queries
		ORDER BY TableExpression, ColumnExpression

		DELETE #child_plan_queries WHERE QueryGUID = @queryGUID

		SET @sql = @sql +
			'SELECT MemberGUID AS PlanGUID ' +
			'FROM ' + @tableExpression + ' ' +
			'WHERE ' + @columnExpression + ' = ' + @planId + ' ' +
			'UNION ALL '
	END

	SET @sql = TRIM('UNION ALL ' FROM @sql)
	EXEC sp_executesql @sql
END
GO


---------------------------------------------

-- dbo.procGetScoreDimensionMember
CREATE proc [dbo].[procGetScoreDimensionMember]
	@MemberGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
AS

declare @out table 
	(
		MemberGUID uniqueidentifier,
		DefaultAttribute nvarchar(max),
		AttributeValue nvarchar(max),
		DimensionGUID uniqueidentifier,
		DimensionName nvarchar(max),
		DimensionTable nvarchar(max)
	)
	
declare @DimensionGUID uniqueidentifier
declare @DimensionName nvarchar(max)
declare @TableExpression nvarchar(max)
declare @DefaultAttributeFriendlyName nvarchar(max)
declare @DefaultAttributeColumnExpression nvarchar(max)

declare dimtables cursor local fast_forward for
select
	SD.DimensionGUID,
	SD.FriendlyName,
	SD.SqlSchemaName + '.' + SD.SQLObjectName,
	SA.FriendlyName,
	SA.sqlcolumnname
from ScoreDimension SD
	inner join ScoreAttribute SA on SA.AttributeGUID = SD.defaultlookupkeyguid

open dimtables
	fetch next from dimtables into @DimensionGUID, @DimensionName, @TableExpression, @DefaultAttributeFriendlyName, @DefaultAttributeColumnExpression
	while @@fetch_status = 0
		begin
		
		declare @wc nvarchar(max)
		set @wc = ''
		if @MemberGUID <> '00000000-0000-0000-0000-000000000000'
			set @wc = ' where MemberGUID = ''' + cast(@MemberGUID as nvarchar(max)) + ''''
		
		declare @sql nvarchar(max)
		set @sql = 'select MemberGUID, ''' + @DefaultAttributeFriendlyName + ''' as DefaultAttribute, ' + @DefaultAttributeColumnExpression + ' as AttributeValue, ''' + cast(@DimensionGUID as nvarchar(max)) + ''', ''' + @DimensionName + ''' as DimensionName, ''' + @TableExpression + ''' as DimensionTable from ' + @TableExpression + @wc
		
		insert into @out
		(MemberGUID, DefaultAttribute, AttributeValue,DimensionGUID, DimensionName, DimensionTable)
		exec sp_executesql @sql
		
		fetch next from dimtables into @DimensionGUID, @DimensionName, @TableExpression, @DefaultAttributeFriendlyName, @DefaultAttributeColumnExpression
		end
close dimtables
deallocate dimtables

select * from @out
GO


---------------------------------------------

-- dbo.procGetSecuredMemberCount
CREATE PROCEDURE [dbo].[procGetSecuredMemberCount]
	@LootGroupPrefix nvarchar(100) = ''
AS
	IF (@LootGroupPrefix = '')
		BEGIN
			SELECT
				COUNT(*)
			FROM
				S3Loot
			WHERE
				LootID NOT LIKE '%|%'
		END
	ELSE
		BEGIN
			SELECT
				COUNT(*)
			FROM
				S3Loot
			WHERE
				LootID LIKE @LootGroupPrefix + '|%'		
		END
GO


---------------------------------------------

-- dbo.procGetSecurityDeniedMembersList
CREATE PROCEDURE [dbo].[procGetSecurityDeniedMembersList] 
				-- Add the parameters for the stored procedure here
				@ListGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', 
				@UserGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
			AS
			BEGIN
				-- SET NOCOUNT ON added to prevent extra result sets from
				-- interfering with SELECT statements.
				SET NOCOUNT ON;


				select cast(slm.ListMemberGUID as varchar(36))
				from SecureListMember slm
				inner join SecureList sl on slm.ListGUID = sl.ListGUID and sl.IsSecured = 1 and sl.ListGUID = @ListGUID
				left join viewS3ACL ACL on ACL.LootID = slm.LootIDOverride and ACL.UserGUID = @UserGUID
				where ACL.IsReadable = 0 or ACL.IsReadable is null
				 
			END
GO


---------------------------------------------

-- dbo.procGetTableReferencesInfo
CREATE PROCEDURE [dbo].[procGetTableReferencesInfo]
	@tableSchema NVARCHAR(max),
	@tableName NVARCHAR(max)
AS	

/*
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2022-09-14	BS		JAZZ-42636  PR Metrics Definition: communication failure error when deleting many metrics with related pi.factmetric data
************************************************************
*/
SELECT DISTINCT U.COLUMN_NAME as ColumnName, R.COLUMN_NAME as RefColumnName, R.TABLE_SCHEMA as RefSchema, R.TABLE_NAME as RefName
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE U
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FK on
  U.CONSTRAINT_CATALOG = FK.UNIQUE_CONSTRAINT_CATALOG AND
  U.CONSTRAINT_SCHEMA = FK.UNIQUE_CONSTRAINT_SCHEMA AND
  U.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE R ON
  R.CONSTRAINT_CATALOG = FK.CONSTRAINT_CATALOG AND
  R.CONSTRAINT_SCHEMA = FK.CONSTRAINT_SCHEMA AND
  R.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON
  CU.CONSTRAINT_CATALOG = U.CONSTRAINT_CATALOG AND
  CU.CONSTRAINT_SCHEMA = U.CONSTRAINT_SCHEMA AND
  CU.CONSTRAINT_NAME = U.CONSTRAINT_NAME AND
  CU.COLUMN_NAME = U.COLUMN_NAME AND
  CU.TABLE_CATALOG = U.TABLE_CATALOG AND 
  CU.TABLE_SCHEMA = U.TABLE_SCHEMA AND
  CU.TABLE_NAME = U.TABLE_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE RC ON
  RC.CONSTRAINT_CATALOG = R.CONSTRAINT_CATALOG AND
  RC.CONSTRAINT_SCHEMA = R.CONSTRAINT_SCHEMA AND
  RC.CONSTRAINT_NAME = R.CONSTRAINT_NAME AND
  RC.COLUMN_NAME = R.COLUMN_NAME AND
  RC.TABLE_CATALOG = R.TABLE_CATALOG AND 
  RC.TABLE_SCHEMA = R.TABLE_SCHEMA AND
  RC.TABLE_NAME = R.TABLE_NAME AND
  RC.ORDINAL_POSITION = CU.ORDINAL_POSITION
WHERE U.TABLE_SCHEMA = @tableSchema AND U.TABLE_NAME = @tableName
GO


---------------------------------------------

-- dbo.procGetTagCloud
CREATE procedure [dbo].[procGetTagCloud] (
	@MaxFontSize int,	
	@TagTable sysname,
	@TagSchema sysname = 'dbo'
)
AS
BEGIN

declare @sql varchar(max);

set @sql = '
declare @MaxFontSize int;
set @MaxFontSize = ' + cast(@MaxFontSize as nvarchar(max)) + '
declare @Min int;
declare @Max int;

WITH Tags (Tag, [Count])
AS
(
	select  
		T.Name as Tag,
		COUNT(T.TagGUID) as [Count]
	from [' + @TagSchema + '].[' + @TagTable + '] TI
		inner join Tag T on T.TagGUID = TI.TagGUID
	GROUP BY T.Name
)
SELECT @Min = MIN([Count]), @Max = MAX([Count]) from Tags

select 
	T.TagGUID,
	T.Name AS [Tag],
	COUNT(TI.TagGUID) as [Count],
	case when COUNT(TI.TagGUID) > @Min then (@MaxFontSize * (COUNT(TI.TagGUID) - @Min)) /   (@Max - @Min) else 1 end as [FontSize]
from [' + @TagSchema + '].[' + @TagTable + '] TI
	inner join Tag T on T.TagGUID = TI.TagGUID
group by T.Name, T.TagGUID

';

print @sql;
exec (@sql);
END
GO


---------------------------------------------

-- dbo.procGetUniqueColumnValueForCopy
CREATE PROCEDURE [dbo].[procGetUniqueColumnValueForCopy]
(
	@schema nvarchar(128),
	@objectname nvarchar(128),
	@column nvarchar(128),
	@desiredvalue varchar(max)
)
AS
BEGIN		
	declare @retval varchar(max);
	declare @sql nvarchar(max);
	
	SET @sql = N'
	declare @index int;
	set @index = 0;
	set @testvalueOUT = @desiredvalue;
	WHILE (1=1) 
	BEGIN
		IF ((SELECT COUNT([' + @column + ']) FROM [' + @schema + '].[' + @objectname + '] WHERE [' + @column + '] = @testvalueOUT) > 0)
		BEGIN
			IF (@index = 0)
			BEGIN
				set @testvalueOUT = @desiredvalue + '' - Copy'';
			END
			ELSE
			BEGIN
				set @testvalueOUT = @desiredvalue + '' ('' + cast(@index as nvarchar(128)) + '') - Copy'';
			END
		
			set @index = @index + 1;
		END
		ELSE
		BEGIN
			break;
		END	
	END'

	exec sp_executesql
		@sql,
		N'@desiredvalue nvarchar(500),
		  @testvalueOUT nvarchar(500) OUTPUT
		',
		@desiredvalue=@desiredvalue,
		@testvalueOUT=@retval OUTPUT;


	select @retval;

END
GO


---------------------------------------------

-- dbo.procGetUnreadMessageCount
CREATE    PROCEDURE [dbo].[procGetUnreadMessageCount]
		@UserGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
 AS
 
	select 	
		count(*)
	from 
		MsgTopic (readuncommitted) T
		inner join MsgMessage (readuncommitted) M on T.TopicGUID = M.TopicGUID 
		inner join viewS3ACLSimple (readuncommitted) ACL on ACL.LootID = T.TopicGUID and ACl.IsReadable = 1 and acl.UserGUID = @UserGUID
	 where 
		not exists(select 1 from MsgTopicArchive (readuncommitted) ta where ta.UserGUID = @UserGUID and ta.TopicGUID = t.TopicGUID)
		and not exists(select 1 from MsgMessageRead (readuncommitted) mr where mr.MessageGUID = m.MessageGUID and mr.UserGUID = @UserGUID and mr.IsRead = 1)
GO


---------------------------------------------

-- dbo.procGetUserSecurityLastModifiedDate
-- =============================================
-- Author:		<Jacky Chau>
-- Create date: <6/24/2008>
-- Description:	<Update the security last modified date for an user>
-- =============================================
CREATE PROCEDURE procGetUserSecurityLastModifiedDate
	-- Add the parameters for the stored procedure here
	@UserGUID uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	SELECT LastModifiedDate 
	FROM   UserSecurityLastModifiedDate
	WHERE  UserGUID = @UserGUID
   
END
GO


---------------------------------------------

-- dbo.procGetViewBaseTables
CREATE procedure [dbo].[procGetViewBaseTables] (
	@ViewSchema sysname,
	@ViewName sysname
)
AS
BEGIN

	select 
		ViewSchema
		,ViewName
		,TableSchema
		,TableName
		,case when TableType = 'VIEW' then 1  else 0 end as [IsView]
		,[Level]
	from viewSysViewBaseTables 
		where ViewName = @ViewName and ViewSchema = @ViewSchema
	Order by [Level]

END
GO


---------------------------------------------

-- dbo.procIRCCheckin
CREATE procedure [dbo].[procIRCCheckin] (
	@UserGUID uniqueidentifier,
	@IRCChatGUID uniqueidentifier,
	@LastMessageID bigint = -1
)
AS
BEGIN
	
	BEGIN TRANSACTION

	--Determine last Checkin Time and Checkin
	declare @LastCheckin datetime;
	declare @Timestamp datetime;
	declare @SQLTableName nvarchar(128)
	
	set @Timestamp = GETDATE();
	
	select @LastCheckin = [LastCheckinTime] from dbo.IRCChatMembership WITH (READUNCOMMITTED)
		where UserGUID = @UserGUID and IRCChatGUID = @IRCChatGUID;
		
	if (@LastCheckin is null)
	begin
		insert into dbo.IRCChatMembership (UserGUID, IRCChatGUID, LastCheckinTime) values (@UserGUID, @IRCChatGUID, @Timestamp);
	end
	else
	begin
		update dbo.IRCChatMembership set LastCheckinTime = @Timestamp where UserGUID = @UserGUID and IRCChatGUID = @IRCChatGUID;
	end
	
		
	--Clean up old users (haven't checked in for 15 seconds)
	delete from dbo.IRCChatMembership where LastCheckinTime < DATEADD(SECOND,-15,GETDATE()) 
	
	
	--Find database table
	select @SQLTableName = SQLTableName from dbo.IRCChat WITH (READUNCOMMITTED )
		where IRCChatGUID = @IRCChatGUID;
		
	
	
	--Begin Dataset Selects - read as dataset by code
	
	--Chat Membership 
	select UP.UserGUID, UP.NameFirst + ' ' + UP.NameLast as [NameFull], UP.UserName, ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin from dbo.IRCChatMembership CM  WITH (READUNCOMMITTED)
		inner join UserProfile UP on UP.UserGUID = CM.UserGUID
		left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
	where CM.IRCChatGUID = @IRCChatGUID	
	
	--Last MessageID
	declare @lSQL varchar(max);
	set @lSQL = 'select COALESCE(MAX(MessageID),0) as [LastMessageID] from [irc].[' + @SQLTableName + ']';
	exec (@lSQL);
	
	
	--New Messages
	declare @sql varchar(max);
	if (@LastMessageID = -1)
	begin
		set @sql = '
		select * from [irc].[' + @SQLTableName + '] where 1=0
		';
	--	set @sql = ' 
	--		select 
	--			C.[MessageID], 
	--			UP.[UserName], 
	--			UP.[UserGUID],
	--			UP.[NameFirst] + '' '' + UP.NameLast as [FullName],
	--			C.[Timestamp] as [Timestamp],
	--			C.[MessageText]
	--		from  [irc].[' + @SQLTableName + ']  C WITH (READUNCOMMITTED)
	--			inner join dbo.UserProfile UP on UP.UserGUID = C.UserGUID
	--		where C.[MessageID]  > (select MAX(MessageID) - 50 from [irc].[' + @SQLTableName + '])
	--		order by C.[MessageID]
	--	';
	end
	else
	begin
		set @sql = '
			select 
				C.[MessageID], 
				UP.[UserName], 
				UP.[UserGUID],
				UP.[NameFirst] + '' '' + UP.NameLast as [FullName],
				C.[Timestamp] as [Timestamp],
				C.[MessageText]
			from  [irc].[' + @SQLTableName + ']  C WITH (READUNCOMMITTED)
				inner join dbo.UserProfile UP on UP.UserGUID = C.UserGUID
			where C.[MessageID]  > ' + cast(@LastMessageID as nvarchar(128)) + '
			order by C.[MessageID]
		';
	end
	exec (@sql);
	
	COMMIT TRANSACTION

END
GO


---------------------------------------------

-- dbo.procIRCClearOrphanedUsers
CREATE PROCEDURE dbo.procIRCClearOrphanedUsers
AS
BEGIN
--Clean up old users (haven't checked in for 15 seconds)
	delete from dbo.IRCChatMembership where LastCheckinTime < DATEADD(SECOND,-15,GETDATE()) 
	END
GO


---------------------------------------------

-- dbo.procIRCCreateChatTable
CREATE procedure [dbo].[procIRCCreateChatTable] (
	@IRCChatGUID uniqueidentifier
)
AS
BEGIN
	
	BEGIN TRANSACTION
	
	declare @SQLTableName nvarchar(128);
	--Find database table
	select @SQLTableName = SQLTableName from dbo.IRCChat WITH (READUNCOMMITTED )
		where IRCChatGUID = @IRCChatGUID;
	
	
	declare @sql varchar(max);
	
	set @sql = 'CREATE TABLE [irc].[' + @SQLTableName + ']  (
		[MessageID] bigint not null primary key identity(1,1),
		[Timestamp] datetime not null default getdate(),
		[UserGUID] uniqueidentifier not null default dbo.ZeroGUID(),
		[MessageText] nvarchar(max) not null default '''');
	'
	print @sql;
	exec (@sql);
	
	COMMIT TRANSACTION

END
GO


---------------------------------------------

-- dbo.procIRCDropChat
create procedure [dbo].[procIRCDropChat] (
	@IRCChatGUID uniqueidentifier
)
AS

	BEGIN TRANSACTION
	
	declare @SQLTableName nvarchar(128);
	--Find database table
	select @SQLTableName = SQLTableName from dbo.IRCChat WITH (READUNCOMMITTED )
		where IRCChatGUID = @IRCChatGUID;
	
	
	declare @sql varchar(max);
	
	set @sql = 'DROP TABLE [irc].[' + @SQLTableName + '];'

	exec (@sql);
	
	COMMIT TRANSACTION
GO


---------------------------------------------

-- dbo.procIRCIsUserInChat
CREATE PROCEDURE [dbo].[procIRCIsUserInChat] (
	@IRCChatGUID uniqueidentifier,
	@UserGUID uniqueidentifier
)
AS
BEGIN
	
	exec procIRCClearOrphanedUsers;
	declare @IsUserInChat bit;
	set @IsUserInChat = 0;
	
	declare @count int;
	select @count = COUNT(M.IRCChatGUID) from dbo.IRCChatMembership M
		where M.IRCChatGUID = @IRCChatGUID and M.UserGUID = @UserGUID;
	
	if (@count > 0)
		set @IsUserInChat = 1;
		
	select @IsUserInChat;
END
GO


---------------------------------------------

-- dbo.procIRCLeaveChat
create procedure [dbo].[procIRCLeaveChat](
	@UserGUID uniqueidentifier,
	@IRCChatGUID uniqueidentifier
)
AS
BEGIN
	delete from dbo.IRCChatMembership where UserGUID = @UserGUID and IRCChatGUID = @IRCChatGUID
END
GO


---------------------------------------------

-- dbo.procIRCSendMessage
CREATE procedure [dbo].[procIRCSendMessage] (
	@UserGUID uniqueidentifier,
	@IRCChatGUID uniqueidentifier,
	@MessageText nvarchar(max)
)
AS
BEGIN
	
	BEGIN TRANSACTION
	
	set @MessageText = REPLACE(@MessageText, '''', '''''')
	declare @SQLTableName nvarchar(128);
	--Find database table
	select @SQLTableName = SQLTableName from dbo.IRCChat WITH (READUNCOMMITTED )
		where IRCChatGUID = @IRCChatGUID;
		
	declare @sql varchar(max);
	
	set @sql = 'insert into [irc].[' + @SQLTableName + '] (MessageText, UserGUID) VALUES (''' + @MessageText + ''',''' + cast(@UserGUID as nvarchar(64)) + ''')'
	
	exec (@sql);
	
	COMMIT TRANSACTION

END
GO


---------------------------------------------

-- dbo.procInitStandardReportSelector
CREATE PROCEDURE [dbo].[procInitStandardReportSelector] 
AS
BEGIN
DECLARE @isExistRELootTypeTable bit;
DECLARE @isExistRESelectorTable bit;

set @isExistRELootTypeTable = 
(SELECT COUNT(NAME)
FROM SYS.TABLES
WHERE NAME = 'RELootType');

set @isExistRESelectorTable = 
(SELECT COUNT(NAME)
FROM SYS.TABLES
WHERE NAME = 'RESelector');

print @isExistRELootTypeTable
print @isExistRESelectorTable

IF @isExistRELootTypeTable = 0
BEGIN
	CREATE TABLE [dbo].[RELootType](
		[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_RELootType_ID]  DEFAULT (newid()),
		[LootType] [int] NOT NULL CONSTRAINT [DF_RELootType_LootType]  DEFAULT ((0)),
		[LootTypeName] [nvarchar](64) NOT NULL CONSTRAINT [DF_RELootType_LootTypeName]  DEFAULT (''),
		[VERSION] [timestamp] NOT NULL,
	 CONSTRAINT [PK_RELootType] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END

INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'FC558834-7EA7-4A8C-94B7-111CAAAAE400',
0,
'Plan'
);

INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'891A6E54-5BC8-4088-85C8-323BCAA7C60E',
3,
'Report'
);



INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'd7927372-c3ad-4e3b-892d-d91de9fad1dc',
2,
'List'
);

INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'108a6a2a-0bf9-4d02-8e1d-cbe627eb12b5',
4,
'PlanType'
);

INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'85f7fe66-d6c9-4c9d-8136-c41f1f1eef8b',
8,
'FormField'
);



INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'45093B3D-35E3-48A2-B25E-756F4A1BC4CF',
7,
'System Section'
);

INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'6691EFEC-D8D9-4C99-ACF7-ACFCE80C9134',
99,
'All'
);

INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'29250C25-DBE4-4E7A-BFC9-E0CC32B501CC',
2,
'List Member'
);

INSERT INTO RELootType
(ID, LootType, LootTypeName)
VALUES
(
'76BDE210-F4CD-4136-BC26-E50F9B6A56DA',
1,
'Folder'
);

IF @isExistRESelectorTable = 0
BEGIN
	CREATE TABLE [dbo].[RESelector](
		[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_REBooleanSelector_ID]  DEFAULT (newid()),
		[Name] [nvarchar](64) NOT NULL,
		[Value] [int] NOT NULL,
		[Type] [nvarchar](64) NOT NULL,
		[VERSION] [timestamp] NOT NULL
	) ON [PRIMARY]
END


INSERT INTO RESelector
(ID, Name, Value, Type)
VALUES
(
'72FFB9CB-BB88-4EF5-BD4F-B76D311CC2D9',
'Yes',
1,
'Boolean'
);

INSERT INTO RESelector
(ID, Name, Value, Type)
VALUES
(
'A2D76819-7832-4078-AE5D-541A274195DB',
'No',
0,
'Boolean'
);

END
GO


---------------------------------------------

-- dbo.procInsertStandardCodeTask
CREATE PROC dbo.procInsertStandardCodeTask 
AS 
 
DECLARE @statusCode INT; 
EXEC dbo.procCreateTask 
@taskTypeName = 'Strata.CS.Jazz.Biz.StandardCodes.StandardCodesSyncTask, Strata.CS.Jazz.Biz', -- varchar(1000) 
@contextXML = '', -- varchar(1000) 
@userName = 'Migration', 
@statusCode = @statusCode OUTPUT;
GO


---------------------------------------------

-- dbo.procIntDeleteInterfaceSectionTables
create procedure [dbo].[procIntDeleteInterfaceSectionTables] (
	@InterfaceSectionId uniqueidentifier,	
	@IntSchema nvarchar(128) = 'int'
)
AS
BEGIN
	
	declare @SectionName varchar(max);
	select @SectionName = Name from dbo.IntDataInterfaceSection where DataInterfaceSectionID  = @InterfaceSectionId
	
	declare @AcceptedTable sysname;
	declare @RejectedTable sysname;
	declare @AcceptedView sysname;
	declare @RejectedView sysname;
	
	select @AcceptedTable = dbo.GetDataIntSectionAcceptedTableName(@InterfaceSectionId);
	select @RejectedTable = dbo.GetDataIntSectionRejectedTableName(@InterfaceSectionId);
	select @AcceptedView = dbo.GetDataIntSectionAcceptedViewName(@SectionName,@InterfaceSectionId);
	select @RejectedView = dbo.GetDataIntSectionRejectedViewName(@SectionName,@InterfaceSectionId);
	
	if (dbo.TableExists(@IntSchema, @AcceptedTable) = 1) begin
		exec procSysDropTable @IntSchema, @AcceptedTable;
	end
	if (dbo.TableExists(@IntSchema, @RejectedTable) = 1) begin
		exec procSysDropTable @IntSchema, @RejectedTable;
	end
	if (dbo.ViewExists(@IntSchema, @AcceptedView) = 1) begin
		exec procSysDropTable @IntSchema, @AcceptedView;
	end
	if (dbo.ViewExists(@IntSchema, @RejectedView) = 1) begin
		exec procSysDropTable @IntSchema, @RejectedView;
	end

END
GO


---------------------------------------------

-- dbo.procIntTransactionCreate
CREATE procedure dbo.procIntTransactionCreate (
	@TransactionGUID uniqueidentifier,
	@ConfigGUID uniqueidentifier,
	@UserID uniqueidentifier,
	@Comment nvarchar(800)
)
as
begin
	insert into [dbo].[IntTransaction] 
		(TransactionGUID, ConfigID, UserID, StartTimeUtc, EndTimeUtc, IsSuccess, HasCompleted, Comment, Files, IsManualEntry)
	values (@TransactionGUID, @ConfigGUID, @UserID, getutcdate(), getutcdate(), 1, 1, @Comment, 'T-SQL', 1)
end
GO


---------------------------------------------

-- dbo.procInvalidateModelWorkbookCache
CREATE PROC procInvalidateModelWorkbookCache 
	@entityguid uniqueidentifier,
	@istemplate bit,
	@isdebugonly bit = 0,
	@source nvarchar(100) = 'Unknown'
AS
	declare @whereClause nvarchar(max)

	IF @istemplate = 1 BEGIN
		--clear models for this template, if caching enabled
		if ((select count(*) from [dbo].[EMFModelTemplate] (readuncommitted) where ModelTemplateGUID = @entityguid and IsModelWorkbookCachable = 1) > 0) begin
			if ((select count(*) from [dbo].[XPlan] (readuncommitted) where ModelTemplateGUID = @entityguid and IsModelWorkbookCached = 1) > 0) begin
				--clear file cache
				update XPlan Set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = @source, LastModelCacheInvalidateDate = getdate() WHERE ModelTemplateGUID = @entityguid and IsModelWorkbookCached = 1

				--clear memory cache
				if ((select count(*) from [dbo].[EMFModelTemplate] (readuncommitted) where ModelTemplateGUID = @entityguid and IsMemoryCachable = 1) > 0) begin
					set @whereClause = ' in(select xp1.PlanGUID from XPlan xp1 (readuncommitted) where xp1.ModelTemplateGUID = ''' + cast(@entityguid as nvarchar(36)) + ''')'
					exec procTEEvictModelCache @whereClause
				end
			end
		end
	END	ELSE BEGIN
		--clear just this model, if caching enabled
		if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) inner join [dbo].[XPlan] p (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID and p.PlanGUID = @entityguid where mt.IsModelWorkbookCachable = 1) > 0) begin
			if ((select count(*) from [dbo].[XPlan] (readuncommitted) where IsModelWorkbookCached = 1 and (PlanGUID = @entityguid or PlanGUID in(select ModelGUID from [dbo].[viewModelDependencies] where ParentModelGUID = @entityguid))) > 0) begin
				--clear file cache
				update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = @source, LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and (PlanGUID = @entityguid or PlanGUID in(select ModelGUID from [dbo].[viewModelDependencies] where ParentModelGUID = @entityguid))

				--clear memory cache
				if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) inner join [dbo].[XPlan] p (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID and p.PlanGUID = @entityguid where mt.IsMemoryCachable = 1) > 0) begin
					set @whereClause = ' in(select xp1.PlanGUID from XPlan xp1 (readuncommitted) where xp1.PlanGUID = ''' + cast(@entityguid as nvarchar(36)) + ''' union all select dep2.ModelGUID from [dbo].[viewModelDependencies] dep2 where dep2.ParentModelGUID = ''' + cast(@entityguid as nvarchar(36)) + ''')'
					exec procTEEvictModelCache @whereClause, @isdebugonly
				end
			end
		end
	END
GO


---------------------------------------------

-- dbo.procInvalidateModelWorkbookCacheByDimension
CREATE proc [dbo].[procInvalidateModelWorkbookCacheByDimension]
	@dimensionGUID uniqueidentifier,
	@whereClause nvarchar(max) = '',
	@isDebug bit = 0,
	@source nvarchar(100) = 'Unknown'
as
	set nocount on
	
	--cancel if this dimension is not a fillin dimension in modeling
	if ((select count(*) from [dbo].[MEScorePlaceholderLabel] phl (readuncommitted) where phl.FillinDimensionGUID = @dimensionGUID) = 0) begin
		return
	end

	declare @dimSource nvarchar(100)
	declare @fullWhereClause nvarchar(max)
	declare @mcSQL nvarchar(max)

	select @dimSource = SQLSchemaName + '.' + SQLObjectName from [dbo].[ScoreDimension] (readuncommitted) where DimensionGUID = @dimensionGUID
	
	if((select count(*) from [dbo].[EMFModelTemplate] (readuncommitted) where IsModelWorkbookCachable = 1) > 0) begin
		set @fullWhereClause = ' in(
				select 
					FI.ModelGUID
				from
					ScoreFillin FI (readuncommitted)
					inner join ' + @dimSource + ' C (readuncommitted) on C.MemberGUID = FI.FillinMemberGUID '
		if (@whereClause != '') begin
			set @fullWhereClause = @fullWhereClause + ' where ' + @whereClause
		end
		set @fullWhereClause = @fullWhereClause + ')'
		
		set @mcSQL = '
			declare @cnt int
			select @cnt = count(*) from XPlan P (readuncommitted) inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID where MT.IsModelWorkbookCachable = 1 and P.PlanGUID ' + @fullWhereClause + '
			if(@cnt > 0) begin
				--clear cache
				update XPlan set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = ''' + @source + ''', LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and PlanGUID ' + @fullWhereClause + '
				
				select @cnt = count(*) from XPlan P (readuncommitted) inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID where MT.IsMemoryCachable = 1 and P.PlanGUID ' + @fullWhereClause + '
				if(@cnt > 0) begin
					exec procTEEvictModelCache ''' + replace(@fullWhereClause, '''', '''''') + '''
				end
			end'

		if(@isDebug = 0) begin
			exec(@mcSQL)
		end else begin
			print @mcSQL
		end
	end
GO


---------------------------------------------

-- dbo.procInvalidateModelWorkbookCacheByDimensionEMF
CREATE proc [dbo].[procInvalidateModelWorkbookCacheByDimensionEMF]
	@dimensionGUID uniqueidentifier,
	@whereClause nvarchar(max) = '',
	@isDebug bit = 0,
	@source nvarchar(100) = 'Unknown'
as
	declare @mcSQL nvarchar(max)
	declare @fullWhereClause nvarchar(max)
	
	if((select count(*) from [dbo].[EMFModelTemplate] where IsModelWorkbookCachable = 1) > 0) begin
		set @fullWhereClause = ' in(
				select 
					FI.ModelGUID
				from
					EMFFillin FI (readuncommitted)
					inner join SecureListMember C (readuncommitted) on C.ListGUID = ''' + cast(@dimensionGUID as nvarchar(36)) + ''' and C.ListMemberGUID = FI.FilledInMemberGUID '
		if (@whereClause != '') begin
			set @fullWhereClause = @fullWhereClause + ' where ' + @whereClause
		end
		set @fullWhereClause = @fullWhereClause + ')'
		
		set @mcSQL = 'update XPlan set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = ''' + @source + ''', LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and PlanGUID ' + @fullWhereClause

		if(@isDebug = 0) begin
			exec(@mcSQL)
		end else begin
			print @mcSQL
		end

		--exec procTEEvictModelCache @fullWhereClause, @isDebug
	end
GO


---------------------------------------------

-- dbo.procInvalidateModelWorkbookCacheByPlanType
CREATE PROC procInvalidateModelWorkbookCacheByPlanType
	@planTypeGUID uniqueidentifier,
	@source nvarchar(100) = 'Unknown'
AS
	--see if this plan type has templates with caching enabled
	if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) inner join [dbo].[PlanTypeModelTemplateLink] ptl (readuncommitted) on ptl.ModelTemplateGUID = mt.ModelTemplateGUID where ptl.PlanTypeGUID = @planTypeGUID and mt.IsModelWorkbookCachable = 1) > 0) begin
		if ((select count(*) from [dbo].[XPlan] (readuncommitted) where PlanTypeGUID = @planTypeGUID and IsModelWorkbookCached = 1) > 0) begin
			--clear file cache
			update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = @source, LastModelCacheInvalidateDate = getdate() where PlanTypeGUID = @planTypeGUID and IsModelWorkbookCached = 1

			--clear memory cache
			if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) inner join [dbo].[PlanTypeModelTemplateLink] ptl (readuncommitted) on ptl.ModelTemplateGUID = mt.ModelTemplateGUID where ptl.PlanTypeGUID = @planTypeGUID and mt.IsMemoryCachable = 1) > 0) begin
				declare @whereClause nvarchar(max)
				set @whereClause = ' in(select x1.PlanGUID from XPlan x1 (readuncommitted) where x1.PlanTypeGUID = ''' + cast(@planTypeGUID as nvarchar(36)) + ''')'
				exec procTEEvictModelCache @whereClause
			end
		end
	end
GO


---------------------------------------------

-- dbo.procInvalidateModelWorkbookCacheByTemplate
CREATE PROC dbo.procInvalidateModelWorkbookCacheByTemplate
	@modelTemplateGUID uniqueidentifier,
	@source nvarchar(100) = 'Unknown',
	@idlePlansOnly bit = 0
AS
	--see if this plan type has templates with caching enabled
	if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) where mt.ModelTemplateGUID = @modelTemplateGUID and mt.IsModelWorkbookCachable = 1) > 0) begin
		if ((select count(*) from [dbo].[XPlan] (readuncommitted) where ModelTemplateGUID = @modelTemplateGUID and IsModelWorkbookCached = 1) > 0) begin
			if (@idlePlansOnly = 0) begin
				--clear file cache
				update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = @source, LastModelCacheInvalidateDate = getdate() where ModelTemplateGUID = @modelTemplateGUID and IsModelWorkbookCached = 1

				--clear memory cache
				if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) where mt.ModelTemplateGUID = @modelTemplateGUID and mt.IsMemoryCachable = 1) > 0) begin
					declare @whereClause nvarchar(max)
					set @whereClause = ' in(select x1.PlanGUID from XPlan x1 (readuncommitted) where x1.ModelTemplateGUID = ''' + cast(@modelTemplateGUID as nvarchar(36)) + ''')'
					exec procTEEvictModelCache @whereClause
				end
			end else begin
				--clear file cache for plans not in memory or refresh queue (this option is used to resolve a specific error where plans have invalid file cache)
				update p set p.IsModelWorkbookCached = 0, p.LastModelCacheInvalidateReason = @source, p.LastModelCacheInvalidateDate = getdate()
				from 
					XPlan p
					inner join emfmodeltemplate t on p.modeltemplateguid = t.modeltemplateguid 
				where 
					t.modeltemplateguid = @modelTemplateGUID
					and t.ismodelworkbookcachable = 1 
					and t.ismemorycachable = 1 
					and p.ismodelworkbookcached = 1
					and not exists(select 1 from modelcachelookup lu where lu.ModelGuid = p.PlanGUID)
					and not exists(select 1 from MEModelRefreshQueue q where q.modelguid = p.planguid)
			end
		end
	end
GO


---------------------------------------------

-- dbo.procInvalidateModelWorkbookCacheByWhereClause
CREATE PROC procInvalidateModelWorkbookCacheByWhereClause
	@xplanWhereClause nvarchar(max),
	@isDebugOnly bit = 0,
	@source nvarchar(100) = 'Unknown'
AS
	declare @sql nvarchar(max)
	
	declare @where nvarchar(max)
	if (@xplanWhereClause != '') begin
		set @where = @xplanWhereClause
	end else begin
		set @where = '(1 = 1)'
	end

	declare @evictWhereClause nvarchar(max)
	set @evictWhereClause = ' in(select x1.PlanGUID from XPlan x1 (readuncommitted) inner join EMFModelTemplate mt1 (readuncommitted) on mt1.ModelTemplateGUID = x1.ModelTemplateGUID where mt1.IsModelWorkbookCachable = 1'
	if (@where != '(1 = 1)') begin
		set @evictWhereClause = @evictWhereClause + ' and x1.' + ltrim(@where)
	end
	set @evictWhereClause = @evictWhereClause + ')'

	if ((select count(*) from [dbo].[EMFModelTemplate] (readuncommitted) where IsModelWorkbookCachable = 1) > 0) begin
		set @sql = '
			if((select count(*) from XPlan p (readuncommitted) inner join EMFModelTemplate mt (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID where p.IsModelWorkbookCached = 1 and mt.IsModelWorkbookCachable = 1 and mt.IsMemoryCachable = 0 and ' + @where + ') > 0) begin
				--clear file cache only
				update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = ''' + @source + ''', LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and ' + @where + '
			end
			if((select count(*) from XPlan p (readuncommitted) inner join EMFModelTemplate mt (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID where p.IsModelWorkbookCached = 1 and mt.IsModelWorkbookCachable = 1 and mt.IsMemoryCachable = 1 and ' + @where + ') > 0) begin
				--clear file cache
				update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = ''' + @source + ''', LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and ' + @where + '
				
				--clear memory cache
				exec procTEEvictModelCache ''' + replace(@evictWhereClause, '''', '''''') + '''
			end
		'
		
		if (@isDebugOnly = 0) begin
			exec(@sql)
		end else begin
			print @sql
		end
	end
GO


---------------------------------------------

-- dbo.procIsModelDriverExceptionsTest
create proc [dbo].[procIsModelDriverExceptionsTest]
with recompile
as
    exec dbo.procSysDropTempTable '##modelattrs'

    select *
    into ##modelattrs
    from viewScoreAttribute 
    where
	    (DimensionName = 'Account' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Dollars Rollup Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Variability')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Staffing')
	    or
	    (DimensionName = 'Job Code' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Job Code' and FriendlyName = 'Variability')
	    or
	    (DimensionName = 'Pay Code Group' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Fiscal Year' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Category')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'IsStatDriver')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'RVU Weight')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Charge Increase')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Job Code')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Next Review')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Wage Rate')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Dollars Financial Reporting Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Dollars Financial Reporting Line Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Units Financial Reporting Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Units Financial Reporting Line Name')
	    or
	    (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Line Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Patient Type Rollup Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Patient Class')
	    or
	    (DimensionName = 'Pay Code Group' and FriendlyName = 'Wage Rate Multiplier')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'Base Pay')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'Specialty')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'IsEmployee')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 1 Threshold')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 2 Threshold')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 3 Threshold')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 4 Threshold')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 5 Threshold')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 6 Threshold')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 1 Rate')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 2 Rate')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 3 Rate')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 4 Rate')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 5 Rate')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Tier 6 Rate')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Volume Target 1')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'OB Volume Target 2')
	    or
	    (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Section')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Account')
	    or
	    (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Is Expense')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Secondary Account')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'IsPhysician')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Departmental Budget' and FriendlyName = 'Is Variable')
	    or
	    (DimensionName = 'Pay Code Group' and FriendlyName = 'IsExcludedfromBenefits')
	    or
	    (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Projection Method')
	    or
	    (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Spread Method')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Is Expense')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Inversion')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'AccountID')
	    or
	    (DimensionName = 'OB Departmental Budget' and FriendlyName = 'DepartmentalBudgetID')
	    or
	    (DimensionName = 'Work Week' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Work Week' and FriendlyName = 'WorkWeekID')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'WorkWeekOverrideID')
	    or
	    (DimensionName = 'Job Code' and FriendlyName = 'WorkWeekOverrideID')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'WorkWeekOverrideID')
	    or
	    (DimensionName = 'OB Departmental Budget' and FriendlyName = 'Entity Default Work WeekID')
	    or
	    (DimensionName = 'Provider' and FriendlyName = 'NPI')
	    or
	    (DimensionName = 'OB Departmental Budget' and FriendlyName = 'Hours per UOS Projection')
	    or
	    (DimensionName = 'OB Departmental Budget' and FriendlyName = 'Hours per UOS Budget')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Employee Cohort Contract Date')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Employee Cohort Merit Type')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Volume Target')
	    or
	    (DimensionName = 'Fiscal Year' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'Account')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'Department Code')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'LOSLink')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Units Financial Reporting Name')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Units Financial Reporting Line Name')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'Patient Class')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Payor Group')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Fiscal Year' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Units Financial Reporting Name')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Units Financial Reporting Line Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'Account')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'Department Code')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'LOSLink')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'Patient Class')
	    or
	    (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Payor Group')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Patient Class')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Payor Group')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Dollars Rollup Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Staffing')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Variability')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Category')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Charge Increase')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'IsStatDriver')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'RVU Weight')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Next Review')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Job Code')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Wage Rate')
	    or
	    (DimensionName = 'Fiscal Year' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Job Code' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Job Code' and FriendlyName = 'Variability')
	    or
	    (DimensionName = 'Payor Group' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'RVU Budget Target')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'Provider Code')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'RVU Conversion Factor')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'RVU Current Target')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'isEmployee')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'Annual RVU Median')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'Provider Speciality')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Dollars Rollup Name')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Fiscal Year' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Job Code' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Payor Group' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Patient Class')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Payor Group')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'OB Staffing')
	    or
	    (DimensionName = 'Account' and FriendlyName = 'Variability')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Category')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'Charge Increase')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'IsStatDriver')
	    or
	    (DimensionName = 'Charge Code' and FriendlyName = 'RVU Weight')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Next Review')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Job Code')
	    or
	    (DimensionName = 'Employee' and FriendlyName = 'Wage Rate')
	    or
	    (DimensionName = 'Job Code' and FriendlyName = 'Variability')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'RVU Budget Target')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'Provider Code')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'RVU Conversion Factor')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'RVU Current Target')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'isEmployee')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'Annual RVU Median')
	    or
	    (DimensionName = 'OB Provider' and FriendlyName = 'Provider Speciality')
	    or
	    (DimensionName = 'Fiscal Year' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Age Cohort')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Medical Surgical')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Service Line')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Service Line Rollup')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Service Line Rollup' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Fiscal Year' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Service Line Rollup' and FriendlyName = 'Name')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Age Cohort')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Medical Surgical')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Service Line')
	    or
	    (DimensionName = 'Modeling Service Line' and FriendlyName = 'Service Line Rollup')

        exec dbo.procSysDropTempTable '#failures'

    create table #failures ([Message] nvarchar(max), [DimensionName] [nvarchar](128), [FriendlyName] [nvarchar](200)) 

    --attributes with IsModelDriver = 0 that should have = 1
    insert into #failures 
    select 'attribute with IsModelDriver = 0 that should have = 1' as Message, DimensionName, FriendlyName
    from viewScoreAttribute where IsModelDriver = 0 and AttributeGUID in(select AttributeGUID from ##modelattrs)

    --attributes with IsModelDriver = 1 that should have = 0
    insert into #failures 
    select 'attribute with IsModelDriver = 1 that should have = 0', DimensionName, FriendlyName
    from viewScoreAttribute where IsModelDriver = 1 and FriendlyName != 'Name' and AttributeGUID not in(select AttributeGUID from ##modelattrs)

    select * from #failures 

    drop table #failures 
    drop table ##modelattrs
GO


---------------------------------------------

-- dbo.procLastModifiedSchema
CREATE proc procLastModifiedSchema as
select s.name,o.name, modify_date, 
case when type_desc = 'USER_TABLE' then 'Table'
when type_desc = 'SQL_STORED_PROCEDURE' then 'Stored Procedure'
when type_desc in ('SQL_INLINE_TABLE_VALUED_FUNCTION', 'SQL_SCALAR_FUNCTION', 'SQL_TABLE_VALUED_FUNCTION') then 'Function'
end as type_desc
from sys.objects o
	inner join sys.schemas s on o.schema_id = s.schema_id
where type in ('U', 'P', 'FN', 'IF', 'TF')
and is_ms_shipped = 0
order by modify_date desc
GO


---------------------------------------------

-- dbo.procLinkedTransferDataBetweenTables
CREATE PROCEDURE [dbo].[procLinkedTransferDataBetweenTables]
(

	@SourceTableExpression varchar(max),
	@TargetTableExpression varchar(max),
	@aWhereClause varchar(max) = '',
	@aSelectClause varchar(max) = '*'
)
AS

declare @WhereClause varchar(max);
set @WhereClause = '';
IF (@aWhereClause <> '')
BEGIN
	SET @WhereClause = ' WHERE ' + @aWhereClause + ' ';
END

declare @sql varchar(max);
set @sql = '

	declare @TargetTableExpression varchar(max);
	set @TargetTableExpression = ''' + @TargetTableExpression + ''';
		
	IF ([dbo].[TableExistsByTableExpression] (@TargetTableExpression) = 1)
		BEGIN
			SET IDENTITY_INSERT ' + @TargetTableExpression + ' ON ;
			INSERT INTO ' + @TargetTableExpression + ' SELECT ' + @aSelectClause + '  FROM ' + @SourceTableExpression + ' ' + @WhereClause + ';
			SET IDENTITY_INSERT ' + @TargetTableExpression + ' OFF ;
		END
	ELSE
		BEGIN
			SELECT ' + @aSelectClause + ' INTO ' + @TargetTableExpression + ' FROM ' + @SourceTableExpression + ' ' + @WhereClause + ';
		END
		
';
print @sql;
exec (@sql);
GO


---------------------------------------------

-- dbo.procLogHistory
create proc [dbo].[procLogHistory]
	@username nvarchar(128),
	@desc nvarchar(4000),
	@cnt int,
	@higuid uniqueidentifier 
as


INSERT INTO [dbo].[HistoryItem]
           (
			OBJECTGUID
			,[HISTORYITEMGUID]
           ,[CATEGORY]
           ,[DESCRIPTION]
           ,ITEMCOUNT
           --,[ISCOMPARABLE]
           --,[ISRECOVERABLE]
           --,[ISVIEWABLE]
           ,[METAXML]
           ,[MODIFIERUSERNAME]
           )
     VALUES
           (
			dbo.ZeroGUID()
           ,@higuid 
           ,'Script' --as Category
           ,@desc --as Description
           ,@cnt
           --,0
           --,0
           --,0
           ,'' --as METAXML
           ,@username
           --,<ITEMCOUNT, int,>
           )
GO


---------------------------------------------

-- dbo.procLogLastSQL
CREATE proc [dbo].[procLogLastSQL]
	@username nvarchar(128),
	@desc nvarchar(4000),
	@higuid uniqueidentifier 
	--@count int out
as

declare @count int
set @count = @@rowcount

INSERT INTO [dbo].[HistoryItem]
           ([HISTORYITEMGUID]
           ,[CATEGORY]
           ,[DESCRIPTION]

           ,[METAXML]
           ,[MODIFIERUSERNAME]
           ,ITEMCOUNT
           )
     VALUES
           (@higuid 
           ,'Script' --as Category
           ,@desc --as Description
           ,'' --as METAXML
           ,@username
           ,@count
           --,<ITEMCOUNT, int,>
           )
GO


---------------------------------------------

-- dbo.procLogLastSQLImport
CREATE proc [dbo].[procLogLastSQLImport]
	@username nvarchar(128),
	@desc nvarchar(4000),
	@higuid uniqueidentifier ,
	@tablename nvarchar(64),
	@category nvarchar(64) = 'Import'
as

declare @count int
set @count = @@rowcount


INSERT INTO [dbo].[HistoryItem]
           ([HISTORYITEMGUID]
           ,[CATEGORY]
           ,[DESCRIPTION]
           ,[METAXML]
           ,[MODIFIERUSERNAME]
           ,ITEMCOUNT
           )
     VALUES
           (@higuid 
           ,@category --as Category
           ,@desc --as Description
           ,@tablename --as METAXML
           ,@username
           ,@count
           --,<ITEMCOUNT, int,>
           )
GO


---------------------------------------------

-- dbo.procLogLastSQLImportWithComments
CREATE proc [dbo].[procLogLastSQLImportWithComments]
	@username nvarchar(128),
	@desc nvarchar(4000),
	@higuid uniqueidentifier ,
	@tablename nvarchar(64),
	@usercomments nvarchar(256),
	@elapsedms int = 0,
	@userguid uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@category nvarchar(64) = 'Import'
as

declare @count int
set @count = @@rowcount


INSERT INTO [dbo].[HistoryItem]
           ([HISTORYITEMGUID]
           ,[CATEGORY]
           ,[DESCRIPTION]
           ,[METAXML]
           ,[MODIFIERUSERNAME]
           ,[USERCOMMENTS]
           ,ITEMCOUNT
           ,ELAPSEDMS
           ,MODIFIERUSERGUID
           )
     VALUES
           (@higuid 
           ,@category --as Category
           ,@desc --as Description
           ,@tablename --as METAXML
           ,@username
           ,@usercomments
           ,@count
           ,@elapsedms
           ,@userguid
           --,<ITEMCOUNT, int,>
           )
GO


---------------------------------------------

-- dbo.procLogObjectHistory
CREATE proc [dbo].[procLogObjectHistory]
	@entityguid uniqueidentifier,
	@desc nvarchar(4000),
	@cnt int,
	@higuid uniqueidentifier OUTPUT
as

declare @username nvarchar(64)
set @username = left(system_user,64)

set @higuid = newid()

INSERT INTO [dbo].[HistoryItem]
           (
			OBJECTGUID
			,[HISTORYITEMGUID]
           ,[CATEGORY]
           ,[DESCRIPTION]
           ,ITEMCOUNT
           --,[ISCOMPARABLE]
           --,[ISRECOVERABLE]
           --,[ISVIEWABLE]
           ,[METAXML]
           ,[MODIFIERUSERNAME]
           )
     VALUES
           (
			@entityguid
           ,@higuid 
           ,'Script' --as Category
           ,@desc --as Description
           ,@cnt
           --,0
           --,0
           --,0
           ,'' --as METAXML
           ,@username
           --,<ITEMCOUNT, int,>
           )
GO


---------------------------------------------

-- dbo.procLogObjectHistoryItemGUID
create proc [dbo].[procLogObjectHistoryItemGUID]
	@entityguid uniqueidentifier,
	@desc nvarchar(4000),
	@cnt int,
	@higuid uniqueidentifier 
as

declare @username nvarchar(64)
set @username = left(system_user,64)

if @higuid is null begin
	print 'Invalid higuid'
	return
end

INSERT INTO [dbo].[HistoryItem]
           (
			OBJECTGUID
			,[HISTORYITEMGUID]
           ,[CATEGORY]
           ,[DESCRIPTION]
           ,ITEMCOUNT
           --,[ISCOMPARABLE]
           --,[ISRECOVERABLE]
           --,[ISVIEWABLE]
           ,[METAXML]
           ,[MODIFIERUSERNAME]
           )
     VALUES
           (
			@entityguid
           ,@higuid 
           ,'Script' --as Category
           ,@desc --as Description
           ,@cnt
           --,0
           --,0
           --,0
           ,'' --as METAXML
           ,@username
           --,<ITEMCOUNT, int,>
           )
GO


---------------------------------------------

-- dbo.procLogObjectHistoryItemGUIDObjectType
create proc [dbo].[procLogObjectHistoryItemGUIDObjectType]
	@objecttype nvarchar(4000),	
	@entityguid uniqueidentifier,
	@desc nvarchar(4000),
	@cnt int,
	@higuid uniqueidentifier
		
as

declare @username nvarchar(64)
set @username = left(system_user,64)

if @higuid is null begin
	print 'Invalid higuid'
	return
end

INSERT INTO [dbo].[HistoryItem]
           (
			OBJECTGUID
			,[HISTORYITEMGUID]
           ,[CATEGORY]
           ,[DESCRIPTION]
           ,ITEMCOUNT
           --,[ISCOMPARABLE]
           --,[ISRECOVERABLE]
           --,[ISVIEWABLE]
           ,[METAXML]
           ,[MODIFIERUSERNAME]
           ,OBJECTTYPE
           )
     VALUES
           (
			@entityguid
           ,@higuid 
           ,'Script' --as Category
           ,@desc --as Description
           ,@cnt
           --,0
           --,0
           --,0
           ,'' --as METAXML
           ,@username
           ,@objecttype
           --,<ITEMCOUNT, int,>
           )
GO


---------------------------------------------

-- dbo.procLogScript
CREATE proc [dbo].[procLogScript]
	@desc nvarchar(4000),
	@higuid uniqueidentifier OUTPUT
as
	set nocount on

	declare @username nvarchar(64)
	set @username = left(system_user,64)

	if (@higuid is null or @higuid = dbo.ZeroGUID() or exists(select 1 from dbo.HistoryItem where HistoryItemGUID = @higuid)) begin
		set @higuid = newid()
	end

	INSERT INTO [dbo].[HistoryItem]
			   ([HISTORYITEMGUID]
			   ,[CATEGORY]
			   ,[DESCRIPTION]
			   ,[METAXML]
			   ,[MODIFIERUSERNAME]
			   )
		 VALUES
			   (@higuid 
			   ,'Script' --as Category
			   ,@desc --as Description
			   ,'' --as METAXML
			   ,@username
			   --,<ITEMCOUNT, int,>
			   )
GO


---------------------------------------------

-- dbo.procLogin
CREATE procedure [dbo].[procLogin] 
	@username nvarchar(64),
	@password nvarchar(64),
	@orgpin nvarchar(6) = '',
	@ipaddress varchar(15) = 'none',
	@tokentype int = 0
AS
SET NOCOUNT ON

declare @userguid uniqueidentifier
declare @cnt int
declare @IsSysAdmin bit
SELECT 
	@userguid = UP.USERGUID,
	@cnt = count(*),
    @IsSysAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0)
FROM 
	UserProfile UP
	left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
WHERE 
	UP.USERNAME = @USERNAME
	AND (convert(varbinary, UP.HASHEDPASSWORD) = convert(varbinary, @PASSWORD))
	AND UP.IsDisabled = 0
group by UP.userguid, IL.GroupingGUID


IF @cnt > 0 BEGIN
	declare @TOKENGUID uniqueidentifier
	SET @TOKENGUID = newid()

	INSERT INTO
		CurrentUser (TOKENGUID, USERGUID, IPADDRESS, TokenType, UserName)
	VALUES
		(@TOKENGUID, @USERGUID, @IPADDRESS, @tokentype, @username)

	
	SELECT @TOKENGUID AS TOKENGUID, @USERGUID as USERGUID, @USERNAME as USERNAME, @IsSysAdmin as ISSYSADMIN, @tokentype as TOKENTYPE
END
GO


---------------------------------------------

-- dbo.procLoginCheck
CREATE procedure [dbo].[procLoginCheck] 
	@username nvarchar(64),
	@password nvarchar(64),
	@orgpin nvarchar(6) = '',
	@ipaddress varchar(15) = 'none'
AS
SET NOCOUNT ON

SELECT 
	cast('00000000-0000-0000-0000-000000000000' as uniqueidentifier) as TOKENGUID,
	UP.USERGUID,
	UP.USERNAME,
	ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin,
	0 as 'TOKENTYPE'
FROM 
	UserProfile UP
	left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
WHERE 
	UP.USERNAME = @USERNAME
	AND convert(varbinary, UP.HASHEDPASSWORD) = convert(varbinary, @PASSWORD)
	AND UP.IsDisabled = 0
GO


---------------------------------------------

-- dbo.procLoginCheckSSO
CREATE procedure [dbo].[procLoginCheckSSO] 
	@username nvarchar(64),
	@authid nvarchar(128),
	@ipaddress varchar(15) = 'None'
AS
SET NOCOUNT ON

SELECT 
	cast('00000000-0000-0000-0000-000000000000' as uniqueidentifier) as TOKENGUID,
	UP.USERGUID,
	UP.USERNAME,
	ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin,
	0 as 'TOKENTYPE'
FROM 
	UserProfile UP
	left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
WHERE 
	UP.USERNAME = @USERNAME
	AND UP.AUTHID = @AUTHID
	AND UP.IsDisabled = 0
GO


---------------------------------------------

-- dbo.procLoginGetUserGUID
create proc procLoginGetUserGUID
	@username nvarchar(max)
as
	select userguid from userprofile where username = @username
GO


---------------------------------------------

-- dbo.procLoginGetUserSalt
CREATE PROCEDURE [dbo].[procLoginGetUserSalt]
@username nvarchar(max)
 AS
 BEGIN
	select salt from userprofile where username = @username
 END
GO


---------------------------------------------

-- dbo.procLoginNewToken
CREATE procedure [dbo].[procLoginNewToken]
	@tokenguid uniqueidentifier,
	@ipaddress varchar(15),
	@ttl integer = 0,
	@updatelastactionstamp bit = 1,
	@tokentype int = 0
as
	SET NOCOUNT ON
	declare @userguid uniqueidentifier
	declare @username nvarchar(64)
	declare @cnt int
	declare @IsSysAdmin bit

	if((select count(*) from [dbo].[CurrentUser] (readuncommitted) where TokenGUID = @tokenguid and UserGUID = '10101010-1111-0000-1111-101010101010') > 0) begin
		select @username = UserName from [dbo].[CurrentUser] where TokenGUID = @tokenguid
		set @userguid = '10101010-1111-0000-1111-101010101010'
		set @cnt = 1
		set @IsSysAdmin = 1
	end else begin
		SELECT 
			@userguid = CU.USERGUID,
			@username = UP.USERNAME,
			@cnt = count(*),
			@IsSysAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0)
		FROM 
			CurrentUser CU (readuncommitted)
			INNER JOIN UserProfile UP (readuncommitted) ON CU.UserGUID = UP.UserGUID
			left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
		WHERE 
			TOKENGUID = @tokenguid
			AND UP.IsDisabled = 0
		group by CU.userguid, UP.username, IL.GroupingGUID
	end

	IF @cnt > 0 BEGIN
		declare @NEWTOKENGUID uniqueidentifier
		SET @NEWTOKENGUID = newid()

		INSERT INTO
			CurrentUser (TOKENGUID, USERGUID, IPADDRESS, LASTACTIONSTAMPUTC, TokenType, UserName)
		VALUES
			(@NEWTOKENGUID, @USERGUID, @IPADDRESS, DATEADD(day,@ttl,getUTCDate()), @tokentype, @username)

		SELECT @NEWTOKENGUID AS TOKENGUID, @USERGUID as USERGUID, @USERNAME as USERNAME, @IsSysAdmin as ISSYSADMIN, @tokentype as TOKENTYPE
	END
GO


---------------------------------------------

-- dbo.procLoginReauthenticate
CREATE PROC [dbo].[procLoginReauthenticate]
	@tokenguid UNIQUEIDENTIFIER,
	@ipaddress VARCHAR(15),
	@ttl INTEGER = 0,
	@updatelastactionstamp BIT = 1
AS
	SET NOCOUNT ON

    IF @updatelastactionstamp = 1 BEGIN
		UPDATE CurrentUser 
		SET LastActionStampUtc = DATEADD(day, @ttl, GETUTCDATE())
		WHERE TOKENGUID = @tokenguid 
	END

	SELECT CU.TOKENGUID, CU.USERGUID, CU.USERNAME,
		CAST((COALESCE((ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS BIT),0)), CASE WHEN CU.UserGUID = dbo.GetSuperUserGUID() THEN 1 ELSE 0 END)) AS BIT) AS [IsSysAdmin],
		CU.TokenType		
	FROM CurrentUser CU
		LEFT JOIN UserProfile UP ON CU.UserGUID = UP.UserGUID
		LEFT JOIN [dbo].[S3IdentityLink] IL ON UP.UserGUID = IL.MemberGUID AND IL.GroupingGUID = (SELECT UserGroupGUID FROM [dbo].[UserGroup] WHERE GlobalID = 'GEN - User Administrator')
	WHERE TOKENGUID = @tokenguid AND ISNULL(UP.IsDisabled, 0) = 0
GO


---------------------------------------------

-- dbo.procLoginRecreate
CREATE PROC [dbo].[procLoginRecreate]
	@tokenguid UNIQUEIDENTIFIER,
	@username NVARCHAR(64),
	@hashedpassword NVARCHAR(64),
	@orgpin NVARCHAR(6) = '',
	@ipaddress VARCHAR(15) = 'none',
	@tokentype INT = 0,
	@ttl INT = 0
AS
SET NOCOUNT ON

DECLARE @userguid UNIQUEIDENTIFIER
DECLARE @cnt INT
DECLARE @IsSysAdmin BIT

SELECT 
	@userguid = USERGUID,
	@cnt = COUNT(*),
    @IsSysAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS BIT), 0)
FROM 
	UserProfile UP
	LEFT JOIN [dbo].[S3IdentityLink] IL ON UP.UserGUID = IL.MemberGUID AND IL.GroupingGUID = (SELECT UserGroupGUID FROM [dbo].[UserGroup] WHERE GlobalID = 'GEN - User Administrator')
WHERE 
	USERNAME = @USERNAME
	AND (CONVERT(VARBINARY, HASHEDPASSWORD) = CONVERT(VARBINARY, @HashedPASSWORD))
	AND IsDisabled = 0
GROUP BY userguid, IL.GroupingGUID

IF @cnt > 0 BEGIN
	DECLARE @LastActionStampUtc DATETIME
	SET @LastActionStampUtc = DATEADD(d,@TTL, GETUTCDATE())
	IF NOT EXISTS(SELECT 1 FROM CurrentUser WHERE TokenGUID = @tokenguid)
	BEGIN
		INSERT INTO CurrentUser (TOKENGUID, USERGUID, IPADDRESS, TokenType, LastActionStampUtc, UserName)
		VALUES(@TOKENGUID, @USERGUID, @IPADDRESS, @tokentype, @LastActionStampUtc, @username)	
	END
	ELSE
	BEGIN
		UPDATE CurrentUser SET LastActionStampUtc = @LastActionStampUtc WHERE TokenGUID = @tokenguid
	END
	SELECT @TOKENGUID AS TOKENGUID, @USERGUID AS USERGUID, @USERNAME AS USERNAME, @IsSysAdmin AS ISSYSADMIN, @tokentype AS TOKENTYPE
END
GO


---------------------------------------------

-- dbo.procLoginSSO
CREATE procedure [dbo].[procLoginSSO] 
	@username nvarchar(64),
	@authid nvarchar(128),
	@ipaddress varchar(15) = 'none',
	@tokentype int = 0

AS
SET NOCOUNT ON

declare @userguid uniqueidentifier
declare @cnt int
declare @IsSysAdmin bit
SELECT 
	@userguid = USERGUID,
	@cnt = count(*),
    @IsSysAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0)
FROM 
	UserProfile UP
	left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
WHERE 
	USERNAME = @USERNAME
	AND AUTHID = @AUTHID
	AND IsDisabled = 0
group by userguid, IL.GroupingGUID


IF @cnt > 0 BEGIN
	DECLARE @tokenguid uniqueidentifier
	SET @TOKENGUID = newid()
	
	INSERT INTO
		CurrentUser (TOKENGUID, USERGUID, IPADDRESS, TokenType, UserName)
	VALUES
		(@TOKENGUID, @USERGUID, @IPADDRESS, @tokentype, @username)

	SELECT @TOKENGUID AS TOKENGUID, @USERGUID as USERGUID, @USERNAME as USERNAME, @IsSysAdmin as ISSYSADMIN, @tokentype as TokenType
END
GO


---------------------------------------------

-- dbo.procLogoffInactiveUsers
CREATE PROC [dbo].[procLogoffInactiveUsers]
AS
    SET NOCOUNT ON
	DECLARE @timeoutMinutes INT
	SET @timeoutMinutes = 360 --121
	INSERT INTO ActionLog(Action, SubAction, Details, Username, DateTimeStamp, Duration)
	SELECT 'Logout', 'Inactivity Logout', CAST(USERGUID AS NVARCHAR(36)), 'procLogoffInactiveUsers', GETUTCDATE(), 0 FROM CurrentUser WHERE DATEDIFF(mi, lastactionstamputc, GETUTCDATE()) > @timeoutMinutes
	DELETE FROM CurrentUser WHERE DATEDIFF(mi, lastactionstamputc, GETUTCDATE()) > @timeoutMinutes
GO


---------------------------------------------

-- dbo.procLogout
CREATE procedure [dbo].[procLogout]
	@tokenguid uniqueidentifier,
	@ipaddress varchar(15) = 'none'
as
	SET NOCOUNT ON

	insert into ActionLog(Action, SubAction, Details, Username, DateTimeStamp, Duration) select 'Logout', 'DB Logout', 'procLogout', UserName, GETDATE(), 0 from [dbo].[CurrentUser] where TOKENGUID = @TOKENGUID

	DELETE FROM CurrentUser where TOKENGUID = @TOKENGUID --and IPADDRESS = @IPADDRESS
GO


---------------------------------------------

-- dbo.procLogoutAllUsers
CREATE procedure [dbo].[procLogoutAllUsers]
as
	SET NOCOUNT ON

	insert into ActionLog(Action, SubAction, Details, Username, DateTimeStamp, Duration) select 'Logout', 'DB Logout', 'procLogoutAllUsers', UserName, GETDATE(), 0 from [dbo].[CurrentUser]

	DELETE FROM CurrentUser WHERE TokenType = 0;
	EXEC dbo.procLogoffInactiveUsers;
GO


---------------------------------------------

-- dbo.procMEImprovDataRemoveDuplicates
CREATE proc dbo.procMEImprovDataRemoveDuplicates
as
	--try to resolve duplicates by removing blank values
	if (exists(select 1 from MEImprovData group by modelguid, row, col having count(*) > 1)) begin
		delete from MEImprovData 
		where 
			Formula = '' and CellValue = '' and
			(
				ImprovDataGUID in(select min(improvdataguid) from MEImprovData group by modelguid, row, col having count(*) > 1) 
				or ImprovDataGUID in(select max(improvdataguid) from MEImprovData group by modelguid, row, col having count(*) > 1)
			)
	end

	--remove remaining duplicates with the same value
	if (exists(select 1 from MEImprovData group by modelguid, row, col, formula, cellvalue having count(*) > 1)) begin
		delete from MEImprovData 
		where 
			ImprovDataGUID in(select min(improvdataguid) from MEImprovData group by modelguid, row, col, formula, cellvalue having count(*) > 1) 
	end
GO


---------------------------------------------

-- dbo.procMEModelChangeDebug
CREATE proc dbo.procMEModelChangeDebug
	@higuid uniqueidentifier,
	@address nvarchar(max),
	@lookbackDays int = 7
as
	--input related info
	declare @modelguid uniqueidentifier
	select @modelguid = ObjectGUID from HistoryItem where HistoryItemGUID = @higuid
	declare @dtname nvarchar(max)
	select
		@dtname = dt.FriendlyName
	from
		ScoreTupleDataHistoryChangeItem ci 
		inner join ScoreDataTable dt on dt.DataTableGUID = ci.DataTableGUID
	where
		ci.HistoryItemGUID = @higuid;

	--determine lookback range: either since last touch to this cell, or X days
	declare @enddate datetime
	select @enddate = DateTimeStamp from HistoryItem where HISTORYITEMGUID = @higuid
	declare @startdate datetime
	select top 1
		@startdate = hi.DATETIMESTAMP
	from
		ScoreTupleDataHistoryChangeItem ci
		inner join HistoryItem hi on hi.HISTORYITEMGUID = ci.HistoryItemGUID
	where
		hi.OBJECTGUID = @modelguid
		and hi.HISTORYITEMGUID != @higuid
		and ci.CellAddress = @address
		and ci.BeforeValueString != ci.AfterValueString
		and hi.DateTimeStamp < @enddate
	order by
		hi.DATETIMESTAMP desc;
	if (@startdate is null) begin
		set @startdate = @enddate - @lookbackDays
	end
	if (datediff(day, @startdate, @enddate) < @lookbackDays) begin
		select @startdate = dateadd(day, -1 * @lookbackDays, @enddate)
	end

	--other touches of this cell
	select
		hi.HistoryItemGUID,
		hi.DateTimeStamp,
		hi.ModifierUserGUID,
		hi.ModifierUserName,
		cast('Debug Cell Changed' as nvarchar(100)) as Category,
		cast(@dtname + ': ' + ci.BeforeValueString + ' -> ' + ci.AfterValueString as nvarchar(max)) as Description
	into ##modeldebug
	from
		ScoreTupleDataHistoryChangeItem ci
		inner join HistoryItem hi on hi.HISTORYITEMGUID = ci.HistoryItemGUID
	where
		hi.OBJECTGUID = @modelguid
		and ci.CellAddress = @address
		and (hi.HISTORYITEMGUID = @higuid or hi.DATETIMESTAMP between @startdate and @enddate)
		and ci.BeforeValueString != ci.AfterValueString;

	--fillin change details
	insert into ##modeldebug
	select
		rli.HistoryItemGUID,
		rli.DateTimeStamp,
		hi.ModifierUserGUID,
		hi.ModifierUserName,
		'Fillin Change' as Category,
		rli.SectionName + ': ' + case when rli.Action = 0 then 'Add' when rli.Action = 1 then 'Move' when rli.Action = 2 then 'Delete' else 'Unknown' end + rli.FillinMemberName as Description
	from 
		ScoreFillinRefreshLogItem rli
		inner join HistoryItem hi on hi.HistoryItemGUID = rli.HistoryItemGUID
	where 
		rli.ModelGUID = @modelguid
		and rli.DateTimeStamp between @startdate and @enddate;

	--other system actions
	insert into ##modeldebug
	select
		hi.HistoryItemGUID,
		hi.DateTimeStamp,
		hi.ModifierUserGUID,
		hi.ModifierUserName,
		hi.Category,
		hi.Description
	from 
		HistoryItem hi
	where 
		(hi.HISTORYITEMGUID = @higuid or hi.DATETIMESTAMP between @startdate and @enddate)
		and (hi.CATEGORY not in('Expansion Changes', 'Model Data Save') or hi.ObjectGUID = @modelguid)
		and CATEGORY not in('', 'Contract Model', 'Excel Reporter', 'Form Data', 'Manual Unlock', 'Patient Population Definition', 'Report Action', 'Role Assignment', 'Service Line Definition', 'Service Line Definitions', 'Structure View', 'Workflow')
		and Description not like '%Exceptions'
		and Description not like 'insert template publish request%'
		and Description not in('Sync Expansion Profiles');
		
	--global model saves
	if (exists(select 1 from XPlan p inner join EMFModelTemplate t on t.ModelTemplateGUID = p.ModelTemplateGUID where p.PlanGUID = @modelguid and t.Name like 'OB Departmental Budget%')) begin
		insert into ##modeldebug
		select
			hi.HistoryItemGUID,
			hi.DateTimeStamp,
			hi.ModifierUserGUID,
			hi.ModifierUserName,
			'Global Model ' + hi.Category as Category,
			p.Name as Description
		from 
			HistoryItem hi
			inner join XPlan p on p.PlanGUID = hi.ObjectGUID
			inner join EMFModelTemplate mt on mt.ModelTemplateGUID = p.ModelTemplateGUID
		where 
			hi.DATETIMESTAMP between @startdate and @enddate
			and hi.CATEGORY in('Expansion Changes', 'Model Data Save')
			and mt.Name not like 'OB Departmental Budget%'
			and mt.Name like 'OB %'
	end
		
	--remove unrelated publishes
	delete data
	from 
		##modeldebug data
		inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID
		left join EMFModelTemplate mt on mt.ModelTemplateGUID = hi.ObjectGUID
	where 
		hi.DESCRIPTION = 'Template Architect Publish'
		and (mt.ModelTemplateGUID is null or not exists(select 1 from XPlan p where p.PlanGUID = @modelguid and p.ModelTemplateGUID = mt.ModelTemplateGUID));
	update data set data.Category = 'Template Publish', data.Description = mt.Name 
	from 
		##modeldebug data
		inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID
		inner join EMFModelTemplate mt on mt.ModelTemplateGUID = hi.ObjectGUID
	where 
		hi.DESCRIPTION = 'Template Architect Publish';
		
	--remove unrelated dimension saves
	declare @frameworkID int
	select @frameworkID = fw.FrameworkID from PlanType pt inner join Folder f on f.FolderGUID = pt.FolderGUID inner join fw.DimFramework fw on fw.Name = f.Name inner join XPlan p on p.PlanTypeGUID = pt.PlanTypeGUID where p.PlanGUID = @modelguid;
	if (@frameworkID is null) begin
		set @frameworkID = 0
	end
	delete data
	from 
		##modeldebug data
		inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID
		inner join ScoreDimension d on d.DimensionGUID = hi.ObjectGUID
	where 
		hi.DESCRIPTION = 'Dimension Save'
		and 
			(not exists(select 1 from ScoreDimensionFramework df where df.DimensionGUID = d.DimensionGUID and df.FrameworkID in(0, @frameworkID))
			or d.FriendlyName like 'Service Line%');
	update data set data.Category = 'Dimension Save', data.Description = d.FriendlyName 
	from 
		##modeldebug data
		inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID
		inner join ScoreDimension d on d.DimensionGUID = hi.ObjectGUID
	where 
		hi.DESCRIPTION = 'Dimension Save';

	--remove unrelated ds2 saves
	delete data
	from
		##modeldebug data
		inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID
		inner join scoretableeditorconfig tec on tec.tableeditorconfigguid = hi.ObjectGUID 
		inner join folder f on f.folderguid = tec.folderguid 
		left join folder pf on pf.folderguid = f.parentfolderguid 
		left join folder ppf on ppf.folderguid = pf.parentfolderguid 
		left join folder pppf on pppf.folderguid = ppf.parentfolderguid 
		inner join fw.dimframework df on df.name = f.name or df.name = isnull(pf.name, 'Missing') or df.name = isnull(ppf.name, 'Missing') or df.name = isnull(pppf.name, 'Missing')
	where
		hi.Category = 'Data Studio 2.0'
		and (df.FrameworkID != @frameworkID or hi.Description = 'SaveView')
	update data set data.Category = 'Data Studio Save', data.Description = tec.FriendlyName
	from
		##modeldebug data
		inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID
		inner join scoretableeditorconfig tec on tec.tableeditorconfigguid = hi.ObjectGUID 
	where
		hi.Category = 'Data Studio 2.0'
		
	--remove unrelated data imports
	delete data
	from 
		##modeldebug data
		inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID
		inner join IntTransaction t on t.TransactionGUID = hi.HistoryItemGUID
		inner join IntConfig c on c.ConfigID = t.ConfigID
	where
		hi.Category = 'Data Integration'
		and not exists(select 1 from dbo.IntConfigFramework cf where cf.ConfigID = c.ConfigID and cf.FrameworkID = @frameworkID);
	update data set data.Description = c.Name
	from 
		##modeldebug data
		inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID
		inner join IntTransaction t on t.TransactionGUID = hi.HistoryItemGUID
		inner join IntConfig c on c.ConfigID = t.ConfigID
	where
		hi.Category = 'Data Integration';

	select * from ##modeldebug data
	order by
		data.DATETIMESTAMP desc,
		data.Category asc;
	drop table ##modeldebug;
GO


---------------------------------------------

-- dbo.procMENativeModelingDisable
CREATE proc dbo.procMENativeModelingDisable
as
	set nocount on
	
	update [ob].[SystemSetting] set Value = '0' where Name = 'Native Modeling Enabled'
	update [cap].[SystemSetting] set Value = '0' where Name = 'Native Modeling Enabled'
	
	declare @templateGUID uniqueidentifier
	declare crsTemplates cursor fast_forward for select ModelTemplateGUID from [dbo].[EMFModelTemplate] where IsMemoryCachable = 1

	open crsTemplates
	fetch next from crsTemplates into @templateGUID
	
	while (@@fetch_status = 0) begin
		exec [dbo].[procInvalidateModelWorkbookCache] @templateGUID, 1, 0, 'procMENativeModelingDisable'
		update [dbo].[EMFModelTemplate] set IsModelWorkbookCachable = 0, IsMemoryCachable = 0 where ModelTemplateGUID = @templateGUID
		update [dbo].[XPlan] set IsModelWorkbookCached = 0 where ModelTemplateGUID = @templateGUID

		fetch next from crsTemplates into @templateGUID
	end
	
	close crsTemplates
	deallocate crsTemplates
	
	truncate table dbo.ModelCacheLookup

	update [dbo].[TEScheduledTask] set IsDisabled = 1 where Name = 'GM Prime Model Cache'
	update ob.SystemSetting set Value = DefaultValue where Name = 'Native Modeling Priming Limit'
	
	print('NOTE: If you intend to leave Native Modeling permanently disabled, you will need to manually update plan and directory toolbars to fix the visibility of Edit Budget and Edit Expansion tools.');
GO


---------------------------------------------

-- dbo.procMENativeModelingEnable
CREATE   PROCEDURE dbo.procMENativeModelingEnable
	@cacheServerName NVARCHAR(100) = 'default',
	@enablePriming BIT = 1,
	@domain NVARCHAR(100) = 'sdt.local',
	@frameworkID SMALLINT = 2, --OB
	@isMemoryCachePersisted BIT = 1,
	@isForTraining BIT = 0
AS
BEGIN
 SET NOCOUNT ON

 IF @frameworkID = 2
 BEGIN
	UPDATE ob.SystemSetting
	SET Value = '1'
	WHERE Name = 'Native Modeling Enabled'
 END

 IF @frameworkID = 1
 BEGIN
	UPDATE cap.SystemSetting
	SET Value = '1'
	WHERE Name = 'Native Modeling Enabled'
 END

 DECLARE @frameworkName NVARCHAR(100)
 DECLARE @frameworkAbbreviation NVARCHAR(10)

 SELECT @frameworkName = Name
 FROM fw.DimFramework
 WHERE FrameworkID = @frameworkID

 SELECT @frameworkAbbreviation = CASE 
   WHEN Abbreviation = 'CM'
      THEN 'CAP'
   ELSE Abbreviation
   END
 FROM fw.DimFramework
 WHERE FrameworkID = @frameworkID

 DECLARE @jazzVersion NVARCHAR(6)

 SELECT @jazzVersion = replace(Setting, '.', '')
 FROM dbo.DBSetting
 WHERE Name = 'GENERAL_APPVERSION'

 IF @cacheServerName = 'default'
 BEGIN
	SELECT @cacheServerName = 'Setting'
	FROM dbo.DBSetting
	WHERE Name = 'MODELING_LOADBALANCED_CACHE_BASE_URL'
 END
 ELSE
 BEGIN
	SET @cacheServerName = 'http://' + @cacheServerName + '.' + @domain
 END

 --dbsettings
 EXEC dbo.procChangeDBSetting 'MODELING_LOADBALANCED_CACHE_BASE_URL', @cacheServerName
 EXEC dbo.procChangeDBSetting 'MODELING_ISFILECACHECOMPRESSED', '0'

 --template settings
 UPDATE dbo.EMFModelTemplate
 SET IsModelWorkbookCachable = @isMemoryCachePersisted,
	IsMemoryCachable = 1,
	IsModelRefreshOnFillinChange = 0
 WHERE Name LIKE @frameworkAbbreviation + ' %'

 --do not clear HasModelDependents for CAP Advanced Project Pro Forma - it's required for Depreciation re-calculation
 DECLARE @capProFormaTemplateGUID UNIQUEIDENTIFIER = '538EAAB2-22B1-41BA-882E-6EFB9C262062'

 UPDATE dbo.EMFModelTemplate
 SET HasModelDependents = 0
 WHERE Name LIKE @frameworkAbbreviation + ' %'
	AND ModelTemplateGUID <> @capProFormaTemplateGUID
 
 --plan settings
 UPDATE dbo.XPlan
 SET IsModelRefreshEnabled = 1,
	IsModelWorkbookCached = 0
 WHERE ModelTemplateGUID IN (
	SELECT mt.ModelTemplateGUID
	FROM dbo.EMFModelTemplate mt
	WHERE mt.Name LIKE @frameworkAbbreviation + ' %'
   )

 --scheduled task
 IF @enablePriming = 1 AND @isMemoryCachePersisted = 1
 BEGIN
	UPDATE dbo.TEScheduledTask
	SET IsDisabled = 0
	WHERE Name = 'GM Prime Model Cache'
 END

 --hide edit expansions in form
 UPDATE dbo.CustomMenuContent
 SET ContentXML = replace(cast(ContentXML AS NVARCHAR(max)), '<Item Value="rmiEditFillIns" Text="~Tool_EditExpansions" LeftLogo="node.png" GUID="2b4e8032-737f-461e-b6bc-b045a7fb6795" PostBack="False" OnClientClick="onEditExpansion();"/>', '')
 WHERE CustomMenuGUID IN (
	SELECT f.CustomMenuGUID
	FROM dbo.FE2Form f
		INNER JOIN dbo.PlanType pt
			ON pt.PlanTypeGUID = f.PlanTypeGUID
		INNER JOIN dbo.Folder ptf
			ON ptf.FolderGuid = pt.FolderGUID
	WHERE ptf.Name = @frameworkName
   )
  AND cast(ContentXML AS NVARCHAR(max)) LIKE '%<Item Value="rmiEditFillIns" Text="~Tool_EditExpansions" LeftLogo="node.png" GUID="2b4e8032-737f-461e-b6bc-b045a7fb6795" PostBack="False" OnClientClick="onEditExpansion();"/>%'

 --limit priming for training
 IF (@frameworkID = 2)
 BEGIN --OB only
	IF (@isForTraining = 1)
	BEGIN
		UPDATE ob.SystemSetting
		SET Value = '10'
		WHERE Name = 'Native Modeling Priming Limit'
	END
  ELSE
  BEGIN
	UPDATE ob.SystemSetting
	SET Value = DefaultValue
	WHERE Name = 'Native Modeling Priming Limit'
  END
 END

 PRINT ('Complete!');
 PRINT ('MANUAL POST STEPS');
 PRINT ('1) Clear Application Cache from Admin Tools');
 PRINT ('2) Ensure Edit Budget tool is visible in both the workspace (Custom Menus->OB Directory Toolbar) and on the form (Plan Type Setup->Edit Form->Edit Toolbar)');

 IF (@enablePriming = 1)
 BEGIN
	PRINT ('3) Wait for tasks to finish and System Diagnostics to show no Modeling issues');
	PRINT ('4) Confirm you can launch a model and navigation looks ok');
 END
END
GO


---------------------------------------------

-- dbo.procMEPHSectionConfigDefaultInsert
CREATE proc [dbo].[procMEPHSectionConfigDefaultInsert] as 
exec procScoreRebuildDimensionMemberView

declare @sql nvarchar(max)

set @sql = '
insert into MEPHSectionConfig
(ModelTemplateGUID, PHSectionDimensionGUID, PHSectionMemberGUID, FriendlyName)
select distinct
	mt.ModelTemplateGUID, k1.DimensionGUID, dm.MemberGUID, dm.MemberName
from
	EMFModelTemplate mt
	inner join EMFModelTemplateLinkSource ls on mt.ModelTemplateGUID = ls.ModelTemplateGUID
	inner join ScoreComposite sc on ls.ParentScoreCompositeTableGUID = sc.CompositeGUID
	inner join ScoreCompositeLink scl on sc.CompositeGUID = scl.CompositeGUID
	inner join ScoreAttribute k1 on scl.Key1GUID = k1.AttributeGUID
	inner join fw.viewScoreDimensionMember dm on k1.DimensionGUID = dm.DimensionGUID
where
	scl.IsPlaceholder = 1
	and not exists (
		select 1 
		from
			MEPHSectionConfig phx
		where
			phx.PHSectionDimensionGUID = k1.DimensionGUID
			and phx.PHSectionMemberGUID = dm.MemberGUID
	)'
	
--dynamic to remove dependency on fw schema
exec (@sql)
GO


---------------------------------------------

-- dbo.procMEPHSectionDuplicatesResolve
CREATE proc dbo.procMEPHSectionDuplicatesResolve
	@isdebug bit = 0
as
	--always remove invalid phsections first to avoid false positives
	delete from [dbo].[MEPHSection] where PHSectionGUID not in(select v.PHSectionGUID from [dbo].[viewMEPHSection] v)

	declare crsDupes cursor fast_forward for select distinct PlanTypeGUID, ModelTemplateGUID, PHSectionDimensionGUID, PHSectionMemberGUID from [dbo].[viewMEPHSectionDuplicates] where ModelTemplateGUID not in(select ChildModelTemplateGUID from [dbo].[MEScoreExpansionProfile])
	declare @ptguid uniqueidentifier
	declare @mtguid uniqueidentifier
	declare @dimguid uniqueidentifier
	declare @memberguid uniqueidentifier
	declare @debugsql nvarchar(max)
	declare @phsectionguid uniqueidentifier

	open crsDupes
	fetch next from crsDupes into @ptguid, @mtguid, @dimguid, @memberguid

	while(@@fetch_status = 0) begin
		select top 1 @phsectionguid = PHSectionGUID from [dbo].[viewMEPHSection] where PlanTypeGUID = @ptguid and ModelTemplateGUID = @mtguid and PHSectionDimensionGUID = @dimguid and PHSectionMemberGUID = @memberguid
		select @debugsql = 'select ''' + cast(@phsectionguid as nvarchar(36)) + ''' as Guess, * from dbo.viewMEPHSectionDuplicates where PlanTypeGUID = ''' + cast(@ptguid as nvarchar(36)) + ''' and ModelTemplateGUID = ''' + cast(@mtguid as nvarchar(36)) + ''' and PHSectionDimensionGUID = ''' + cast(@dimguid as nvarchar(36)) + ''' and PHSectionMemberGUID = ''' + cast(@memberguid as nvarchar(36)) + ''''
		if (@isdebug = 1) begin
			print @debugsql
		end

		--if one of the dupes is not configured, delete that one
		if ((select count(*) from [dbo].[MEPHSection] where PlanTypeGUID = @ptguid and ModelTemplateGUID = @mtguid and PHSectionDimensionGUID = @dimguid and PHSectionMemberGUID = @memberguid and RuleType != 0) = 1) begin
			if (@isdebug = 1) begin
				print 'AUTO: duplicates differ by type, delete ''none'' sections
				'
			end else begin
				delete from [dbo].[MEPHSection] where PlanTypeGUID = @ptguid and ModelTemplateGUID = @mtguid and PHSectionDimensionGUID = @dimguid and PHSectionMemberGUID = @memberguid and RuleType = 0
			end
		end else begin
			--if dupes are identical delete the one that is invisible in PSM
			if((select count(*) from [dbo].[viewMEPHSectionDuplicates] d where d.PlanTypeGUID = @ptguid and d.ModelTemplateGUID = @mtguid and d.PHSectionDimensionGUID = @dimguid and d.PHSectionMemberGUID = @memberguid and not exists(select 1 from [dbo].[viewMEPHSectionDuplicates] f where f.PlanTypeGUID = @ptguid and f.ModelTemplateGUID = @mtguid and f.PHSectionDimensionGUID = @dimguid and f.PHSectionMemberGUID = @memberguid and f.FriendlyName = d.FriendlyName and f.SortType = d.SortType and f.IsConstantIndex = d.IsConstantIndex and f.RootHierarchyPath = d.RootHierarchyPath and f.DefaultHierarchyPath = d.DefaultHierarchyPath and f.IsAppend = d.IsAppend and f.IsHidden = d.IsHidden and f.IsReadOnly = d.IsReadOnly and f.IsExclusive = d.IsExclusive and f.RuleType = d.RuleType and f.IsOneTime = d.IsOneTime and f.IsClearOnRefresh = d.IsClearOnRefresh and f.ExclusivityGroup = d.ExclusivityGroup and f.IsOrderByName = d.IsOrderByName and f.PHSectionGUID != d.PHSectionGUID)) = 0) begin
				if (@isdebug = 1) begin
					print 'AUTO: duplicates are identical, delete extras
					'
				end else begin
					delete from [dbo].[MEPHSection] where PHSectionGUID = @phsectionguid
				end
			end else begin
				--otherwise we will remove the first one listed in viewMEPHSection, as this should be the one that is invisible in PSM
				if (@isdebug = 1) begin
					print 'GUESS: duplicates differ by misc properties
					'
				end else begin
					delete from [dbo].[MEPHSection] where PHSectionGUID = @phsectionguid
				end
			end
		end

		fetch next from crsDupes into @ptguid, @mtguid, @dimguid, @memberguid
	end

	close crsDupes
	deallocate crsDupes

	if (@isdebug = 0) begin
		exec [dbo].[procMEScoreExpansionProfileSyncTemplatesAll] @isPreservingChildMappings = 1

		if (exists(select 1 from [dbo].[viewMEPHSectionDuplicates])) begin
			print 'FAILED: Some duplicate PH sections count not be auto-resolved.'
		end else begin
			print 'Success'
		end
	end
GO


---------------------------------------------

-- dbo.procMEScoreExpansionGetMaxCount
CREATE PROC [dbo].[procMEScoreExpansionGetMaxCount]
	@templateGUID UNIQUEIDENTIFIER,
	@phSectionName NVARCHAR(100),
	@ignoreOverrides bit = 0
AS
	DECLARE @baseCount INT = NULL,
			@ovrCount INT = NULL,
			@baseTemplateGUID UNIQUEIDENTIFIER = @templateGUID;

	IF EXISTS (SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID) BEGIN
		-- find base template guid
		SELECT TOP 1 @baseTemplateGUID = [ParentModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile]	WHERE [ChildModelTemplateGUID] = @templateGUID
	END

	SELECT @baseCount = MAX(E.[Count]) 
	FROM [dbo].[MEScoreExpansion] AS E WITH (READUNCOMMITTED) 
		INNER JOIN [dbo].[viewMECell] AS XC ON E.[ExcelCellGUID] = XC.[CellGUID]
	WHERE E.[GlobalID] = @phSectionName AND XC.[BookGUID] = @baseTemplateGUID

	SELECT @ovrCount = MAX(OVR.[CountOverride]) 
	FROM [dbo].[MEScoreExpansionOverride] AS OVR 
		INNER JOIN [dbo].[MEScoreExpansionProfile] AS P ON P.[ExpansionProfileGUID] = OVR.[ExpansionProfileGUID] 
	WHERE OVR.[ExpansionGlobalID] = @phSectionName AND P.[ChildModelTemplateGUID] = @templateGUID

	IF (@baseCount IS NULL) BEGIN
		SELECT 0
	END ELSE BEGIN
		IF (@ovrCount IS NOT NULL and @ignoreOverrides = 0) BEGIN
			SELECT @ovrCount
		END ELSE BEGIN
			SELECT @baseCount
		END
	END
GO


---------------------------------------------

-- dbo.procMEScoreExpansionProfileApplyOverrides
create proc dbo.procMEScoreExpansionProfileApplyOverrides
	@childMTGUID uniqueidentifier
as
	set nocount on
	
	update SE set SE.Count = OVR.CountOverride
	from
		[dbo].[MEScoreExpansion] SE
		inner join [dbo].[viewMECell] XC on XC.ExcelCellGUID = SE.ExcelCellGUID
		inner join [dbo].[MEScoreExpansionProfile] EP on EP.ChildModelTemplateGUID = XC.ModelTemplateGUID
		inner join [dbo].[MEScoreExpansionOverride] OVR on OVR.ExpansionGlobalID = SE.GlobalID and OVR.ExpansionProfileGUID = EP.ExpansionProfileGUID
	where
		XC.ModelTemplateGUID = @childMTGUID
GO


---------------------------------------------

-- dbo.procMEScoreExpansionProfileDelete
create proc dbo.procMEScoreExpansionProfileDelete
	@profileGUID uniqueidentifier
as
	declare @childMTGUID uniqueidentifier
	select @childMTGUID = ChildModelTemplateGUID from [dbo].[MEScoreExpansionProfile] where ExpansionProfileGUID = @profileGUID

	exec [dbo].[procEMFRemoveTemplateMappings] @childMTGUID

	delete from [dbo].[S3SimplePermission] where LootID in(select MS.ModelSectionGUID from [dbo].[ModelSection] MS inner join [dbo].[EMFModelTemplateWorksheet] WS on WS.WorksheetGUID = MS.SheetGUID where WS.ModelTemplateGUID = @childMTGUID)
	delete from [dbo].[ModelSection] where SheetGUID in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS where WS.ModelTemplateGUID = @childMTGUID)
	delete from [dbo].[MEPHSectionRuleValue] where PHSectionGUID in(select PHS.PHSectionGUID from [dbo].[MEPHSection] PHS where PHS.ModelTemplateGUID = @childMTGUID)
	delete from [dbo].[MEPHSection] where ModelTemplateGUID = @childMTGUID
	delete from [dbo].[MEFillinTemplate] where ModelTemplateGUID = @childMTGUID
	delete from [dbo].[EMFModelTemplateWorksheet] where ModelTemplateGUID = @childMTGUID;
	delete from [dbo].[EMFModelTemplateLinkSource] where ModelTemplateGUID = @childMTGUID;
	delete from [dbo].[DataPathFile_ModelTemplate] where CAST(FullPath as nvarchar(51)) = 'ModelTemplates\' + CAST(@childMTGUID as nvarchar(36));
	delete from [dbo].[EMFModelTemplate] where ModelTemplateGUID = @childMTGUID

	delete from [dbo].[MEScoreExpansionProfile] where ExpansionProfileGUID = @profileGUID
GO


---------------------------------------------

-- dbo.procMEScoreExpansionProfileFitPlans
CREATE PROC [dbo].[procMEScoreExpansionProfileFitPlans]
    @templateGUID UNIQUEIDENTIFIER,
    @planGUIDList NVARCHAR(MAX) = NULL,
    @expansionPadding TINYINT = 10
AS
    SET NOCOUNT ON

    IF EXISTS (SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID)
    BEGIN
        -- we are in the child profile, switch to main template
        SELECT TOP 1 @templateGUID = [ParentModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID
    END
    
    IF EXISTS (SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ParentModelTemplateGUID] = @templateGUID)
    BEGIN

        CREATE TABLE #PossiblePlanToTemplateMap (
            [PlanGUID] UNIQUEIDENTIFIER NOT NULL,
            [ModelTemplateGUID] UNIQUEIDENTIFIER NOT NULL,
            [UsageOrder] INT NOT NULL
        );

        CREATE TABLE #NewPlanToTemplateMap (
            [PlanGUID] UNIQUEIDENTIFIER NOT NULL,
            [ModelTemplateGUID] UNIQUEIDENTIFIER NOT NULL
        );

        -- find all templates for each plan it would fit
        INSERT INTO #PossiblePlanToTemplateMap([PlanGUID], [ModelTemplateGUID], [UsageOrder])
            SELECT 
                P.[PlanGUID],
                M.[ModelTemplateGUID],
                M.[UsageOrder]
            FROM [dbo].[XPlan] AS P
                CROSS APPLY 
                (
                    SELECT [ChildModelTemplateGUID] AS [ModelTemplateGUID], [UsageOrder] FROM [dbo].[MEScoreExpansionProfile] AS SEP WHERE SEP.[ParentModelTemplateGUID] = @templateGUID
                    UNION
                    SELECT @templateGUID AS [ModelTemplateGUID], -1 AS [UsageOrder]
                ) AS M
                LEFT JOIN 
                ( -- plans that don't fit in at least one of any profile's overrides
                        SELECT
                            DISTINCT
                                FC.[PlanGUID] AS [PlanGUID],
                                SEP.[ChildModelTemplateGUID] AS [ModelTemplateGUID]
                        FROM [dbo].[MEScoreExpansionOverride] AS OVR
                            INNER JOIN [dbo].[MEScoreExpansionProfile] AS SEP ON SEP.[ExpansionProfileGUID] = OVR.[ExpansionProfileGUID]
                            INNER JOIN 
                            (
                                SELECT -- fillin counts
                                    P.[PlanGUID],
                                    PHS.[FriendlyName],
                                    P.[ModelTemplateGUID],
                                    SUM(CASE WHEN FI.[FillinGUID] IS NULL THEN 0 ELSE 1 END) AS [FillinCount]
                                FROM [dbo].[XPlan] AS P WITH (READUNCOMMITTED)
                                    INNER JOIN [dbo].[MEPHSection] AS PHS WITH (READUNCOMMITTED) ON PHS.[ModelTemplateGUID] = P.[ModelTemplateGUID]
                                    LEFT JOIN [dbo].[ScoreFillin] AS FI WITH (READUNCOMMITTED) ON FI.[ModelGUID] = P.[PlanGUID] AND FI.[PlaceholderSectionMemberGUID] = PHS.[PHSectionMemberGUID]
                                WHERE
                                    ((P.[ModelTemplateGUID] = @templateGUID) OR (P.[ModelTemplateGUID] IN (SELECT [ChildModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ParentModelTemplateGUID] = @templateGUID)))
                                GROUP BY
                                    P.[PlanGUID],
                                    PHS.[FriendlyName],
                                    P.[ModelTemplateGUID]
                            ) AS FC ON OVR.[ExpansionGlobalID] = FC.[FriendlyName]
                        WHERE
                            ((FC.[FillinCount] + @expansionPadding) > OVR.[CountOverride])
                ) AS DNF ON DNF.[PlanGUID] = P.PlanGUID AND DNF.[ModelTemplateGUID] = M.[ModelTemplateGUID]
            WHERE 
                    ((P.[ModelTemplateGUID] = @templateGUID) OR (P.[ModelTemplateGUID] IN (SELECT [ChildModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ParentModelTemplateGUID] = @templateGUID)))
                AND (DNF.[PlanGUID] IS NULL) -- exclude invalid mapping
                AND ((@planGUIDList IS NULL) OR (P.[PlanGUID] IN (SELECT [guid] FROM [dbo].ConvertCSGuidsToTable(@planGUIDList, ','))));

        -- find the smallest template for each plan
        INSERT INTO #NewPlanToTemplateMap([PlanGUID], [ModelTemplateGUID])
            SELECT
                MAP.[PlanGUID],
                MAP.[ModelTemplateGUID]
            FROM #PossiblePlanToTemplateMap AS MAP
                INNER JOIN 
                (
                    SELECT 
                        M.[PlanGUID], 
                        MAX(M.[UsageOrder]) as [MaxUsageOrder] 
                    FROM #PossiblePlanToTemplateMap AS M 
                    GROUP BY M.[PlanGUID]
                ) AS MAXMAP ON MAXMAP.[PlanGUID] = MAP.[PlanGUID]
                INNER JOIN [dbo].[XPlan] AS EXISTINGPLAN ON EXISTINGPLAN.[PlanGUID] = MAP.[PlanGUID]
            WHERE 
                    MAP.[UsageOrder] = MAXMAP.[MaxUsageOrder] -- the smallest profile
                AND EXISTINGPLAN.[ModelTemplateGUID] <> MAP.[ModelTemplateGUID] -- exclude plans that are already in correct profile
                AND ((@planGUIDList IS NULL) OR (MAP.[PlanGUID] IN (SELECT [guid] FROM [dbo].ConvertCSGuidsToTable(@planGUIDList, ','))));

        IF EXISTS (SELECT TOP 1 1 FROM #NewPlanToTemplateMap)
        BEGIN
            
            -- move plans
            UPDATE P
            SET P.[ModelTemplateGUID] = NP.[ModelTemplateGUID]
            FROM [dbo].[XPlan] AS P
                INNER JOIN #NewPlanToTemplateMap AS NP ON NP.[PlanGUID] = P.[PlanGUID];

            -- move workspace data
            UPDATE IMPR
            SET IMPR.[WorksheetGUID] = NWS.[WORKSHEETGUID]
            FROM 
                [dbo].[MEImprovData] AS IMPR
                INNER JOIN [dbo].[XPlan] AS P ON P.[PlanGUID] = IMPR.[ModelGUID]
                INNER JOIN #NewPlanToTemplateMap AS NP ON NP.[PlanGUID] = P.[PlanGUID]
                INNER JOIN [dbo].[EMFModelTemplateWorksheet] AS WS ON WS.WorksheetGUID = IMPR.WorksheetGUID
                INNER JOIN [dbo].[EMFModelTemplateWorksheet] AS NWS ON NWS.[Name] = WS.[Name] AND NWS.[ModelTemplateGUID] = P.[ModelTemplateGUID]
            WHERE
                WS.[ModelTemplateGUID] <> P.[ModelTemplateGUID];

            -- invalidate cache for the used plans
            DECLARE @usedPlanGUIDList NVARCHAR(MAX) = NULL;
            SELECT @usedPlanGUIDList = ISNULL(@usedPlanGUIDList + ',', '') + CAST([PlanGUID] AS VARCHAR(36)) FROM #NewPlanToTemplateMap
            DECLARE @xplanWhereClause NVARCHAR(MAX) = 'PlanGUID in (SELECT [guid] FROM [dbo].ConvertCSGuidsToTable(''' + @usedPlanGUIDList + ''', '',''))';
            EXEC [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @xplanWhereClause, 0, 'procMEScoreExpansionProfileFitPlans';

        END

        -- cleanup
        DROP TABLE #PossiblePlanToTemplateMap;
        DROP TABLE #NewPlanToTemplateMap;
    
    END

    -- fix fillin templates
    UPDATE X SET X.[FillinTemplateGUID] = CT.[FillinTemplateGUID] FROM [dbo].[XPlan] AS X INNER JOIN [dbo].[MEFillinTemplate] AS PT ON PT.[FillinTemplateGUID] = X.[FillinTemplateGUID] INNER JOIN [dbo].[MEFillinTemplate] AS CT ON CT.[ModelTemplateGUID] = X.[ModelTemplateGUID] AND CT.[ModelTemplateGUID] != PT.[ModelTemplateGUID] AND CT.[Name] = PT.[Name];
    UPDATE X SET X.[FillinTemplateGUID] = [dbo].ZeroGUID() FROM [dbo].[XPlan] AS X WHERE NOT EXISTS(SELECT 1 FROM [dbo].[MEFillinTemplate] AS FI WHERE FI.[FillinTemplateGUID] = X.[FillinTemplateGUID] AND FI.[ModelTemplateGUID] = X.[ModelTemplateGUID]);
    UPDATE X SET X.[FillinTemplateGUID] = FI.[FillinTemplateGUID] FROM [dbo].[XPlan] AS X INNER JOIN [dbo].[MEFillinTemplate] AS FI ON FI.[ModelTemplateGUID] = X.[ModelTemplateGUID] AND FI.[IsDefault] = 1 WHERE X.[FillinTemplateGUID] = [dbo].ZeroGUID();

RETURN
GO


---------------------------------------------

-- dbo.procMEScoreExpansionProfileRecommend
CREATE PROC [dbo].[procMEScoreExpansionProfileRecommend]
    @templateGUID UNIQUEIDENTIFIER
AS
    SET NOCOUNT ON;

    IF EXISTS (SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID)
    BEGIN
        -- we are in the child template, switch to main template
        SELECT TOP 1 @templateGUID = [ParentModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID;
    END

    DECLARE @newProfileWasCreated BIT = 0;
    CREATE TABLE #newScoreExpansionOverrides (
        [ExpansionGlobalID] NVARCHAR(100) NOT NULL,
        [CountOverride] INT NOT NULL
    );

    -- find outlier sections and create overrides
    INSERT INTO #newScoreExpansionOverrides ([ExpansionGlobalID], [CountOverride])
    SELECT
        DISTINCT
            RMC.[SectionName] AS [ExpansionGlobalID],
            RMC.[RecommendedMaxCount] AS [CountOverride]
    FROM [dbo].[TemplateSettings] AS TS
        INNER JOIN [dbo].[MEScoreExpansionRecommendedMaxCount] AS RMC
            ON RMC.[SectionName] = SUBSTRING(TS.[SettingID], 18, LEN(TS.[SettingID]))
    WHERE 1=1 
        AND TS.[TemplateGUID] = @templateGUID
        AND TS.[SettingID] LIKE 'Section Counts%'
        AND RMC.[RecommendedMaxCount] < COALESCE(TS.[Value], 0);

    -- outlier profile must have flag IsOutlier and be the first profile
    DECLARE @outlierProfileGUID UNIQUEIDENTIFIER = (SELECT TOP 1 [ExpansionProfileGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE ([ParentModelTemplateGUID] = @templateGUID) AND ([IsOutlier] = 1) AND ([UsageOrder] = 0));
    DECLARE @removeExistingProfiles BIT = 0;
    
    -- remove all existing profiles if
        -- outlier profile does not exist and there are overrides
        -- outlier profile exists and there no overrides
    IF       (@outlierProfileGUID IS NULL AND EXISTS(SELECT TOP 1 1 FROM #newScoreExpansionOverrides))
        OR (@outlierProfileGUID IS NOT NULL AND NOT EXISTS(SELECT TOP 1 1 FROM #newScoreExpansionOverrides))
    BEGIN
        SET @removeExistingProfiles = 1;
    END

    IF (@removeExistingProfiles = 1) 
    BEGIN
        -- remove all existing profiles
        -- there won't be more than 2-3 profiles
        DECLARE profilesToRemoveCursor CURSOR FAST_FORWARD FOR
            SELECT [ExpansionProfileGUID], [ChildModelTemplateGUID]
            FROM [dbo].[MEScoreExpansionProfile] WITH (READUNCOMMITTED)
            WHERE [ParentModelTemplateGUID] = @templateGUID
            ORDER BY [UsageOrder] DESC;

        DECLARE @currentProfileGUID UNIQUEIDENTIFIER, @currentChildMTGUID UNIQUEIDENTIFIER;

        OPEN profilesToRemoveCursor;
        FETCH NEXT FROM profilesToRemoveCursor INTO @currentProfileGUID, @currentChildMTGUID;
        WHILE(@@FETCH_STATUS = 0)
        BEGIN

            -- move workspace data to Parent template (must be done before removing model template)
            UPDATE IMPR
            SET IMPR.[WorksheetGUID] = NWS.[WORKSHEETGUID]
            FROM [dbo].[MEImprovData] AS IMPR
                INNER JOIN [dbo].[EMFModelTemplateWorksheet] AS WS
                    ON WS.[WorksheetGUID] = IMPR.[WorksheetGUID] AND WS.[ModelTemplateGUID] = @currentChildMTGUID
                INNER JOIN [dbo].[EMFModelTemplateWorksheet] AS NWS
                    ON NWS.[Name] = WS.[Name] AND NWS.[ModelTemplateGUID] = @templateGUID;

            -- delete model template
            EXEC [dbo].[procEMFRemoveTemplateMappings] @currentChildMTGUID, 0;
            DELETE FROM [dbo].[PlanTypeModelTemplateLink] WHERE [ModelTemplateGUID] = @currentChildMTGUID;
            DELETE FROM [dbo].[EMFModelTemplate] WHERE [ModelTemplateGUID] = @currentChildMTGUID;
            DELETE FROM [dbo].[DataPathFile_ModelTemplate] WHERE [FullPath] LIKE ('%' + CAST(@currentChildMTGUID AS NVARCHAR(36)) + '%');

            -- delete expansion profile and overrides
            DELETE FROM [dbo].[MEScoreExpansionOverride] WHERE [ExpansionProfileGUID] = @currentProfileGUID;
            DELETE FROM [dbo].[MEScoreExpansionProfile] WHERE [ExpansionProfileGUID] = @currentProfileGUID;

            -- move all plans to Parent template
            UPDATE [dbo].[XPlan] SET [ModelTemplateGUID] = @templateGUID WHERE [ModelTemplateGUID] = @currentChildMTGUID;

            FETCH NEXT FROM profilesToRemoveCursor INTO @currentProfileGUID, @currentChildMTGUID;
        END
        CLOSE profilesToRemoveCursor;
        DEALLOCATE profilesToRemoveCursor;
    END
    
    -- create outlier profile
    IF EXISTS(SELECT TOP 1 1 FROM #newScoreExpansionOverrides)
    BEGIN
        IF (@outlierProfileGUID IS NOT NULL) -- there is existing outlier profile: update existing overrides
        BEGIN
            -- remove existing overrides
            DELETE FROM [dbo].[MEScoreExpansionOverride] WHERE [ExpansionProfileGUID] = @outlierProfileGUID;

            -- add new overrides
            INSERT INTO [dbo].[MEScoreExpansionOverride] ([ExpansionProfileGUID], [ExpansionGlobalID], [CountOverride])
                SELECT @outlierProfileGUID, [ExpansionGlobalID], [CountOverride] FROM #newScoreExpansionOverrides;

            -- move all plans to Parent template
            DECLARE @childMTGUID UNIQUEIDENTIFIER = (SELECT TOP 1 [ChildModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ExpansionProfileGUID] = @outlierProfileGUID)
            UPDATE [dbo].[XPlan] SET [ModelTemplateGUID] = @templateGUID WHERE [ModelTemplateGUID] = @childMTGUID;

            PRINT 'Outlier profile updated!';
        END
        ELSE
        BEGIN
            -- create new outlier profile
            SET @outlierProfileGUID = NEWID();

            -- outlier profile is always Profile 1
            INSERT INTO [dbo].[MEScoreExpansionProfile] ([ExpansionProfileGUID], [ParentModelTemplateGUID], [Name], [UsageOrder], [IsOutlier]) 
                SELECT @outlierProfileGUID, @templateGUID, 'Profile 1', 0, 1;

            -- add overrides for outlier profile
            INSERT INTO [dbo].[MEScoreExpansionOverride] ([ExpansionProfileGUID], [ExpansionGlobalID], [CountOverride])
                SELECT @outlierProfileGUID, [ExpansionGlobalID], [CountOverride] FROM #newScoreExpansionOverrides;

            SET @newProfileWasCreated = 1;

            PRINT 'Outlier profile created!';
        END
    END

    -- disable/enable NM for parent template
    DECLARE @isNativeModelingEnabled BIT = (SELECT TOP 1 [Value] FROM [ob].[SystemSetting] WHERE [Name] = 'Native Modeling Enabled')

    IF (@isNativeModelingEnabled = 1)
    BEGIN
        IF (((SELECT TOP 1 [ExpansionProfileGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE ([ParentModelTemplateGUID] = @templateGUID) AND ([IsOutlier] = 1) AND ([UsageOrder] = 0)) IS NULL) OR exists(select 1 from [ob].[SystemSetting] where [Name] = 'Native Modeling Limits Enabled' and [Value] = '0'))
        BEGIN
            UPDATE [dbo].[EMFModelTemplate] SET [IsModelWorkbookCachable] = 1, [IsMemoryCachable] = 1 WHERE [ModelTemplateGUID] = @templateGUID;
        END
        ELSE 
        BEGIN
            EXEC [dbo].[procInvalidateModelWorkbookCache] @templateGUID, 1, 0, 'procMENativeModelingDisable'; 
            UPDATE [dbo].[EMFModelTemplate] SET [IsModelWorkbookCachable] = 0, [IsMemoryCachable] = 0 WHERE [ModelTemplateGUID] = @templateGUID;
        END
    END

    -- create normal profile if needed

    -- clear temp table
    DELETE FROM #newScoreExpansionOverrides;

    -- find overrides for new profile
    INSERT INTO #newScoreExpansionOverrides ([ExpansionGlobalID], [CountOverride])
    SELECT
        DISTINCT
            [ExpansionGlobalID],
            [CountOverride]
    FROM
        [dbo].[viewMEPHSectionAnalysisRecommendation]
    WHERE 
        ModelTemplateGUID = @templateGUID;
        
    -- create profile
    IF EXISTS(SELECT TOP 1 1 FROM #newScoreExpansionOverrides)
    BEGIN
        DECLARE @newProfileGUID UNIQUEIDENTIFIER = NEWID();
        DECLARE @newProfileUsageOrder INT = (SELECT COUNT(*) FROM [dbo].[MEScoreExpansionProfile] WHERE [ParentModelTemplateGUID] = @templateGUID);

        -- create profile
        INSERT INTO [dbo].[MEScoreExpansionProfile] ([ExpansionProfileGUID], [ParentModelTemplateGUID], [Name], [UsageOrder], [IsOutlier]) 
            SELECT @newProfileGUID, @templateGUID, 'Profile ' + CAST((@newProfileUsageOrder + 1) AS NVARCHAR(2)), @newProfileUsageOrder, 0;

        -- create overrides
        INSERT INTO [dbo].[MEScoreExpansionOverride] ([ExpansionProfileGUID], [ExpansionGlobalID], [CountOverride])
            SELECT @newProfileGUID, [ExpansionGlobalID], [CountOverride] FROM #newScoreExpansionOverrides;

        SET @newProfileWasCreated = 1;

        PRINT 'New profile created!';
    END

    -- drop temp table
    DROP TABLE #newScoreExpansionOverrides;

    -- sync templates
    IF (@newProfileWasCreated = 1)
    BEGIN
        -- build out the new template for this profile so we can apply plans to it
        EXEC [dbo].[procMEScoreExpansionProfileSyncTemplates] @templateGUID, 0, 0;
    END
GO


---------------------------------------------

-- dbo.procMEScoreExpansionProfileSyncTemplates
CREATE proc [dbo].[procMEScoreExpansionProfileSyncTemplates]
	@parentMTGUID uniqueidentifier,
	@isPreservingChildMappings bit = 1,
	@isPreservingNavSections bit = 1
as
	set nocount on
	
	declare @profileGUID uniqueidentifier
	declare @childMTGUID uniqueidentifier
	declare @nativeModelingEnabled bit = (select top 1 [Value] from [ob].[SystemSetting] where Name = 'Native Modeling Enabled')
	declare crsProfiles cursor fast_forward for select ExpansionProfileGUID, ChildModelTemplateGUID from [dbo].[MEScoreExpansionProfile] where ParentModelTemplateGUID = @parentMTGUID order by UsageOrder

	open crsProfiles
	fetch next from crsProfiles into @profileGUID, @childMTGUID

	while(@@fetch_status = 0) begin
		if (@childMTGUID = dbo.ZeroGUID()) begin
			if (@isPreservingChildMappings = 1) begin
				--template files incorrectly won't get created in this case, so skip
				print 'Invalid parameter value: isPreservingChildMappings'
				return
			end
		
			--child template missing, add new
			select @childMTGUID = newid()
			update [dbo].[MEScoreExpansionProfile] set ChildModelTemplateGUID = @childMTGUID where ExpansionProfileGUID = @profileGUID

			--add template
			insert into [dbo].[EMFModelTemplate] ([ModelTemplateGUID], [Name], [Description], [Type], [IsPublished], [IsExpanded], [IsSafeModeOn], [DefaultFormGUID], [IsNewLabelsOnly], [IsUsingHashJoin], [IsScoreFillinAdvancedMode], [IsModelWorkbookCachable], [HasModelDependents], [IsModelRefreshOnFillinChange], [IsReadUncommittedLoad], [IsReadUncommittedSave], [IsMemoryCachable], [PublishOrder], [EditExpansionsMode], [TemplateVersion], [IsUsingOpenWorkbookFormat], [IsHidden])
			select @childMTGUID, MT.Name + ' (' + EP.Name + ')', 'Expansion Profile of ' + MT.[Name], MT.[Type], MT.[IsPublished], MT.[IsExpanded], MT.[IsSafeModeOn], MT.[DefaultFormGUID], MT.[IsNewLabelsOnly], MT.[IsUsingHashJoin], MT.[IsScoreFillinAdvancedMode], @nativeModelingEnabled, MT.[HasModelDependents], MT.[IsModelRefreshOnFillinChange], MT.[IsReadUncommittedLoad], MT.[IsReadUncommittedSave], @nativeModelingEnabled, MT.[PublishOrder], MT.[EditExpansionsMode], MT.[TemplateVersion], MT.[IsUsingOpenWorkbookFormat], cast(1 as bit)
			from [dbo].[EMFModelTemplate] MT inner join [dbo].[MEScoreExpansionProfile] EP on EP.ParentModelTemplateGUID = MT.ModelTemplateGUID and EP.ChildModelTemplateGUID = @childMTGUID
			where ModelTemplateGUID = @parentMTGUID
			
			--link template to plantype
			insert into [dbo].[PlanTypeModelTemplateLink] (PlanTypeGUID, ModelTemplateGUID) select PlanTypeGUID, @childMTGUID from [dbo].[PlanTypeModelTemplateLink] where ModelTemplateGUID = @parentMTGUID
			
		end else begin
			--child template exists, first clear mappings
			if (@isPreservingChildMappings = 0) begin
				exec [dbo].[procEMFRemoveTemplateMappings] @childMTGUID, 0
			end
			
			--sync template
			update CMT 
			set 
				CMT.Name = PMT.Name + ' (' + EP.Name + ')',
				CMT.DefaultFormGUID = PMT.DefaultFormGUID,
				CMT.IsScoreFillinAdvancedMode = PMT.IsScoreFillinAdvancedMode, 
				CMT.IsModelWorkbookCachable = @nativeModelingEnabled, 
				CMT.HasModelDependents = PMT.HasModelDependents, 
				CMT.IsModelRefreshOnFillinChange = PMT.IsModelRefreshOnFillinChange, 
				CMT.IsReadUncommittedLoad = PMT.IsReadUncommittedLoad, 
				CMT.IsReadUncommittedSave = PMT.IsReadUncommittedSave, 
				CMT.IsMemoryCachable = @nativeModelingEnabled,
				CMT.EditExpansionsMode = PMT.EditExpansionsMode,
				CMT.TemplateVersion = PMT.TemplateVersion,
				CMT.IsUsingOpenWorkbookFormat = PMT.IsUsingOpenWorkbookFormat,
				CMT.IsHidden = 1
			from
				[dbo].[EMFModelTemplate] CMT
				inner join [dbo].[MEScoreExpansionProfile] EP on EP.ChildModelTemplateGUID = CMT.ModelTemplateGUID
				inner join [dbo].[EMFModelTemplate] PMT on PMT.ModelTemplateGUID = EP.ParentModelTemplateGUID
			where
				CMT.ModelTemplateGUID = @childMTGUID

			--remove deleted fillin templates from the child also
			delete from [dbo].[MEFillinTemplate] where ModelTemplateGUID = @childMTGUID and Name not in(select pfit.Name from [dbo].[MEFillinTemplate] pfit where pfit.ModelTemplateGUID = @parentMTGUID);

			--remove other info so we can re-add latest from parent
			if (@isPreservingNavSections = 0) begin
				delete from [dbo].[S3SimplePermission] where LootID in(select MS.ModelSectionGUID from [dbo].[ModelSection] MS inner join [dbo].[EMFModelTemplateWorksheet] WS on WS.WorksheetGUID = MS.SheetGUID where WS.ModelTemplateGUID = @childMTGUID)
				delete from [dbo].[S3SimplePermission] where LootID in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS where WS.ModelTemplateGUID = @childMTGUID)
				delete from [dbo].[ModelSection] where SheetGUID in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS where WS.ModelTemplateGUID = @childMTGUID)
			end
			delete from [dbo].[ModelSection] where SheetGUID not in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS)
			delete from [dbo].[MEPHSectionRuleValue] where PHSectionGUID in(select PHS.PHSectionGUID from [dbo].[MEPHSection] PHS where PHS.ModelTemplateGUID = @childMTGUID)
			delete from [dbo].[MEPHSection] where ModelTemplateGUID = @childMTGUID
			if (@isPreservingChildMappings = 0) begin
				delete from [dbo].[EMFModelTemplateWorksheet] where ModelTemplateGUID = @childMTGUID;
				delete from [dbo].[EMFModelTemplateLinkSource] where ModelTemplateGUID = @childMTGUID;
				delete from [dbo].[DataPathFile_ModelTemplate] where CAST(FullPath as nvarchar(51)) = 'ModelTemplates\' + CAST(@childMTGUID as nvarchar(36));
			end
		end
		
		if (@isPreservingChildMappings = 0) begin
			--add worksheets
			insert into [dbo].[EMFModelTemplateWorksheet] ([WorksheetGUID], [ModelTemplateGUID], [Name], [DesignerMetaData], [TransformStateGUID], [IsImprov], [IsHiddenOnExpand], [HiddenRows], [HiddenColumns], [IsHeadingsHiddenOnExpand], [ZoomLevel], [IsChartsEnabled], [NameSourceAddress], [DefaultCellAddress], [FreezePanesCellAddress], [IsDefaultSheet], [CounterCellAddress], [CloneCount], [IsClearingByNameCell])
			select newid(), @childMTGUID, [Name], [DesignerMetaData], [TransformStateGUID], [IsImprov], [IsHiddenOnExpand], [HiddenRows], [HiddenColumns], [IsHeadingsHiddenOnExpand], [ZoomLevel], [IsChartsEnabled], [NameSourceAddress], [DefaultCellAddress], [FreezePanesCellAddress], [IsDefaultSheet], [CounterCellAddress], [CloneCount], [IsClearingByNameCell]
			from [dbo].[EMFModelTemplateWorksheet]
			where ModelTemplateGUID =  @parentMTGUID

			--duplicate improv data cannot be handled, so remove it
			delete i
			from 
				MEImprovData i
				inner join ob.viewDimDepartmentalBudget b on b.MemberGUID = i.ModelGUID
				inner join dbo.XPlan p on p.PlanGUID = b.MemberGUID
			where
				p.ModelTemplateGUID in(@childMTGUID, @parentMTGUID)
				and i.ModelGUID in(select sq.modelguid from (select distinct id.modelguid, id.worksheetguid from MEImprovData id group by id.modelguid, id.worksheetguid) sq group by sq.modelguid having count(*) > 1);

			--fix any remaining orphan improv data
			update i set i.WorksheetGUID = ws.WorksheetGUID
			from 
				MEImprovData i
				inner join ob.viewDimDepartmentalBudget b on b.MemberGUID = i.ModelGUID
				inner join dbo.XPlan p on p.PlanGUID = b.MemberGUID
				inner join dbo.EMFModelTemplateWorksheet ws on ws.ModelTemplateGUID = p.ModelTemplateGUID and ws.Name = 'Workspace'
			where
				p.ModelTemplateGUID in(@childMTGUID, @parentMTGUID)
				and i.WorksheetGUID != ws.WorksheetGUID;
				
			--add link sources
			insert into [dbo].[EMFModelTemplateLinkSource] ([LinkSourceGUID], [Name], [ModelTemplateGUID], [ParentSubtableGUID], [ParentModelDataConfigGUID], [ParentScoreCompositeTableGUID], [IsSelf])
			select newid(), [Name], @childMTGUID, [ParentSubtableGUID], [ParentModelDataConfigGUID], [ParentScoreCompositeTableGUID], [IsSelf]
			from [dbo].[EMFModelTemplateLinkSource]
			where ModelTemplateGUID = @parentMTGUID

			--add template files
			insert into [dbo].[DataPathFile_ModelTemplate] ([FileGUID], [FullPath], [FileName], [CreationTime], [LastModifiedTime], [Data], [IsLocked])
			select newid(), replace([FullPath], cast(@parentMTGUID as nvarchar(36)), cast(@childMTGUID as nvarchar(36))), replace([FileName], cast(@parentMTGUID as nvarchar(36)), cast(@childMTGUID as nvarchar(36))), getdate(), getdate(), [Data], 0
			from [dbo].[DataPathFile_ModelTemplate]
			where FullPath like 'ModelTemplates\%' and CAST(FullPath as nvarchar(51)) = 'ModelTemplates\' + CAST(@parentMTGUID as nvarchar(36))
		end

		--add ph sections
		insert into [dbo].[MEPHSection] ([PHSectionGUID], [ModelTemplateGUID], [PHSectionDimensionGUID], [PHSectionMemberGUID], [PlanTypeGUID], [FriendlyName], [SortType], [IsConstantIndex], [RootHierarchyPath], [DefaultHierarchyPath], [IsAppend], [IsHidden], [IsReadOnly], [IsExclusive], [RuleType], [IsOneTime], [IsClearOnRefresh], [ExclusivityGroup], [IsOrderByName], [IsOrderByNameSkippingCode])
		select newid(), @childMTGUID, [PHSectionDimensionGUID], [PHSectionMemberGUID], [PlanTypeGUID], [FriendlyName], [SortType], [IsConstantIndex], [RootHierarchyPath], [DefaultHierarchyPath], [IsAppend], [IsHidden], [IsReadOnly], [IsExclusive], [RuleType], [IsOneTime], [IsClearOnRefresh], [ExclusivityGroup], [IsOrderByName], [IsOrderByNameSkippingCode]
		from [dbo].[MEPHSection]
		where ModelTemplateGUID = @parentMTGUID
		
		--add new fillin templates
		insert into [dbo].[MEFillinTemplate] ([FillinTemplateGUID], [Name], [ModelTemplateGUID], [IsDefault])
		select newid(), fit.[Name], @childMTGUID, fit.[IsDefault]
		from [dbo].[MEFillinTemplate] fit
		where fit.ModelTemplateGUID = @parentMTGUID
		and not exists(select 1 from [dbo].[MEFillinTemplate] ex where ex.ModelTemplateGUID = @childMTGUID and ex.Name = fit.Name)
		
		--fix fillin template on existing plans
		update XP set XP.FillinTemplateGUID = dbo.ZeroGUID() from [dbo].[XPlan] XP where XP.FillinTemplateGUID != dbo.ZeroGUID() and XP.FillinTemplateGUID not in(select FT.FillinTemplateGUID from [dbo].[MEFillinTemplate] FT where FT.ModelTemplateGUID = XP.ModelTemplateGUID);
		update XP set XP.FillinTemplateGUID = FT.FillinTemplateGUID from [dbo].[XPlan] XP inner join [dbo].[MEFillinTemplate] FT on FT.ModelTemplateGUID = XP.ModelTemplateGUID and FT.IsDefault = 1 where XP.FillinTemplateGUID = dbo.ZeroGUID();
		
		--add ph section rules
		insert into [dbo].[MEPHSectionRuleValue] ([PHSectionRuleValueGUID], [PHSectionGUID], [RuleValueKey], [RuleValue], [SortOrder], [FillinTemplateGUID])
		select newid(), CPHS.[PHSectionGUID], RV.[RuleValueKey], RV.[RuleValue], RV.[SortOrder], isnull(CFT.[FillinTemplateGUID], dbo.ZeroGUID())
		from 
			[dbo].[MEPHSectionRuleValue] RV
			inner join [dbo].[MEPHSection] PPHS on PPHS.PHSectionGUID = RV.PHSectionGUID
			inner join [dbo].[MEPHSection] CPHS on PPHS.PHSectionMemberGUID = CPHS.PHSectionMemberGUID and PPHS.IsHidden = CPHS.IsHidden and CPHS.ModelTemplateGUID = @childMTGUID
			left join [dbo].[MEFillinTemplate] PFT on PFT.FillinTemplateGUID = RV.FillinTemplateGUID
			left join [dbo].[MEFillinTemplate] CFT on CFT.Name = PFT.Name and CFT.ModelTemplateGUID = @childMTGUID
		where PPHS.ModelTemplateGUID = @parentMTGUID

		--fix ph section rule values (for rules that reference other ph sections, like union rule)
		update CRV set CRV.RuleValue = cast(CPHS.PHSectionGUID as nvarchar(36))
		from 
			[dbo].[MEPHSectionRuleValue] CRV
			inner join [dbo].[MEPHSection] PPHS on cast(PPHS.PHSectionGUID as nvarchar(36)) = CRV.RuleValue and PPHS.ModelTemplateGUID = @parentMTGUID
			inner join [dbo].[MEPHSection] CPHS on PPHS.PHSectionMemberGUID = CPHS.PHSectionMemberGUID and PPHS.IsHidden = CPHS.IsHidden and CPHS.ModelTemplateGUID = @childMTGUID
		where
			exists (select 1 from [dbo].[MEPHSection] CP where CP.PHSectionGUID = CRV.PHSectionGUID and CP.ModelTemplateGUID = @childMTGUID)
			
		--add model sections
		if ((@isPreservingNavSections = 0) or (not exists(select 1 from [dbo].[ModelSection] where SheetGUID in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS where WS.ModelTemplateGUID = @childMTGUID)))) begin
			insert into [dbo].[ModelSection] ([ModelSectionGUID], [Name], [Range], [Address], [SheetGUID], [ParentGUID], [SortOrder], [IsInherit], [IsHidden])
			select newid(), MS.[Name], MS.[Range], MS.[Address], CWS.WorksheetGUID, MS.[ParentGUID], MS.[SortOrder], MS.[IsInherit], MS.[IsHidden]
			from 
				[dbo].[ModelSection] MS
				inner join [dbo].[EMFModelTemplateWorksheet] PWS on PWS.WorksheetGUID = MS.SheetGUID
				inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.Name = PWS.Name and CWS.ModelTemplateGUID = @childMTGUID
			where PWS.ModelTemplateGUID = @parentMTGUID
		
			--fix model section parents
			update CMS set CMS.ParentGUID = CP.ModelSectionGUID
			from
				[dbo].[ModelSection] CMS
				inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.WorksheetGUID = CMS.SheetGUID
				inner join [dbo].[ModelSection] PP on PP.ModelSectionGUID = CMS.ParentGUID
				inner join [dbo].[ModelSection] CP on CP.Address = PP.Address and CP.SheetGUID = CMS.SheetGUID
			where
				CWS.ModelTemplateGUID = @childMTGUID;
			update CMS set CMS.ParentGUID = CMS.SheetGUID
			from
				[dbo].[ModelSection] CMS
				inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.WorksheetGUID = CMS.SheetGUID
			where
				CWS.ModelTemplateGUID = @childMTGUID
				and CMS.ParentGUID in(select PWS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] PWS where PWS.ModelTemplateGUID = @parentMTGUID);
				
			--add model section security
			insert into [dbo].[S3SimplePermission] (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
			select CMS.ModelSectionGUID, PSP.IdentityGUID, PSP.ReadValue, PSP.WriteValue, PSP.SecureValue
			from 
				[dbo].[ModelSection] MS
				inner join [dbo].[EMFModelTemplateWorksheet] PWS on PWS.WorksheetGUID = MS.SheetGUID
				inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.Name = PWS.Name and CWS.ModelTemplateGUID = @childMTGUID
				inner join [dbo].[ModelSection] CMS on CMS.Address = MS.Address and CMS.SheetGUID = CWS.WorksheetGUID
				inner join [dbo].[S3SimplePermission] PSP on PSP.LootID = MS.ModelSectionGUID
			where PWS.ModelTemplateGUID = @parentMTGUID

			--add model sheet security
			insert into [dbo].[S3SimplePermission] (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
			select CWS.WorksheetGUID, PSP.IdentityGUID, PSP.ReadValue, PSP.WriteValue, PSP.SecureValue
			from 
				[dbo].[EMFModelTemplateWorksheet] PWS
				inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.Name = PWS.Name and CWS.ModelTemplateGUID = @childMTGUID
				inner join [dbo].[S3SimplePermission] PSP on PSP.LootID = PWS.WorksheetGUID
			where PWS.ModelTemplateGUID = @parentMTGUID
		end

		fetch next from crsProfiles into @profileGUID, @childMTGUID
	end

	close crsProfiles
	deallocate crsProfiles

	declare @higuid uniqueidentifier
	exec procLogScript 'Sync Expansion Profiles' , @higuid output
GO


---------------------------------------------

-- dbo.procMEScoreExpansionProfileSyncTemplatesAll
CREATE proc dbo.procMEScoreExpansionProfileSyncTemplatesAll
	@isPreservingChildMappings bit = 1,
	@isPreservingNavSections bit = 1
as
	declare @mtGUID uniqueidentifier
	declare crsTemplates cursor fast_forward for select distinct ParentModelTemplateGUID from [dbo].[MEScoreExpansionProfile]
	
	open crsTemplates
	fetch next from crsTemplates into @mtGUID
	
	while(@@fetch_status = 0) begin
		exec [dbo].[procMEScoreExpansionProfileSyncTemplates] @mtGUID, @isPreservingChildMappings, @isPreservingNavSections
	
		fetch next from crsTemplates into @mtGUID
	end
	
	close crsTemplates
	deallocate crsTemplates
GO


---------------------------------------------

-- dbo.procMigrateScriptGet
CREATE proc [dbo].[procMigrateScriptGet]
	@schema nvarchar(8),
	@sourcedb nvarchar(100)
as
	declare @tableName nvarchar(100)
	declare crsTables cursor for select name from sys.tables where schema_id in(select schema_id from sys.schemas where name = @schema)

	open crsTables
	fetch next from crsTables into @tableName

	declare @migratesql nvarchar(max)

	while(@@FETCH_STATUS = 0) begin
		exec procMigrateScriptGetByTable @schema, @sourcedb, @tableName
		
		fetch next from crsTables into @tableName
	end

	close crsTables
	deallocate crsTables
GO


---------------------------------------------

-- dbo.procMigrateScriptGetByDimension
create proc [dbo].[procMigrateScriptGetByDimension]
	@schema nvarchar(16),
	@sourcedb nvarchar(100),
	@tableName nvarchar(100),
	@whereClause nvarchar(4000) = '',
	@isExecuting bit = 0
as
	if((select count(*) from sys.tables where name = @tableName and schema_id in(select schema_id from sys.schemas where name = @schema)) = 0) begin
		RAISERROR ('Destination table not found.', 18, 0)
		return
	end

	declare @tableId int
	select @tableId = object_id from sys.tables where name = @tableName and schema_id in(select schema_id from sys.schemas where name = @schema)

	declare @migratesql nvarchar(max)
	set @migratesql = ''

	declare @identName nvarchar(100)
	select @identName = name from sys.identity_columns where object_id = @tableId

	declare @columnName nvarchar(100)

	set @migratesql = @migratesql + 'insert into [' + @schema + '].[' + @tableName + '] (MemberGUID,'
	
	declare crsColumns1 cursor for select name from sys.columns where object_id = @tableId and system_type_id != 189 and is_computed = 0 and name !=  @identName and name != 'MemberGUID'
	open crsColumns1
	fetch next from crsColumns1 into @columnName
	while(@@FETCH_STATUS = 0) begin
		set @migratesql = @migratesql + '[' + @columnName + '],'
		fetch next from crsColumns1 into @columnName
	end
	close crsColumns1
	deallocate crsColumns1
	
	set @migratesql = LEFT(@migratesql, len(@migratesql) - 1) + ') 
select (case when MemberGUID in(select ex.MemberGUID from [' + @schema + '].[' + @tableName + '] ex) then newid() else MemberGUID end) as MemberGUID, '

	declare crsColumns2 cursor for select name from sys.columns where object_id = @tableId and system_type_id != 189 and is_computed = 0 and name !=  @identName and name != 'MemberGUID'
	open crsColumns2
	fetch next from crsColumns2 into @columnName
	while(@@FETCH_STATUS = 0) begin
		set @migratesql = @migratesql + '[' + @columnName + '],'
		fetch next from crsColumns2 into @columnName
	end
	close crsColumns2
	deallocate crsColumns2
	
	set @migratesql = LEFT(@migratesql, len(@migratesql) - 1) + ' 
from ' + @sourcedb + '.[' + @schema + '].['
	set @migratesql = @migratesql + @tableName + ']
'


	--prevent dupes
	if(@migratesql not like '%where %') begin
		set @migratesql = @migratesql + 'where '
	end else begin
		set @migratesql = @migratesql + ' and '
	end
	set @migratesql = @migratesql + 'Name not in(select Name from [' + @schema + '].[' + @tableName + '])'
	
	--add optional where clause
	if(@whereClause != '') begin
		if(@migratesql not like '%where %') begin
			set @migratesql = @migratesql + 'where '
		end else begin
			set @migratesql = @migratesql + ' and '
		end
		set @migratesql = @migratesql + @whereClause + '
'
	end else begin
		set @migratesql = @migratesql + '
'
	end
	
	set @migratesql = @migratesql + '
'
	
	if(@isExecuting = 1) begin
		exec(@migratesql)
	end else begin
		print @migratesql
	end
GO


---------------------------------------------

-- dbo.procMigrateScriptGetByTable
CREATE proc [dbo].[procMigrateScriptGetByTable]
	@schema nvarchar(16),
	@sourcedb nvarchar(100),
	@tableName nvarchar(100),
	@whereClause nvarchar(4000) = '',
	@isExecuting bit = 0,
	@isFromView bit = 0,
	@isTestingIndexes bit = 1,
	@isTestingPrimaryKeys bit = 1
as
	if((select count(*) from sys.tables where name = @tableName and schema_id in(select schema_id from sys.schemas where name = @schema)) = 0) begin
		RAISERROR ('Destination table not found.', 18, 0)
		return
	end

	declare @tableId int
	select @tableId = object_id from sys.tables where name = @tableName and schema_id in(select schema_id from sys.schemas where name = @schema)

	declare @migratesql nvarchar(max)
	set @migratesql = ''

	declare @columnName nvarchar(100)

	--identity insert on if contains identity column
	if((select COUNT(*) from sys.identity_columns where object_id = @tableId) > 0) begin
		set @migratesql = @migratesql + 'set identity_insert [' + @schema + '].[' + @tableName + '] on
'
	end
	
	--truncate fact tables
	if(left(@tableName, 4) = 'Fact') begin
		set @migratesql = @migratesql + 'truncate table [' + @schema + '].[' + @tableName + ']
'
	end
	
	set @migratesql = @migratesql + 'insert into [' + @schema + '].[' + @tableName + '] ('
	
	declare crsColumns1 cursor for select name from sys.columns where object_id = @tableId and system_type_id != 189 and is_computed = 0
	open crsColumns1
	fetch next from crsColumns1 into @columnName
	while(@@FETCH_STATUS = 0) begin
		set @migratesql = @migratesql + '[' + @columnName + '],'
		fetch next from crsColumns1 into @columnName
	end
	close crsColumns1
	deallocate crsColumns1
	
	set @migratesql = LEFT(@migratesql, len(@migratesql) - 1) + ') 
select '

	declare crsColumns2 cursor for select name from sys.columns where object_id = @tableId and system_type_id != 189 and is_computed = 0
	open crsColumns2
	fetch next from crsColumns2 into @columnName
	while(@@FETCH_STATUS = 0) begin
		set @migratesql = @migratesql + '[' + @columnName + '],'
		fetch next from crsColumns2 into @columnName
	end
	close crsColumns2
	deallocate crsColumns2
	
	set @migratesql = LEFT(@migratesql, len(@migratesql) - 1) + ' 
from ' + @sourcedb + '.[' + @schema + '].['
	if(@isFromView = 1) begin
		set @migratesql = @migratesql + 'view'
	end
	set @migratesql = @migratesql + @tableName + ']
'

	--prevent dupes
	declare @keyname nvarchar(64)
	declare crsUniqueKeys cursor for
		select
			c.name
		from
			sys.columns c
			inner join sys.index_columns ic on ic.object_id = c.object_id and ic.column_id = c.column_id
			inner join sys.indexes i on i.index_id = ic.index_id and i.object_id = ic.object_id
			inner join sys.key_constraints kc on kc.name = i.name
			inner join sys.tables t on t.object_id = kc.parent_object_id
		where
			i.is_unique = 1
			and ((i.name like 'PK_%' and @isTestingPrimaryKeys = 1) or @isTestingIndexes = 1)
			and t.object_id = @tableId
	open crsUniqueKeys
	fetch next from crsUniqueKeys into @keyname
	while(@@FETCH_STATUS = 0) begin
		if(@migratesql not like '%where %') begin
			set @migratesql = @migratesql + 'where '
		end else begin
			set @migratesql = @migratesql + ' and '
		end
		set @migratesql = @migratesql + @keyname + ' not in(select ' + @keyname + ' from [' + @schema + '].[' + @tableName + '])'

		fetch next from crsUniqueKeys into @keyname
	end
	close crsUniqueKeys
	deallocate crsUniqueKeys
	
	--add optional where clause
	if(@whereClause != '') begin
		if(@migratesql not like '%where %') begin
			set @migratesql = @migratesql + 'where '
		end else begin
			set @migratesql = @migratesql + ' and '
		end
		set @migratesql = @migratesql + @whereClause + '
'
	end else begin
		set @migratesql = @migratesql + '
'
	end
	
	--identity insert off
	if((select COUNT(*) from sys.identity_columns where object_id = @tableId) > 0) begin
		set @migratesql = @migratesql + 'set identity_insert [' + @schema + '].[' + @tableName + '] off
'
	end

	set @migratesql = @migratesql + '
'
	
	if(@isExecuting = 1) begin
		exec(@migratesql)
	end else begin
		print @migratesql
	end
GO


---------------------------------------------

-- dbo.procMigrateScriptGetByTableComparison
CREATE proc [dbo].[procMigrateScriptGetByTableComparison]
	@schema nvarchar(16),
	@sourcedb nvarchar(100),
	@tableName nvarchar(100),
	@whereClause nvarchar(4000) = '',
	@isExecuting bit = 0,
	@isFromView bit = 0,
	@isTestingIndexes bit = 1,
	@isTestingPrimaryKeys bit = 1	
as

-------------------------
			--Post Comparison of table copies across DBs
			--Output: Target Count to bring over, Table, Resulting Count
			--see [dbo].[procSyncEMFDimensionWithScore] for messaging stuff
-------------------------


declare @sourcecomparesql nvarchar(max)
set @sourcecomparesql = ''
	if(@isFromView = 1) begin
		set @sourcecomparesql = @sourcecomparesql + 'select count(*) as srccount from ' + @sourcedb + '.[' + @schema + '].[view' + @tablename + ']'
	end else begin
		set @sourcecomparesql = @sourcecomparesql + 'select count(*) as srccount from ' + @sourcedb + '.[' + @schema + '].[' + @tablename + ']'
	end


--declare @targetcomparesql nvarchar(max)
--set @targetcomparesql = ''
--	if(@isFromView = 1) begin
--		set @targetcomparesql = @targetcomparesql + 'select count(*) as tgtcount from [' + @@servername + '].[' + DB_NAME() + '].[' + @schema + '].[view' + @tablename + ']'
--	end else begin	
--		set @targetcomparesql = @targetcomparesql + 'select count(*) as tgtcount from [' + @@servername + '].[' + DB_NAME() + '].[' + @schema + '].[' + @tablename + ']'
--	end
	
		
declare @targetcomparesql nvarchar(max)
set @targetcomparesql = ''
	if(@isFromView = 1) begin
		set @targetcomparesql = @targetcomparesql + 'select count(*) as tgtcount from [' + @schema + '].[view' + @tablename + ']'
	end else begin	
		set @targetcomparesql = @targetcomparesql + 'select count(*) as tgtcount from [' + @schema + '].[' + @tablename + ']'
	end	



 ----Handle Blank Where Clause - sourcesql
 if(@whereClause != '') begin
			set @sourcecomparesql = @sourcecomparesql + ' where ' + @whereclause			
		end else begin
			set @sourcecomparesql = @sourcecomparesql			
end

 ----Handle Blank Where Clause - targetsql
 if(@whereClause != '') begin
			set @targetcomparesql = @targetcomparesql + ' where ' + @whereclause			
		end else begin
			set @targetcomparesql = @targetcomparesql			
end


declare @comparisonsql nvarchar(max)
set @comparisonsql = ''
set @comparisonsql = 'select tgtcount - srccount from ('
	+ @sourcecomparesql + ') src left join (' + @targetcomparesql + ') tgt on 1 = 1'


--print @sourcecomparesql
--print @targetcomparesql
--print @comparisonsql


	if(@isExecuting = 1) begin
		exec(@comparisonsql)
	end else begin
		select @sourcecomparesql = REPLACE(@sourcecomparesql, 'count(*) as srccount', '*')
		select @targetcomparesql = REPLACE(@targetcomparesql, 'count(*) as tgtcount', '*')
		print @comparisonsql
		print @sourcecomparesql
		print @targetcomparesql
	end
GO


---------------------------------------------

-- dbo.procMigrateScriptUpdateAttributeGUID
CREATE proc [dbo].[procMigrateScriptUpdateAttributeGUID]
	@sourcedb nvarchar(500),
	@attributeGuidNew uniqueidentifier,
	@attributeGuidOld uniqueidentifier
as
	DECLARE @resultTable table(Query nvarchar(max))

	DECLARE @migratesqlDropFK table(query nvarchar(max))
	DECLARE @migratesqlCreateFK table(query nvarchar(max))
	DECLARE @migratesqlCreateFKTable table(query nvarchar(max))

	DECLARE @fKName nvarchar(400), @tableName nvarchar(200), @colName nvarchar(200), @schemaName nvarchar(10);

	DECLARE fkCursor CURSOR FOR
		SELECT
		fk.name As FKName,
		tp.name As ParentTable,
		cp.name As ParentColumn,
		s.name As SchemaName
		FROM 
			sys.foreign_keys fk
		INNER JOIN 
			sys.tables tp ON fk.parent_object_id = tp.object_id
		INNER JOIN 
			sys.tables tr ON fk.referenced_object_id = tr.object_id
		INNER JOIN 
			sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
		INNER JOIN 
			sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
		INNER JOIN 
			sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
		INNER JOIN 
				sys.schemas s on s.schema_id=tp.schema_id
		where tr.name='ScoreAttribute' and cr.name = 'AttributeGUID'
		ORDER BY
		tp.name, cp.column_id
	OPEN fkCursor

	FETCH NEXT FROM fkCursor 
	INTO @fKName, @tableName, @colName, @schemaName

	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		INSERT INTO @migratesqlCreateFK
		SELECT ' ALTER TABLE ' + '[' + @schemaName + '].[' + @tableName + '] ' +
		'ADD CONSTRAINT '+ @fKName + ' FOREIGN KEY (' +  @colName + ') '
		 + 'REFERENCES ' + '[dbo].[ScoreAttribute](AttributeGUID)'

		INSERT INTO @migratesqlDropFK
		SELECT ' ALTER TABLE ' + '[' + @schemaName + '].[' + @tableName + '] ' +
		'DROP CONSTRAINT '+ @fKName

		INSERT INTO @migratesqlCreateFKTable
		SELECT ' UPDATE ' + '[' + @schemaName + '].[' + @tableName + '] SET ' + @colName + ' = ''' + convert(varchar(38), @attributeGuidNew) +
		''' WHERE ' + @colName + ' = ''' +convert(varchar(38), @attributeGuidOld) + ''''

		FETCH NEXT FROM fkCursor 
		INTO @fKName, @tableName, @colName, @schemaName
	END

	CLOSE fkCursor
	DEALLOCATE fkCursor

	INSERT INTO @resultTable
	SELECT * FROM @migratesqlDropFK

	INSERT INTO @resultTable
	SELECT ' UPDATE ' +  '[dbo].[ScoreAttribute] SET AttributeGUID=''' + convert(nvarchar(38), @attributeGuidNew) + 
		''' WHERE AttributeGUID=''' + convert(nvarchar(38), @attributeGuidOld) + ''''

	INSERT INTO @resultTable
	SELECT ' UPDATE ' +  '[dbo].[ScoreDimension] SET DefaultKeyGUID=''' + convert(nvarchar(38), @attributeGuidNew) + 
		''' WHERE DefaultKeyGUID=''' + convert(nvarchar(38), @attributeGuidOld) + ''''

	INSERT INTO @resultTable
	SELECT ' UPDATE ' +  '[dbo].[ScoreDimension] SET DefaultLookupKeyGUID=''' + convert(nvarchar(38), @attributeGuidNew) + 
		''' WHERE DefaultLookupKeyGUID=''' + convert(nvarchar(38), @attributeGuidOld) + ''''

	INSERT INTO @resultTable
	SELECT ' UPDATE ' +  '[dbo].[ScoreAttribute] SET InferredSourceGUID=''' + convert(nvarchar(38), @attributeGuidNew) + 
		''' WHERE InferredSourceGUID=''' + convert(nvarchar(38), @attributeGuidOld) + ''''

	INSERT INTO @resultTable
	SELECT ' UPDATE ' +  '[dbo].[ScoreAttribute] SET InferredAttributeGuid=''' + convert(nvarchar(38), @attributeGuidNew) + 
		''' WHERE InferredAttributeGuid=''' + convert(nvarchar(38), @attributeGuidOld) + ''''

	INSERT INTO @resultTable
	SELECT ' UPDATE [dbo].[IntDataInterfaceField] SET ScoreKeyGUID=''' + convert(nvarchar(38), @attributeGuidNew) + 
		''' WHERE ScoreKeyGUID=''' + convert(nvarchar(38), @attributeGuidOld) + ''''

	INSERT INTO @resultTable
	SELECT * FROM @migratesqlCreateFKTable

	DECLARE tablesCursor CURSOR FOR
			SELECT c.name AS ColName, t.name AS TableName, s.name AS SchemaName
				FROM sys.columns c
			INNER JOIN 
				sys.tables t ON c.object_id = t.object_id
			INNER JOIN 
				sys.schemas s on s.schema_id=t.schema_id
			WHERE  (c.name LIKE '%AttributeGUID' or c.name LIKE '%AttributeID') 
			and t.Name <> 'ScoreAttribute'
			and c.Name <> 'ClientReportSectionAttributeGUID' and c.Name <> 'RuleEngineFilterAttributeGUID' and c.Name <> 'ScheduleIncludedAttributeGUID'
			and s.name<>'bak' and s.name<>'data'
			order by c.name
	OPEN tablesCursor

	FETCH NEXT FROM tablesCursor 
	INTO @colName, @tableName, @schemaName

	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		INSERT INTO @resultTable
		SELECT ' UPDATE ' + '[' + @schemaName + '].[' + @tableName + '] SET ' + @colName + ' = ''' + convert(varchar(38), @attributeGuidNew) +
		''' WHERE ' + @colName + ' = ''' +convert(varchar(38), @attributeGuidOld) + ''''

		FETCH NEXT FROM tablesCursor 
		INTO @colName, @tableName, @schemaName
	END

	CLOSE tablesCursor
	DEALLOCATE tablesCursor

	INSERT INTO @resultTable
	SELECT * FROM @migratesqlCreateFK

	SELECT * FROM @resultTable
GO


---------------------------------------------

-- dbo.procMigrateScriptUpdateDimensionGUID
CREATE proc [dbo].[procMigrateScriptUpdateDimensionGUID]
	@sourcedb nvarchar(500),
	@dimensionGuidNew uniqueidentifier,
	@dimensionGuidOld uniqueidentifier
as
	DECLARE @resultTable table(Query nvarchar(max))

	DECLARE @migratesqlDropFK table(query nvarchar(max))
	DECLARE @migratesqlCreateFK table(query nvarchar(max))

	DECLARE @fKName nvarchar(400), @tableName nvarchar(200), @colName nvarchar(200), @schemaName nvarchar(10);

	DECLARE fkCursor CURSOR FOR
		SELECT
		fk.name As FKName,
		tp.name As ParentTable,
		cp.name As ParentColumn,
		s.name As SchemaName
		FROM 
			sys.foreign_keys fk
		INNER JOIN 
			sys.tables tp ON fk.parent_object_id = tp.object_id
		INNER JOIN 
			sys.tables tr ON fk.referenced_object_id = tr.object_id
		INNER JOIN 
			sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
		INNER JOIN 
			sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
		INNER JOIN 
			sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
		INNER JOIN 
				sys.schemas s on s.schema_id=tp.schema_id
		where tr.name='ScoreDimension' and cr.name = 'DimensionGUID'
		ORDER BY
		tp.name, cp.column_id
	OPEN fkCursor

	FETCH NEXT FROM fkCursor 
	INTO @fKName, @tableName, @colName, @schemaName

	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		INSERT INTO @migratesqlCreateFK
		SELECT ' ALTER TABLE ' + '[' + @schemaName + '].[' + @tableName + '] ' +
		'ADD CONSTRAINT '+ @fKName + ' FOREIGN KEY (' +  @colName + ') '
		 + 'REFERENCES ' + '[dbo].[ScoreDimension](DimensionGUID)'

		INSERT INTO @migratesqlDropFK
		SELECT ' ALTER TABLE ' + '[' + @schemaName + '].[' + @tableName + '] ' +
		'DROP CONSTRAINT '+ @fKName

		FETCH NEXT FROM fkCursor 
		INTO @fKName, @tableName, @colName, @schemaName
	END

	CLOSE fkCursor
	DEALLOCATE fkCursor

	INSERT INTO @resultTable
	SELECT * FROM @migratesqlDropFK

	INSERT INTO @resultTable
	SELECT ' UPDATE ' +  '[dbo].[ScoreDimension] SET DimensionGUID=''' + convert(nvarchar(38), @dimensionGuidNew) + 
		''' WHERE DimensionGUID=''' + convert(nvarchar(38), @dimensionGuidOld) + ''''
		
	INSERT INTO @resultTable
	SELECT ' UPDATE ' +  '[dbo].[S3SimplePermission] SET LootID=''' + convert(nvarchar(38), @dimensionGuidNew) + 
		''' WHERE LootID=''' + convert(nvarchar(38), @dimensionGuidOld) + ''''

	DECLARE tablesCursor CURSOR FOR
		SELECT c.name AS ColName, t.name AS TableName, s.name AS SchemaName
		FROM sys.columns c
			INNER JOIN 
				sys.tables t ON c.object_id = t.object_id
			INNER JOIN 
				sys.schemas s on s.schema_id=t.schema_id
			WHERE  (c.name LIKE '%DimensionGUID' or c.name LIKE '%DimensionID') 
			and t.Name<>'AMMultiEditGroup' and t.name<>'ScoreDimension' and t.Name<>'DimensionInfo' and not t.Name like ('EMF%')
			and c.name<>'FWDimensionGUID' and c.name<>'RegisteredDimensionGUID' and c.name<>'PlaceholderDimensionGUID' and c.name<>'PoolDimensionGUID' 
			and s.name<>'bak' and s.name<>'data'
			order by c.name
	OPEN tablesCursor

	FETCH NEXT FROM tablesCursor 
	INTO @colName, @tableName, @schemaName

	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		INSERT INTO @resultTable
		SELECT ' UPDATE ' + '[' + @schemaName + '].[' + @tableName + '] SET ' + @colName + ' = ''' + convert(varchar(38), @dimensionGuidNew) +
		''' WHERE ' + @colName + ' = ''' +convert(varchar(38), @dimensionGuidOld) + ''''

		FETCH NEXT FROM tablesCursor 
		INTO @colName, @tableName, @schemaName
	END

	CLOSE tablesCursor
	DEALLOCATE tablesCursor

	INSERT INTO @resultTable
	SELECT * FROM @migratesqlCreateFK

	SELECT * FROM @resultTable
GO


---------------------------------------------

-- dbo.procModelDataConfigReindex
CREATE proc [dbo].[procModelDataConfigReindex]
	@mdcguid uniqueidentifier
as
	/*
	declare @guid uniqueidentifier
	set @guid = newid()
	exec procModelDataConfigReindex  @guid
	*/
	declare @sql varchar(max)
	set @sql = '
	DBCC DBREINDEX (''' + dbo.GetZZModelTemplateMappingTableName(@mdcguid) + ''', '' '', 80)
	DBCC DBREINDEX (''' + dbo.GetZZModelDataTableName(@mdcguid) + ''', '' '', 80)
	'
	print @sql
	exec(@sql)
GO


---------------------------------------------

-- dbo.procModelSectionChildSecurityRefresh
CREATE PROCEDURE [dbo].[procModelSectionChildSecurityRefresh]
AS
BEGIN
	WHILE EXISTS
	  (
		SELECT TOP 1 1
		FROM [dbo].[S3SimplePermission] sec1
		  INNER JOIN [dbo].[ModelSection] ms ON sec1.[LootID] = ms.[ModelSectionGUID]
		  INNER JOIN [dbo].[S3SimplePermission] sec2 ON ms.[ParentGUID] = sec2.[LootID]	AND sec1.[IdentityGUID] = sec2.[IdentityGUID]
		WHERE 1=1
		  AND ms.[IsInherit] = 1
		  AND 
			(
				 sec1.[ReadValue]   <> sec2.[ReadValue]
			  OR sec1.[WriteValue]  <> sec2.[WriteValue]
			  OR sec1.[SecureValue] <> sec2.[SecureValue]
			)
	  )
	  BEGIN
		UPDATE sec1
		SET sec1.[ReadValue] = sec2.[ReadValue],
		  sec1.[WriteValue]  = sec2.[WriteValue],
		  sec1.[SecureValue] = sec2.[SecureValue]
		FROM [dbo].[S3SimplePermission] sec1
		  INNER JOIN [dbo].[ModelSection] ms ON sec1.[LootID] = ms.[ModelSectionGUID]
		  INNER JOIN [dbo].[S3SimplePermission] sec2 ON ms.[ParentGUID] = sec2.[LootID]	AND sec1.[IdentityGUID] = sec2.[IdentityGUID]
		WHERE 1 = 1
		  AND ms.[IsInherit] = 1
		  AND 
			(
				  sec1.[ReadValue]  <> sec2.[ReadValue]
			  OR sec1.[WriteValue]  <> sec2.[WriteValue]
			  OR sec1.[SecureValue] <> sec2.[SecureValue]
			)
	  END
END
GO


---------------------------------------------

-- dbo.procMsgBatchReportUpgrade
CREATE proc dbo.procMsgBatchReportUpgrade
	@reportGUID uniqueidentifier,
	@messageGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
as
	--copy this message over to the messaging 2.0 tables
	--this is a hack due to the old MessageGenerator not being able to talk to messaging 2.0 directly
	
	insert into [dbo].[EmailThread] (EmailThreadGUID, Subject, DateTimeStamp, ItemGUID, IsForReporting)
	select R.ReportGUID, 'Report Snapshots - ' + R.Name, min(T.DateCreated), dbo.ZeroGUID(), 1 from [dbo].[MsgTopic] T inner join [dbo].[REReport] R (readuncommitted) on R.Name = T.Tag
	where R.ReportGUID = @reportGUID and not exists(select 1 from [dbo].[EmailThread] EX where EX.EmailThreadGUID = R.ReportGUID) and T.Tag != ''
	group by R.ReportGUID, R.Name

	insert into [dbo].[EmailMessage] (EmailMessageGUID, EmailThreadGUID, Subject, DateTimeStamp, Body, SenderUserGUID)
	select M.MessageGUID, cast(max(cast(R.ReportGUID as nvarchar(36))) as uniqueidentifier), M.Subject, M.DateCreated, M.Body, M.AuthorGUID from [dbo].[MsgMessage] M inner join [dbo].[MsgTopic] T on T.TopicGUID = M.TopicGUID inner join [dbo].[REReport] R (readuncommitted) on R.Name = T.Tag
	where (@messageGUID = '00000000-0000-0000-0000-000000000000' or M.MessageGUID = @messageGUID) and not exists(select 1 from [dbo].[EmailMessage] EX where EX.EmailMessageGUID = M.MessageGUID) and T.Tag != ''
	group by M.MessageGUID, M.Subject, M.DateCreated, M.Body, M.AuthorGUID
	having exists(select 1 from [dbo].[EmailThread] EXT where EXT.EmailThreadGUID = cast(max(cast(R.ReportGUID as nvarchar(36))) as uniqueidentifier))
	
	update EM set EM.SenderUserGUID = S.UserGUID
	from
		[dbo].[EmailMessage] EM
		inner join [dbo].[EmailThread] EMT on EMT.EmailThreadGUID = EM.EmailThreadGUID
		inner join [dbo].[MsgMessage] M on M.MessageGUID = EM.EmailMessageGUID
		inner join [dbo].[MsgTopic] T on T.TopicGUID = M.TopicGUID
		inner join [dbo].[viewS3ACLSimple] S on S.LootID = T.TopicGUID and IsReadable = 1
	where
		EMT.EmailThreadGUID = @reportGUID
		and (@messageGUID = '00000000-0000-0000-0000-000000000000' or M.MessageGUID = @messageGUID)
GO


---------------------------------------------

-- dbo.procMsgClearEmailActivity
CREATE proc [dbo].[procMsgClearEmailActivity]
(
	@NumDaysToKeep int = 30
)
 as

delete from MsgEmailActivity where Timestamp < DATEADD(DAY, -@NumDaysToKeep, GETDATE())
GO


---------------------------------------------

-- dbo.procMsgMarkAllMessagesRead
CREATE proc [dbo].[procMsgMarkAllMessagesRead] as

delete from msgmessageread

CREATE TABLE #tempMessageRead(
	[UserGUID] [uniqueidentifier] ,
	[MessageGUID] [uniqueidentifier],
)

--add all users that are recipients of topics
insert into #tempMessageRead
 select s.UserGUID, m.MessageGUID from MsgTopic T 
 inner join msgmessage m on t.topicguid = m.topicguid 
 inner join dbo.viewS3ACLSimple s on cast(t.TopicGUID as varchar(36)) = s.LootID 
 inner join userprofile u on u.userguid = s.userguid
 where s.IsReadable = 1 and t.topicguid not in (select topicguid from msgtopicarchive where userguid = u.userguid)
 
 --add all user message combos for unsecured forums
 insert into #tempMessageRead
 select u.userguid, x.messageguid from userprofile u, 
(select m.messageguid from msgmessage m 
inner join msgtopic t on t.topicguid = m.topicguid
inner join msgforum f on t.forumguid = f.forumguid  where f.ForumType = 0 ) x

--add all user message combos for secured forums
insert into #tempMessageRead
select s.userguid,m.messageguid from msgmessage m inner join msgtopic t on t.topicguid = m.topicguid
inner join msgforum f on t.forumguid = f.forumguid and f.ForumType = 1
inner join XPlan p on f.EntityGUID = p.PlanGUID
inner join viewS3ACL s on s.LootID = p.CachedLootID
inner join userprofile u on u.userguid = s.userguid
where s.IsReadable = 1

--update the message read table
insert into msgmessageread
select x.userguid, x.messageguid, 1, getdate() from 
(select distinct userguid, messageguid from #tempMessageRead ) x

drop table #tempMessageRead
GO


---------------------------------------------

-- dbo.procMsgMessageCreate
CREATE proc [dbo].[procMsgMessageCreate]
(
	@FromUsername nvarchar(max),
	@ToUsername nvarchar(max),
	@MessageTypeGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@ForumGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@Subject nvarchar(max) = 'New Message',
	@Body nvarchar(max)	= ''
)
 as

	if (@FromUsername = '' or @ToUsername = '') begin
		print 'Message could not be created. Usernames were not specified'
		return
	end
	
	Declare @fromUserGUID uniqueidentifier
	Declare @toUserGUID uniqueidentifier

	Set @fromUserGUID = (select userguid from UserProfile where UserName = @FromUsername)
	Set @toUserGUID = (select userguid from UserProfile where UserName = @ToUsername)
	
	if (@fromUserGUID = dbo.ZeroGUID() or @fromUserGUID is null) begin
		print 'Message could not be created. From user does not exist in the database.'
		return
	end
	
	if (@toUserGUID = dbo.ZeroGUID() or @toUserGUID is null) begin
		print 'Message could not be created. To user does not exist in the database.'
		return
	end
	
	if (select COUNT(*) from MsgMessageType where MessageTypeGUID = @MessageTypeGUID) = 0 begin
		print 'Message could not be created. Message type does not exist in the database.'
		return
	end
	
	Declare @newTopicGUID uniqueidentifier
	Declare @newMessageGUID uniqueidentifier
	Declare @topicType int
	
	Declare @messageTypeType int
	Set @messageTypeType = (select [TYPE] from MsgMessageType where MessageTypeGUID = @MessageTypeGUID)
	
	if (@messageTypeType = 0) begin
		--forum
		
		if (select COUNT(*) from MsgForum where ForumGUID = @ForumGUID) = 0 begin
			print 'Message could not be created. Forum does not exist in the database.'
			return
		end
	
		Declare @forumType int
		Set @forumType = (select forumtype from MsgForum where ForumGUID = @ForumGUID)
		
		if (@forumType = 0) begin
			--general forum
			Set @topicType = 0
		end else if (@forumType = 1) begin
			--plan forum
			Set @topicType = 1
		end else begin
			print 'Message could not be created. Incorrect type specified for forum.'
			return
		end
		
	end else if (@messageTypeType = 1) begin
		--notification
		Set @topicType = 3
		Set @ForumGUID = dbo.ZeroGUID()
	end else if (@messageTypeType = 2) begin
		--private message
		set @topicType = 2
		Set @ForumGUID = dbo.ZeroGUID()
	end else begin
		print 'Message could not be created. Incorrect type specified for message type.'
		return
	end
	
	Set @newTopicGUID = (select NEWID())
	insert into MsgTopic (TopicGUID, ForumGUID, AuthorGUID, Name, TopicType) values (@newTopicGUID, @ForumGUID, @fromUserGUID, @Subject, @topicType)
	
	Set @newMessageGUID = (select NEWID())
	insert into MsgMessage (MessageGUID, TopicGUID, MessageTypeGUID, ReplyToMsgGUID, [Subject], Body, AuthorGUID, DateSent) values (@newMessageGUID, @newTopicGUID, @MessageTypeGUID, dbo.ZeroGUID(), @Subject, @Body, @fromUserGUID, '1/1/1900')
	
	--add security for From & To user
	insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values (@newTopicGUID, @fromUserGUID, 1, 1, 1)
	insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values (@newTopicGUID, @toUserGUID, 1, 1, 1)
	
	print 'Message created successfully'
GO


---------------------------------------------

-- dbo.procMsgRemoveAll
CREATE PROC dbo.procMsgRemoveAll

AS

-- remove file attachments linked to messages
delete from FileAttachment where entityguid in (select messageguid from msgmessage)

-- truncate tables
delete from  MsgAttachment
delete from  MsgBookmark
delete from  MsgEmailActivity
delete from  MsgMessage
delete from  MsgMessagePlanLink
delete from  MsgMessageRead
delete from  MsgTopic
delete from  MsgTopicArchive
delete from  MsgForum
delete from  MsgForumRead
delete from  MsgForumViewed


delete from  MsgEmailSummary

delete from  EmailRecipient
delete from  EmailMessage
delete from  EmailThread
GO


---------------------------------------------

-- dbo.procPlanCreate
CREATE proc [dbo].[procPlanCreate]  
 @PlanGuid UNIQUEIDENTIFIER  
 ,@PlanTypeName VARCHAR(450)  
 ,@PlanName VARCHAR(450)  
 ,@authorUserName VARCHAR(450)  
 ,@templateName VARCHAR(450)  
 ,@planDimensionFQN VARCHAR(450) = ''  
 ,@lootPrefix NVARCHAR(10) = 'P|'  
 ,@isSettingAuthor BIT = 1  
 ,@isRefreshingSecurity BIT = 1  
 ,@isRefreshDirectoryField BIT = 1  
 ,@isRunningPlantypeScript BIT = 0  
 ,@formDefGUID UNIQUEIDENTIFIER = '00000000-0000-0000-0000-000000000000'
 ,@wfMapGUID UNIQUEIDENTIFIER = '00000000-0000-0000-0000-000000000000'
 ,@isCreateMissingFormData BIT = 1  
 ,@isFromPlanImporter BIT = 0
as  
  
-- validation  
if len(@templateName) = 0 begin print 'template name required' return end  
if len(@lootPrefix) = 0 begin print 'loot prefix is required' return end  
  
declare @cnt int  
select @cnt = COUNT(*) from xplan where PlanGUID = @PlanGuid  
if @cnt > 0 begin  
 print 'plan already exists ' + cast(@PlanGuid as varchar(36))  
 return  
end  
  
-- initialization  
select @PlanName = dbo.GetWebSafeString(@PlanName)  
  
declare @ptguid uniqueidentifier   
declare @ptdimguid uniqueidentifier  
select @ptguid = plantypeguid, @ptdimguid = DimensionGUID from PlanType where Name = @PlanTypeName  
  
declare @mtguid uniqueidentifier    
if LEN(@templateName) = 0 begin  
 select top 1 @mtguid = ModelTemplateGUID from plantypemodeltemplatelink where plantypeguid = @ptguid  
end else begin  
 select top 1 @mtguid = ModelTemplateGUID from emfmodeltemplate where Name like @templateName  
end  
  
declare @formguid uniqueidentifier  
  
  
IF @formDefGUID = '00000000-0000-0000-0000-000000000000' BEGIN  
select top 1 @formguid = formguid from fe2form where plantypeguid = @ptguid  
END ELSE BEGIN  
select top 1 @formguid = formguid from fe2form where formguid = @formDefGUID  
END  
  
  
declare @authorRoleGUID uniqueidentifier  
select @authorRoleGUID = userroleguid from UserRole where Type = 1  
  
declare @authorUserGUID uniqueidentifier  
select @authorUserGUID = userguid from UserProfile where UserName = @authorUserName  
if (@authorUserGUID is null) select @authorUserGUID = usergroupguid from UserGroup where Name = @authorUserName  
if (@authorUserGUID is null and (@authorUserName like 'sdt\%' or @authorUserName = 'System')) set @authorUserGUID = '10101010-1111-0000-1111-101010101010'

declare @nameFFGUID uniqueidentifier  
select @nameFFGUID = NameFormFieldGUID from PlanType where PlanTypeGUID = @ptguid
  
  
-- validation  
if @PlanName is null begin print '@PlanName is null' return end  
if @ptguid is null begin print '@ptguid is null' return end  
if @authorUserGUID is null begin print '@authorUserGUID is null' return end  
if @mtguid is null begin print '@mtguid is null' return end  
if @formguid is null begin print '@formguid is null' return end  
  
PRINT 'Creating plan: ' + cast(@PlanGuid AS NVARCHAR(36))  
  
declare @planid int  
  
insert into XPlan (planguid,  DefaultFormDefGUID, ModelTemplateGUID, PlanTypeGUID)  
select  
 @PlanGuid,  
 @formguid ,  
 @mtguid,  
 @ptguid  
   
set @planid = @@IDENTITY  
    
-- insert dimension member, and add security  
-- info: dimension attributes will be ignored by this procedure  
-- need to insert into all non view backed secondary groups then insert into primary group last 
--       because security trigger is on primary group and inner joins to secondary groups will filter out members if they dont exist in secondary group
declare @planMemberSql AS NVARCHAR(MAX)  
if (len(@planDimensionFQN) > 0) begin  
	-- insert into secondary groups
	declare @planMemberGroupName nvarchar(450)
	declare crsDimGroups cursor fast_forward for 
		select DG.SchemaName + '.' + DG.ObjectName 
		from ScoreDimensionGroup DG 
		where 
			DG.DimensionGUID = @ptdimguid
			and (DG.ObjectName not like 'view%' or (DG.SchemaName + '.' + DG.ObjectName like replace(replace(@planDimensionFQN, '[', ''), ']', '') + '%' and DG.ObjectName like '%_custom'))
			and DG.DimensionGroupGUID not in (select primarygroupguid from scoredimension where dimensionguid = @ptdimguid)
	open crsDimGroups		
	fetch next from crsDimGroups into @planMemberGroupName
	while(@@FETCH_STATUS = 0) begin
		SET @planMemberSql = 'INSERT INTO ' + @planMemberGroupName + ' (MemberGUID) VALUES (''' + cast(@PlanGuid AS NVARCHAR(36)) + ''')'  
		EXEC (@planMemberSql)  
		fetch next from crsDimGroups into @planMemberGroupName
	end
	close crsDimGroups
	deallocate crsDimGroups
	
	-- insert into primary group
	set @planMemberSql = 'If not exists (select * from ' + @planDimensionFQN + ' where MemberGUID = ''' +   + cast(@PlanGuid AS NVARCHAR(36)) + ''')' + ' INSERT INTO ' + @planDimensionFQN + ' (MemberGUID) VALUES (''' + cast(@PlanGuid AS NVARCHAR(36)) + ''')'  
	EXEC (@planMemberSql)  
end  

declare @plandimguid uniqueidentifier;
set @plandimguid = (select dimensionguid from PlanType where Name=@PlanTypeName)
EXEC [dbo].[procScoreDimensionCacheRefresh] @dimensionGUID = @plandimguid
  
-- refresh security  
if @isRefreshingSecurity = 1 begin  
 exec procScoreSetDimensionSecurity30 @ptdimguid  
end  
  
-- set author  
declare @lootid nvarchar(max)  
if @isSettingAuthor = 1 begin  
 set @lootid = @lootPrefix + cast(@planid as varchar(max))  
 exec dbo.procS3AssignIdentityToSpecialRole @authoruserguid, 1, @lootid  
end  
  
-- add/update directory cache  
EXEC procDirectoryAddEntry @PlanGuid, @ptguid  
  
-- add name to formdata - NO LONGER DONE
  
-- add to workflow  
IF @wfMapGUID = '00000000-0000-0000-0000-000000000000' BEGIN  
	IF @isFromPlanImporter = 0 BEGIN
		insert into WFToken ( EntityGUID, WorkflowMapGUID, WorkflowStepGUID )  
		 select @PlanGuid, wf.WorkflowMapGUID,wfs.WorkflowStepGUID  
		 from   
		  PlanTypeWorkflowMapLink  wf  
		  inner join WFWorkflowStep wfs on wf.WorkflowMapGUID = wfs.WorkflowMapGUID  
		 where PlanTypeGUID = @ptguid and IsRequiredWorkflow = 1 and IsStart = 1  
 	END
END ELSE BEGIN  
 insert into WFToken ( EntityGUID, WorkflowMapGUID, WorkflowStepGUID )  
 select @PlanGuid, wf.WorkflowMapGUID,wfs.WorkflowStepGUID  
 from   
  PlanTypeWorkflowMapLink  wf  
  inner join WFWorkflowStep wfs on wf.WorkflowMapGUID = wfs.WorkflowMapGUID  
 where PlanTypeGUID = @ptguid and wf.WorkflowMapGUID = @wfMapGUID  
END  
  
-- fillin default  
exec procScoreFillinSetByTemplateDefault @PlanGuid, 0  
  
  
-- (optional) @ptguid  
if @isRunningPlantypeScript = 1 begin  
   
 DECLARE @saveScriptGUID AS UNIQUEIDENTIFIER  
 DECLARE @saveScriptGUID2 AS UNIQUEIDENTIFIER  
   
 DECLARE @saveScript AS VARCHAR(MAX)  
 DECLARE @saveScript2 AS VARCHAR(MAX)  
   
    select @saveScriptGUID = OnSaveCustomScriptGUID from PlanType where PlanTypeGUID = @ptguid   
    select @saveScriptGUID2 = OnSaveCustomScript2GUID from PlanType where PlanTypeGUID = @ptguid   
   
 IF @saveScriptGUID <> '00000000-0000-0000-0000-000000000000' BEGIN  
  select @saveScript = scripttext from CustomScript where CustomScriptGUID = @saveScriptGUID  
  set @saveScript = REPLACE(@saveScript, '@PlanGuidList', '''' + cast(@PlanGuid AS nvarchar(36)) + '''')  
  exec (@saveScript)  
 END  
   
 IF @saveScriptGUID2 <> '00000000-0000-0000-0000-000000000000' BEGIN  
  select @saveScript2 = scripttext from CustomScript where CustomScriptGUID = @saveScriptGUID2  
  set @saveScript2 = REPLACE(@saveScript2, '@PlanGuidList', '''' + cast(@PlanGuid AS nvarchar(36)) + '''')  
  exec (@saveScript2)  
 END  
    
end  
  
-- create missing form field  
IF @isCreateMissingFormData = 1 BEGIN  
 exec procFormDataCreateMissing @ptguid  
END  
  
-- refresh fields in directory cache  
IF @isRefreshDirectoryField = 1 BEGIN  
 EXEC procDirectoryRefreshFieldAll @ptguid  
END
GO


---------------------------------------------

-- dbo.procPlanDelete
CREATE PROCEDURE [dbo].[procPlanDelete] 
	 @PlanGUID AS UNIQUEIDENTIFIER,
	 @PlanDimension AS NVARCHAR(128),
	 @LootPrefix AS NVARCHAR(16) = 'P|',
	 @IsDeletingData AS BIT = 0
AS
-- assumptions
-- no score facts

PRINT 'Deleting ' + CAST(@PlanGUID AS NVARCHAR(36))

DECLARE @LootGroupID NVARCHAR(128)
SELECT @LootGroupID = CachedLootID FROM XPlan WHERE PlanGUID = @PlanGUID

DECLARE @ModelTemplateGUID AS UNIQUEIDENTIFIER 
SET @ModelTemplateGUID = (SELECT ModelTemplateGUID FROM XPlan WHERE PlanGUID = @PlanGUID)

IF @PlanGUID IS NULL BEGIN
	Print 'Plan not found'
	RETURN
END

IF @ModelTemplateGUID IS NULL BEGIN
	Print 'Template not found: ' + CAST(@ModelTemplateGUID AS NVARCHAR(36))
	RETURN
END

--Cache
exec [dbo].[procInvalidateModelWorkbookCache] @PlanGUID, 0, 0, 'procPlanDelete'

DECLARE @SharedSecurityCount int
select @SharedSecurityCount = count(*) from [dbo].[XPlan] P (readuncommitted) inner join [dbo].[PlanType] PT (readuncommitted) on PT.PlanTypeGUID = P.PlanTypeGUID inner join [dbo].[ScoreDimension] D (readuncommitted) on D.DimensionGUID = PT.DimensionGUID where P.PlanGUID = @PlanGUID and D.IsSharingSecurity = 1

--Plan Dimension
DECLARE @planDimensionDeleteSql AS NVARCHAR(MAX)
SET @planDimensionDeleteSql = 'DELETE ' + @PlanDimension + ' WHERE memberguid = ''' + CAST(@PlanGUID AS NVARCHAR(36)) + ''''
EXEC (@planDimensionDeleteSql)

--XPlan
DELETE
	XPlan
WHERE
	PlanGUID = @PlanGUID

--remove dependent history records
DELETE FROM dbo.WFHistory WHERE EntityGUID = @PlanGUID

--S3 (loot and assignment), if the plan does not share security
if (@SharedSecurityCount = 0) begin
	EXEC dbo.procS3ClearSecurityByLootGroup @LootGroupID
end

--delete model data
if @IsDeletingData = 1 begin

	DECLARE @deleteSql AS NVARCHAR(MAX)
	DECLARE @whereSql AS NVARCHAR(MAX)

	SET @deleteSql = 'delete data from zzviewModelDataBasic_{mdcnamefriendly} data where data.plansguid = ''' + CAST(@PlanGUID AS NVARCHAR(36)) + ''''
	SET @whereSql = 'where modeldataconfigguid in (SELECT LS.ParentModelDataConfigGUID FROM EMFModelTemplateLinkSource LS WHERE LS.IsSelf = 1 AND LS.ModelTemplateGUID = ''' + CAST(@ModelTemplateGUID AS NVARCHAR(36)) + ''')'

	exec procEMFRunForManyStructures @deleteSql, @whereSql, 1, 1

	--score (implementation incomplete)
	delete from [dbo].[ScoreFillin] where ModelGUID = @PlanGUID
	exec [dbo].[procScoreFillinTableRefresh] @PlanGUID
end
GO


---------------------------------------------

-- dbo.procPlanDeleteAll
CREATE PROCEDURE [dbo].[procPlanDeleteAll] 
	 @PlanDimension AS NVARCHAR(128),
	 @IsExecuting as bit = 0
AS

declare @idattr nvarchar(100)
select @idattr = A.SQLColumnName 
from [dbo].[ScoreAttribute] A inner join [dbo].[ScoreDimensionGroup] DG on DG.DimensionGroupGUID = A.DimensionGroupGUID inner join [dbo].[ScoreDimension] D on DG.DimensionGUID = D.DimensionGUID and A.AttributeGUID = D.DefaultKeyGUID 
where (DG.SchemaName + '.' + DG.ObjectName) = @PlanDimension or (D.SQLSchemaName + '.' + D.SQLObjectName) = @PlanDimension
		or ('[' + DG.SchemaName + '].[' + DG.ObjectName + ']') = @PlanDimension or ('[' + D.SQLSchemaName + '].[' + D.SQLObjectName + ']') = @PlanDimension

declare @sql as nvarchar(max) = '
declare plancursor CURSOR FAST_FORWARD FOR
	select 
		dimp.memberguid,
		p.name
	from ' + @PlanDimension + ' dimp
		left join xplan p on p.planguid = dimp.memberguid
	where
		' + @idattr + ' != 0
		
open plancursor;

declare @memberguid uniqueidentifier;
declare @planname nvarchar(100);

FETCH NEXT FROM plancursor into @memberguid, @planname
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		print (''Deleting Plan: '' + @planname);
		exec procPlanDelete @memberguid, ''' + @PlanDimension + ''', default, 1		
		FETCH NEXT FROM plancursor into @memberguid, @planname
	END
close plancursor;
deallocate plancursor;

delete from ' + @PlanDimension + ' where ' + @idattr + ' != 0
'

if (@IsExecuting=1) 
	begin
		exec (@sql)
	end
else
	begin
		print @sql
	end


RETURN
GO


---------------------------------------------

-- dbo.procPlanHistoryInsert
create procedure procPlanHistoryInsert
	@planGUIDList nvarchar(max),
	@userGUID uniqueidentifier,
	@category nvarchar(64),
	@description nvarchar(4000)
as
	insert into HistoryItem (HISTORYITEMGUID, OBJECTGUID, OBJECTTYPE, DATETIMESTAMP, MODIFIERUSERGUID, CATEGORY, DESCRIPTION, MODIFIERUSERNAME, ITEMCOUNT, METAXML)
	select
		NEWID(),
		P.PlanGUID,
		'',
		GETDATE(),
		@userGUID,
		@category,
		@description,
		coalesce((select NameFull from UserProfile where UserGUID = @userGUID), ''),
		1,
		''
	from
		XPlan P
	where
		P.PlanGUID in(select [guid] from dbo.ConvertCSGuidsToTable(@planGUIDList, ','))
GO


---------------------------------------------

-- dbo.procPlanMarkModelWorkbookAsCached
CREATE PROC procPlanMarkModelWorkbookAsCached
	@planguid uniqueidentifier
AS
	UPDATE XPlan SET IsModelWorkbookCached = 1 WHERE PlanGUID = @planguid
GO


---------------------------------------------

-- dbo.procPopulateCMFactsWithAllAccounts
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1        2020-11-13  KF      JAZZ-8741   My Performance | Standard Metric - UOS Non Staffing
*************************************************************/
CREATE PROCEDURE [dbo].[procPopulateCMFactsWithAllAccounts]
@MetricGUID uniqueidentifier
AS

DECLARE @AccountDimensionGUID uniqueidentifier, @BucketGUID uniqueidentifier

SELECT @BucketGUID = BucketGUID
FROM dbo.CMMetric
WHERE MetricGUID = @MetricGUID

SELECT @AccountDimensionGUID = DimensionGUID
FROM dbo.ScoreDimension
WHERE GlobalID = 'Account'

IF @BucketGUID IS NOT NULL
BEGIN 
  DELETE FROM dbo.CMFacts
  WHERE BucketGUID = @BucketGUID

  INSERT INTO dbo.CMFacts (DimensionGUID, MemberGUID, BucketGUID)
  SELECT @AccountDimensionGUID, MemberGUID, @BucketGUID
  FROM fw.DimAccount
END
GO


---------------------------------------------

-- dbo.procPopulateDataDictionaryFieldsValueExamples
-- =============================================
-- Author:		Yaroslav Dembitskyi
-- Create date: 7/20/2017
-- Description:	Populates [dbo].[DataDictionaryFieldValueExample] based on existing data. Also provides possibility to update example value for specific scoreGuid
-- Change History:
-- 2/6/2019		yrhee	Remove cursors and invalid keylink lookups
-- =============================================

CREATE PROC [dbo].[procPopulateDataDictionaryFieldsValueExamples] (
	@specificScoreGuidToUpdate UNIQUEIDENTIFIER = NULL
)
AS
BEGIN

	IF OBJECT_ID('tempdb..#tempDataDictionaryGUIDs') IS NOT NULL 
	BEGIN
		DROP TABLE #tempDataDictionaryGUIDs;
	END

	CREATE TABLE #tempDataDictionaryGUIDs (ScoreGUID UNIQUEIDENTIFIER)
	
	IF(@specificScoreGuidToUpdate IS NOT NULL)
	BEGIN
		INSERT INTO #tempDataDictionaryGUIDs
		SELECT @specificScoreGuidToUpdate
	END
	ELSE
	BEGIN
		INSERT INTO #tempDataDictionaryGUIDs
		SELECT DISTINCT GivenScoreAttributeGUID 
		FROM dbo.viewDataDictionary
	END		
	
	-- =============================================
	-- Get Attribute Values (incl KeyLinks)
	-- =============================================
	DECLARE @sqlAttributes NVARCHAR(MAX) = 
		(
			SELECT dbo.STRAGGR(
				' SELECT TOP 1 ''' + AttributeGUIDAsText + ''' AttributeGUID, '
				+ CASE WHEN ColumnTypeName = 'bit' 
						  THEN ' ''True/False'' ExampleValue ' 
					   WHEN ColumnTypeName LIKE '%datetime%' 
						  THEN ' CONVERT(CHAR(10), ['+ SQLColumnName + '], 103) + SUBSTRING(CONVERT(varchar, [' + SQLColumnName + '], 0),12, 8) ExampleValue ' 
							+ FromWhereClause 
					   ELSE ' CONVERT(NVARCHAR(4000),['+ SQLColumnName + ']) ExampleValue ' 
							+ FromWhereClause END
				, ' UNION ALL ', '') 
			FROM
			(
				SELECT DISTINCT 
					CONVERT(NVARCHAR(40), attr.AttributeGUID) AttributeGUIDAsText, 
					attr.SQLColumnName, 
					TYPE_NAME(attr.ColumnType) ColumnTypeName,
					' FROM [' + dim.SQLSchemaName + '].[' + dim.SQLObjectName + '] (NOLOCK) WHERE CONVERT(NVARCHAR(4000),[' + attr.SQLColumnName + ']) <> '''' ' 
						+ CASE WHEN TYPE_NAME(attrKey.ColumnType) LIKE '%int' THEN ' and [' + attrKey.SQLColumnName + '] <> 0 ' ELSE '' END FromWhereClause
				FROM #tempDataDictionaryGUIDs dd
				INNER JOIN ScoreAttribute attr WITH (READUNCOMMITTED) ON dd.ScoreGUID = attr.AttributeGUID
				INNER JOIN ScoreDimensionGroup gr WITH (READUNCOMMITTED) ON attr.DimensionGroupGUID = gr.DimensionGroupGUID
				INNER JOIN ScoreDimension dim WITH (READUNCOMMITTED) ON gr.DimensionGUID = dim.DimensionGUID
				INNER JOIN ScoreAttribute attrKey WITH (READUNCOMMITTED) ON dim.DefaultKeyGUID = attrKey.AttributeGUID
				INNER JOIN dbo.viewSysColumns col WITH (READUNCOMMITTED) ON col.SchemaName = dim.SQLSchemaName AND col.ObjectName = dim.SQLObjectName AND col.ColumnName = attr.SQLColumnName
			) t1 
		);
	
	-- =============================================
	-- Get Measure Values
	-- =============================================
	DECLARE @sqlMeasures NVARCHAR(MAX) = 
		(
			SELECT dbo.STRAGGR(
				' SELECT TOP 1 ''' + MeasureGUIDAsText + ''' MeasureGUID, '
				+ CASE WHEN ColumnTypeName = 'bit' 
						  THEN ' ''True/False'' ExampleValue ' 
					   WHEN ColumnTypeName LIKE '%datetime%' 
						  THEN ' CONVERT(CHAR(10), ['+ SQLColumnName + '], 103) + SUBSTRING(CONVERT(varchar, [' + SQLColumnName + '], 0),12, 8) ExampleValue ' 
							+ FromWhereClause 
					   ELSE ' CONVERT(NVARCHAR(4000),['+ SQLColumnName + ']) ExampleValue ' 
							+ FromWhereClause END 
				, ' UNION ALL ', '') 
			FROM
			(
				SELECT DISTINCT 
					CONVERT(NVARCHAR(40), m.MeasureGUID) MeasureGUIDAsText,
					m.SQLColumnName, 
					TYPE_NAME(m.ColumnTypeValue) ColumnTypeName, 
					' FROM [' + dt.SQLSchemaName + '].[' + dt.SQLObjectName + '] (NOLOCK) WHERE CONVERT(NVARCHAR(4000),[' + m.SQLColumnName + ']) <> '''' ' FromWhereClause
				FROM #tempDataDictionaryGUIDs dd
				INNER JOIN ScoreMeasure m WITH (READUNCOMMITTED) ON dd.ScoreGUID = m.MeasureGUID	
				INNER JOIN ScoreDataTable dt WITH (READUNCOMMITTED) ON m.DataTableGUID = dt.DataTableGUID
				INNER JOIN dbo.viewSysColumns col WITH (READUNCOMMITTED) ON col.SchemaName = dt.SQLSchemaName AND col.ObjectName = dt.SQLObjectName AND col.ColumnName = m.SQLColumnName
			) t1 
		);
	
	-- =====================================================
	-- Final Updates to dbo.DataDictionaryFieldValueExample
	-- =====================================================
	DECLARE @sqlFinal NVARCHAR(MAX) =
		'CREATE TABLE #ExampleValues (ScoreGUID UNIQUEIDENTIFIER, ExampleValue NVARCHAR(4000)) '
	
	IF (@sqlMeasures IS NOT NULL)
	BEGIN
		SET @sqlFinal = @sqlFinal 
			+ ' INSERT INTO #ExampleValues (ScoreGUID, ExampleValue)
				SELECT MeasureGUID, ExampleValue
				FROM (' + @sqlMeasures + ') tMeas '
	END
    
	IF (@sqlAttributes IS NOT NULL)
	BEGIN
		SET @sqlFinal = @sqlFinal 
			+ ' INSERT INTO #ExampleValues (ScoreGUID, ExampleValue)
				SELECT AttributeGUID, ExampleValue
				FROM (' + @sqlAttributes + ') tAttr '
	END
	
	SET @sqlFinal = @sqlFinal 
			+ ' UPDATE dd
				SET dd.ExampleValue = ev.ExampleValue
				FROM dbo.DataDictionaryFieldValueExample dd
				INNER JOIN #ExampleValues ev ON dd.ScoreGUID = ev.ScoreGUID
				WHERE dd.ExampleValue != ev.ExampleValue
	
				INSERT INTO dbo.DataDictionaryFieldValueExample (ScoreGUID, ExampleValue)
				SELECT ev.ScoreGUID, ev.ExampleValue
				FROM #ExampleValues ev
				LEFT JOIN dbo.DataDictionaryFieldValueExample dd on ev.ScoreGUID = dd.ScoreGUID
				WHERE dd.ScoreGUID IS NULL '

	IF (@specificScoreGuidToUpdate IS NULL) -- DON'T DELETE IF SINGLE GUID
	BEGIN
		SET @sqlFinal = @sqlFinal
			+ ' DELETE FROM dbo.DataDictionaryFieldValueExample
				WHERE ScoreGUID NOT IN (SELECT ScoreGUID FROM #ExampleValues) '
	END

	SET @sqlFinal = @sqlFinal 
		+ ' DROP TABLE #ExampleValues ';

	EXEC(@sqlFinal);

	IF OBJECT_ID('tempdb..#tempDataDictionaryGUIDs') IS NOT NULL 
	BEGIN
		DROP TABLE #tempDataDictionaryGUIDs;
	END
END
GO


---------------------------------------------

-- dbo.procPrintLongText
create proc dbo.procPrintLongText
	@String NVARCHAR(MAX)
as
	DECLARE @CurrentEnd BIGINT; /* track the length of the next substring */
	DECLARE @offset tinyint; /*tracks the amount of offset needed */
	set @string = replace(  replace(@string, char(13) + char(10), char(10))   , char(13), char(10))

	WHILE LEN(@String) > 1
	BEGIN
	    IF CHARINDEX(CHAR(10), @String) between 1 AND 4000
	    BEGIN
	           SET @CurrentEnd =  CHARINDEX(char(10), @String) -1
	           set @offset = 2
	    END
	    ELSE
	    BEGIN
	           SET @CurrentEnd = 4000
	            set @offset = 1
	    END   
	    PRINT SUBSTRING(@String, 1, @CurrentEnd) 
	    set @string = SUBSTRING(@String, @CurrentEnd+@offset, LEN(@String))   
	END
GO


---------------------------------------------

-- dbo.procRESQLReportRegisteredAttributeFixReferences
CREATE proc dbo.procRESQLReportRegisteredAttributeFixReferences
	@reportGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@attributeGUIDCSV nvarchar(max) = '',
	@beforeColumnName nvarchar(100) = '',
	@afterColumnName nvarchar(100) = '',
	@dataViewGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
as
	------------------------------------------
	-- AD HOC REPORTS
	------------------------------------------
	
	--fix broken ad hoc parameters - always works as long as the attribute is registered
	update p set p.ColumnName = ra.ColumnName, p.Name = case when @afterColumnName = '' then p.Name else @afterColumnName end
	from
		viewREClientReportParameter_Broken bk
		inner join REClientReportParameter p on p.ClientReportParameterGUID = bk.ClientReportParameterGUID
		inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and cast(ra.AttributeGUID as nvarchar(36)) = p.AttributeID
	where
		bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000'
		and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or exists(select 1 from REClientReportDataSourceLink l where l.ReportGUID = bk.ReportGUID and l.DataSourceGUID = @dataViewGUID))

	--fix broken ad hoc section attributes - always works as long as the attribute is registered
	update sa set sa.ColumnName = ra.ColumnName, sa.Name = case when @afterColumnName = '' then sa.Name else @afterColumnName end
	from
		viewREClientReportSectionAttribute_Broken bk
		inner join REClientReportSectionAttribute sa on sa.ClientReportSectionAttributeGUID = bk.ClientReportSectionAttributeGUID
		inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and cast(ra.AttributeGUID as nvarchar(36)) = sa.AttributeID
	where
		bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000'
		and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or exists(select 1 from REClientReportDataSourceLink l where l.ReportGUID = bk.ReportGUID and l.DataSourceGUID = @dataViewGUID))

	------------------------------------------
	-- SQL REPORTS
	------------------------------------------
	
	--NOTE: not fixing display names because this would break excel report references that cannot be updated via SQL

	--fix broken sql report display columns that match rename parameters
	if (@attributeGUIDCSV != '' and @beforeColumnName != '' and @afterColumnName != '') begin
		update dc set dc.ColumnName = ra.ColumnName
		from
			viewRESQLReportDisplayColumn_Broken bk
			inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = bk.SQLReportSetupGUID
			inner join RESQLReportDisplayColumn dc on dc.DisplayColumnGUID = bk.DisplayColumnGUID
			inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and ra.ColumnName = @afterColumnName
			inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
			inner join (select guid as AttributeGUID from dbo.ConvertCSGuidsToTable(@attributeGUIDCSV, ',')) csv on csv.AttributeGUID = a.AttributeGUID or csv.AttributeGUID = a.ForeignKeyGUID or csv.AttributeGUID = a.InferredAttributeGUID
		where
			(dc.ColumnName = @beforeColumnName or @beforeColumnName like dc.ColumnName + ' Name')
			and (bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000')
			and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or rs.DataViewGUID = @dataViewGUID)
	end else begin
		--fix broken sql report display columns - only works if column name mismatch is only due to extra/missing spaces
		update dc set dc.ColumnName = ra.ColumnName
		from
			viewRESQLReportDisplayColumn_Broken bk
			inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = bk.SQLReportSetupGUID
			inner join RESQLReportDisplayColumn dc on dc.DisplayColumnGUID = bk.DisplayColumnGUID
			inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and replace(ra.ColumnName, ' ', '') = replace(dc.ColumnName, ' ', '')
		where
			bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000'
			and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or rs.DataViewGUID = @dataViewGUID)
	end

	--fix broken sql report filter columns that match rename parameters
	if (@attributeGUIDCSV != '' and @beforeColumnName != '' and @afterColumnName != '') begin
		update fc set fc.ColumnName = ra.ColumnName
		from
			viewRESQLReportFilterColumn_Broken bk
			inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = bk.SQLReportSetupGUID
			inner join RESQLReportFilterColumn fc on fc.FilterColumnGUID = bk.FilterColumnGUID
			inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and ra.ColumnName = @afterColumnName
			inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
			inner join (select guid as AttributeGUID from dbo.ConvertCSGuidsToTable(@attributeGUIDCSV, ',')) csv on csv.AttributeGUID = a.AttributeGUID or csv.AttributeGUID = a.ForeignKeyGUID or csv.AttributeGUID = a.InferredAttributeGUID
		where
			(fc.ColumnName = @beforeColumnName or @beforeColumnName like fc.ColumnName + ' Name')
			and (bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000')
			and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or rs.DataViewGUID = @dataViewGUID)
	end else begin
		--fix broken sql report filter columns - only works if column name mismatch is only due to extra/missing spaces
		update fc set fc.ColumnName = ra.ColumnName
		from
			viewRESQLReportFilterColumn_Broken bk
			inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = bk.SQLReportSetupGUID
			inner join RESQLReportFilterColumn fc on fc.FilterColumnGUID = bk.FilterColumnGUID
			inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and replace(ra.ColumnName, ' ', '') = replace(fc.ColumnName, ' ', '')
		where
			bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000'
			and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or rs.DataViewGUID = @dataViewGUID)
	end

	------------------------------------------
	-- EXCEL REPORTS
	------------------------------------------
	
	--fix broken excel reporter sort columns that match rename parameters
	if (@attributeGUIDCSV != '' and @beforeColumnName != '' and @afterColumnName != '') begin
		update p set p.ColumnName = ra.ColumnName
		from
			viewRESortingParameter_Broken bk
			inner join RESortingParameter p on p.ParameterGUID = bk.ParameterGUID
			inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and ra.ColumnName = @afterColumnName
			inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
			inner join (select guid as AttributeGUID from dbo.ConvertCSGuidsToTable(@attributeGUIDCSV, ',')) csv on csv.AttributeGUID = a.AttributeGUID or csv.AttributeGUID = a.ForeignKeyGUID or csv.AttributeGUID = a.InferredAttributeGUID
		where
			(p.ColumnName = @beforeColumnName or @beforeColumnName like p.ColumnName + ' Name')
			and (bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000')
			and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or bk.DataViewGUID = @dataViewGUID)
	end else begin
		--fix broken excel reporter sort columns - only works if column name mismatch is only due to extra/missing spaces
		update p set p.ColumnName = ra.ColumnName
		from
			viewRESortingParameter_Broken bk
			inner join RESortingParameter p on p.ParameterGUID = bk.ParameterGUID
			inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and replace(ra.ColumnName, ' ', '') = replace(p.ColumnName, ' ', '')
		where
			bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000'
			and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or bk.DataViewGUID = @dataViewGUID)
	end

	------------------------------------------
	-- DASHBOARDS
	------------------------------------------
	if (@dataViewGUID = '00000000-0000-0000-0000-000000000000') begin
		--fix broken desktop parameters
		update bk set bk.ColumnName = ra.ColumnName, bk.Name = case when @afterColumnName = '' then bk.Name else @afterColumnName end
		from 
			viewDesktopParameter_Broken bk
			inner join (
				select
					dp.DesktopParameterGUID,
					max(ra.ColumnName) as ColumnName
				from
					DesktopParameter dp
					inner join REReport r on dp.ReportGuidsCSV like '%' + cast(r.ReportGUID as nvarchar(36)) + '%'
					inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = r.ReportGUID and cast(ra.AttributeGUID as nvarchar(36)) = dp.AttributeID
				group by
					dp.DesktopParameterGUID
			) ra on ra.DesktopParameterGUID = bk.DesktopParameterGUID
	end
GO


---------------------------------------------

-- dbo.procRESQLReportRegisteredAttributeRename
CREATE proc [dbo].[procRESQLReportRegisteredAttributeRename]
	@attributeGUID uniqueidentifier,
	@oldName nvarchar(100),
	@newName nvarchar(100),
	@DataViewGUID uniqueidentifier = null
as
	--get all linked attributes
	declare @refAttributes nvarchar(max)
	select 
		@refAttributes = dbo.strAggr(cast(a.AttributeGUID as nvarchar(36)), ',', '') 
	from 
		viewScoreAttribute a 
	where 
		a.AttributeGUID = @attributeGUID 
		or a.ForeignKeyGUID = @attributeGUID 
		or a.InferredAttributeGUID = @attributeGUID		
	if (@refAttributes is null or @refAttributes = '') begin
		return
	end

	--include CAP attributes that are inferred through Project
	declare @refAttributesCAP nvarchar(max)
	select 
		@refAttributesCAP = dbo.strAggr(cast(a.AttributeGUID as nvarchar(36)), ',', '') 
	from 
		viewScoreAttribute a 
	where 
		a.ForeignKeyGUID in(select guid from dbo.ConvertCSGuidsToTable(@refAttributes, ','))
		or a.InferredAttributeGUID in(select guid from dbo.ConvertCSGuidsToTable(@refAttributes, ','))
	if (@refAttributesCAP is not null and @refAttributesCAP != '') begin
		set @refAttributes = @refAttributes + ',' + @refAttributesCAP
	end

	--include MR Department attributes if renaming a Department attribute
	if (exists(select 1 from viewScoreAttribute where AttributeGUID = @attributeGUID and DimensionName = 'Department')) begin
		declare @refAttributesMR nvarchar(max)
		select 
			@refAttributesMR = dbo.strAggr(cast(mra.AttributeGUID as nvarchar(36)), ',', '') 
		from 
			viewScoreAttribute a 
			inner join viewScoreAttribute mra on mra.SQLColumnName = a.SQLColumnName
		where 
			a.DimensionName = 'Department'
			and mra.DimensionName = 'MR Department'
			and (
				a.AttributeGUID = @attributeGUID 
				or a.ForeignKeyGUID = @attributeGUID 
				or a.InferredAttributeGUID = @attributeGUID		
			)
		if (@refAttributesMR is not null and @refAttributesMR != '') begin
			set @refAttributes = @refAttributes + ',' + @refAttributesMR
		end
	end

	--update registered attribute alias
	update ra set ra.ColumnAlias = @newName
	from 
		RESQLReportRegisteredAttribute ra
		inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID
		left JOIN RESQLReportRegisteredDimension d ON ra.RegisteredDimensionGUID = d.RegisteredDimensionGUID

	where
		a.AttributeGUID in(select guid from dbo.ConvertCSGuidsToTable(@refAttributes, ','))
		and (ra.ColumnAlias = @oldName or @oldName like ra.ColumnAlias + ' Name')
		and (d.DataViewGUID = @DataViewGUID or @DataViewGUID is NULL)

	--fix report dependencies
	exec dbo.procRESQLReportRegisteredAttributeFixReferences '00000000-0000-0000-0000-000000000000', @refAttributes, @oldName, @newName, @DataViewGUID
GO


---------------------------------------------

-- dbo.procRefreshViews
CREATE procedure [dbo].[procRefreshViews] as

DECLARE @tables NVARCHAR(4000)
DECLARE @view SYSNAME
DECLARE @sql NVARCHAR(500)

SET @tables = NULL


SET @sql = N'EXEC sp_refreshView '

DECLARE viewCsr CURSOR READ_ONLY FAST_FORWARD FOR
SELECT 
	 v.SchemaName + '.[' + v.ObjectName + ']' 
FROM 
	dbo.viewSysViews v
WHERE 
	v.ObjectName NOT LIKE 'sys%'
	and v.ObjectName not like 'viewS3%'
	and v.ObjectName != 'viewPlaceholders'
	and v.ObjectName != 'viewWFEntity'	
	and v.ObjectName not like 'viewWFReviewerAssignmentNoDelegates%'	
	and v.SchemaName != 'bak'
order by v.SchemaName, v.ObjectName	
	
--AND @tables IS NULL 
--OR CHARINDEX(OBJECT_NAME(vtu.table_name), N',' + @tables + N',') > 0

OPEN viewCsr

SELECT cast('' as varchar(255)) as viewName into #broken

FETCH NEXT FROM viewCsr INTO @view
WHILE @@FETCH_STATUS = 0
BEGIN
	--PRINT @sql + @view
	BEGIN TRY
		EXEC(@sql + '''' + @view + '''')     
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT >= 1 ROLLBACK
		INSERT INTO #broken (viewName) values (@view)
		--print @@trancount
	END CATCH
	
	FETCH NEXT FROM viewCsr INTO @view
END 

CLOSE viewCsr
DEALLOCATE viewCsr

truncate table RefreshViewsLog;

insert into RefreshViewsLog(BrokenViewName, BrokenViewDropSQL, BrokenViewSelectSQL)
select distinct 
	viewName as BrokenViewName, 
	'drop view ' + viewname as BrokenViewDropSQL,
	'select top 1 * from ' + viewname as BrokenViewSelectSQL
from #broken where viewname <> ''

drop table #broken
select * from RefreshViewsLog
GO


---------------------------------------------

-- dbo.procReinitializeApplicationModes
CREATE proc [dbo].[procReinitializeApplicationModes]
AS
BEGIN
truncate table ApplicationMode
set identity_insert ApplicationMode ON;
insert into ApplicationMode (ApplicationModeID,Name) VALUES (0, 'No Access');
insert into ApplicationMode (ApplicationModeID,Name) VALUES (1, 'Simple Mode');
insert into ApplicationMode (ApplicationModeID,Name) VALUES (2, 'Advanced Mode');
insert into ApplicationMode (ApplicationModeID,Name) VALUES (3, 'Super User Mode');
set identity_insert ApplicationMode OFF;
END
GO


---------------------------------------------

-- dbo.procRemoveController
CREATE    PROCEDURE [dbo].[procRemoveController]
@ControllerID as uniqueidentifier
 AS

DELETE FROM dbo.ActiveControllers WHERE ControllerID=@ControllerID
GO


---------------------------------------------

-- dbo.procRemoveOrphanedMappingsAndDataByDimension
-- =================================================================================
-- Author:		Graydon Foreman
-- Create date: Oct 29, 2007
-- Description:	Removes mappings and data associated with deleted members
-- =================================================================================
CREATE PROCEDURE [dbo].[procRemoveOrphanedMappingsAndDataByDimension]
	@DIMENSIONGUID as uniqueidentifier,
	@debug bit = 0
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @FillInDimensionGUID uniqueidentifier
	SELECT @FillInDimensionGUID = FillInDimensionGUID FROM SecureList WHERE ListGUID = @DimensionGUID

	IF @FillInDimensionGUID = '00000000-0000-0000-0000-000000000000' BEGIN
		SET @FillInDimensionGUID  = @DimensionGUID
	END


	--------------------------
	-- Mapping Removal
	--------------------------

	DECLARE @MappingTable nvarchar(256)
	DECLARE @mapsql nvarchar(4000)

	-- Find all dynamic mapping tables
	DECLARE zzMapTable  CURSOR LOCAL FAST_FORWARD
		FOR SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE 'zzEMFModelTemplateMapping%' AND COLUMN_NAME = dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID)
	OPEN zzMapTable
	FETCH NEXT FROM zzMapTable INTO @MappingTable

	-- Delete this member from mapping tables
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @debug = 1 BEGIN
			SET @mapsql = 'SELECT * FROM '
		END ELSE BEGIN
			SET @mapsql = 'DELETE FROM '
		END

		SET @mapsql = @mapsql + @MappingTable + ' WHERE ' + dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + ' != ''00000000-0000-0000-0000-000000000000'' AND ' + dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + ' NOT IN(SELECT LISTMEMBERGUID FROM SecureListMember WHERE LISTGUID = ''' + cast(@DimensionGUID as nvarchar(36)) + ''')'
		EXECUTE (@mapsql)

		FETCH NEXT FROM zzMapTable INTO @MappingTable
	END

	CLOSE zzMapTable
	DEALLOCATE zzMapTable

	--------------------------
	-- Data Removal
	--------------------------

	DECLARE @DataTable nvarchar(256)
	DECLARE @datasql nvarchar(4000)

	-- Find all dynamic data tables
	DECLARE zzDataTable CURSOR LOCAL FAST_FORWARD
		FOR SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE 'zzEMFModelData%' AND COLUMN_NAME = dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID)
	OPEN zzDataTable
	FETCH NEXT FROM zzDataTable INTO @DataTable

	-- Delete this member from data tables
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @debug = 1 BEGIN
			SET @datasql = 'SELECT * FROM '
		END ELSE BEGIN
			SET @datasql = 'DELETE FROM '
		END
		SET @datasql = @datasql + @DataTable + ' WHERE ' + dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + ' != ''00000000-0000-0000-0000-000000000000'' AND ' + dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + ' NOT IN(SELECT LISTMEMBERGUID FROM SecureListMember WHERE LISTGUID = ''' + cast(@FillInDimensionGUID as nvarchar(36)) + ''')'
		EXECUTE (@datasql)

		FETCH NEXT FROM zzDataTable INTO @DataTable
	END

	CLOSE zzDataTable
	DEALLOCATE zzDataTable
END
GO


---------------------------------------------

-- dbo.procRemoveOrphanedZZTables
CREATE proc [dbo].[procRemoveOrphanedZZTables] as 

declare crsMDTables CURSOR FOR
select name from sysobjects where name like 'zzEMF%' order by name

open crsMDTables;

DECLARE @tableName as varchar(100)
DECLARE @mdcguid uniqueidentifier
DECLARE @guidstring varchar(36)
DECLARE @guidstart int
DECLARE @cnt int

FETCH NEXT FROM crsMDTables into @tableName
WHILE (@@FETCH_STATUS = 0) BEGIN


	SET @guidstart = charindex('_',@tableName)
	SET @guidstring = replace(right(@tablename,len(@tablename) - @guidstart),'_','-')
	SET @mdcguid = @guidstring
	
	SELECT @cnt = count(*) FROM EMFModelDataConfig where modeldataconfigguid = @mdcguid
	
	if @cnt = 0 begin
		print 'drop table ' + @tableName
	end
	FETCH NEXT FROM crsMDTables into @tableName
END

close crsMDTables
DEALLOCATE crsMDTables
GO


---------------------------------------------

-- dbo.procRemoveScoreDataTables
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE dbo.procRemoveScoreDataTables
	@SchemaName varchar(64)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	Declare @SQL varchar(8000)
	Declare @tblname varchar(128)

    Declare crs_tblname Cursor LOCAL Forward_Only  For SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @SchemaName
 	OPEN crs_tblname;
	FETCH NEXT FROM crs_tblname into @tblname;
	WHILE (@@FETCH_STATUS = 0)
	BEGIN
		Set @SQL = 'drop table ' + @schemaname + '.' + @tblname
		print 'Dropping table ' + @schemaname + '.' + @tblname
		exec (@sql)
		exec (@sql) --drop again in case there are foreign keys that errored
		FETCH NEXT FROM crs_tblname into @tblname;
	END
	CLOSE crs_tblname;
	DEALLOCATE crs_tblname;
	
END
GO


---------------------------------------------

-- dbo.procRemoveWorkerFromActiveController
CREATE    PROCEDURE [dbo].[procRemoveWorkerFromActiveController]
@ControllerID as uniqueidentifier,
@WorkerID as uniqueidentifier
 AS

IF ((select count(*) from [dbo].[ActiveControllers] where ControllerID=@ControllerID AND WorkerID=@WorkerID) > 0)
BEGIN
	DELETE FROM [dbo].[ActiveControllers] WHERE ControllerID=@ControllerID AND WorkerID=@WorkerID
END
GO


---------------------------------------------

-- dbo.procReportCopyClientReport
create proc [dbo].[procReportCopyClientReport] 
	@sourcedbname nvarchar(max), 
	@reportguid uniqueidentifier
as
	set nocount on
	exec procReportCopyClientReportXDB @sourcedbname, @reportguid
GO


---------------------------------------------

-- dbo.procReportCopyClientReportXDB
CREATE proc [dbo].[procReportCopyClientReportXDB]
	@sourcedb nvarchar(100),
	@reportGUID uniqueidentifier,
	@toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@debug bit = 0
as	
	declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36))
	
	if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin
		RAISERROR ('Report Name cannot be blank.', 18, 0)
		return
	end
	
	if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin
		print 'Report ' + @reportGUIDStr + ' already exists.'
		return	
	end

	declare @isExecuting bit
	if(@debug = 1) begin
		set @isExecuting = 0
	end else begin
		set @isExecuting = 1
	end

	--put fields in root folder if no folder specified
	declare @folderguid uniqueidentifier
	if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin
		select @folderguid = RootFolderGUID from FolderSet where Type = 4
	end else begin
		set @folderguid = @toFolderGUID
	end
	
	declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + ''''
	declare @whereSection nvarchar(4000) = 'ClientReportSectionGUID in(select l.ClientReportSectionGUID from ' + @sourcedb + '.dbo.REClientReportSectionLink l where l.' + @whereReport + ')'

	--copy dataview
	declare @whereDataView nvarchar(4000) = 'DataViewGUID in (select DataSourceGUID from ' + @sourcedb + '.dbo.REClientReportDataSourceLink s where s.reportguid = ''' + CAST(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'DataView', @whereDataView, @isExecuting
	
	--setup default security for DataVie
	insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select NEWID(), DataViewGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit)
	from DataView where DataViewGUID not in(select sp.LootID from S3SimplePermission sp)

	
	--copy registered dimensions	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESqlReportRegisteredDimension', @whereDataView, @isExecuting
	
	--copy registered attributes
	declare @whereRegisteredAttribute nvarchar(4000) = 'RegisteredDimensionGUID in (select registereddimensionguid from ' + @sourcedb + '.dbo.resqlreportregistereddimension where ' + @whereDataView + ')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportRegisteredAttribute', @whereRegisteredAttribute, @isExecuting	
			
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereReport, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSetup', @whereReport, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSection', @whereSection, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSectionLink', @whereReport, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportConditionalFormat', @whereReport, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportDataSourceLink', @whereReport, @isExecuting, 0, 0, 0
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportParameter', @whereReport, @isExecuting
	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportCalculation', @whereSection, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSectionAttribute', @whereSection, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSectionMeasure', @whereSection, @isExecuting
	
	--for reports that now don't have a valid folder, move to specified folder
	if(@isExecuting = 1) begin
		update REReport set FolderGUID = @folderguid where FolderGUID not in(select f.FolderGUID from Folder f)
	end else begin
		print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select f.FolderGUID from Folder f)'
	end
	
	--setup default security
	insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit)
	from REReport where ReportGUID not in(select sp.LootID from S3SimplePermission sp)
GO


---------------------------------------------

-- dbo.procReportCopyCubeReport
-- =============================================
-- Author:		Mitch and Jacky
-- Create date: Now
-- Description:	Copies Cube Reports from any database to this one
-- =============================================
CREATE PROCEDURE [dbo].[procReportCopyCubeReport] 
	-- Add the parameters for the stored procedure here
	@sourcedbname nvarchar(max), 
	@reportguid uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

declare @sql as nvarchar(max)
set @sql = 
'
declare @reportguid as uniqueidentifier 
set @reportguid = ''' + cast(@reportGUID as nvarchar(128)) + '''

declare @reportSetupGUID as uniqueidentifier 
set @reportsetupguid = (select top 1 Cubereportsetupguid from ' + @sourcedbname + '.[dbo].RECubeReportSetup where ReportGUID=@reportguid)

if @reportguid <> dbo.ZeroGUID() and (select COUNT(*) from REReport where ReportGUID=@reportguid) = 0 begin
	-- copy report
	insert into REReport
	select * from
		' + @sourcedbname + '.[dbo].REReport
	where reportguid=@reportguid

	-- copy report setup
	insert into RECubeReportSetup
	select * from 
		' + @sourcedbname + '.[dbo].RECubeReportSetup
	where ReportGUID=@reportguid

	-- copy Dimension
	insert into RECubeReportDimension
	select * from 
		' + @sourcedbname + '.[dbo].RECubeReportDimension
	where CubeReportSetupGUID=@reportSetupGUID	

	-- copy dimension Levels
	insert into RECubeReportLevel
	select * from 
		' + @sourcedbname + '.[dbo].RECubeReportLevel
	where CubeReportDimensionGUID in (Select cubereportdimensionguid from RECubeReportDimension where CubeReportSetupGUID = @reportSetupGUID)
	
	-- copy Measure
	insert into RECubeReportMeasure
	select * from 
		' + @sourcedbname + '.[dbo].RECubeReportMeasure
	where CubeReportSetupGUID=@reportSetupGUID	
	
	-- copy Parameters
	insert into RECubeReportParameter
	select * from 
		' + @sourcedbname + '.[dbo].RECubeReportParameter
	where CubeReportSetupGUID=@reportSetupGUID	
	
	-- set security
	insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values (@reportguid, ''00000000-0000-0000-0000-000000000001'', 1, 1, 1)
end'

exec(@sql)

END
GO


---------------------------------------------

-- dbo.procReportCopyDSCubeReport
Create proc [dbo].[procReportCopyDSCubeReport]
	@sourcedb nvarchar(100),
	@reportGUID uniqueidentifier,
	@toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@debug bit = 0
as	
	declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36))
	
	if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin
		RAISERROR ('Report Name cannot be blank.', 18, 0)
		return
	end
	
	if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin
		print 'Report ' + @reportGUIDStr + ' already exists.'
		return	
	end

	declare @isExecuting bit
	if(@debug = 1) begin
		set @isExecuting = 0
	end else begin
		set @isExecuting = 1
	end

	--put fields in root folder if no folder specified
	declare @folderguid uniqueidentifier
	if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin
		select @folderguid = RootFolderGUID from FolderSet where Type = 4
	end else begin
		set @folderguid = @toFolderGUID
	end
	
	declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + ''''
	declare @whereSection nvarchar(4000) = 'DSCubeReportSectionGUID in(select l.DSCubeReportSectionGUID from ' + @sourcedb + '.dbo.REDSCubeReportSectionLink l where l.' + @whereReport + ')'
	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereReport, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSetup', @whereReport, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSection', @whereSection, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSectionLink', @whereReport, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportConditionalFormat', @whereReport, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportDataSourceLink', @whereReport, @isExecuting, 0, 0, 0
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportParameter', @whereReport, @isExecuting
	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportCalculation', @whereSection, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSectionAttribute', @whereSection, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSectionMeasure', @whereSection, @isExecuting
	
	--for reports that now don't have a valid folder, move to specified folder
	if(@isExecuting = 1) begin
		update REReport set FolderGUID = @folderguid where FolderGUID not in(select f.FolderGUID from Folder f)
	end else begin
		print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select f.FolderGUID from Folder f)'
	end
	
	--setup default security
	insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit)
	from REReport where ReportGUID not in(select sp.LootID from S3SimplePermission sp)
GO


---------------------------------------------

-- dbo.procReportCopyERReport
-- =============================================
-- Author:		Mitch and Jacky
-- Create date: Now
-- Description:	Copies Cube Reports from any database to this one
-- =============================================
CREATE PROCEDURE [dbo].[procReportCopyERReport] 
	-- Add the parameters for the stored procedure here
	@sourcedbname nvarchar(max), 
	@reportguid uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	exec procReportCopyERXDB @sourcedbname, @reportguid
	
END
GO


---------------------------------------------

-- dbo.procReportCopyERXDB
CREATE proc [dbo].[procReportCopyERXDB]
	@sourcedb nvarchar(100),
	@reportGUID uniqueidentifier,
	@toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@debug bit = 0
as
	declare @whereClause nvarchar(4000)
	
	if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin
		RAISERROR ('Report Name cannot be blank.', 18, 0)
		return
	end

	declare @isExecuting bit
	if(@debug = 1) begin
		set @isExecuting = 0
	end else begin
		set @isExecuting = 1
	end

	--put fields in root folder if no folder specified
	declare @folderguid uniqueidentifier
	if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin
		select @folderguid = RootFolderGUID from FolderSet where Type = 4
	end else begin
		set @folderguid = @toFolderGUID
	end
	
	--copy report	
	set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereClause, @isExecuting

	-- Actual excel file
	set @whereClause = 'fullpath = ''Reporting\VSTO Excel Reports\' + cast(@reportGUID as nvarchar(36)) + '.xls'''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'DataPathFile_Reporting', @whereClause, @isExecuting
	
	--copy the sheetconfigs
	set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'resheetconfig', @whereClause, @isExecuting

	--copy the exconfigs from the sheet configs 
	set @whereClause = 'sheetguid in (select sheetguid from ' + @sourcedb + '.dbo.RESheetConfig where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'reexconfig', @whereClause, @isExecuting
	
	--copy the exconfigfiltermembers from the sheet configs 
	set @whereClause = 'ExConfigGUID in (select ExConfigGUID from ' + @sourcedb + '.dbo.REExConfig ex inner join ' + @sourcedb + '.dbo.RESheetConfig sh on sh.SheetGUID = ex.SheetGUID where sh.reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REExConfigFilterMembers', @whereClause, @isExecuting, 0, 0, 0
	
	if(@isExecuting = 1) begin
		update REReport set FolderGUID = @folderguid where FolderGUID not in(select FolderGUID from Folder)
	end else begin
		print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select FolderGUID from Folder)'
	end
	
	--sql reports
	declare @sql as nvarchar(max)
	set @sql = '	
	declare @reportguid as uniqueidentifier 
	set @reportguid = ''' + cast(@reportGUID as nvarchar(36)) + '''
	declare @csv nvarchar(max) 
	select @csv = coalesce(@csv + '','','''') + cast(sourceguid  as nvarchar(128)) from ' + @sourcedb + '.[dbo].[redatasource] where reportguid = @reportguid and sourcetype = 6

	declare @repsql as nvarchar(200)
	set @repsql = ''procReportCopySQLXDB ''''' + @sourcedb + ''''', {guidq}, ''''00000000-0000-0000-0000-000000000000'''', ' + cast(@debug as nvarchar(1)) + '''

	exec procRunForManyGUIDs @repsql, @csv, ' + cast(@isExecuting as nvarchar(1))
	print ''
	exec(@sql)
	print ''
		
	-- datasources
	set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDataSource', @whereClause, @isExecuting
	
	-- numbering parameter
	set @whereClause = 'DatasourceGUID in (select datasourceguid from ' + @sourcedb + '.dbo.redatasource where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RENumberingParameter', @whereClause, @isExecuting	

	-- query parameter
	set @whereClause = 'DatasourceGUID in (select datasourceguid from ' + @sourcedb + '.dbo.redatasource where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'requeryparameter', @whereClause, @isExecuting		

	-- sorting parameter
	set @whereClause = 'DatasourceGUID in (select datasourceguid from ' + @sourcedb + '.dbo.redatasource where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'resortingparameter', @whereClause, @isExecuting			

	-- grouping parameters
	set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'regroupingparameter', @whereClause, @isExecuting	

	-- grouping parameter links
	set @whereClause = 'groupingparameterguid in (select groupingparameterguid from ' + @sourcedb + '.dbo.regroupingparameter where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'regroupingparameterlink', @whereClause, @isExecuting				

	--setup default security
	insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit)
	from REReport where ReportGUID not in(select LootID from S3SimplePermission)
GO


---------------------------------------------

-- dbo.procReportCopyExtractReport
CREATE proc [dbo].[procReportCopyExtractReport] 
	@sourcedbname nvarchar(max), 
	@reportguid uniqueidentifier
as
	set nocount on
	exec procReportCopyExtractReportXDB @sourcedbname, @reportguid
GO


---------------------------------------------

-- dbo.procReportCopyExtractReportXDB
CREATE proc [dbo].[procReportCopyExtractReportXDB]
	@sourcedb nvarchar(100),
	@reportGUID uniqueidentifier,
	@toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@debug bit = 0
AS	
	declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36))
	

	if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin
		RAISERROR ('Report Name cannot be blank.', 18, 0)
		return
	end

	if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin
		print 'Report ' + @reportGUIDStr + ' already exists.'
		return	
	end

	exec procReportCopyClientReportXDB @sourcedb, @reportGUID, @toFolderGUID, @debug


	declare @isExecuting bit
	if(@debug = 1) begin
		set @isExecuting = 0
	end else begin
		set @isExecuting = 1
	end
		
	declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + ''''
	declare @whereSection nvarchar(4000) = 'ClientReportSetupGUID in (select l.ClientReportSetupGUID from ' + @sourcedb + '.dbo.REClientReportSetup l where l.' + @whereReport + ')'
	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REExtractReportOutputColumn', @whereSection, @isExecuting
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REExtractReportOutputFormat', @whereSection, @isExecuting
GO


---------------------------------------------

-- dbo.procReportCopyFileReport
CREATE proc [dbo].[procReportCopyFileReport] 
	@sourcedbname nvarchar(max), 
	@reportguid uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	exec procReportCopyFileXDB @sourcedbname, @reportguid
END
GO


---------------------------------------------

-- dbo.procReportCopyFileXDB
CREATE proc [dbo].[procReportCopyFileXDB]
	@sourcedb nvarchar(100),
	@reportGUID uniqueidentifier,
	@toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@debug bit = 0
as
	declare @whereClause nvarchar(4000)
	
	if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin
		RAISERROR ('Report GUID cannot be blank.', 18, 0)
		return
	end

	declare @isExecuting bit
	if(@debug = 1) begin
		set @isExecuting = 0
	end else begin
		set @isExecuting = 1
	end

	--put fields in root folder if no folder specified
	declare @folderguid uniqueidentifier
	if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin
		select @folderguid = RootFolderGUID from FolderSet where Type = 4
	end else begin
		set @folderguid = @toFolderGUID
	end
	
	--copy report	
	set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereClause, @isExecuting

	--copy report setup
	declare @whereReportSetup nvarchar(4000) = 'FileReportSetupGUID in (select rs.filereportsetupguid from ' + @sourcedb + '.dbo.REFileReportSetup rs where rs.reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REFileReportSetup', @whereReportSetup, @isExecuting

	--actual file
	set @whereClause = 'FileName like ''%' + cast(@reportGUID as nvarchar(36)) + '%'''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'DataPathFile_Reporting', @whereClause, @isExecuting
	
	--for reports that now don't have a valid folder, move to specified folder
	if(@isExecuting = 1) begin
		update REReport set FolderGUID = @folderguid where FolderGUID not in(select sf.FolderGUID from Folder sf)
	end else begin
		print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select sf.FolderGUID from Folder sf)'
	end
	
	--setup default security
	insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit)
	from REReport where ReportGUID not in(select p.LootID from S3SimplePermission p)
GO


---------------------------------------------

-- dbo.procReportCopyMDReport
CREATE PROCEDURE [dbo].[procReportCopyMDReport] 
	-- Add the parameters for the stored procedure here
	@sourcedbname nvarchar(max), 
	@reportguid uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	exec procReportCopyMDXDB @sourcedbname, @reportguid
	
END
GO


---------------------------------------------

-- dbo.procReportCopyMDXDB
create PROCEDURE [dbo].[procReportCopyMDXDB]
	@sourcedb nvarchar(100),
	@reportGUID uniqueidentifier,
	@toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@debug bit = 0
as	
	declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36))
	
	if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin
		RAISERROR ('Report Name cannot be blank.', 18, 0)
		return
	end
	
	if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin
		print 'Report ' + @reportGUIDStr + ' already exists.'
		return	
	end

	declare @isExecuting bit
	if(@debug = 1) begin
		set @isExecuting = 0
	end else begin
		set @isExecuting = 1
	end

	--put fields in root folder if no folder specified
	declare @folderguid uniqueidentifier
	if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin
		select @folderguid = RootFolderGUID from FolderSet where Type = 4
	end else begin
		set @folderguid = @toFolderGUID
	end
	
	--copy report
	declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereReport, @isExecuting
			
	--copy report setup
	declare @whereReportSetup nvarchar(4000) = 'ModelDataReportSetupGUID in (select rs.modeldatareportsetupguid from ' + @sourcedb + '.dbo.REModelDataReportSetup rs where rs.reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REModelDataReportSetup', @whereReportSetup, @isExecuting
	
	--setup default security
	insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit)
	from REReport where ReportGUID not in(select LootID from S3SimplePermission)
GO


---------------------------------------------

-- dbo.procReportCopyReport
CREATE PROCEDURE [dbo].[procReportCopyReport]  
	@ReportGUID as UniqueIdentifier,
	@SourceDBName as nvarchar(max)
AS
BEGIN
	SET NOCOUNT ON;

	declare @sql as nvarchar(max)
	set @sql = '
	    declare @reporttype nvarchar(max)
	    
	    select top 1 @reporttype = AssemblyQualifiedName from ' + @SourceDBName + '.[dbo].[rereport] where ReportGUID = ''' + Cast(@ReportGUID as Nvarchar(max)) + '''
	    
	    if @reporttype like ''Strata.Reporting.ExcelReporter%''
	    begin 
			exec [procReportCopyERReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + '''
	    end	
	    else if @reporttype like ''Strata.CubeReporter%''
	    begin
			exec [procReportCopyCubeReport] ''' + @SourceDBName + ''',  ''' + Cast(@ReportGUID as Nvarchar(max)) + '''
	    end
	    else if @reporttype like ''Strata.X.Biz.Reporting.SQLReport%''
	    begin 
			exec [procReportCopySQLReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + '''
	    end
	    else if @reporttype like ''Strata.X.Biz.Reporting.ModelDataReport%''
	    begin 
			exec [procReportCopyMDReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + '''
	    end
	    else if @reporttype like ''Strata.X.Biz.Reporting.FileReport%''
	    begin 
			exec [procReportCopyFileReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + '''
	    end
	    else if @reporttype like ''Strata.CS.Jazz.Biz.Reporting.ClientReport%''
	    begin 
			exec [procReportCopyClientReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + '''
	    end
	    else if @reporttype like ''Strata.CS.Jazz.Biz.Reporting.DSCubeReport%''
	    begin 
			exec [procReportCopyDSCubeReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + '''
	    end	    
	'
	    
	    exec (@sql)
	end
GO


---------------------------------------------

-- dbo.procReportCopySQLReport
-- =============================================
-- Author:		Mitch and Jacky
-- Create date: Now
-- Description:	Copies Cube Reports from any database to this one
-- =============================================
CREATE PROCEDURE [dbo].[procReportCopySQLReport] 
	-- Add the parameters for the stored procedure here
	@sourcedbname nvarchar(max), 
	@reportguid uniqueidentifier
AS
BEGIN
	
	exec procReportCopySQLXDB @sourcedbname, @reportguid
	
END
GO


---------------------------------------------

-- dbo.procReportCopySQLXDB
--Author: jchau
--Branch: Earwig
--Forward


CREATE proc [dbo].[procReportCopySQLXDB]
	@sourcedb nvarchar(100),
	@reportGUID uniqueidentifier,
	@toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@debug bit = 0
as	
	declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36))
	
	if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin
		RAISERROR ('Report Name cannot be blank.', 18, 0)
		return
	end
	
	if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin
		print 'Report ' + @reportGUIDStr + ' already exists.'
		return	
	end

	declare @isExecuting bit
	if(@debug = 1) begin
		set @isExecuting = 0
	end else begin
		set @isExecuting = 1
	end

	--put fields in root folder if no folder specified
	declare @folderguid uniqueidentifier
	if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin
		select @folderguid = RootFolderGUID from FolderSet where Type = 4
	end else begin
		set @folderguid = @toFolderGUID
	end
	
	--copy dataview
	declare @whereDataView nvarchar(4000) = 'DataViewGUID in (select dataviewguid from ' + @sourcedb + '.dbo.resqlreportsetup s where s.reportguid = ''' + CAST(@reportGUID as nvarchar(36)) + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'DataView', @whereDataView, @isExecuting
	
	--copy registered dimensions	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESqlReportRegisteredDimension', @whereDataView, @isExecuting
	
	--copy registered attributes
	declare @whereRegisteredAttribute nvarchar(4000) = 'RegisteredDimensionGUID in (select registereddimensionguid from ' + @sourcedb + '.dbo.resqlreportregistereddimension where ' + @whereDataView + ')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportRegisteredAttribute', @whereRegisteredAttribute, @isExecuting	
			
	--copy report	
	declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereReport, @isExecuting

	--copy report setup
	declare @whereReportSetup nvarchar(4000) = 'SQLReportSetupGUID in (select sqlreportsetupguid from ' + @sourcedb + '.dbo.resqlreportsetup where reportguid = ''' + @reportGUIDStr + ''')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportSetup', @whereReportSetup, @isExecuting
	
	--copy display columns	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportDisplayColumn', @whereReportSetup, @isExecuting

	--copy filter columns	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportFilterColumn', @whereReportSetup, @isExecuting
	
	--copy pivot columns	
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportPivotColumn', @whereReportSetup, @isExecuting
	
	--copy pivot column filters
	declare @wherePivotColumnFilter nvarchar(4000) = 'PivotColumnGUID in (select PivotColumnGUID from ' + @sourcedb + '.dbo.RESQLReportPivotColumn where ' + @whereReportSetup + ')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportPivotColumnFilter', @wherePivotColumnFilter, @isExecuting
	
	--for reports that now don't have a valid folder, move to specified folder
	if(@isExecuting = 1) begin
		update REReport set FolderGUID = @folderguid where FolderGUID not in(select FolderGUID from Folder)
	end else begin
		print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select FolderGUID from Folder)'
	end
	
	--setup default security
	insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit)
	from REReport where ReportGUID not in(select LootID from S3SimplePermission)



RETURN
GO


---------------------------------------------

-- dbo.procReportCopySystemReport
-- =============================================
-- Author:		Mitch and Jacky
-- Create date: Now
-- Description:	Copies System Reports from any database to this one
-- =============================================
CREATE PROCEDURE [dbo].[procReportCopySystemReport] 
	-- Add the parameters for the stored procedure here
	@sourcedbname nvarchar(max), 
	@reportguid uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	declare @reportguidstring as nvarchar(128)
	set @reportguidstring = cast(@reportGUID as nvarchar(128))
	declare @where as nvarchar(max)
	set @where = 'REPORTGUID = ''' + @reportguidstring + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedbname, 'REReport', @where, 1, 0, 0 

	declare @reportfilename as varchar(64)
	set @reportfilename = (select 'ExReports\' + REPLACE(Name,' ','') from rereport where reportguid = @reportguid)

    set @where = 'fullpath like (''' + @reportfilename + '%'')'
	exec procMigrateScriptGetByTable 'dbo', @sourcedbname, 'datapathfile', @where, 1, 0, 0
	
	set @where = 'reportguid = ''' + @reportguidstring + ''''
	exec procMigrateScriptGetByTable 'dbo', @sourcedbname, 'REExReportSetup', @where, 1, 0, 0
	
	insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values (@reportguid, '00000000-0000-0000-0000-000000000001', 1, 1, 1)

	exec procReportValidateFolderGUID @reportguid

END
GO


---------------------------------------------

-- dbo.procReportDebug
-- Fix Scripts


CREATE PROCEDURE [dbo].[procReportDebug]
	@ReportGUID uniqueidentifier
AS
BEGIN

	select R.AuthorFullName, R.Name, R.ReportGUID, R.DateCreated, R.DateLastModified from [dbo].REReport R
	where ReportGUID = @ReportGUID

	select Name, cast(parametervaluexml as xml) as [ParameterXML] from [dbo].regroupingparameter 
	where reportguid = @ReportGUID

	select ds.Name as DataSourceName, r.Name as SQLReportName, r.ReportGUID as SQLReportGUID, dv.SQLViewName from [dbo].REDataSource ds 
		inner join [dbo].REReport r on ds.SourceGUID=r.ReportGUID
		inner join [dbo].RESQLReportSetup rs on rs.ReportGUID=r.ReportGUID
		inner join [dbo].DataView dv on dv.DataViewGUID = rs.DataViewGUID
	where ds.ReportGUID=@reportguid
	order by ds.Name

END
GO


---------------------------------------------

-- dbo.procReportDeleteERReport
CREATE PROCEDURE [dbo].[procReportDeleteERReport] 
	-- Add the parameters for the stored procedure here
	@reportguid uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	-- Excel File
	delete from datapathfile_reporting where fullpath = 'Reporting\VSTO Excel Reports\' + convert(varchar(max), @reportguid) + '.xls'

	-- ER Configs
	delete from REExConfig where SheetGUID in (select SheetGUID from RESheetConfig where ReportGUID=@reportguid)
	delete from RESheetConfig where ReportGUID=@reportguid
	
	-- Parameters
	delete from RENumberingParameter where DataSourceGUID in (select DataSourceGUID from REDataSource where ReportGUID=@reportguid)
	delete from REQueryParameter where DataSourceGUID in (select DataSourceGUID from REDataSource where ReportGUID=@reportguid)
	delete from RESortingParameter where DataSourceGUID in (select DataSourceGUID from REDataSource where ReportGUID=@reportguid)
	
	delete from REGroupingParameterLink where GroupingParameterGUID in (select groupingparameterguid from regroupingparameter where reportguid = @reportguid)
	delete from REGroupingParameter where ReportGUID=@reportguid
	
	-- Data Sources
	delete from REDataSource where ReportGUID=@reportguid
	
	-- REReport
	delete from REReport where ReportGUID=@reportguid
	
	-- Remove orphaned datasources
	exec procReportRemoveOrphanedERDatasources 
	
	print 'Success'
	
END

RETURN
GO


---------------------------------------------

-- dbo.procReportRemoveBatchReports
CREATE PROC dbo.[procReportRemoveBatchReports]

as

declare crsGUIDs_1 CURSOR FOR
	select r.ReportGuid from REReport r where r.IsBatchReport = 1
	
open crsGUIDs_1;

-- Delete ER reports
declare @reportGuid uniqueidentifier
FETCH NEXT FROM crsGUIDs_1 into @reportGuid
WHILE (@@FETCH_STATUS = 0) 
	BEGIN		
		exec dbo.procReportDeleteERReport @reportGuid					
		FETCH NEXT FROM crsGUIDs_1 into @reportGuid
	END
close crsGUIDs_1;
DEALLOCATE crsGUIDs_1;
GO


---------------------------------------------

-- dbo.procReportRemoveCachedReportsByPlan
CREATE PROCEDURE [dbo].[procReportRemoveCachedReportsByPlan] 
	@planguid as uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	-- Remove any cached reports tied to that plan
	delete from RECachedReport where Identifier like '%' + CAST(@planguid as varchar(36)) + '%'
	
END

RETURN
GO


---------------------------------------------

-- dbo.procReportRemoveCachedReportsByPlanType
CREATE PROCEDURE [dbo].[procReportRemoveCachedReportsByPlanType]
	@plantypeguid as uniqueidentifier
AS
BEGIN
	SET NOCOUNT ON
	
--GET ALL THE PLANGUIDS from the plantype
declare crsGUIDs CURSOR FOR
	select PLANGUID
	from XPlan WHERE PlanTypeGUID = @plantypeguid
	
open crsGUIDs;

-- Loop through them and remove for each planguid with the 
--Remove Cached reports by plan
declare @guid uniqueidentifier
FETCH NEXT FROM crsGUIDs into @guid
WHILE (@@FETCH_STATUS = 0) 
	BEGIN	
		exec procReportRemoveCachedReportsByPlan @guid
		
		FETCH NEXT FROM crsGUIDs into @guid
	END
END

Deallocate crsGUIDs
GO


---------------------------------------------

-- dbo.procReportRemoveCachedReportsByReport
-- =============================================
-- Author:		Jacky
-- Create date: Now
-- Description:	Remove cached reports with missing reportguids and stale datapathfile for missing cached reports
-- =============================================
CREATE PROCEDURE [dbo].[procReportRemoveCachedReportsByReport] 
	@reportguid as uniqueidentifier
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	-- Remove any cached reports tied to that plan
	delete from RECachedReport where ReportGUID=@reportguid
	
	-- Remove any datapath file with missing cached reports
	delete from DataPathFile where FullPath like 'Reporting\Cached Reports\%' and cast(LEFT(filename, 36) as uniqueidentifier) not in (select cachedreportguid from RECachedReport)
	
END
GO


---------------------------------------------

-- dbo.procReportRemoveOrphanedCachedReports
-- =============================================
-- Author:		Jacky
-- Create date: Now
-- Description:	Remove cached reports with missing reportguids and stale datapathfile for missing cached reports
-- =============================================
CREATE PROCEDURE [dbo].[procReportRemoveOrphanedCachedReports] 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	-- Remove any cached reports with missing report guids
	delete from RECachedReport where ReportGUID not in (select ReportGUID from REReport)
	
	-- rolling delete of datapath file
	CREATE TABLE #LogDeleted (fileGUID uniqueidentifier);

	WHILE (1 = 1)
	BEGIN
		DELETE top (1000) DataPathFile_Reporting
			OUTPUT deleted.FileGUID into #LogDeleted
		FROM DataPathFile_Reporting TH 
		WHERE TH.FullPath like 'Reporting\Cached Reports\%' and cast(LEFT(TH.filename, 36) as uniqueidentifier) not in (select cachedreportguid from RECachedReport)

		if ((select COUNT(*) from #LogDeleted) = 0)
		BEGIN
			BREAK;
		END

		delete from #LogDeleted;

	END

	DROP TABLE #LogDeleted;

END


RETURN
GO


---------------------------------------------

-- dbo.procReportRemoveOrphanedDataPathFiles
CREATE PROC dbo.procReportRemoveOrphanedDataPathFiles

AS

delete from datapathfile_reporting
where FileName like '%.xls' and FileName not  in (select CAST(reportguid as nvarchar(36)) + '.xls' from REReport)

delete from datapathfile_reporting
where FileName like '%.pdf' and FileName not  in (select CAST(reportguid as nvarchar(36)) + '.pdf' from REReport)

exec dbo.procReportRemoveOrphanedCachedReports
GO


---------------------------------------------

-- dbo.procReportRemoveOrphanedERDatasources
-- =================================================================================
-- Author:		Jacky Chau
-- Create date: December 14, 2009
-- Description:	Removes orphaned ER datasource SQL reports
-- =================================================================================
CREATE PROC [dbo].[procReportRemoveOrphanedERDatasources] AS
	set nocount on;

	declare @count int

	select
		distinct RE.ReportGUID as rguid
	into #orphans
	from
		REReport RE 
		left join REDataSource DS on DS.SourceGUID=RE.ReportGUID
	where 
		RE.IsDataSource=1 and DS.ReportGUID is null	

	delete from REReport where ReportGUID in(select rguid from #orphans)

	select @count = count(*) from #orphans

	drop table #orphans

	print cast(@count as varchar(12)) + ' reports removed'
GO


---------------------------------------------

-- dbo.procReportValidateFolderGUID
-- =============================================
-- Author:		Mitch
-- checks to see if the reports folder guid exists if it does do nothing
-- if it doesnt place in the root reports folder '62D99FB1-12A2-4BE7-8D1D-92B60A181FA3'
-- =============================================
CREATE PROCEDURE [dbo].[procReportValidateFolderGUID]
	@reportguid AS uniqueidentifier
AS
BEGIN

	declare @folderguid as uniqueidentifier
	select @folderguid = FolderGUID from REReport where ReportGUID = @reportguid

	if (select COUNT(*) from Folder where FolderGuid = @folderguid) = 0
	begin
		update REReport SET FolderGUID = (SELECT TOP 1 RootFolderGUID from FolderSet where Type = 4) WHERE ReportGUID = @reportguid
	end
END
GO


---------------------------------------------

-- dbo.procRollingDeleteNoTruncateOnTable
CREATE PROC [dbo].[procRollingDeleteNoTruncateOnTable] 
	@tableSchema nvarchar(128),
	@tableName nvarchar(128),
	@identityColumn nvarchar(128), --SHOULD Be RowID 95% of the time
	@fromClause nvarchar(max),
	@whereClause nvarchar(max),
	@deleteRecordCount int,
	@isPrintingStatement bit = 1,
	@identityTableAlias nvarchar(128) = ''
AS
/**** The stored procedure is created based on dbo.procRollingDeleteOnTable ****/
/**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI				Description
** 1		2022-09-20	KF			JAZZ-6746		JAZZ-36879 PR\\Metrics Definition: communication failure error when deleting many metrics with related pi.factmetric data
*************************************************************/


IF (@fromClause is null or @fromClause = '')
BEGIN
	raiserror( 'FROM CLAUSE IS EMPTY ', 0, 1) WITH NOWAIT;
	RETURN
END

IF (@deleteRecordCount <= 0) 
BEGIN
	raiserror( 'ERROR: Delete Record Count is Less than or equal to zero ', 0, 1) WITH NOWAIT;
	RETURN
END

-- GET THE IDENTITY TYPE
DECLARE @sqlType int, @maxlength int, @precision int, @scale int
select  
	@sqlType = c.system_type_id, @maxlength = c.max_length, @precision = c.precision, @scale = c.scale 
from sys.columns c
inner join sys.objects o ON o.object_id = c.object_id
inner join sys.schemas s ON s.schema_id = o.schema_id
WHERE s.name = @tableSchema AND o.name = @tableName AND c.name = @identityColumn

declare @sqlStringType nvarchar(128)
SET @sqlStringType = dbo.GetSQLFullyQualifiedType(@sqlType, @maxlength, @precision, @scale)

DECLARE @idcol nvarchar(128)
SET @idcol = 'id' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '')  --replace guid with no dashes and start the table name with a 'g'

DECLARE @tempTable nvarchar(128)
SET @tempTable = '[data].RollingDelete' + @tableName + 'g' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '')  --replace guid with no dashes and start the table name with a 'g'

--CREATE THE SQL STATEMENT

DECLARE @sql as NVARCHAR(MAX)
SET @sql = 
'

DECLARE @start BIGINT;
DECLARE @end BIGINT;
DECLARE @step BIGINT;
'

IF @identityTableAlias <> ''
BEGIN
	Set @identityTableAlias =  @identityTableAlias + '.';
END


SET @sql = @sql + '

	CREATE TABLE ' + @tempTable + '
	(
		' + @idcol + ' bigint identity(1,1),
		' + @identityColumn + ' ' + @sqlStringType + ' --lookup type
	)
	WITH (DATA_COMPRESSION = PAGE) 

	CREATE CLUSTERED INDEX IX_' + @idcol + '_ID_IDENTITY
		ON '+ @tempTable + '(' + @idcol + ', ' + @identityColumn + '); 


	SELECT @start = MIN(' + @identityTableAlias + @identityColumn + '), @end = MAX(' + @identityTableAlias + @identityColumn + ')
	FROM ' + @FROMCLAUSE
	
	IF NOT( @whereClause  is null or @whereClause  = '')
	BEGIN
		SET @sql = @sql + ' WHERE ' + @whereclause
	END
	
SET @sql = @sql + '
	
	WHILE (@start <= @end)
	BEGIN  
		SET @step = @start + 499999;
            
		If @step > @end
		BEGIN
			SET @step = @end;
		END
		INSERT INTO ' + @tempTable + '
		SELECT ' + @identityTableAlias + @identityColumn + '
		FROM ' + @FROMCLAUSE 
	
	IF NOT( @whereClause  is null or @whereClause  = '')
	BEGIN
		SET @sql = @sql + ' WHERE ' + @whereclause + ' and ' + @identityTableAlias + @identityColumn + ' BETWEEN @start AND @step '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' WHERE ' + @identityTableAlias + @identityColumn + ' BETWEEN @start AND @step '
	END
	
	SET @sql = @sql + '
                    
		SET @start = @start + 500000;
	END
'
	SET @sql = @sql + ' 

	raiserror( ''Starting standard delete path on: ' +  @tableSchema + '.' + @tableName + ''' , 0, 1) WITH NOWAIT;
	DECLARE 
		@maxid AS BIGINT
		,@currentid BIGINT
		,@nowAsString varchar(30)
	select @currentid = 1
	select @maxid=max(' + @idcol + ' ) FROM ' + @tempTable + '
		
	while @currentid<=@maxid
	begin
	  set @nowAsString = convert( varchar(30), getdate(), 121 );
	  raiserror( ''@currentid %I64d at %s...'', 0, 1, @currentid, @nowAsString ) WITH NOWAIT ;
	  DELETE TN FROM ' + @tableSchema + '.' + @tableName + ' TN
	  INNER JOIN '+ @tempTable + ' DT ON DT.' + @identityColumn + ' = TN.' + @identityColumn + ' AND DT.' + @idcol + '  BETWEEN @currentid AND @currentid + ' + CAST(@deleteRecordCount AS NVARCHAR(10)) + '
	  SET @currentid = @currentid + ' + CAST(@deleteRecordCount AS NVARCHAR(10)) + ' + 1
	END
	raiserror( ''Finished delete on: ' + @tableSchema + '.' + @tableName + ''' , 0, 1) WITH NOWAIT;
	

	DROP TABLE ' + @tempTable + '
'

IF @isPrintingStatement = 1
BEGIN
	PRINT (cast(@sql as ntext));
END
ElSE
BEGIN
	EXEC (@sql);
END
GO


---------------------------------------------

-- dbo.procRollingDeleteOnTable
CREATE PROC [dbo].[procRollingDeleteOnTable] 
	@tableSchema nvarchar(128),
	@tableName nvarchar(128),
	@identityColumn nvarchar(128), --SHOULD Be RowID 95% of the time
	@fromClause nvarchar(max),
	@whereClause nvarchar(max),
	@deleteRecordCount int,
	@truncateThreshold decimal(4, 3),
	@isPrintingStatement bit = 1,
	@identityTableAlias nvarchar(128) = ''
AS

IF (@fromClause is null or @fromClause = '')
BEGIN
	raiserror( 'FROM CLAUSE IS EMPTY ', 0, 1) WITH NOWAIT;
	RETURN
END

IF (@deleteRecordCount <= 0) 
BEGIN
	raiserror( 'ERROR: Delete Record Count is Less than or equal to zero ', 0, 1) WITH NOWAIT;
	RETURN
END

-- GET THE IDENTITY TYPE
DECLARE @sqlType int, @maxlength int, @precision int, @scale int
select  
	@sqlType = c.system_type_id, @maxlength = c.max_length, @precision = c.precision, @scale = c.scale 
from sys.columns c
inner join sys.objects o ON o.object_id = c.object_id
inner join sys.schemas s ON s.schema_id = o.schema_id
WHERE s.name = @tableSchema AND o.name = @tableName AND c.name = @identityColumn

declare @sqlStringType nvarchar(128)
SET @sqlStringType = dbo.GetSQLFullyQualifiedType(@sqlType, @maxlength, @precision, @scale)

DECLARE @idcol nvarchar(128)
SET @idcol = 'id' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '')  --replace guid with no dashes and start the table name with a 'g'

DECLARE @tempTable nvarchar(128)
SET @tempTable = '[data].RollingDelete' + @tableName + 'g' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '')  --replace guid with no dashes and start the table name with a 'g'

--CREATE THE SQL STATEMENT

DECLARE @sql as NVARCHAR(MAX)
SET @sql = 
'

DECLARE @start BIGINT;
DECLARE @end BIGINT;
DECLARE @step BIGINT;
DECLARE @filteredRecordCount FLOAT
SELECT @filteredRecordCount = COUNT(1)
FROM ' + @FROMCLAUSE + ' 
'

IF NOT( @whereClause  is null or @whereClause  = '')
BEGIN
	SET @sql = @sql + 'WHERE ' + @whereclause
END


IF @identityTableAlias <> ''
BEGIN
	Set @identityTableAlias =  @identityTableAlias + '.';
END


SET @sql = @sql + '
DECLARE @unfilteredRecordCount bigint
SELECT @unfilteredRecordCount = row_count from sys.dm_db_partition_stats ps where ps.object_id=object_id(''' + @tableSchema + '.' + @tableName + ''') and ps.index_id < 2
--Just TRUNCATE THE TABLE
IF (@filteredRecordCount = @unfilteredRecordCount)
BEGIN
	raiserror( ''TRUNCATING TABLE ' + @tableName + ''', 0, 1) WITH NOWAIT;
	TRUNCATE TABLE ' + @tableSchema + '.' + @tableName + '
END
ELSE 
BEGIN
	CREATE TABLE ' + @tempTable + '
	(
		' + @idcol + ' bigint identity(1,1),
		' + @identityColumn + ' ' + @sqlStringType + ' --lookup type
	)
	WITH (DATA_COMPRESSION = PAGE) 

	CREATE CLUSTERED INDEX IX_' + @idcol + '_ID_IDENTITY
		ON '+ @tempTable + '(' + @idcol + ', ' + @identityColumn + '); 


SELECT @start = MIN(' + @identityTableAlias + @identityColumn + '), @end = MAX(' + @identityTableAlias + @identityColumn + ')
	FROM ' + @FROMCLAUSE
	
	IF NOT( @whereClause  is null or @whereClause  = '')
	BEGIN
		SET @sql = @sql + ' WHERE ' + @whereclause
	END
	
SET @sql = @sql + '
	
WHILE (@start <= @end)
BEGIN  
    SET @step = @start + 499999;
            
    If @step > @end
    BEGIN
        SET @step = @end;
    END           
	INSERT INTO ' + @tempTable + '
	SELECT ' + @identityTableAlias + @identityColumn + '
	FROM ' + @FROMCLAUSE 
	
	IF NOT( @whereClause  is null or @whereClause  = '')
	BEGIN
		SET @sql = @sql + ' WHERE ' + @whereclause + ' and ' + @identityTableAlias + @identityColumn + ' BETWEEN @start AND @step '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' WHERE ' + @identityTableAlias + @identityColumn + ' BETWEEN @start AND @step '
	END
	
SET @sql = @sql + '
                    
    SET @start = @start + 500000;
END
'
	DECLARE @truncateTableName NVARCHAR(120);
	SET @truncateTableName = 'tempRollingDelete' + @tableName + REPLACE(REPLACE(REPLACE(convert(varchar, getdate(), 113), '-', '_'), ':', '_'), ' ', '_');

	SET @sql = @sql + ' 

	--Just TRUNCATE THE TABLE
	IF (@filteredRecordCount = @unfilteredRecordCount)
	BEGIN
		raiserror( ''TRUNCATING TABLE '+ @tableName + ''', 0, 1) WITH NOWAIT;
		TRUNCATE TABLE ' + @tableSchema + '.' + @tableName + '
	END
	ELSE
	BEGIN
		raiserror( ''Starting standard delete path on: ' +  @tableSchema + '.' + @tableName + ''' , 0, 1) WITH NOWAIT;
		DECLARE 
			@maxid AS BIGINT
			,@currentid BIGINT
			,@nowAsString varchar(30)
		select @currentid = 1
		select @maxid=max(' + @idcol + ' ) FROM ' + @tempTable + '
		
		while @currentid<=@maxid
		begin
		  set @nowAsString = convert( varchar(30), getdate(), 121 );
		  raiserror( ''@currentid %I64d at %s...'', 0, 1, @currentid, @nowAsString ) WITH NOWAIT ;
		  DELETE TN FROM ' + @tableSchema + '.' + @tableName + ' TN
		  INNER JOIN '+ @tempTable + ' DT ON DT.' + @identityColumn + ' = TN.' + @identityColumn + ' AND DT.' + @idcol + '  BETWEEN @currentid AND @currentid + ' + CAST(@deleteRecordCount AS NVARCHAR(10)) + '
		  SET @currentid = @currentid + ' + CAST(@deleteRecordCount AS NVARCHAR(10)) + ' + 1
		END
		raiserror( ''Finished delete on: ' + @tableSchema + '.' + @tableName + ''' , 0, 1) WITH NOWAIT;
	END

	DROP TABLE ' + @tempTable + '
END
'

IF @isPrintingStatement = 1
BEGIN
	PRINT (cast(@sql as ntext));
END
ElSE
BEGIN
	EXEC (@sql);
END
GO


---------------------------------------------

-- dbo.procRollingUpdateOnTable
CREATE PROCEDURE dbo.procRollingUpdateOnTable
	@tableSchema nvarchar(128),
	@tableName nvarchar(128),
	@identityColumn nvarchar(128), --SHOULD RowID 95% of the time
	@updateStatement nvarchar(max),
	@fromClause nvarchar(max),
	@whereClause nvarchar(max),
	@updateRecordCount int,	
	@isPrintingStatement bit = 0
AS

IF (@updateRecordCount <= 0) 
BEGIN
	raiserror( 'ERROR: Delete Record Count is Less than or equal to zero ', 0, 1) WITH NOWAIT;
	RETURN
END

-- GET THE IDENTITY TYPE
DECLARE @sqlType int, @maxlength int, @precision int, @scale int
select  
	@sqlType = c.system_type_id, @maxlength = c.max_length, @precision = c.precision, @scale = c.scale 
from sys.columns c
inner join sys.objects o ON o.object_id = c.object_id
inner join sys.schemas s ON s.schema_id = o.schema_id
WHERE o.name = @tableName AND s.name = @tableSchema AND c.name = @identityColumn

declare @sqlStringType nvarchar(128)
SET @sqlStringType = dbo.GetSQLFullyQualifiedType(@sqlType, @maxlength, @precision, @scale)
DECLARE @idcol nvarchar(128)
SET @idcol = 'id' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '')  --replace guid with no dashes and start the table name with a 'g'

--SET THE TEMP TABLE NAME
DECLARE @tempTable nvarchar(128)
SET @tempTable = '[data].' + [dbo].[GetSQLColumnSafeGuid](NEWID())

--CREATE THE SQL STATEMENT
DECLARE @sql as NVARCHAR(MAX)
SET @sql = 
'
DECLARE @start BIGINT;
DECLARE @end BIGINT;
DECLARE @step BIGINT;

CREATE TABLE ' + @tempTable + '
(
	' + @idcol + ' bigint identity(1,1),
	' + @identityColumn + ' ' + @sqlStringType + ' --lookup type
)
	WITH (DATA_COMPRESSION = PAGE) 

	CREATE CLUSTERED INDEX IX_' + @idcol + '_ID_IDENTITY
		ON '+ @tempTable + '(' + @idcol + ', ' + @identityColumn + '); 


SELECT @start = MIN(' + @identityColumn + '), @end = MAX(' + @identityColumn + ')
	FROM ' + @FROMCLAUSE 	
	
IF NOT( @whereClause  is null or @whereClause  = '')
BEGIN
	SET @sql = @sql + ' WHERE ' + @whereclause
END
	
SET @sql = @sql + '
	
WHILE (@start <= @end)
BEGIN  
    SET @step = @start + 499999;
            
    If @step > @end
    BEGIN
        SET @step = @end;
    END           
	INSERT INTO ' + @tempTable + '
	
	
	
	SELECT ' + @identityColumn + '
	FROM ' + @FROMCLAUSE 
	
	IF NOT( @whereClause  is null or @whereClause  = '')
	BEGIN
		SET @sql = @sql + ' WHERE ' + @whereclause + ' and ' + @identityColumn + ' BETWEEN @start AND @step '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' WHERE ' + @identityColumn + ' BETWEEN @start AND @step '
	END
	
SET @sql = @sql + '
                    
    SET @start = @start + 500000;
END
'
SET @sql = @sql + ' 

DECLARE @filteredRecordCount bigint
SELECT @filteredRecordCount = COUNT(1) FROM ' + @tempTable + ' 
DECLARE @unfilteredRecordCount bigint
SELECT @unfilteredRecordCount = COUNT(1) FROM ' + @tableSchema + '.' + @tableName + ' (nolock)

DECLARE 
	@maxid AS BIGINT
	,@currentid BIGINT
	,@nowAsString varchar(30)
select @currentid = 1
select @maxid=max(' + @idcol + ') FROM ' + @tempTable + '
		
while @currentid<=@maxid
begin
    set @nowAsString = convert( varchar(30), getdate(), 121 );
    raiserror( ''@currentid %I64d at %s...'', 0, 1, @currentid, @nowAsString ) WITH NOWAIT ;
	UPDATE ' + @tableSchema + '.' + @tableName + ' SET ' + @updateStatement + ' FROM ' + @tableSchema + '.' + @tableName + ' TN
	INNER JOIN '+ @tempTable + ' DT ON DT.' + @identityColumn + ' = TN.' + @identityColumn + ' AND DT.' + @idcol + ' BETWEEN @currentid AND @currentid + ' + CAST(@updateRecordCount AS NVARCHAR(10)) + '
	SET @currentid = @currentid + ' + CAST(@updateRecordCount AS NVARCHAR(10)) + ' + 1
END


DROP TABLE ' + @tempTable + '
'

IF @isPrintingStatement = 1
BEGIN
	PRINT (@sql);
END
ElSE
BEGIN
	EXEC (@sql);
END
GO


---------------------------------------------

-- dbo.procRollingUpdateOnTableWithEncounterID
CREATE PROC [dbo].[procRollingUpdateOnTableWithEncounterID]
	@tableSchema nvarchar(128),
	@tableName nvarchar(128),
	@identityColumn nvarchar(128), --SHOULD RowID 95% of the time
	@updateStatement nvarchar(max),
	@fromClause nvarchar(max),
	@whereClause nvarchar(max),
	@tempTableAlias NVARCHAR(MAX),
	@enounterIDTable NVARCHAR(MAX),
	@updateRecordCount int,	
	@isPrintingStatement bit = 0,
	@targetTableAlias NVARCHAR(100) = 'Target',
	@encounterTableAlias NVARCHAR(100) = 'PE'
AS

IF (@updateRecordCount <= 0) 
BEGIN
	raiserror( 'ERROR: Delete Record Count is Less than or equal to zero ', 0, 1) WITH NOWAIT;
	RETURN
END

-- GET THE IDENTITY TYPE
DECLARE @sqlType int, @maxlength int, @precision int, @scale int
select  
	@sqlType = c.system_type_id, @maxlength = c.max_length, @precision = c.precision, @scale = c.scale 
from sys.columns c
inner join sys.objects o ON o.object_id = c.object_id
inner join sys.schemas s ON s.schema_id = o.schema_id
WHERE o.name = @tableName AND s.name = @tableSchema AND c.name = @identityColumn

declare @sqlStringType nvarchar(128)
SET @sqlStringType = dbo.GetSQLFullyQualifiedType(@sqlType, @maxlength, @precision, @scale)
DECLARE @idcol nvarchar(128)
SET @idcol = 'id' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '')  --replace guid with no dashes and start the table name with a 'g'

--GET THE DATE
DECLARE @currDate datetime
SET @currDate = GETDATE()
DECLARE @currDateString nvarchar(60)
SET @currDateString = REPLACE(REPLACE(CAST(@currDate as NVARCHAR(50)), ' ', ''), ':', '')
DECLARE @tempTable nvarchar(128)
SET @tempTable = '[data].' + @currDateString

--CREATE THE SQL STATEMENT
DECLARE @sql as NVARCHAR(MAX)
SET @sql = 
'

CREATE TABLE ' + @tempTable + '
(
	' + @idcol + ' bigint identity(1,1),
	' + @identityColumn + ' ' + @sqlStringType + ', --lookup type
	EncounterID BIGINT
)
	WITH (DATA_COMPRESSION = PAGE) 

	CREATE CLUSTERED INDEX IX_' + @idcol + '_ID_IDENTITY
		ON '+ @tempTable + '(' + @idcol + ', ' + @identityColumn + '); 


INSERT INTO ' + @tempTable + '
SELECT '+@targetTableAlias+'.' + @identityColumn + ', ' + @encounterTableAlias + '.EncounterID
FROM ' + @FROMCLAUSE + '
' 
if NOT(@whereClause is null or @whereClause = '')
BEGIN
	SET @sql = @sql + 'WHERE ' + @whereclause
END
SET @sql = @sql + ' 

DECLARE @filteredRecordCount bigint
SELECT @filteredRecordCount = COUNT(1) FROM ' + @tempTable + ' 
DECLARE @unfilteredRecordCount bigint
SELECT @unfilteredRecordCount = COUNT(1) FROM ' + @tableSchema + '.' + @tableName + ' (nolock)

DECLARE 
	@maxid AS BIGINT
	,@currentid BIGINT
	,@nowAsString varchar(30)
select @currentid = 1
select @maxid=max(' + @idcol + ') FROM ' + @tempTable + '
		
while @currentid<=@maxid
begin
    set @nowAsString = convert( varchar(30), getdate(), 121 );
    raiserror( ''@currentid %I64d at %s...'', 0, 1, @currentid, @nowAsString ) WITH NOWAIT ;
	UPDATE ' + @tableSchema + '.' + @tableName + ' SET ' + @updateStatement + ' FROM ' + @tableSchema + '.' + @tableName + ' TN
	INNER JOIN '+ @tempTable + ' '+ @tempTableAlias + ' ON '+ @tempTableAlias + '.' + @identityColumn + ' = TN.' + @identityColumn + ' AND '+ @tempTableAlias + '.' + @idcol + ' BETWEEN @currentid AND @currentid + ' + CAST(@updateRecordCount AS NVARCHAR(10)) + '
	SET @currentid = @currentid + ' + CAST(@updateRecordCount AS NVARCHAR(10)) + ' + 1
END


DROP TABLE ' + @tempTable + '
'

IF @isPrintingStatement = 1
BEGIN
	PRINT (@sql);
END
ElSE
BEGIN
	EXEC (@sql);
END
GO


---------------------------------------------

-- dbo.procRunForManyGUIDs
CREATE proc procRunForManyGUIDs 
	 @sql varchar(max)
	, @guids varchar(max)
	, @isExecuting bit
as
--set @guids = '47413A00-1994-4606-8948-2BDFEDAC1FB9,63A2935D-EDB8-4DAF-863F-677831C6AC4E'
--set @sql = 'print {guidq}'
--set @isExecuting = 1

declare crsGUIDs CURSOR FOR
	select guid
	from dbo.CSVGuidsToTable(@guids)
	
open crsGUIDs;

declare @sqli varchar(max)
declare @guid uniqueidentifier
FETCH NEXT FROM crsGUIDs into @guid
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		SET @sqli = replace(
					replace(@sql,'{guidq}','''' + cast(@guid as varchar(36)) + '''')
					,'{guid}',cast(@guid as varchar(36)))
		
		if @isExecuting = 1 begin
			exec(@sqli)
		end else begin
			print @sqli
		end

		FETCH NEXT FROM crsGUIDs into @guid
	END
close crsGUIDs;
DEALLOCATE crsGUIDs;
GO


---------------------------------------------

-- dbo.procRunForManyPlanGUIDsFromPlanType
CREATE proc [dbo].[procRunForManyPlanGUIDsFromPlanType] 
	 @sql varchar(max)
	, @plantypeguid uniqueidentifier
	, @isExecuting bit
as

declare crsGUIDs CURSOR FOR
	select planguid
	from xplan where plantypeguid = @plantypeguid
	
open crsGUIDs;

declare @sqli varchar(max)
declare @guid uniqueidentifier
FETCH NEXT FROM crsGUIDs into @guid
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		SET @sqli = replace(
					replace(@sql,'{guidq}','''' + cast(@guid as varchar(36)) + '''')
					,'{guid}',cast(@guid as varchar(36)))
		
		if @isExecuting = 1 begin
			exec(@sqli)
		end else begin
			print @sqli
		end

		FETCH NEXT FROM crsGUIDs into @guid
	END
close crsGUIDs;
DEALLOCATE crsGUIDs;
GO


---------------------------------------------

-- dbo.procRunScheduledIntegrationTask
CREATE PROCEDURE [dbo].[procRunScheduledIntegrationTask]
(
	@ConfigID uniqueidentifier,
	@ConfigScheduleID uniqueidentifier,
    @IsDebugOnly bit = 0
)
AS
begin					

DECLARE @statusCode INT;   

DECLARE @contextXML VARCHAR(MAX) = '<ScheduledIntegrationTaskConfig xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Strata.CS.Jazz.Biz.DataIntegration.Tasks"><ConfigGUID>' + cast(@ConfigID as nvarchar(100)) + '</ConfigGUID><IsSingleTask>false</IsSingleTask><ScheduleGUID>' + cast(@ConfigScheduleID as nvarchar(100)) + '</ScheduleGUID></ScheduledIntegrationTaskConfig>';


	if (@IsDebugOnly = 0)
	begin
		EXEC dbo.procCreateTask
			@taskTypeName = 'Strata.CS.Jazz.Biz.DataIntegration.Tasks.ScheduledIntegrationTask, Strata.CS.Jazz.Biz', -- varchar(1000)
			@contextXML = @contextXML,
			@userName = 'Run Integration',
			@statusCode = @statusCode OUTPUT,
			@taskSource = 'procRunScheduledIntegrationTask'
	END
    
end
GO


---------------------------------------------

-- dbo.procS3AssignGroupToRole
CREATE procedure dbo.[procS3AssignGroupToRole]
	@GroupName as nvarchar(128),
	@RoleID smallint,
	@LootGroupID nvarchar(128),
	@HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
AS


DECLARE @userGUID AS UNIQUEIDENTIFIER

DECLARE 
	userCursor CURSOR READ_ONLY
FOR
	select
		MU.UserGUID
	from S3IdentityLink IL
		inner join UserGroup G on G.UserGroupGUID = IL.GroupingGUID
		left join UserGroup MG on MG.UserGroupGUID = IL.MemberGUID
		left join UserProfile MU on MU.UserGUID = IL.MemberGUID
	where G.Name = @GroupName and IL.Distance <> 0

OPEN 
	userCursor
	
FETCH NEXT FROM userCursor
INTO @userGUID

WHILE @@FETCH_STATUS = 0
BEGIN
	--PRINT @userGUID
	
	
	DECLARE @script AS NVARCHAR(1024)
	SET @script = ''
	
	
	SET @script = 'EXEC procS3AssignIdentityToRole ''' + CAST(@userGUID AS NVARCHAR(36)) + ''', ' + CAST(@RoleID AS NVARCHAR(10)) + ', ''' + @LootGroupID + ''''
	
	PRINT @script
	EXEC (@script)
	
	FETCH NEXT FROM userCursor
	INTO @userGUID
END

CLOSE userCursor
DEALLOCATE userCursor
GO


---------------------------------------------

-- dbo.procS3AssignIdentityToGroup
CREATE procedure [dbo].[procS3AssignIdentityToGroup]
	@MEMBERGUID uniqueidentifier,
	@GROUPINGGUID uniqueidentifier
as

DECLARE @cnt int
declare @ucnt int
SELECT 
	@ucnt = COUNT(*) 
FROM
	USERPROFILE 
WHERE
	userguid = @MEMBERGUID

declare @isuser bit
IF @ucnt = 0 
	set @isuser = 0
else
	set @isuser = 1

select
	@cnt = @ucnt + count(*)
from
	usergroup
where
	usergroupguid = @memberguid
	and type = 0

IF @cnt = 0 BEGIN
	PRINT cast(@MEMBERGUID as varchar(36)) + ' is invalid identity (not user or group)'
	RETURN
END

SELECT 
	@cnt = COUNT(*) 
FROM
	USERGROUP
WHERE
	USERGROUP.USERGROUPGUID = @GROUPINGGUID
	and USERGROUP.TYPE = 0

IF @cnt = 0 BEGIN
	PRINT cast(@GROUPINGGUID as varchar(36)) + ' is invalid identity (group)'
	RETURN
END

SELECT
	@cnt = count(*)
FROM
	S3IdentityLink
WHERE
	GroupingGUID = @GRoupingGUID
	and MemberGUID = @memberguid
	and distance = 1

IF @CNT > 0 begin
	print 'member ' + cast(@memberguid as varchar(36)) + ' is already in group ' + cast(@groupingguid as varchar(36))
	return
end

INSERT INTO 
	S3IdentityLink 
	(GroupingGUID, MemberGUID, Fullpath, Distance) 
select
	@GROUPINGGUID, @MEMBERGUID, '\' + cast(@GROUPINGGUID as varchar(36)) + '\' + cast(@MEMBERGUID as varchar(36)) + '\', 1
GO


---------------------------------------------

-- dbo.procS3AssignIdentityToRole
CREATE procedure [dbo].[procS3AssignIdentityToRole]
	@IdentityGUID uniqueidentifier,
	@RoleID smallint,
	@LootGroupID nvarchar(128),
	@HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
as

DECLARE @cnt int
declare @ucnt int
SELECT 
	@ucnt = COUNT(*) 
FROM
	USERPROFILE 
WHERE
	userguid = @IdentityGUID

declare @isuser bit
IF @ucnt = 0 
	set @isuser = 0
else
	set @isuser = 1

select
	@cnt = @ucnt + count(*)
from
	usergroup
where
	usergroupguid = @IdentityGUID
	and type = 0

IF @cnt = 0 BEGIN
	PRINT cast(@IdentityGUID as varchar(36)) + ' is invalid identity (not user or group)'
	RETURN
END


SELECT 
	@cnt = COUNT(*) 
FROM
	USERROLE
WHERE
	USERROLE.RoleID = @RoleID

IF @cnt = 0 BEGIN
	PRINT cast(@RoleID as varchar(36)) + ' is invalid role'
	RETURN
END

SELECT 
	@cnt = COUNT(*) 
FROM
	S3LootGroup
WHERE
	LootGroupID = @LootGroupID

IF @cnt = 0 BEGIN
	PRINT cast(@LootGroupID as varchar(36)) + ' is invalid loot'
	RETURN
END



SELECT
	@CNT = COUNT(*)
from
	S3RoleAssignment ra
where
	ra.IdentityGUID = @IdentityGUID
	and ra.LootGroupID = @LootGroupID
	and ra.RoleID = @RoleID

IF @cnt > 0 begin
	PRINT cast(@IdentityGUID as varchar(36)) + ' already in role ' + cast(@RoleID as varchar(36)) + ' for loot ' + cast(@LootGroupID as nvarchar(128)) 
	return
end

INSERT INTO 
	S3RoleAssignment ( IdentityGUID,LootGroupID, RoleID, HistoryItemGUID)
VALUES
	(@IdentityGUID, @LootGroupID, @RoleID, @HistoryItemGUID)


--
--
--IF (@PARENTUSERGROUPGUID != @IDENTITYGUID)
--BEGIN
--	DECLARE @FULLPATH as varchar(800)
--	SET @FULLPATH = '\' + cast(@PARENTUSERGROUPGUID as varchar(36)) + '\' + cast(@IDENTITYGUID as varchar(36)) + '\'
--
--	IF @USERGROUPCHILDTYPE = 0
--		INSERT INTO S2IdentityLink (GroupingGUID, MemberGUID, Fullpath, Distance, GroupingIdentityGUID, GroupingLootGroupID, IsUser) VALUES(@PARENTUSERGROUPGUID, @IDENTITYGUID, @FULLPATH, 1, @GROUPINGIDENTITYGUID, @LootGroupID, 1)
--	
--	IF @USERGROUPCHILDTYPE = 1 
--		INSERT INTO S2IdentityLink (GroupingGUID, MemberGUID, Fullpath, Distance, GroupingIdentityGUID, GroupingLootGroupID, IsUser) VALUES(@PARENTUSERGROUPGUID, @IDENTITYGUID, @FULLPATH, 1, @GROUPINGIDENTITYGUID, @LootGroupID, 0)
--END
--
--
--
GO


---------------------------------------------

-- dbo.procS3AssignIdentityToSpecialRole
CREATE procedure [dbo].[procS3AssignIdentityToSpecialRole]
	@IdentityGUID uniqueidentifier,
	@RoleTypeID int,
	@LootGroupID nvarchar(128)
as
	set nocount on

	INSERT INTO 
		S3RoleAssignment ( IdentityGUID,LootGroupID, RoleID)
	SELECT
		@IdentityGUID,
		@LootGroupID,
		r.RoleID
	from
		[dbo].[UserRole] r (readuncommitted)
	where
		r.Type = @RoleTypeID
		and not exists(select 1 from [dbo].[S3RoleAssignment] ex (readuncommitted) where ex.IdentityGUID = @IdentityGUID and ex.LootGroupID = @LootGroupID and ex.RoleID = r.RoleID)
GO


---------------------------------------------

-- dbo.procS3AssignSecurityToButton
CREATE procedure [dbo].[procS3AssignSecurityToButton]
	@lootId nvarchar(max),
	@identityGuid uniqueidentifier
as

declare @systemSectionRootLootId uniqueidentifier = '1F30ED4A-DFA5-4EA6-8457-20D23DB372C3'

-- Get read access roleId
declare @readAccessRoleId int
select @readAccessRoleId = roleid from dbo.UserRole where Name = 'Access - Read Allow'

-- Add to System Section Permission Set
declare @psetid int
select top 1 @psetid =  PermissionSetID from [dbo].[S3PermissionSet] where Name in ('System Sections', 'SS - System')

if (@psetid is null) 
begin
	print 'System Section permission set not found'
	return
end

if (@readAccessRoleId is null) 
begin
	print 'Access - Read Allow role not found'
	return
end

-- Recreate Loot to ensure it's in the right permission set
delete from S3Loot where LootID = @lootId and PermissionSetID != @psetid

insert into [dbo].[S3Loot] (LootID, PermissionSetID)
select @lootId, @psetid where not exists (select 1 from [dbo].[S3Loot] inn where inn.LootID = @lootId)

-- Set up relationship with root system section
insert into [dbo].[S3LootGroup] (LootID, LootGroupID)
select @lootId, @systemSectionRootLootId
	where not exists (select 1 from [dbo].[S3LootGroup] inn where inn.LootID=@lootId and inn.LootGroupID=@systemSectionRootLootId)
union all
select @lootId, @lootId
	where not exists (select 1 from [dbo].[S3LootGroup] inn where inn.LootID=@lootId and inn.LootGroupID=@lootId)

-- Add role assignment
declare @roleAssignmentCount int
select @roleAssignmentCount = COUNT(*) from S3RoleAssignment where LootGroupID=@lootId and RoleId=@readAccessRoleId and IdentityGuid = @identityguid

if (@roleAssignmentCount = 0)
begin		
	insert into dbo.S3RoleAssignment(IdentityGUID, RoleId, LootGroupID)
	select @identityGuid,@readAccessRoleId,	@lootId
end
GO


---------------------------------------------

-- dbo.procS3ClearAssignmentByLootGroupRole
-- =============================================
-- Author:		William Yuan
-- Create date: 8/28
-- Description:	Clears security based on entity and role combination. Security 2.0 
-- =============================================



CREATE PROCEDURE [dbo].[procS3ClearAssignmentByLootGroupRole]
	-- Add the parameters for the stored procedure here
	@LootGroupID nvarchar(128),
	@RoleID smallint,
	@HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
AS
BEGIN
	SET NOCOUNT ON;
	

	UPDATE
		S3RoleAssignment
	SET
		IsMarkedDeleted = 1,
		HistoryItemGUID = @HistoryItemGUID
	WHERE
		LootGroupID = @LootGroupID
		AND RoleID = @RoleID
		

END
GO


---------------------------------------------

-- dbo.procS3ClearAssignmentByLootGroupRoleIdentity
-- =============================================
-- Author:		William Yuan
-- Create date: 8/28
-- Description:	Clears security based on entity and role combination. Security 2.0 
-- =============================================



CREATE PROCEDURE [dbo].[procS3ClearAssignmentByLootGroupRoleIdentity]
	-- Add the parameters for the stored procedure here
	@LootGroupID nvarchar(128),
	@RoleID smallint,
	@IDENTITYGUID uniqueidentifier,
	@HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
AS
BEGIN
	SET NOCOUNT ON;
	

	UPDATE
		S3RoleAssignment
	SET
		IsMarkedDeleted = 1,
		HistoryItemGUID = @HistoryItemGUID
	WHERE
		LootGroupID = @LootGroupID
		AND RoleID = @RoleID
		AND IdentityGUID = @IdentityGUID
		

END
GO


---------------------------------------------

-- dbo.procS3ClearSecurityByLootGroup
CREATE PROCEDURE [dbo].[procS3ClearSecurityByLootGroup]
	@LootGroupID nvarchar(128)
AS
BEGIN
	SET NOCOUNT ON;

	DELETE
		S3Loot
	WHERE
		LootId = @LootGroupID

	DELETE
		S3RoleAssignment
	WHERE
		LootGroupID = @LootGroupID
		
	DELETE
		S3LootGroup
	WHERE
		LootGroupID = @LootGroupID

END
GO


---------------------------------------------

-- dbo.procS3CopyRoleAssignments
CREATE procedure [dbo].[procS3CopyRoleAssignments]

	@SRCLootGroupID nvarchar(128),
	@DSTLootGroupID nvarchar(128)

as


insert into S3RoleAssignment ( IdentityGUID, RoleID, LootGroupID)
select
	IdentityGUID, RoleID, @DSTLootGroupID
from
	S3RoleAssignment
where
	LootGroupID = @SRCLootGroupID
	and not exists (
		select 1
		from
			S3RoleAssignment rax 
		where
			rax.IdentityGUID = S3RoleAssignment.IdentityGUID	
			and rax.RoleID = S3RoleAssignment.RoleID
			and rax.LootGroupID = @DSTLootGroupID
	)
GO


---------------------------------------------

-- dbo.procS3DebugLoot
CREATE proc [dbo].[procS3DebugLoot]
	@lootID nvarchar(100),
	@userNameOrGUID nvarchar(100)
as
	--find the user
	declare @userGUID uniqueidentifier
	declare @userNameFull nvarchar(100)
	declare @username nvarchar(100)
	select @userGUID = UserGUID, @userNameFull = NameFull, @username = UserName from UserProfile where UserName = @userNameOrGUID or NameFull = @userNameOrGUID or CAST(UserGUID as nvarchar(36)) = @userNameOrGUID
	if(@userGUID is null) begin
		print 'User not found'
		return
	end
	print 'User: ' + @userNameFull + ' (' + @username + ')'
	print ''

	--verify the loot exists
	if((select COUNT(*) from S3Loot where LootID =  @lootID) = 0) begin
		print 'Loot not found'
		return
	end

	--user access
	declare @read nvarchar(10); declare @write nvarchar(10); declare @secure nvarchar(10); declare @delete nvarchar(10); declare @create nvarchar(10);
	if((select COUNT(*) from viewS3ACL where LootID = @lootID and UserGUID = @userGUID) > 0) begin
		select @read = case when coalesce(IsReadable, 0) = 1 then ' Read' else '' end, @write = case when coalesce(IsWritable, 0) = 1 then ' Write' else '' end, @secure = case when coalesce(IsSecurable, 0) = 1 then ' Secure' else '' end, @delete = case when coalesce(IsDeletable, 0) = 1 then ' Delete' else '' end, @create = case when coalesce(IsCreatable, 0) = 1 then ' Create' else '' end from viewS3ACL where LootID = @lootID and UserGUID = @userGUID
		print 'User Access:' + @read + @write + @create + @delete + @secure
	end else begin
		print 'User Access: (none)'
	end

	--role assignments
	declare @roledetail nvarchar(max); declare @identname nvarchar(100); declare @roleassign nvarchar(100); declare @assigngroup nvarchar(100)
	set @roledetail = ''
	declare crsRoles cursor fast_forward for select distinct IdentityName, RoleName, LootGroupID from viewS3RoleAssignmentDetail where LootID = @lootID and UserGUID = @userGUID
	open crsRoles
	fetch next from crsRoles into @identname, @roleassign, @assigngroup
	while(@@FETCH_STATUS = 0) begin
		if(@roledetail != '') begin set @roledetail = @roledetail + ', ' end
		set @roledetail = @roledetail + @identname + ' -> ' + @roleassign + ' (' + @assigngroup + ')'
		fetch next from crsRoles into @identname, @roleassign, @assigngroup
	end
	close crsRoles
	deallocate crsRoles
	print 'User Assignments: ' + @roledetail
	print ''
	
	--permission set
	declare @pset nvarchar(100)
	declare @psetid int
	select @pset = PS.Name, @psetid = PS.PermissionSetID from S3Loot L inner join S3PermissionSet PS on PS.PermissionSetID = L.PermissionSetID where L.LootID = @lootID
	print 'Permission Set: ' + @pset

	--parents
	declare @parents nvarchar(max)
	declare @parent nvarchar(100)
	set @parents = ''
	declare crsParents cursor fast_forward for select LootGroupID from S3LootGroup where LootID = @lootID and LootID != LootGroupID
	open crsParents
	fetch next from crsParents into @parent
	while(@@FETCH_STATUS = 0) begin
		if(@parents != '') begin set @parents = @parents + ', ' end
		set @parents = @parents + @parent
		fetch next from crsParents into @parent
	end
	close crsParents
	deallocate crsParents
	print 'Parents: ' + @parents
	print ''

	--access detail
	declare @readdetail nvarchar(max); declare @writedetail nvarchar(max); declare @securedetail nvarchar(max); declare @deletedetail nvarchar(max); declare @createdetail nvarchar(max); 
	set @readdetail = ''; set @writedetail = ''; set @securedetail = ''; set @deletedetail = ''; set @createdetail = ''; 
	declare @roleid int; declare @rolename nvarchar(100); declare @lootgroup nvarchar(100); declare @readallow int; declare @readdeny int; declare @writeallow int; declare @writedeny int; declare @secureallow int; declare @securedeny int; declare @deleteallow int; declare @deletedeny int; declare @createallow int; declare @createdeny int;
	declare crsDetails cursor fast_forward for select distinct RoleID, RoleName, LootGroupID, ReadAllowPts, ReadDenyPts, WriteAllowPts, WriteDenyPts, SecureAllowPts, SecureDenyPts, DeleteAllowPts, DeleteDenyPts, CreateAllowPts, CreateDenyPts from viewS3ACLDetail where LootID = @lootID and UserGUID = @userGUID
	open crsDetails
	fetch next from crsDetails into @roleid, @rolename, @lootgroup, @readallow, @readdeny, @writeallow, @writedeny, @secureallow, @securedeny, @deleteallow, @deletedeny, @createallow, @createdeny
	while(@@FETCH_STATUS = 0) begin
		if(@readallow > 0) begin if(@readdetail != '') begin set @readdetail = @readdetail + ', ' end set @readdetail = @readdetail + @rolename + ' +' + cast(@readallow as nvarchar(16)) + ' (' + @lootgroup + ')' end
		if(@readdeny > 0) begin if(@readdetail != '') begin set @readdetail = @readdetail + ', ' end set @readdetail = @readdetail + @rolename + ' -' + cast(@readdeny as nvarchar(16)) + ' (' + @lootgroup + ')' end

		if(@writeallow > 0) begin if(@writedetail != '') begin set @writedetail = @writedetail + ', ' end set @writedetail = @writedetail + @rolename + ' +' + cast(@writeallow as nvarchar(16)) + ' (' + @lootgroup + ')' end
		if(@writedeny > 0) begin if(@writedetail != '') begin set @writedetail = @writedetail + ', ' end set @writedetail = @writedetail + @rolename + ' -' + cast(@writedeny as nvarchar(16)) + ' (' + @lootgroup + ')' end

		if(@createallow > 0) begin if(@createdetail != '') begin set @createdetail = @createdetail + ', ' end set @createdetail = @createdetail + @rolename + ' +' + cast(@createallow as nvarchar(16)) + ' (' + @lootgroup + ')' end
		if(@createdeny > 0) begin if(@createdetail != '') begin set @createdetail = @createdetail + ', ' end set @createdetail = @createdetail + @rolename + ' -' + cast(@createdeny as nvarchar(16)) + ' (' + @lootgroup + ')' end

		if(@deleteallow > 0) begin if(@deletedetail != '') begin set @deletedetail = @deletedetail + ', ' end set @deletedetail = @deletedetail + @rolename + ' +' + cast(@deleteallow as nvarchar(16)) + ' (' + @lootgroup + ')' end
		if(@deletedeny > 0) begin if(@deletedetail != '') begin set @deletedetail = @deletedetail + ', ' end set @deletedetail = @deletedetail + @rolename + ' -' + cast(@deletedeny as nvarchar(16)) + ' (' + @lootgroup + ')' end

		if(@secureallow > 0) begin if(@securedetail != '') begin set @securedetail = @securedetail + ', ' end set @securedetail = @securedetail + @rolename + ' +' + cast(@secureallow as nvarchar(16)) + ' (' + @lootgroup + ')' end
		if(@securedeny > 0) begin if(@securedetail != '') begin set @securedetail = @securedetail + ', ' end set @securedetail = @securedetail + @rolename + ' -' + cast(@securedeny as nvarchar(16)) + ' (' + @lootgroup + ')' end

		fetch next from crsDetails into @roleid, @rolename, @lootgroup, @readallow, @readdeny, @writeallow, @writedeny, @secureallow, @securedeny, @deleteallow, @deletedeny, @createallow, @createdeny
	end
	close crsDetails
	deallocate crsDetails
	print 'Read Detail: ' + @readdetail
	print 'Write Detail: ' + @writedetail
	print 'Create Detail: ' + @createdetail
	print 'Delete Detail: ' + @deletedetail
	print 'Secure Detail: ' + @securedetail
	print 'Detail Legend: +X => Allow Weight X, -Y => Deny Weight Y'
	print ''

	--permission set detail
	declare @psreadhowto nvarchar(max); declare @pswritehowto nvarchar(max); declare @pscreatehowto nvarchar(max); declare @psdeletehowto nvarchar(max); declare @pssecurehowto nvarchar(max);
	set @psreadhowto = ''; set @pswritehowto = ''; set @pscreatehowto = ''; set @psdeletehowto = ''; set @pssecurehowto = '';
	declare @psrole nvarchar(100); declare @psread int; declare @pswrite int; declare @pssecure int; declare @pscreate int; declare @psdelete int;
	declare crsPSDetail cursor fast_forward for select R.Name, P.ReadAllowPts, P.WriteAllowPts, P.SecureAllowPts, P.CreateAllowPts, P.DeleteAllowPts from S3Permission P inner join UserRole R on R.RoleID = P.RoleID where P.PermissionSetID = @psetid
	open crsPSDetail
	fetch next from crsPSDetail into @psrole, @psread, @pswrite, @pssecure, @pscreate, @psdelete
	while(@@FETCH_STATUS = 0) begin
		if(@psread > 0) begin if(@psreadhowto != '') begin set @psreadhowto = @psreadhowto + ', ' end set @psreadhowto = @psreadhowto + @psrole + ' (+' + CAST(@psread as nvarchar(16)) + ')' end	
		if(@pswrite > 0) begin if(@pswritehowto != '') begin set @pswritehowto = @pswritehowto + ', ' end set @pswritehowto = @pswritehowto + @psrole + ' (+' + CAST(@pswrite as nvarchar(16)) + ')' end	
		if(@pscreate > 0) begin if(@pscreatehowto != '') begin set @pscreatehowto = @pscreatehowto + ', ' end set @pscreatehowto = @pscreatehowto + @psrole + ' (+' + CAST(@pscreate as nvarchar(16)) + ')' end	
		if(@psdelete > 0) begin if(@psdeletehowto != '') begin set @psdeletehowto = @psdeletehowto + ', ' end set @psdeletehowto = @psdeletehowto + @psrole + ' (+' + CAST(@psdelete as nvarchar(16)) + ')' end	
		if(@pssecure > 0) begin if(@pssecurehowto != '') begin set @pssecurehowto = @pssecurehowto + ', ' end set @pssecurehowto = @pssecurehowto + @psrole + ' (+' + CAST(@pssecure as nvarchar(16)) + ')' end	
		
		fetch next from crsPSDetail into @psrole, @psread, @pswrite, @pssecure, @pscreate, @psdelete
	end
	close crsPSDetail
	deallocate crsPSDetail
	print 'How To Get Read: ' + @psreadhowto
	print 'How To Get Write: ' + @pswritehowto
	print 'How To Get Create: ' + @pscreatehowto
	print 'How To Get Delete: ' + @psdeletehowto
	print 'How To Get Secure: ' + @pssecurehowto
GO


---------------------------------------------

-- dbo.procS3DebugMember
CREATE proc [dbo].[procS3DebugMember]
	@dimensionNameOrGUID nvarchar(100),
	@memberNameOrGUID nvarchar(100),
	@userNameOrGUID nvarchar(100)
as
	--find the dimension
	declare @dimGUID uniqueidentifier
	declare @dimName nvarchar(100)
	declare @dimSQL nvarchar(100)
	declare @issecure bit
	select @dimGUID = DimensionGUID, @dimName = FriendlyName, @dimSQL = SQLSchemaName + '.' + SQLObjectName, @issecure = IsSecured from ScoreDimension where FriendlyName = @dimensionNameOrGUID or CAST(DimensionGUID as nvarchar(36)) = @dimensionNameOrGUID
	if(@dimGUID is null) begin
		print 'Dimension not found'
		return
	end
	if(@issecure = 0) begin
		print 'Dimension is not secured!'
		return
	end
	print 'Dimension: ' + @dimName

	--get the loot prefix
	declare @lootattr nvarchar(100)
	declare @prefix nvarchar(50)
	select @lootattr = A.SQLColumnName, @prefix = A.SecuredLootGroupPrefix from ScoreAttribute A
		inner join ScoreDimensionGroup SG on SG.DimensionGroupGUID = A.DimensionGroupGUID
		inner join ScoreDimension D on D.DimensionGUID = SG.DimensionGUID
	 where A.IsSecuredLootID = 1 and D.DimensionGUID = @dimGUID
	if(@lootattr is null) begin
		print 'Secure loot ID column not found'
		return
	end
	if(@prefix != '') begin
		set @prefix = @prefix + '|'
	end

	declare @sql nvarchar(max)
	set @sql = '
		--find the member loot
		declare @lootID nvarchar(100)
		declare @memberName nvarchar(450)
		select @memberName = Name, @lootID = ''' + @prefix + ''' + cast(' + @lootattr + ' as nvarchar(100)) from ' + @dimSQL + ' where Name = ''' + @memberNameOrGUID + ''' or cast(MemberGUID as nvarchar(36)) = ''' + @memberNameOrGUID + '''
		if(@lootID is null) begin
			print ''Member not found''
			return
		end
		print ''Member: '' + @memberName + '' ('' + @lootID + '')''

		exec procS3DebugLoot @lootID, ''' + @userNameOrGUID + '''
	'
	exec(@sql)
GO


---------------------------------------------

-- dbo.procS3DebugPlan
CREATE proc [dbo].[procS3DebugPlan]
	@planNameOrGUID nvarchar(450),
	@userNameOrGUID nvarchar(100)
as
	--check for dupes
	if((select COUNT(*) from XPlan where Name = @planNameOrGUID) > 1) begin
		print 'Plan name is not unique.  Please provide the PlanGUID.'
		return
	end

	--find the plan loot
	declare @lootID nvarchar(100)
	declare @planName nvarchar(450)
	select @planName = Name, @lootID = CachedLootID from XPlan where Name = @planNameOrGUID or CAST(PlanGUID as nvarchar(36)) = @planNameOrGUID
	if(@lootID is null) begin
		print 'Plan not found'
		return
	end
	print 'Plan: ' + @planName + ' (' + @lootID + ')'

	exec procS3DebugLoot @lootID, @userNameOrGUID
GO


---------------------------------------------

-- dbo.procS3DeleteOrphans
CREATE proc [dbo].[procS3DeleteOrphans]
	@lootGroupPrefix nvarchar(100) = null,
	@isExecuting bit = 0
as
	IF @lootGroupPrefix=''
	BEGIN
		RAISERROR(N'LootGroupPrefix couldn''t be empty string', 1, 16)
		RETURN
	END	

	CREATE TABLE #s3orphan(
	[LootID] [nvarchar](128) NOT NULL,
	[PermissionSetID] [smallint] NOT NULL)
	
	IF @lootGroupPrefix IS NULL OR @lootGroupPrefix = 'P'
	BEGIN
		insert into #s3orphan select LootID, PermissionSetID from S3Loot where LootGroupPrefix = 'P' and LootID not in(select CachedLootID from [dbo].[XPlan])
	END

	declare @sql nvarchar(max)
	select @sql = dbo.straggr('insert into #s3orphan select LootID, PermissionSetID from S3Loot where LootGroupPrefix = ''' + SecuredLootGroupPrefix + ''' and LootID not in(select ''' + SecuredLootGroupPrefix + '|'' + cast(' + SQLColumnName + ' as nvarchar(16)) from ' + DimensionSQLObjectExpression + ')', '
	', '') from viewScoreAttribute where IsSecuredLootID = 1 and ((SecuredLootGroupPrefix not in('', 'P') AND @lootGroupPrefix IS NULL) OR (SecuredLootGroupPrefix = @lootGroupPrefix AND @lootGroupPrefix IS NOT NULL))
	exec(@sql)
	
	if (@isExecuting = 1) begin
		delete x 
		from S3LootGroup x
		inner join #s3orphan y on x.LootID =  y.LootID
		
		delete x 
		from S3RoleAssignment x
		inner join #s3orphan y on x.LootGroupID =  y.LootID

		delete x 
		from S3Loot x
		inner join #s3orphan y on x.LootID =  y.LootID
	end

	select * from #s3orphan
	drop table #s3orphan
GO


---------------------------------------------

-- dbo.procS3EnsureSimplePermissionDefaultForStrata
create proc procS3EnsureSimplePermissionDefaultForStrata
as
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 1, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 1)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 3, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 3)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 4, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 4)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 6, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 6)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 8, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 8)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 9, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 9)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 10, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 10)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 11, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 11)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 12, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 12)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 13, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 13)
	insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 14, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 14)
GO


---------------------------------------------

-- dbo.procS3GetUserGUIDsAssignedToPRGroups
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		 Description
** 1		2019-12-05	HV			TK-80875 PR | Emails
*************************************************************/
CREATE PROCEDURE dbo.procS3GetUserGUIDsAssignedToPRGroups
  @PRCategory nvarchar(64)
AS

SELECT DISTINCT MemberGUID FROM [dbo].[S3IdentityLink] il
INNER JOIN [dbo].[UserGroup] ug on ug.UserGroupGUID = il.GroupingGUID
WHERE ug.Category = @PRCategory
GO


---------------------------------------------

-- dbo.procS3GetUsersAssignedToMRDepartments
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		 Description
** 1		2019-11-21	KF			B-24581  PR | Emails - Responsibility / User Picker - Daily
** 2		2022-05-24	HV			JAZZ-38243  PR Roles PR notifications emails
*************************************************************/
CREATE PROCEDURE dbo.procS3GetUsersAssignedToMRDepartments
  @RoleIDs nvarchar(max)
AS

SELECT * FROM
(
	-- Department level
	SELECT S.RoleID, S.UserGUID, U.NameFull as UserNameFull FROM viewS3RoleAssignmentDetail S
	INNER JOIN dbo.UserProfile U ON U.UserGUID = S.UserGUID
	WHERE
	  U.IsDisabled = 0
	  AND S.IsDirectAssignment = 1
	  AND S.LootID Like 'MRDept|%'
	  AND S.RoleID IN (select val from ConvertCSValuesToTable(@RoleIDs, ','))

	UNION

	-- Rollup levels
	SELECT S.RoleID, S.UserGUID, U.NameFull as UserNameFull FROM viewS3RoleAssignmentDetail S
	INNER JOIN dbo.UserProfile U ON U.UserGUID = S.UserGUID
	WHERE
	  U.IsDisabled = 0
	  AND S.LootID Like 'MRDept|%'
	  AND (S.LootGroupID Like 'SYS%' OR S.LootGroupID Like 'ENT%' OR S.LootGroupID Like 'DeptRollup%')
	  AND S.RoleID IN (select val from ConvertCSValuesToTable(@RoleIDs, ','))
) as R
INNER JOIN 
(
	SELECT DISTINCT MemberGUID FROM [dbo].[S3IdentityLink] il
	INNER JOIN [dbo].[UserGroup] ug on ug.UserGroupGUID = il.GroupingGUID
	WHERE ug.Category = 'PR' 
) as G 
on R.UserGUID = G.MemberGUID
GO


---------------------------------------------

-- dbo.procS3GetUsersAssignedToMRDepartmentsForPR
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		 Description
** 1		2022-06-02	KF			JAZZ-38243  PR Roles PR notifications emails
*************************************************************/
CREATE PROCEDURE [dbo].[procS3GetUsersAssignedToMRDepartmentsForPR]
  @RoleIDs nvarchar(max)
AS

IF OBJECT_ID('tempdb..#roleIDs') IS NOT NULL DROP TABLE #roleIDs;
CREATE TABLE #roleIDs (RoleID INT Primary Key)

INSERT INTO #roleIDs (RoleID)
SELECT val FROM ConvertCSValuesToTable(@RoleIDs, ',')

SELECT R.* FROM
(
	-- Department level
	SELECT S.RoleID, S.UserGUID, U.NameFull as UserNameFull FROM viewS3RoleAssignmentDetail S
	INNER JOIN dbo.UserProfile U ON U.UserGUID = S.UserGUID
	INNER JOIN #roleIDs R ON R.RoleID = S.RoleID
	WHERE
	  U.IsDisabled = 0
	  AND S.IsDirectAssignment = 1
	  AND S.LootID Like 'MRDept|%'
	  
	UNION

	-- Rollup levels
	SELECT S.RoleID, S.UserGUID, U.NameFull as UserNameFull FROM viewS3RoleAssignmentDetail S
	INNER JOIN dbo.UserProfile U ON U.UserGUID = S.UserGUID
	INNER JOIN #roleIDs R ON R.RoleID = S.RoleID
	WHERE
	  U.IsDisabled = 0
	  AND S.LootID Like 'MRDept|%'
	  AND (S.LootGroupID Like 'SYS%' OR S.LootGroupID Like 'ENT%' OR S.LootGroupID Like 'DeptRollup%')
) as R
INNER JOIN UserRole UR ON UR.RoleID = R.RoleID
INNER JOIN 
(
	SELECT DISTINCT MemberGUID FROM [dbo].[S3IdentityLink] il
	INNER JOIN [dbo].[UserGroup] ug on ug.UserGroupGUID = il.GroupingGUID
	WHERE ug.Category = 'PR' 
) as PG ON PG.MemberGUID = R.UserGUID
LEFT JOIN
(
	SELECT DISTINCT MemberGUID FROM [dbo].[S3IdentityLink] il
	INNER JOIN [dbo].[UserGroup] ug on ug.UserGroupGUID = il.GroupingGUID
	WHERE ug.Category = 'MR' 
) as MG ON MG.MemberGUID = R.UserGUID
WHERE UR.Category = 'PR' OR (UR.Category = 'MR' AND MG.MemberGUID IS NOT NULL)

IF OBJECT_ID('tempdb..#roleIDs') IS NOT NULL DROP TABLE #roleIDs;
GO


---------------------------------------------

-- dbo.procS3IdentityLinkAddMissing
CREATE proc [dbo].[procS3IdentityLinkAddMissing] as

INSERT INTO S3IdentityLink (GroupingGUID, MemberGUID, FullPath, Distance)
SELECT
	Userguid,
	UserGuid,
	'\' + cast(userguid as varchar(36)) + '\',
	0
FROM
	UserProfile
WHERE
	not exists (select 1 from S3IdentityLink il where il.GroupingGUID = UserGUID and il.MemberGUID = UserGUID)

--distance 1 to everyone group
INSERT INTO S3IdentityLink (GroupingGUID, MemberGUID, FullPath, Distance)
SELECT
	'00000000-0000-0000-0000-000000000001',
	ins.UserGuid,
	'\00000000-0000-0000-0000-000000000001\' + cast(ins.userguid as varchar(36)) + '\',
	1
FROM
	userprofile INS
WHERE
	not exists (select 1 from S3IdentityLink il where il.GroupingGUID = '00000000-0000-0000-0000-000000000001' and il.MemberGUID = UserGUID)
	
INSERT INTO S3IdentityLink (GroupingGUID, MemberGUID, FullPath, Distance)
SELECT
	ins.UserGroupGUID,
	ins.UserGroupGUID,
	'\' + cast(ins.UserGroupGUID as varchar(36)) + '\',
	0
FROM
	UserGroup ins
WHERE
	not exists (
		select  1 
		from S3IdentityLink ilx
		where ilx.MemberGUID = ins.UserGroupGUID and ilx.GroupingGUID = ins.UserGroupGUID
		)
GO


---------------------------------------------

-- dbo.procS3IdentityLinkFixFullpaths
CREATE proc procS3IdentityLinkFixFullpaths
	@isDebugOnly bit = 0
as
	declare @fullpath nvarchar(400)
	declare @fixed nvarchar(400)
	declare @pos int
	declare crsLinks cursor read_only fast_forward for select Fullpath from S3IdentityLink (readuncommitted) where Fullpath not like '\%' or ((len(Fullpath) - 1) / 37.0) != floor((len(Fullpath) - 1) / 37.0)
	open crsLinks
	fetch next from crsLinks into @fullpath
	while(@@FETCH_STATUS = 0) begin
		set @fixed = @fullpath
		set @pos = 1
		while (@pos < LEN(@fixed)) begin
			if (SUBSTRING(@fixed, @pos, 1) != '\') begin
				if (@pos = 1) begin
					set @fixed = '\' + @fixed
				end else begin
					set @fixed = SUBSTRING(@fixed, 1, @pos - 1) + '\' + SUBSTRING(@fixed, @pos, len(@fixed) - @pos + 1)
				end
			end
			set @pos = @pos + 37
		end
		
		print @fullpath + ' -> ' + @fixed
		if (@isDebugOnly = 0) begin
			if((select count(*) from [dbo].[S3IdentityLink] where Fullpath = @fixed) > 0) begin
				delete from [dbo].[S3IdentityLink] where Fullpath = @fullpath
			end else begin
				update [dbo].[S3IdentityLink] set Fullpath = @fixed where Fullpath = @fullpath
			end
		end
		
		fetch next from crsLinks into @fullpath
	end
	close crsLinks
	deallocate crsLinks
	
	update il set il.Fullpath = il.Fullpath + '\' from S3IdentityLink il where il.Fullpath not like '%\' and not exists(select 1 from S3IdentityLink ex where ex.Fullpath = il.Fullpath + '\')
GO


---------------------------------------------

-- dbo.procS3LootGroupUpdateSystemSection
CREATE proc [dbo].[procS3LootGroupUpdateSystemSection] as


declare @psid int
select @psid = permissionsetid from S3PermissionSet where MetaForUpgrade = '1F30ED4A-DFA5-4EA6-8457-20D23DB372C3'

if @psid is null begin
	print 'This depends on the existence of a s3permissionset with metaforupgrade = 1F30ED4A-DFA5-4EA6-8457-20D23DB372C3'
	return
end

insert into S3Loot ( LootID, PermissionSetID)
select
	ss.SYSTEMSECTIONGUID,@psid
from
	SystemSection ss
where
	not exists (
		select 1
		from
			S3Loot l
		where
			l.LootID = CAST(ss.systemsectionguid as varchar(36))
	)
--******************
--******************
--Create S3LootGroup for secured systemsections
--******************
--******************

create table #S3LootGroup( LootID nvarchar(128), LootGroupID nvarchar(128))
	

insert into #S3LootGroup( LootID,LootGroupID)
select CAST(ss1 as varchar(36)), CAST(ss1 as varchar(36)) from viewSystemSectionFlat
union all
select CAST(ss1 as varchar(36)), CAST(ss2 as varchar(36)) from viewSystemSectionFlat where ss2 is not null 
union all
select CAST(ss1 as varchar(36)), CAST(ss3 as varchar(36)) from viewSystemSectionFlat where ss3 is not null 
union all
select CAST(ss1 as varchar(36)), CAST(ss4 as varchar(36)) from viewSystemSectionFlat where ss4 is not null 
union all
select CAST(ss1 as varchar(36)), CAST(ss5 as varchar(36)) from viewSystemSectionFlat where ss5 is not null 
union all
select CAST(ss1 as varchar(36)), CAST(ss6 as varchar(36)) from viewSystemSectionFlat where ss6 is not null 



--delete invalid ones
DELETE lg FROM S3LootGroup lg WHERE
	lg.LootID IN (select nlg.LootID from #S3LootGroup nlg)
	and NOT EXISTS (
		SELECT 1
		FROM #S3LootGroup  nlg
		WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid
	)

--add valid ones
INSERT INTO S3LootGroup (LootID, LootGroupID)
SELECT
	lootid, lootgroupid
FROM	
	#S3LootGroup nlg
WHERE
	NOT EXISTS (
		SELECT 1
		FROM S3LootGroup lg
		WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid
	)	

drop table #s3lootgroup
GO


---------------------------------------------

-- dbo.procS3MenuSecurityAfterSave
create proc dbo.procS3MenuSecurityAfterSave
as
	--replace user management system center security with latest menu item security
	delete from S3simplepermission where lootid in('68E8430F-F3BC-4286-B73D-6CDEA144F7BC', 'BA346C79-C2D0-4CA2-8090-CC71719A1B5B');
	insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select s.sectionguid, p.identityguid, p.readvalue, p.writevalue, p.securevalue from S3simplepermission p cross join SystemCenterSection s where p.lootid = 'd62a6536-9bfb-4bde-b945-eda88ab0e19e' and s.sectionguid in('68E8430F-F3BC-4286-B73D-6CDEA144F7BC', 'BA346C79-C2D0-4CA2-8090-CC71719A1B5B');
GO


---------------------------------------------

-- dbo.procS3PlanTypeLootExpressionSet
CREATE proc procS3PlanTypeLootExpressionSet
	@planTypeGUID uniqueidentifier,
	@lootIDSQLExpression nvarchar(100),
	@defaultPermissionSetID smallint,
	@isUpdatingExistingPlans bit = 0
as
	if((select COUNT(*) from PlanType where PlanTypeGUID = @planTypeGUID) = 0) begin
		print 'Plan type not found'
		return
	end

	update PlanType set LootIDSQLExpression = @lootIDSQLExpression where PlanTypeGUID = @planTypeGUID

	if(@isUpdatingExistingPlans = 1) begin
		select CachedLootID into ##oldloot from XPlan where PlanTypeGUID = @planTypeGUID

		declare @updateSQL nvarchar(4000)
		set @updateSQL = @updateSQL + 'update XPlan set CachedLootID = ' + @lootIDSQLExpression + ' where PlanTypeGUID = ''' + cast(@planTypeGUID as nvarchar(36)) + ''';'
		
		delete from S3Loot where LootID in(select CachedLootID from ##oldloot) and LootID not in(select CachedLootID from XPlan)
		
		insert into S3Loot(LootID, PermissionSetID) select CachedLootID, @defaultPermissionSetID from XPlan where PlanTypeGUID = @planTypeGUID and CachedLootID not in(select LootID from S3Loot)
		
		drop table ##oldloot
	end
GO


---------------------------------------------

-- dbo.procS3RebuildLootView
--/****** Object:  StoredProcedure [dbo].[procScoreRunForManyStructures]    Script Date: 10/16/2009 15:50:12 ******/
--SET ANSI_NULLS ON
--GO

--SET QUOTED_IDENTIFIER ON
--GO

CREATE proc [dbo].[procS3RebuildLootView]
as


declare @dropSQL nvarchar(max)
set @dropsql = 'if dbo.ViewExists(''data'',''viewS3LootPossible'') = 1 begin
	drop view data.viewS3LootPossible
end'
exec(@dropsql)

declare @viewSQL varchar(max)

--secured system sections
set @viewSQL = '
create view data.viewS3LootPossible as
select lootid, ''SecureListMember'' as LootType, Name from securelistmember where listguid in (select listguid from securelist where issecured = 1)
'

--secured dimensions
declare crsScoreDim CURSOR FOR
	select '
select 
	''' + case when len(sa.securedlootgroupprefix) > 0 then sa.securedlootgroupprefix + '|' else '' end
	+ ''' + cast(' + sa.sqlcolumnname + ' as varchar(max)), 
	''DimensionMember'', 
	cast(' + sadlk.sqlcolumnname + ' as varchar(max)) 
from 
	[' + sd.sqlschemaname + '].[' + sd.sqlobjectname + ']'
	from 
		ScoreDimension SD
		inner join viewScoreAttribute SA on sd.dimensionguid = sa.dimensionguid
		inner join viewScoreAttribute SADLK on sd.dimensionguid = sadlk.dimensionguid and sd.defaultlookupkeyguid = sadlk.attributeguid
	where
		sd.issecured = 1
		and sa.issecuredlootid = 1
		and 
		(
			dbo.viewexists(sd.sqlschemaname,sd.sqlobjectname) = 1
			or dbo.tableexists(sd.sqlschemaname,sd.sqlobjectname) = 1
		)

open crsScoreDim;

declare @dimsql varchar(max)

FETCH NEXT FROM crsScoreDim into @dimsql
WHILE (@@FETCH_STATUS = 0) 	BEGIN
	set @viewSQL = @viewSQL  + '
	UNION ALL
	' + @dimsql
	FETCH NEXT FROM crsScoreDim into @dimsql
end

close crsscoredim
deallocate crsscoredim

exec(@viewsql)
GO


---------------------------------------------

-- dbo.procS3RebuildStatistics
create proc dbo.procS3RebuildStatistics
as
	if (not exists(select 1 from fw.SystemSetting where Name = 'ACL Statistics Auto-Rebuild' and Value = '1')) begin
		return
	end

	UPDATE STATISTICS [dbo].[S3IdentityLink] with fullscan;
	UPDATE STATISTICS [dbo].[S3Loot] with fullscan ;
	UPDATE STATISTICS [dbo].[S3LootGroup] with fullscan ;
	UPDATE STATISTICS [dbo].[S3LootRefreshLog] with fullscan ;
	UPDATE STATISTICS [dbo].[S3Permission] with fullscan ;
	UPDATE STATISTICS [dbo].[S3PermissionSet] with fullscan ;
	UPDATE STATISTICS [dbo].[S3RoleAssignment] with fullscan ;
	UPDATE STATISTICS [dbo].[S3SimplePermission] with fullscan ;
	UPDATE STATISTICS [dbo].[S3SimplePermissionDefault] with fullscan ;
	UPDATE STATISTICS [dbo].[S3UserACLRegenRequest] with fullscan ;
GO


---------------------------------------------

-- dbo.procS3RemoveIdentityFromRole
CREATE procedure [dbo].[procS3RemoveIdentityFromRole]
	@IdentityGUID uniqueidentifier,
	@RoleID smallint,
	@LootGroupID nvarchar(128),
	@HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
as

DECLARE @cnt int
declare @ucnt int
SELECT 
	@ucnt = COUNT(*) 
FROM
	USERPROFILE 
WHERE
	userguid = @IdentityGUID

declare @isuser bit
IF @ucnt = 0 
	set @isuser = 0
else
	set @isuser = 1

select
	@cnt = @ucnt + count(*)
from
	usergroup
where
	usergroupguid = @IdentityGUID
	and type = 0

IF @cnt = 0 BEGIN
	PRINT cast(@IdentityGUID as varchar(36)) + ' is invalid identity (not user or group)'
	RETURN
END

SELECT 
	@cnt = COUNT(*) 
FROM
	USERROLE
WHERE
	USERROLE.RoleID = @RoleID

IF @cnt = 0 BEGIN
	PRINT cast(@RoleID as varchar(36)) + ' is invalid role'
	RETURN
END

SELECT 
	@cnt = COUNT(*) 
FROM
	S3LootGroup
WHERE
	LootGroupID = @LootGroupID

IF @cnt = 0 BEGIN
	PRINT cast(@LootGroupID as varchar(36)) + ' is invalid loot'
	RETURN
END

SELECT
	@CNT = COUNT(*)
from
	S3RoleAssignment ra
where
	ra.IdentityGUID = @IdentityGUID
	and ra.LootGroupID = @LootGroupID
	and ra.RoleID = @RoleID

IF @cnt = 0 begin
	PRINT cast(@IdentityGUID as varchar(36)) + ' is not in role ' + cast(@RoleID as varchar(36)) + ' for loot ' + cast(@LootGroupID as nvarchar(128)) 
	return
end

DELETE FROM
	S3RoleAssignment
WHERE
	IdentityGUID = @IdentityGUID
	and RoleID = @RoleID
	and LootGroupID = @LootGroupID
GO


---------------------------------------------

-- dbo.procS3SetSimplePermissionDefault
CREATE PROCEDURE [dbo].[procS3SetSimplePermissionDefault]
	@EntityType int,
	@IdentityGUID uniqueidentifier,
	@ReadValue bit = 1,
	@WriteValue bit = 0,
	@SecureValue bit = 0
AS
BEGIN
	SET NOCOUNT ON;

	-- EntityTypes
	-- 1: Folder
	-- 3: Report
	-- 4: PlanType
	-- 6: MessagingTopic
	-- 8: FormField
	-- 9: FormSection
	-- 10: Pool
	-- 11: ListInsertionPoint
	-- 12: CustomAction
	-- 13: UserGroup
	-- 14: Workflow

	insert into S3SimplePermissionDefault(EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue)
	values(@EntityType, @IdentityGUID, @ReadValue, @WriteValue, @SecureValue)

END
GO


---------------------------------------------

-- dbo.procS3SyncUserDirectRoleAssignments
CREATE proc [procS3SyncUserDirectRoleAssignments] (
	@SourceUserName nvarchar(64),
	@TargetUserName nvarchar(64)
	)
AS
BEGIN

	declare @TargetUserGUID uniqueidentifier;
	declare @SourceUserGUID uniqueidentifier;
	select @TargetUserGUID = userguid from UserProfile where UserName = @TargetUserName;
	select @SourceUserGUID = userguid from UserProfile where UserName = @SourceUserName;
	
	
	if (@TargetUserGUID is null) 
	begin
		print 'Couldn''t find target user: ' + @TargetUserName
		return;
	end
	if (@SourceUserGUID is null) 
	begin
		print 'Couldn''t find target user: ' + @SourceUserName
		return;
	end
	
	insert into S3RoleAssignment
		(IdentityGUID, RoleID, LootGroupID)
	select 
	  @TargetUserGUID,
	  D.RoleID,
	  D.LootGroupID
	from viewS3RoleAssignmentDirect D
		left join viewS3RoleAssignmentDirect C 
			on C.LootGroupID = D.LootGroupID
			and C.RoleID = D.RoleID  
			and C.IdentityGUID = @TargetUserGUID
	where D.IdentityGUID = (select userguid from UserProfile where UserName = @SourceUserName)
		and D.RoleID <> (select RoleID from UserRole where Name = 'Author') 
		and C.IdentityGUID is null;


END
GO


---------------------------------------------

-- dbo.procS3UserAdminEnsureAccess
CREATE proc dbo.procS3UserAdminEnsureAccess
	@userGUID uniqueidentifier
as
	declare @isAdmin bit
	select @isAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) from dbo.UserProfile UP
	left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator')
	where UP.UserGUID = @userGUID

	if (@isAdmin = 1) begin
		--add user setup menu access if not already present from group assignments
		insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
		select 'd62a6536-9bfb-4bde-b945-eda88ab0e19e', u.UserGUID, 1, 1, 0 
		from dbo.UserProfile u 
		where u.UserGUID = @userGUID
		and not exists(select 1 from viewS3AclSimple acl where acl.UserGUID = u.UserGUID and acl.LootID = 'd62a6536-9bfb-4bde-b945-eda88ab0e19e')
	end else begin
		--remove user setup menu access if directly assigned
		delete from S3SimplePermission where LootID = 'd62a6536-9bfb-4bde-b945-eda88ab0e19e' and IdentityGUID = @userGUID;
	end

	--sync security changes to system center
	exec dbo.procS3MenuSecurityAfterSave
GO


---------------------------------------------

-- dbo.procSMCGetDatabaseGUID
CREATE PROCEDURE [dbo].[procSMCGetDatabaseGUID](
	@ReturnVal uniqueidentifier OUTPUT
)
AS
BEGIN

	declare @SMC_SERVER nvarchar(128);
	declare @SMC_DB nvarchar(128);
	declare @DatabaseGUID uniqueidentifier;
	
	select @SMC_SERVER = Setting from DBSetting where Name = 'SMC_PRIMARY_SERVER'
	select @SMC_DB = setting from DBSetting where Name = 'SMC_PRIMARY_DATABASE'
	if (@SMC_SERVER is null)
	begin
		print 'SMC_PRIMARY_SERVER NOT SET.';
		return;
	end
	if (@SMC_DB is null)
	begin
		print 'SMC_PRIMARY_DATABASE NOT SET.';
		return;
	end
	
	declare @sql nvarchar(max);
	set @sql = '
	select 
		@DBGUID_OUT = DatabaseGUID
	from [' + @SMC_SERVER + '].[' + @SMC_DB + '].[dbo].[viewDatabaseInfo]
         where (LinkedServerName = ''' + @@SERVERNAME + ''' OR LinkedServerName = ''' + @@SERVERNAME + '.sdt.local'' OR LinkedServerName = ''' + replace(@@SERVERNAME, '\', '.sdt.local\') + ''' OR replace(LinkedServerName, ''.sdt.local\'', ''\'') = ''' + @@SERVERNAME + ''') AND PhysicalName = ''' + DB_NAME() + '''
	'

	EXECUTE sp_executesql
	@sql,
	N'@DBGUID_OUT uniqueidentifier OUTPUT',
	@DBGUID_OUT=@DatabaseGUID OUTPUT;

    SELECT @ReturnVal = @DatabaseGUID;
END
GO


---------------------------------------------

-- dbo.procSR2EnsureBoundYearAlign
create proc dbo.procSR2EnsureBoundYearAlign
as
	--make sure year on bounds data matches year on corresponding model data, in case model year structure changed

	declare @datatable nvarchar(100)
	declare @boundstable nvarchar(100)
	declare @sql nvarchar(max)

	declare crsTables cursor fast_forward for
	select s.name + '.' + replace(t.name, 'Bounds', '') as DataTableName, s.name + '.' + t.name as BoundsTableName from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where t.name like '%bounds'

	open crsTables
	fetch next from crsTables into @datatable, @boundstable

	while(@@fetch_status = 0) begin
		set @sql = '
			update b set b.FiscalYearID = f.FiscalYearID 
			from 
				' + @boundstable + ' b 
				inner join ' + @datatable + ' f on f.RowID = b.RowID 
			where 
				b.FiscalYearID != f.FiscalYearID
		'
		BEGIN TRY
			exec(@sql)
		END TRY
		BEGIN CATCH
			--LOL
		END CATCH
			
		fetch next from crsTables into @datatable, @boundstable
	end

	close crsTables
	deallocate crsTables
GO


---------------------------------------------

-- dbo.procSR2EnsurePlanFillinCache
create proc dbo.procSR2EnsurePlanFillinCache
	@planGUIDList nvarchar(max) = ''
as
	if (@planguidList = '') begin
		update fi set fi.FillinMemberName = p.Name
		from
			[dbo].[ScoreFillin] fi
			inner join [dbo].[XPlan] p with (readuncommitted) on p.PlanGUID = fi.FillinMemberGUID
		where
			fi.FillinMemberName != p.Name

		exec [dbo].[procScoreFillinTableRefreshAll]
	end else begin
		if (exists(select 1 from [dbo].[ScoreFillin] fi with (readuncommitted) inner join [dbo].[XPlan] p with (readuncommitted) on p.PlanGUID = fi.FillinMemberGUID where p.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@planGUIDList, ',')) and fi.FillinMemberName != p.Name)) begin
			update fi set fi.FillinMemberName = p.Name
			from
				[dbo].[ScoreFillin] fi
				inner join  [dbo].[XPlan] p with (readuncommitted) on p.PlanGUID = fi.FillinMemberGUID
			where
				p.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@planGUIDList, ','))
				and fi.FillinMemberName != p.Name

			exec [dbo].[procScoreFillinTableRefresh] @planGUIDList
		end
	end
GO


---------------------------------------------

-- dbo.procSR2RiskBinsCalculate
CREATE proc dbo.procSR2RiskBinsCalculate
	@riskResultGUID uniqueidentifier,
	@binCount int
as
	set nocount on
	
	declare @min decimal(19, 8)
	declare @max decimal(19, 8)
	declare @step decimal(19, 8)
	
	select @min = coalesce((select MIN(Value) from [dbo].[SR2RiskResultDetail] where RiskResultGUID = @riskResultGUID), 0)
	select @max = coalesce((select MAX(Value) from [dbo].[SR2RiskResultDetail] where RiskResultGUID = @riskResultGUID), 0)
	set @step = ((@max - @min) / cast(@binCount as decimal(19, 8)))

	if (@min = @max) begin
		update [dbo].[SR2RiskResultDetail] set BinNumber = 0 where RiskResultGUID = @riskResultGUID
	end else begin
		declare @binIndex as int = 0
		declare @binLowerBound as decimal(19, 8) = @min
		
		while (@binIndex < @binCount) begin
			update [dbo].[SR2RiskResultDetail] set BinNumber = @binIndex where RiskResultGUID = @riskResultGUID and Value >= @binLowerBound
		
			set @binIndex = @binIndex + 1
			set @binLowerBound = @binLowerBound + @step
		end
	end
GO


---------------------------------------------

-- dbo.procScoreAttributeIsModelDriverRefresh
create proc dbo.procScoreAttributeIsModelDriverRefresh
as
	update [dbo].[ScoreAttribute] set IsModelDriver = 0
	update [dbo].[ScoreAttribute] set IsModelDriver = 1 where exists(select 1 from [dbo].[MEScorePlaceholderLabel] phl (readuncommitted) where phl.FillinAttributeGUID = AttributeGUID)
GO


---------------------------------------------

-- dbo.procScoreAttributeSchemaUpdate
create proc procScoreAttributeSchemaUpdate
	@attributeguid uniqueidentifier
as

update
	sa
set
	sa.CachedInferredSQLColumnType =sac.CachedInferredSQLColumnType,
	sa.ColumnType =sac.ColumnType,
	sa.ComputedValueDefinition =sac.ComputedValueDefinition,
	sa.DefaultValueDefinition =sac.DefaultValueDefinition,
	--sa.DimensionGroupIsTable =sac.DimensionGroupIsTable,
	sa.ForeignKeyColumn =sac.ForeignKeyColumn,
	sa.ForeignKeyOnDelete =sac.ForeignKeyOnDelete,
	sa.ForeignKeySchema =sac.ForeignKeySchema,
	sa.ForeignKeyTable =sac.ForeignKeyTable,
	sa.IdentityIncrement =sac.IdentityIncrement,
	sa.IdentitySeed =sac.IdentitySeed,
	sa.IsColumnExist =sac.IsColumnExist,
	sa.IsComputed =sac.IsComputed,
	sa.IsForeignKeyed =sac.IsForeignKeyed,
	sa.IsIdentity =sac.IsIdentity,
	sa.IsNullable =sac.IsNullable,
	sa.MaxLength =sac.MaxLength,
	sa.Precision =sac.Precision,
	sa.Scale =sac.Scale
from
	ScoreAttribute sa
	inner join viewScoreAttributeSchemaInfo sac on sa.AttributeGUID = sac.AttributeGUID
where
	sa.AttributeGUID = @attributeguid
GO


---------------------------------------------

-- dbo.procScoreAttributeSchemaUpdateAll
CREATE proc [dbo].[procScoreAttributeSchemaUpdateAll] (
	@DimensionGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
) as

update
	sa
set
	sa.CachedInferredSQLColumnType =sac.CachedInferredSQLColumnType,
	sa.ColumnType =sac.ColumnType,
	sa.ComputedValueDefinition =sac.ComputedValueDefinition,
	sa.DefaultValueDefinition =sac.DefaultValueDefinition,
	--sa.DimensionGroupIsTable =sac.DimensionGroupIsTable,
	sa.ForeignKeyColumn =sac.ForeignKeyColumn,
	sa.ForeignKeyOnDelete =sac.ForeignKeyOnDelete,
	sa.ForeignKeySchema =sac.ForeignKeySchema,
	sa.ForeignKeyTable =sac.ForeignKeyTable,
	sa.IdentityIncrement =sac.IdentityIncrement,
	sa.IdentitySeed =sac.IdentitySeed,
	sa.IsColumnExist =sac.IsColumnExist,
	sa.IsComputed =sac.IsComputed,
	sa.IsForeignKeyed =sac.IsForeignKeyed,
	sa.IsIdentity =sac.IsIdentity,
	sa.IsNullable =sac.IsNullable,
	sa.MaxLength =sac.MaxLength,
	sa.Precision =sac.Precision,
	sa.Scale =sac.Scale
from
	ScoreAttribute sa
	inner join ScoreDimensionGroup g on g.DimensionGroupGUID = sa.DimensionGroupGUID
	inner join ScoreDimension d on d.DimensionGUID = g.DimensionGUID
	inner join viewScoreAttributeSchemaInfo sac on sa.AttributeGUID = sac.AttributeGUID
where
	(d.DimensionGUID = @DimensionGUID or @DimensionGUID = '00000000-0000-0000-0000-000000000000')
	and
	(sa.CachedInferredSQLColumnType <>sac.CachedInferredSQLColumnType or
	sa.ColumnType <>sac.ColumnType or
	sa.ComputedValueDefinition <>sac.ComputedValueDefinition or
	sa.DefaultValueDefinition <>sac.DefaultValueDefinition or
	--sa.DimensionGroupIsTable <>sac.DimensionGroupIsTable or
	sa.ForeignKeyColumn <>sac.ForeignKeyColumn or
	sa.ForeignKeyOnDelete <>sac.ForeignKeyOnDelete or
	sa.ForeignKeySchema <>sac.ForeignKeySchema or
	sa.ForeignKeyTable <>sac.ForeignKeyTable or
	sa.IdentityIncrement <>sac.IdentityIncrement or
	sa.IdentitySeed <>sac.IdentitySeed or
	sa.IsColumnExist <>sac.IsColumnExist or
	sa.IsComputed <>sac.IsComputed or
	sa.IsForeignKeyed <>sac.IsForeignKeyed or
	sa.IsIdentity <>sac.IsIdentity or
	sa.IsNullable <>sac.IsNullable or
	sa.MaxLength <>sac.MaxLength or
	sa.Precision <>sac.Precision or
	sa.Scale <>sac.Scale )
RETURN
GO


---------------------------------------------

-- dbo.procScoreAttributeSettingAddMissing
CREATE proc [dbo].[procScoreAttributeSettingAddMissing]
as
	--non-inferred attributes default based on attribute-framework and dimension-framework linkages
	insert into ScoreAttributeSetting (AttributeGUID, DimensionGUID, IsCustom, IsMarkedForDeletion, IsUsed, CAPIsUsed, DSSIsUsed, MRIsUsed, OBIsUsed, PRIsUsed, SPIsUsed)
	select 
		a.AttributeGUID, 
		a.DimensionGUID, 
		0 as IsCustom, 
		0 as IsMarkedForDeletion, 
		(case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(dss.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'DSS %' or a.FriendlyName like '% DSS' then 1 else 0 end) as IsUsed, 
		(case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(cap.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'CAP %' or a.FriendlyName like '% CAP' or a.FriendlyName like 'Capital %' or a.FriendlyName like '% Capital' then 1 else 0 end) as CAPIsUsed, 
		(case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(dss.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'DSS %' or a.FriendlyName like '% DSS' then 1 else 0 end) as DSSIsUsed, 
		(case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(mr.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'MR %' or a.FriendlyName like '% MR' or a.FriendlyName like '% MR %' then 1 else 0 end) as MRIsUsed, 
		(case when isnull(ob.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'OB %' or a.FriendlyName like '% OB' then 1 else 0 end) as OBIsUsed, 
		(case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(pr.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'PR %' or a.FriendlyName like '% PR' or a.FriendlyName like '% PR %' or a.FriendlyName like 'PI %' or a.FriendlyName like '% PI' or a.FriendlyName like '% PI %' then 1 else 0 end) as PRIsUsed, 
		(case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(sp.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'SP %' or a.FriendlyName like '% SP' then 1 else 0 end) as SPIsUsed
	from 
		viewScoreAttribute a
		left join viewScoreAttributeFramework fw on fw.AttributeGUID = a.AttributeGUID and fw.FrameworkID = 0
		left join viewScoreAttributeFramework cap on cap.AttributeGUID = a.AttributeGUID and cap.FrameworkID = 1
		left join viewScoreAttributeFramework dss on dss.AttributeGUID = a.AttributeGUID and dss.FrameworkID = 6
		left join viewScoreAttributeFramework mr on mr.AttributeGUID = a.AttributeGUID and mr.FrameworkID = 3
		left join viewScoreAttributeFramework ob on ob.AttributeGUID = a.AttributeGUID and ob.FrameworkID = 2
		left join viewScoreAttributeFramework pr on pr.AttributeGUID = a.AttributeGUID and pr.FrameworkID = 5
		left join viewScoreAttributeFramework sp on sp.AttributeGUID = a.AttributeGUID and sp.FrameworkID = 4
	where
		not exists(select 1 from ScoreAttributeSetting sa where sa.AttributeGUID = a.AttributeGUID)
		and a.InferredAttributeGUID = '00000000-0000-0000-0000-000000000000'

	--inferred attributes just pull from their parent attribute, except for Department
	insert into ScoreAttributeSetting (AttributeGUID, DimensionGUID, IsCustom, IsMarkedForDeletion, IsUsed, CAPIsUsed, DSSIsUsed, MRIsUsed, OBIsUsed, PRIsUsed, SPIsUsed)
	select 
		a.AttributeGUID, 
		a.DimensionGUID, 
		pas.IsCustom, 
		0 as IsMarkedForDeletion, 
		pas.IsUsed, 
		pas.CAPIsUsed, 
		pas.DSSIsUsed, 
		pas.MRIsUsed, 
		pas.OBIsUsed, 
		pas.PRIsUsed, 
		pas.SPIsUsed
	from 
		viewScoreAttribute a
		inner join ScoreAttributeSetting pas on pas.AttributeGUID = a.InferredAttributeGUID
	where
		not exists(select 1 from ScoreAttributeSetting sa where sa.AttributeGUID = a.AttributeGUID)
		and a.InferredAttributeGUID != '00000000-0000-0000-0000-000000000000'
		and a.DimensionName != 'Department'
	update sas set
		sas.IsCustom = pas.IsCustom,
		sas.IsUsed = pas.IsUsed, 
		sas.CAPIsUsed = pas.CAPIsUsed, 
		sas.DSSIsUsed = pas.DSSIsUsed, 
		sas.MRIsUsed = pas.MRIsUsed, 
		sas.OBIsUsed = pas.OBIsUsed, 
		sas.PRIsUsed = pas.PRIsUsed, 
		sas.SPIsUsed = pas.SPIsUsed
	from 
		viewScoreAttribute a
		inner join ScoreAttributeSetting sas on sas.AttributeGUID = a.AttributeGUID
		inner join ScoreAttributeSetting pas on pas.AttributeGUID = a.InferredAttributeGUID
	where
		a.InferredAttributeGUID != '00000000-0000-0000-0000-000000000000'
		and a.DimensionName != 'Department'
		and (
			sas.IsCustom != pas.IsCustom or
			sas.IsUsed != pas.IsUsed or
			sas.CAPIsUsed != pas.CAPIsUsed or
			sas.DSSIsUsed != pas.DSSIsUsed or
			sas.MRIsUsed != pas.MRIsUsed or
			sas.OBIsUsed != pas.OBIsUsed or
			sas.PRIsUsed != pas.PRIsUsed or
			sas.SPIsUsed != pas.SPIsUsed
		)

	update sas
	set sas.PRIsUsed=1, sas.MRIsUsed=1
	from
		scoreattributesetting sas
		join scoreattribute attr on sas.AttributeGUID = attr.AttributeGUID
		join ScoreDimensionGroup gr on attr.DimensionGroupGUID = gr.DimensionGroupGUID
		join ScoreDimension dim on dim.DimensionGUID = gr.DimensionGUID
	where 
		dim.FriendlyName='MR Department'
		and (sas.PRIsUsed=0 or sas.MRIsUsed=0)
GO


---------------------------------------------

-- dbo.procScoreAttributeSettingSetFromDI
CREATE proc dbo.procScoreAttributeSettingSetFromDI
as
	with diUsage as (
		select 
			x.AttributeGUID
			,max(case when x.FrameworkID in(0, 1) then 1 else 0 end) as CAPIsUsed
			,max(case when x.FrameworkID in(0, 2) then 1 else 0 end) as OBIsUsed
			,max(case when x.FrameworkID in(0, 3) then 1 else 0 end) as MRIsUsed
			,max(case when x.FrameworkID in(0, 4) then 1 else 0 end) as SPIsUsed
			,max(case when x.FrameworkID in(0, 5) then 1 else 0 end) as PRIsUsed
			,max(case when x.FrameworkID in(0, 6) then 1 else 0 end) as DSSIsUsed
			,max(case when x.FrameworkID in(0, 6) then 1 else 0 end) as IsUsed
		from (
			select
				dif.ScoreKeyGUID as AttributeGUID,
				c.FrameworkID
			from
				IntConfig c
				inner join IntDataInterfaceSection dis on dis.DataInterfaceID = c.DataInterfaceID
				inner join IntDataInterfaceField dif on dif.DataInterfaceSectionID = dis.DataInterfaceSectionID
			where
				datediff(day, c.LastRunAtUtc, getutcdate()) <= 120
				and dif.IsHidden = 0
			union all
			select
				dif.GivenScoreAttributeGUID as AttributeGUID,
				c.FrameworkID
			from
				IntConfig c
				inner join IntDataInterfaceSection dis on dis.DataInterfaceID = c.DataInterfaceID
				inner join IntDataInterfaceField dif on dif.DataInterfaceSectionID = dis.DataInterfaceSectionID
			where
				datediff(day, c.LastRunAtUtc, getutcdate()) <= 120
				and dif.IsHidden = 0
		) x
		group by x.AttributeGUID
	)
	update s set s.IsUsed = (case when di.IsUsed = 1 then 1 else s.IsUsed end), s.CAPIsUsed = (case when di.CAPIsUsed = 1 then 1 else s.CAPIsUsed end), s.OBIsUsed = (case when di.OBIsUsed = 1 then 1 else s.OBIsUsed end), s.MRIsUsed = (case when di.MRIsUsed = 1 then 1 else s.MRIsUsed end), s.SPIsUsed = (case when di.SPIsUsed = 1 then 1 else s.SPIsUsed end), s.PRIsUsed = (case when di.PRIsUsed = 1 then 1 else s.PRIsUsed end), s.DSSIsUsed = (case when di.DSSIsUsed = 1 then 1 else s.DSSIsUsed end)
	from 
		ScoreAttributeSetting s
		inner join diUsage di on di.AttributeGUID = s.AttributeGUID

	exec dbo.procScoreAttributeSettingAddMissing
GO


---------------------------------------------

-- dbo.procScoreClearLootRefreshTriggers
--Forward
create procedure [dbo].[procScoreClearLootRefreshTriggers](
	@DimensionGUID uniqueidentifier
)
AS
BEGIN

	declare crsCursor CURSOR LOCAL FAST_FORWARD FOR
		select SchemaName, Name from ViewSysTriggers
	where Name like '%' + [dbo].GetScoreLootRefreshTriggerName(@DimensionGUID) + '%'
		
	open crsCursor;

	declare @SchemaName sysname;
	declare @TriggerName sysname;

	FETCH NEXT FROM crsCursor into @SchemaName, @TriggerName
	WHILE (@@FETCH_STATUS = 0) 
		BEGIN
			
			exec procSysDropTrigger @SchemaName, @TriggerName
			
			FETCH NEXT FROM crsCursor into @SchemaName, @TriggerName
		END
	close crsCursor;
	DEALLOCATE crsCursor;

END

RETURN
GO


---------------------------------------------

-- dbo.procScoreCompositeModifiedAt
--Author: gforeman
--Branch: Firefly
--Forward
CREATE proc [dbo].[procScoreCompositeModifiedAt]
	@compositeguid uniqueidentifier
as
select coalesce((select MAX(ModifiedAt) from 
	(
		select sc.ModifiedAt from ScoreComposite sc where sc.CompositeGUID = @compositeguid
		union all
		select sl.ModifiedAt from ScoreCompositeLink sl where sl.CompositeGUID = @compositeguid
		union all
		select dt1.ModifiedAt from ScoreDataTable dt1 where dt1.DataTableGUID in(select sc.DataTableGUID1 from ScoreComposite sc where sc.CompositeGUID = @compositeguid)
		union all
		select sm1.ModifiedAt from ScoreMeasure sm1 where sm1.DataTableGUID in(select sc.DataTableGUID1 from ScoreComposite sc where sc.CompositeGUID = @compositeguid)
		union all
		select dtkl1.ModifiedAt from ScoreDataTableKeyLink dtkl1 where dtkl1.DataTableGUID in(select sc.DataTableGUID1 from ScoreComposite sc where sc.CompositeGUID = @compositeguid)
		union all
		select sa1.DateModified as ModifiedAt from ScoreAttribute sa1 where sa1.AttributeGUID in(select dtkl1.KeyGUID from ScoreDataTableKeyLink dtkl1 where dtkl1.DataTableGUID in(select sc.DataTableGUID1 from ScoreComposite sc where sc.CompositeGUID = @compositeguid))
		union all
		select dt2.ModifiedAt from ScoreDataTable dt2 where dt2.DataTableGUID in(select sc.DataTableGUID2 from ScoreComposite sc where sc.CompositeGUID = @compositeguid)
		union all
		select sm2.ModifiedAt from ScoreMeasure sm2 where sm2.DataTableGUID in(select sc.DataTableGUID2 from ScoreComposite sc where sc.CompositeGUID = @compositeguid)
		union all
		select dtkl2.ModifiedAt from ScoreDataTableKeyLink dtkl2 where dtkl2.DataTableGUID in(select sc.DataTableGUID2 from ScoreComposite sc where sc.CompositeGUID = @compositeguid)
		union all
		select sa2.DateModified as ModifiedAt from ScoreAttribute sa2 where sa2.AttributeGUID in(select dtkl2.KeyGUID from ScoreDataTableKeyLink dtkl2 where dtkl2.DataTableGUID in(select sc.DataTableGUID2 from ScoreComposite sc where sc.CompositeGUID = @compositeguid))
	) x
), getdate())	--return current date if invalid guid passed
GO


---------------------------------------------

-- dbo.procScoreCopyComposite
CREATE PROCEDURE [dbo].[procScoreCopyComposite] (
	@CompositeGUID uniqueidentifier,
	@TargetDatabase varchar(4000),  -- [Server].[Database] for example: [ittestserv01\sql2005].[TSMChampaign]
	@IsIncludeData bit = 0,
	@IsDebugOnly bit = 0
)
AS

--Copy Both DataTables (does not need dynamic sql)
declare @DataTable1GUID uniqueidentifier;
declare @DataTable2GUID uniqueidentifier;
select @DataTable1GUID = DataTableGUID1, @DataTable2GUID = DataTableGUID2 from ScoreComposite where CompositeGUID = @CompositeGUID;

execute [dbo].procScoreCopyDataTable @DataTable1GUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly;
execute [dbo].procScoreCopyDataTable @DataTable2GUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly;

---Now register the composite and copy composite links (requiring dynamic sql)
declare @sql varchar(max)
set @sql = '

declare @TargetDatabase varchar(4000);
declare @CompositeGUID uniqueidentifier;
declare @Source_FriendlyName nvarchar(max);
declare @Target_Count int;

set @CompositeGUID = ''' + Cast(@CompositeGUID as varchar(64)) + ''';
set @TargetDatabase = ''' + @TargetDatabase + ''';

--Check for Existence
select @Source_FriendlyName = FriendlyName from dbo.ScoreComposite
	WHERE CompositeGUID = @CompositeGUID
SELECT @Target_Count = COUNT(*) from ' + @TargetDatabase + '.[dbo].[ScoreComposite] 
	WHERE CompositeGUID = @CompositeGUID Or FriendlyName = @Source_FriendlyName;

if (@Target_Count > 0)
BEGIN
	print ''Composite Exists in Target Database'';
	RETURN;
END

--Copy Composite into new table
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreComposite] 
(CompositeGUID,DataTableGUID1,DataTableGUID2,IsWrittenToDB,FriendlyName)
SELECT top 1 
CompositeGUID,DataTableGUID1,DataTableGUID2,IsWrittenToDB,FriendlyName
from dbo.ScoreComposite WHERE CompositeGUID = @CompositeGUID;

--Copy CompositeLinks into new table (have to account for Identity..so do this custom columns
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreCompositeLink]
	(CompositeGUID,CompositeLinkGUID,IsFixedIndex,IsPlaceholder,Key1AttributeGUID,Key1GUID,Key2AttributeGUID,Key2GUID,PlaceholderIndexMeasureGUID,SQLCustomLinkExpression,Type)
SELECT
	LINK.CompositeGUID,LINK.CompositeLinkGUID,LINK.IsFixedIndex,LINK.IsPlaceholder,LINK.Key1AttributeGUID,FK1.AttributeGUID,LINK.Key2AttributeGUID,FK2.AttributeGUID,LINK.PlaceholderIndexMeasureGUID,LINK.SQLCustomLinkExpression,LINK.Type
 from 
 	[dbo].[ScoreCompositeLink] LINK 
	inner join viewScoreAttribute K1 on K1.AttributeGUID = LINK.Key1GUID
	inner join viewScoreAttribute K2 on K2.AttributeGUID = LINK.Key2GUID
	left join ' + @TargetDatabase + '.[dbo].[viewScoreAttribute] FK1 on FK1.SQLColumnName = K1.SQLColumnName and FK1.DimensionName = K1.DimensionName
	left join ' + @TargetDatabase + '.[dbo].[viewScoreAttribute] FK2 on FK2.SQLColumnName = K2.SQLColumnName and FK2.DimensionName = K2.DimensionName
where CompositeGUID=@CompositeGUID
'
print @sql;

if @IsDebugOnly = 0 
BEGIN
	exec (@sql);
END
GO


---------------------------------------------

-- dbo.procScoreCopyDataTable
CREATE PROCEDURE [dbo].[procScoreCopyDataTable] (
	@DataTableGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',
	@TargetDatabase varchar(4000),  -- [Server].[Database] for example: [ittestserv01\sql2005].[TSMChampaign]
	@IsIncludeData bit = 0,
	@IsDebugOnly bit = 0,
	@aFriendlyName varchar(max) = ''
)
AS

if (@aFriendlyName <> '')
BEGIN
	print 'Recursive Call';
	declare @DTGUID uniqueidentifier;
	select @DTGUID=DatatableGUID from ScoreDatatable where FriendlyName = @aFriendlyName;
	exec dbo.procScoreCopyDataTable @DTGUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly;
	RETURN;
END

print ' Copying Dimensions '
--First Must Copy all dimensions that are a part of this datatable (have keys)
-- this does not require dynamic sql
DECLARE  DimensionCursor CURSOR FOR
SELECT Distinct(DimensionGUID), (select count(*) from [dbo].[viewScoreAttribute] A where A.DimensionGUID = D.DimensionGUID) as AttributeCount from ScoreDimension D where
	D.DimensionGUID IN (
	--ALL DIMENSIONS IN DT
	select DIM.DimensionGUID from ScoreDataTable DT
		inner join ScoreDataTableKeyLink DTKEYLINK	on DT.DataTableGUID = DTKEYLINK.DataTableGUID
		inner join viewScoreAttribute ATT on ATT.AttributeGUID = DTKEYLINK.KeyGUID
		inner join ScoreDimension DIM on DIM.DimensionGUID = ATT.DimensionGUID
	where DT.DataTableGUID = @DataTableGUID
	UNION
	--INCLUDE FK_DIMENSIONS OF ANY ATTRIBUTES
	select DIM_FK.DimensionGUID from ScoreDataTable DT
		inner join ScoreDataTableKeyLink DTKEYLINK	on DT.DataTableGUID = DTKEYLINK.DataTableGUID
		inner join viewScoreAttribute ATT on ATT.AttributeGUID = DTKEYLINK.KeyGUID
		inner join ScoreDimension DIM on DIM.DimensionGUID = ATT.DimensionGUID
		inner join viewScoreAttribute ATT_FK on ATT.ForeignKeyGUID = ATT_FK.AttributeGUID
		inner join ScoreDimension DIM_FK on ATT_FK.DimensionGUID = DIM_FK.DimensionGUID
	where DT.DataTableGUID = @DataTableGUID)
order by AttributeCount asc -- do smaller dimensions first, as presumably the larger dimensions depend on them


Open DimensionCursor
declare @DimGUID uniqueidentifier
declare @AttrCount int
FETCH NEXT FROM DimensionCursor INTO @DimGUID, @AttrCount
WHILE (@@FETCH_STATUS = 0)
BEGIN
	EXECUTE dbo.procScoreCopyDimension @DimGUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly;
	FETCH NEXT FROM DimensionCursor INTO @DimGUID, @AttrCount
END
CLOSE DimensionCursor
DEALLOCATE DimensionCursor


declare @SQLSchemaName varchar(max);
declare @SQLObjectName varchar(max);
select @SQLSchemaName = SQLSchemaName,
	@SQLObjectName = SQLObjectName 
		from ScoreDataTable where DataTableGUID = @DataTableGUID;

print ' Copying Datatable '
declare @sql varchar(max)
set @sql = '

declare @TargetDatabase varchar(4000);
declare @DataTableGUID uniqueidentifier;
declare @Source_FriendlyName nvarchar(max);
declare @Target_Count int;
set @DataTableGUID = ''' + Cast(@DataTableGUID as varchar(64)) + ''';
set @TargetDatabase = ''' + @TargetDatabase + ''';

--Check for Existence
select @Source_FriendlyName = FriendlyName from dbo.ScoreDataTable
	WHERE DataTableGUID = @DataTableGUID
select @Target_Count = COUNT(*) from ' + @TargetDatabase + '.[dbo].[ScoreDataTable] 
	WHERE DataTableGUID = @DataTableGUID Or FriendlyName = @Source_FriendlyName;

if (@Target_Count > 0)
BEGIN
	print ''DataTable Exists in Target Database'';
	RETURN;
END

--Copy DataTable into new table
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDataTable] 
 (DataTableGUID,FriendlyName,Description,SQLSchemaName,SQLObjectName,SQLTableAlias,IsWrittenToDB,DisplayFormatAttributeGUID,GlobalID,IsCompositeMappingTable,IsCompositeBoundsTable,FrameworkID,IsWrittenIfZero)
SELECT top 1 
  DataTableGUID,FriendlyName,Description,SQLSchemaName,SQLObjectName,SQLTableAlias,IsWrittenToDB,DisplayFormatAttributeGUID,GlobalID,IsCompositeMappingTable,IsCompositeBoundsTable,FrameworkID,IsWrittenIfZero
 from dbo.ScoreDataTable WHERE DataTableGUID = @DataTableGUID;

--Copy KeyLinks into new table
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDataTableKeyLink] 
 (DataTableKeyLinkGUID,DataTableGUID,KeyGUID)
SELECT 
  LINK.DataTableKeyLinkGUID,LINK.DataTableGUID,FK1.AttributeGUID
FROM dbo.ScoreDataTableKeyLink LINK
	inner join viewScoreAttribute K1 on K1.AttributeGUID = LINK.KeyGUID
	left join ' + @TargetDatabase + '.[dbo].[viewScoreAttribute] FK1 on FK1.SQLColumnName = K1.SQLColumnName and FK1.DimensionName = K1.DimensionName
WHERE DataTableGUID = @DataTableGUID;


--Copy Measures into new table
declare @measureWhere nvarchar(450)
set @measureWhere = ''DataTableGUID = '''''' + cast(@DataTableGUID as nvarchar(36)) + ''''''''
exec ' + @TargetDatabase + '.dbo.procMigrateScriptGetByTable ''dbo'', ''[' + cast(SERVERPROPERTY('SERVERNAME') as varchar(4000)) + '].[' + DB_NAME() + ']'', ''ScoreMeasure'', @measureWhere, 1

--Never Copy Data but always Copy the Schema
-- DONT DO THIS ANYMORE, SYNC FIRST
--EXEC ' + @TargetDatabase + '.[dbo].[procLinkedTransferDataBetweenTables] ''[' + cast(SERVERPROPERTY('SERVERNAME') as varchar(4000)) + '].[' + DB_NAME() + '].' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ''',''' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + '''
--		,'' 1=0 '';

';

print @sql;

if @IsDebugOnly = 0 
BEGIN
	exec (@sql);
END
GO


---------------------------------------------

-- dbo.procScoreCopyDimension
CREATE PROCEDURE [dbo].[procScoreCopyDimension] (
	@DimensionGUID uniqueidentifier='00000000-0000-0000-0000-000000000000',
	@TargetDatabase varchar(4000),  -- [Server].[Database] for example: [ittestserv01\sql2005].[TSMChampaign]
	@IsIncludeData bit = 0,
	@IsDebugOnly bit = 0,
	@IsIncludeForeignKeyDimensions bit = 0,
	@IsBuildingTables bit = 0
)
AS


if (@DimensionGUID = '00000000-0000-0000-0000-000000000000')
BEGIN
	RETURN;
END

--Dont want to framework transfer account ph if missing, as it conflicts with ob account ph - everyone will have one or the other already
if (exists (select 1 from [dbo].[ScoreDimension] (nolock) where DimensionGUID = @DimensionGUID and FriendlyName = 'Account PH')) begin return end

print 'Copying Dimension';
declare @SQLSchemaName nvarchar(128);
declare @SQLObjectName nvarchar(max);
select 
	@SQLSchemaName = SQLSchemaName,
	@SQLObjectName = SQLObjectName
from [dbo].[ScoreDimension] where DimensionGUID = @DimensionGUID


--Check Foreign Key Dimensions
if (@IsIncludeForeignKeyDimensions = 1) 
begin
	declare crsCursor  CURSOR FAST_FORWARD LOCAL FOR
	   select distinct FKD.DimensionGUID, FKD.FriendlyName from ScoreDimension D
			inner join viewScoreAttribute A on A.DimensionGUID = D.DimensionGUID
			inner join viewScoreAttribute FKA on FKA.AttributeGUID = A.ForeignKeyGUID
			inner join ScoreDimension FKD on FKD.DimensionGUID = FKA.DimensionGUID
		where D.DimensionGUID = @DimensionGUID
	open crsCursor;
	declare @fkDimGUID uniqueidentifier;
	declare @fkName varchar(max);
	FETCH NEXT FROM crsCursor into @fkDimGUID, @fkName;

	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		print 'Copying Foreign Key Dimension: ' + @fkName;
		exec procScoreCopyDimension @fkDimGUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly, @IsBuildingTables;
		FETCH NEXT FROM crsCursor into @fkDimGUID, @fkName
	END
	close crsCursor;
	DEALLOCATE crsCursor;
end


if (@IsBuildingTables = 1 or @IsIncludeData = 1) begin
	
	declare @GroupSchema nvarchar(128);
	declare @GroupObject nvarchar(128);
	declare grpCursor  CURSOR FAST_FORWARD LOCAL FOR
	   select G.SchemaName, G.ObjectName from ScoreDimension D
			inner join ScoreDimensionGroup G on D.DimensionGUID = G.DimensionGUID
		where D.DimensionGUID = @DimensionGUID
	open grpCursor;
	FETCH NEXT FROM grpCursor into @GroupSchema, @GroupObject;

	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		declare @remoteSQL varchar(max);
		set @remoteSQL = '';
		--disallow building a view
		if (@IsBuildingTables = 1 and dbo.IsView(@GroupSchema,@GroupObject) = 0) begin
			print 'Remotely Building Group Table: ' + '[' + @GroupSchema + '].[' + @GroupObject + ']''';
			set @remoteSQL = @remoteSQL + ' exec ' + @TargetDatabase + '.[sqlgen].procCopyRemoteTable ''[' + cast(SERVERPROPERTY('SERVERNAME') as varchar(4000)) + '].[' + DB_NAME() + ']'', ''' + @GroupSchema + ''', ''' + @GroupObject + ''';
'			
		end
		--attempt to transfer regardless
		if (@IsIncludeData = 1) begin
			print 'Transfering Data to ' + '[' + @GroupSchema + '].[' + @GroupObject + ']''';			
			set @remoteSQL = @remoteSQL + ' EXEC ' + @TargetDatabase + '.[dbo].[procLinkedTransferDataBetweenTables] ''[' + cast(SERVERPROPERTY('SERVERNAME') as varchar(4000)) + '].[' + DB_NAME() + '].' + (select [dbo].[GetSQLTableExpression](@GroupSchema, @GroupObject)) + ''',''' + (select [dbo].[GetSQLTableExpression](@GroupSchema, @GroupObject)) + '''';			
		end
		print @remoteSQL;		
		if (@IsDebugOnly = 0) begin
			exec (@remoteSQL);
		end
				
		FETCH NEXT FROM grpCursor into @GroupSchema, @GroupObject;
	END
	close grpCursor;
	DEALLOCATE grpCursor;


	
end

declare @sql varchar(max)
set @sql = '

declare @DimensionGUID uniqueidentifier;
set @DimensionGUID = ''' + Cast(@DimensionGUID as varchar(64)) + ''';
declare @IsIncludeData bit;
set @IsIncludeData = ' + Cast(@IsIncludeData as varchar) + ';

declare @Target_Count int;
declare @Source_FriendlyName nvarchar(max);


select @Source_FriendlyName = FriendlyName from [dbo].[ScoreDimension] where DimensionGUID = @DimensionGUID;

select @Target_Count = Count(*) from ' + @TargetDatabase + '.[dbo].[ScoreDimension] 
where DimensionGUID = @DimensionGUID OR FriendlyName = @Source_FriendlyName;
	
if (@Target_Count > 0) 
BEGIN
	print ''Dimension Exists in Target Database''
	Return;
END

--Copy Dimension into new table
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDimension]
 (	DimensionGUID, 
	FriendlyName, 
	Description,
	SQLTableAlias, 
	DefaultKeyGUID, 
	DefaultHierarchyGUID, 
	DefaultLookupKeyGUID, 
	IsSecured, 
	PermissionSetID, 
	SQLSchemaName, 
	SQLObjectName, 
	DefaultMemberGUID, 
	IsSysAdminOnly,
	IsAllowMemberDelete,
	IsAllowMemberAdd,
	PrimaryGroupGUID,
	IsStock,
	DateModified,
	PickerType,
	IsSharingSecurity ,
	DimensionVersion
)
 SELECT top 1 
	DimensionGUID, 
	FriendlyName, 
	Description,
	SQLTableAlias, 
	DefaultKeyGUID, 
	DefaultHierarchyGUID, 
	DefaultLookupKeyGUID, 
	IsSecured, 
	PermissionSetID, 
	SQLSchemaName, 
	SQLObjectName, 
	DefaultMemberGUID, 
	IsSysAdminOnly,
	IsAllowMemberDelete,
	IsAllowMemberAdd,
	PrimaryGroupGUID,
	IsStock,
	DateModified,
	PickerType,
	IsSharingSecurity,
	DimensionVersion
  from dbo.ScoreDimension WHERE DimensionGUID = @DimensionGUID;

-- Copy Dimension Groups
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDimensionGroup]
(DimensionGroupGUID, DimensionGUID, Name, Description, SchemaName, ObjectName, IsStock, DateModified)
SELECT
	DimensionGroupGUID, DimensionGUID, Name, Description, SchemaName, ObjectName, IsStock, DateModified
from dbo.ScoreDimensionGroup WHERE DimensionGUID = @DimensionGUID;

--Copy Attributes into new table
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreAttribute] 
 (AttributeGUID, 
  DimensionGroupGUID, 
  FriendlyName, 
  IsWrittenToDB, 
  IsKey, 
  IsSecuredLootID, 
  IsSecuredLootGroupID, 
  SecuredLootGroupPrefix, 
  SQLColumnName, 
  DefaultSortAttributeGUID, 
  ForeignKeyGUID, 
  IsRequired, 
  SpecialAttributeIndex, 
  IsCopiedWithPlan, 
  DisplayOrder,
  IsHidden, 
  DateModified, 
  AttributeType,
  MetaXML,
  InferredSourceGUID,
  InferredColumnName,
  InferredAttributeGUID,
  HelpText,
  ColumnType,
  ComputedValueDefinition,
  IsComputed,
  IsIdentity,
  IdentityIncrement,
  IdentitySeed,
  IsNullable,
  DefaultValueDefinition,
  Precision,
  Scale,
  MaxLength,
  IsColumnExist,
  IsForeignKeyed,
  ForeignKeySchema,
  ForeignKeyTable,
  ForeignKeyColumn,
  ForeignKeyOnDelete,
  CachedInferredSQLColumnType,
  IsFKAutoFilter,
  JoinTypeVal
  )
SELECT 
 A.AttributeGUID, 
  A.DimensionGroupGUID, 
  A.FriendlyName, 
  A.IsWrittenToDB, 
  A.IsKey, 
  A.IsSecuredLootID, 
  A.IsSecuredLootGroupID, 
  A.SecuredLootGroupPrefix, 
  A.SQLColumnName, 
  A.DefaultSortAttributeGUID, 
  A.ForeignKeyGUID, 
  A.IsRequired, 
  A.SpecialAttributeIndex, 
  A.IsCopiedWithPlan, 
  A.DisplayOrder,
  A.IsHidden, 
  A.DateModified, 
  A.AttributeType,
  A.MetaXML,
  A.InferredSourceGUID,
  A.InferredColumnName,
  A.InferredAttributeGUID,
  A.HelpText,
  A.ColumnType,
  A.ComputedValueDefinition,
  A.IsComputed,
  A.IsIdentity,
  A.IdentityIncrement,
  A.IdentitySeed,
  A.IsNullable,
  A.DefaultValueDefinition,
  A.Precision,
  A.Scale,
  A.MaxLength,
  A.IsColumnExist,
  A.IsForeignKeyed,
  A.ForeignKeySchema,
  A.ForeignKeyTable,
  A.ForeignKeyColumn,
  A.ForeignKeyOnDelete,
  A.CachedInferredSQLColumnType,
  A.IsFKAutoFilter,
  A.JoinTypeVal
 from dbo.viewScoreAttribute A 
	inner join ScoreDimensionGroup G on G.DimensionGroupGUID = A.DimensionGroupGUID
	inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID	
WHERE D.DimensionGUID = @DimensionGUID;

--Copy Hierarchies
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreHierarchy] 
	(HierarchyGUID, DimensionGUID, FriendlyName, PathAlias, DateModified)
SELECT 
    HierarchyGUID, DimensionGUID, FriendlyName, PathAlias, DateModified
from dbo.ScoreHierarchy WHERE DimensionGUID = @DimensionGUID;


--Copy Hierarchy Attribute Links
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreHierarchyAttributeLink]
(HierarchyAttributeLinkGUID,
	HierarchyGUID,
	AttributeGUID,
	DisplayAttributeGUID,
	SortOrder, 
	IsDependentOnChild, 
	DateModified,
	IsAttributeFiltered,
	FilterAttributeGUID,
	FilterString
)
SELECT
	LINK.HierarchyAttributeLinkGUID,
	LINK.HierarchyGUID,
	LINK.AttributeGUID,
	LINK.DisplayAttributeGUID,
	LINK.SortOrder, 
	LINK.IsDependentOnChild, 
	LINK.DateModified,
	LINK.IsAttributeFiltered,
	LINK.FilterAttributeGUID,
	LINK.FilterString
  from ScoreHierarchyAttributeLink LINK
	inner join viewScoreAttribute ATT on ATT.AttributeGUID = LINK.AttributeGUID
	inner join ScoreDimension DIM on ATT.DimensionGUID = DIM.DimensionGUID
		where DIM.DimensionGUID = @DimensionGUID;

--Copy Dimension Framework
INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDimensionFramework]
(DimensionGUID,
	FrameworkID
)
SELECT
	DFW.DimensionGUID,
	DFW.FrameworkID
FROM ScoreDimensionFramework DFW
	WHERE DFW.DimensionGUID = @DimensionGUID;
	


--SIMPLE PERMISSIONS
if not exists (select 1 from ' + @TargetDatabase + '.[dbo].[S3SimplePermission] where LootID = @DimensionGUID and IdentityGUID = (select UserGroupGUID from ' + @TargetDatabase + '.[dbo].[UserGroup] where Name = ''Everyone'')) begin
	insert into ' + @TargetDatabase + '.[dbo].[S3SimplePermission] (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	VALUES (@DimensionGUID, (select UserGroupGUID from ' + @TargetDatabase + '.[dbo].[UserGroup] where Name = ''Everyone''), 1,1,1)
end

';
print @sql;

if @IsDebugOnly = 0 
BEGIN
	exec (@sql);
END
GO


---------------------------------------------

-- dbo.procScoreDataTableCreateParamTypes
create proc dbo.procScoreDataTableCreateParamTypes
	@isDebug bit = 0
as
	declare @dtguid uniqueidentifier
	declare @sql nvarchar(max)
	declare crsTables cursor fast_forward for
		select 
			dt.DataTableGUID, '
			if (exists(select 1 from sys.schemas s inner join sys.types t on t.schema_id = s.schema_id where s.name = ''' + dt.SQLSchemaName + ''' and t.name = ''' + dt.SQLObjectName + 'TableType'')) begin
				drop type ' + dt.SQLSchemaName + '.' + dt.SQLObjectName + 'TableType;
			end
			create type ' + dt.SQLSchemaName + '.' + dt.SQLObjectName + 'TableType as table (
				[RowID] int{0}
			);'
		from 
			dbo.ScoreDataTable dt
		where
			dt.FriendlyName not like '% Aggregate'
			and exists(select 1 from dbo.ScoreComposite c where c.DataTableGUID2 = dt.DataTableGUID and exists(select 1 from EMFModelTemplateLinkSource emf where emf.ParentScoreCompositeTableGUID = c.CompositeGUID))
			and exists(select 1 from dbo.ScoreMeasure m where m.DataTableGUID = dt.DataTableGUID and m.IsWrittenToDB = 1)

	open crsTables
	fetch next from crsTables into @dtguid, @sql

	declare @measures nvarchar(max)
	declare @measure nvarchar(max)

	while (@@fetch_status = 0) begin
		declare crsMeasures cursor fast_forward for
			select m.ColName from (
				select 
					', [' + m.SQLColumnName + '] ' + t.name + case when t.name = 'varchar' then '(' + cast(m.MaxLength as nvarchar(8)) + ')' when t.name = 'nvarchar' and m.MaxLength <= 4000 then '(' + cast(m.MaxLength as nvarchar(8)) + ')' when t.name = 'nvarchar' and m.MaxLength > 4000 then '(4000)' when t.name = 'decimal' then '(' + cast(m.Precision as nvarchar(8)) + ',' + cast(m.Scale as nvarchar(8)) + ')' else '' end as ColName
				from 
					dbo.ScoreMeasure m
					inner join sys.types t on t.system_type_id = m.ColumnTypeValue
				where
					m.IsWrittenToDB = 1
					and m.DataTableGUID = @dtguid
					and t.name != 'sysname'
				union all
				select 
					', [' + m.SpecialFormulaSQLColumnName + '] nvarchar(max)' as ColName
				from 
					dbo.ScoreMeasure m
					inner join sys.types t on t.system_type_id = m.ColumnTypeValue
				where
					m.IsWrittenToDB = 1
					and m.DataTableGUID = @dtguid
					and t.name != 'sysname'
					and m.SpecialFormulaSQLColumnName != ''
				union all
				select 
					', [' + m.SpecialCommentSQLColumnName + '] nvarchar(max)' as ColName
				from 
					dbo.ScoreMeasure m
					inner join sys.types t on t.system_type_id = m.ColumnTypeValue
				where
					m.IsWrittenToDB = 1
					and m.DataTableGUID = @dtguid
					and t.name != 'sysname'
					and m.SpecialCommentSQLColumnName != ''
			) m
			order by m.ColName

		open crsMeasures
		fetch next from crsMeasures into @measure

		set @measures = ''

		while (@@fetch_status = 0) begin
			set @measures = @measures + @measure

			fetch next from crsMeasures into @measure
		end

		close crsMeasures
		deallocate crsMeasures

		set @sql = replace(@sql, '{0}', @measures)

		if (@isDebug = 0) begin 
			exec(@sql)
		end else begin
			print @sql
		end

		fetch next from crsTables into @dtguid, @sql
	end

	close crsTables
	deallocate crsTables
GO


---------------------------------------------

-- dbo.procScoreDataTableEnsureDefaults
create proc procScoreDataTableEnsureDefaults
as
	declare @sql nvarchar(max)
	declare crsScripts cursor fast_forward for
		select distinct
			'ALTER TABLE ' + s.name + '.' + t.name + ' ADD CONSTRAINT DF_' + t.name + '_' + c.name + ' DEFAULT 0 FOR ' + c.name
		from 
			sys.columns c 
			inner join sys.tables t on t.object_id = c.object_id 
			inner join sys.schemas s on s.schema_id = t.schema_id
			inner join ScoreDataTable dt on dt.SQLObjectName = t.name and dt.SQLSchemaName = s.name
		where 
			c.name like '%ID' 
			and c.name != 'RowID' 
			and system_type_id in(48, 52, 56) 
			and default_object_id = 0
	open crsScripts
	fetch next from crsScripts into @sql
	while(@@FETCH_STATUS = 0) begin
		exec(@sql)
		fetch next from crsScripts into @sql
	end
	close crsScripts
	deallocate crsScripts
GO


---------------------------------------------

-- dbo.procScoreDataTableKeyLinkSchemaUpdate
create proc [dbo].[procScoreDataTableKeyLinkSchemaUpdate]
	@datatableguid uniqueidentifier = '00000000-0000-0000-0000-000000000000'
as

update
	obj
set
	obj.ColumnID = objschema.ColumnID,
	obj.ColumnName = objschema.ColumnName,
	obj.ColumnTypeValue = objschema.ColumnTypeValue,
	obj.ComputedValueDefinition = objschema.ComputedValueDefinition,
	obj.DefaultValueDefinition = objschema.DefaultValueDefinition,
	obj.ForeignKeyColumn = objschema.ForeignKeyColumn,
	obj.ForeignKeyOnDelete = objschema.ForeignKeyOnDelete,
	obj.ForeignKeySchema = objschema.ForeignKeySchema,
	obj.ForeignKeyTable = objschema.ForeignKeyTable,
	obj.IdentityIncrement = objschema.IdentityIncrement,
	obj.IdentitySeed = objschema.IdentitySeed,
	obj.IsComputed = objschema.IsComputed,
	obj.IsForeignKeyed = objschema.IsForeignKeyed,
	obj.IsIdentity = objschema.IsIdentity,
	obj.IsNullable = objschema.IsNullable,
	obj.IsPartOfPrimaryKey = objschema.IsPartOfPrimaryKey,
	obj.IsPartOfUniqueIndex = objschema.IsPartOfUniqueIndex,
	obj.IsPrimaryKey = objschema.IsPrimaryKey,
	obj.IsUniqueIndex = objschema.IsUniqueIndex,
	obj.MaxLength = objschema.MaxLength,
	obj.ObjectID = objschema.ObjectID,
	obj.ObjectName = objschema.ObjectName,
	obj.ObjectType = objschema.ObjectType,
	obj.Precision = objschema.Precision,
	obj.Scale = objschema.Scale,
	obj.SchemaName = objschema.SchemaName	
from
	ScoreDataTableKeyLink obj
	inner join viewScoreDataTableKeyLinkSchemaInfo objschema on obj.DataTableKeyLinkGUID = objschema.DataTableKeyLinkGUID
where
	@datatableguid in (obj.datatableguid, dbo.zeroguid())
	and (
		obj.ColumnID <> objschema.ColumnID or
		obj.ColumnName <> objschema.ColumnName or
		obj.ColumnTypeValue <> objschema.ColumnTypeValue or
		obj.ComputedValueDefinition <> objschema.ComputedValueDefinition or
		obj.DefaultValueDefinition <> objschema.DefaultValueDefinition or
		obj.ForeignKeyColumn <> objschema.ForeignKeyColumn or
		obj.ForeignKeyOnDelete <> objschema.ForeignKeyOnDelete or
		obj.ForeignKeySchema <> objschema.ForeignKeySchema or
		obj.ForeignKeyTable <> objschema.ForeignKeyTable or
		obj.IdentityIncrement <> objschema.IdentityIncrement or
		obj.IdentitySeed <> objschema.IdentitySeed or
		obj.IsComputed <> objschema.IsComputed or
		obj.IsForeignKeyed <> objschema.IsForeignKeyed or
		obj.IsIdentity <> objschema.IsIdentity or
		obj.IsNullable <> objschema.IsNullable or
		obj.IsPartOfPrimaryKey <> objschema.IsPartOfPrimaryKey or
		obj.IsPartOfUniqueIndex <> objschema.IsPartOfUniqueIndex or
		obj.IsPrimaryKey <> objschema.IsPrimaryKey or
		obj.IsUniqueIndex <> objschema.IsUniqueIndex or
		obj.MaxLength <> objschema.MaxLength or
		obj.ObjectID <> objschema.ObjectID or
		obj.ObjectName <> objschema.ObjectName or
		obj.ObjectType <> objschema.ObjectType or
		obj.Precision <> objschema.Precision or
		obj.Scale <> objschema.Scale or
		obj.SchemaName <> objschema.SchemaName
	)
GO


---------------------------------------------

-- dbo.procScoreDataTableKeyLinkSchemaUpdateMissing
--Forward
create proc procScoreDataTableKeyLinkSchemaUpdateMissing
as
	if ((select count(*) from [dbo].ScoreDataTableKeyLink where columnname = '') > 0) begin
		declare @dtguid uniqueidentifier
		declare crsTables cursor fast_forward for select DataTableGUID from [dbo].ScoreDataTableKeyLink where columnname = ''
		
		open crsTables
		fetch next from crsTables into @dtguid
		
		while(@@fetch_status = 0) begin
			exec [dbo].[procScoreDataTableKeyLinkSchemaUpdate] @dtguid
		
			fetch next from crsTables into @dtguid
		end
		
		close crsTables
		deallocate crsTables
	end
	
RETURN
GO


---------------------------------------------

-- dbo.procScoreDeleteComposite
CREATE Procedure [dbo].[procScoreDeleteComposite]
(
	@CompositeGUID uniqueidentifier
)
AS

	print 'Deleting CompositeLinks';
	DELETE FROM ScoreCompositeLink where CompositeGUID = @CompositeGUID;
	
	print 'Deleting Composite';
	DELETE FROM ScoreComposite where CompositeGUID = @CompositeGUID
GO


---------------------------------------------

-- dbo.procScoreDeleteCompositeFull
CREATE proc procScoreDeleteCompositeFull
	@compositeGUID uniqueidentifier
as

begin try
	begin transaction 
	declare @dt1g uniqueidentifier
	declare @dt1schema sysname
	declare @dt1name sysname
	declare @dt2g uniqueidentifier
	declare @dt2schema sysname
	declare @dt2name sysname

	select 
		@dt1g = dt1.DataTableGUID,
		@dt1schema = dt1.SQLSchemaName,
		@dt1name = dt1.SQLObjectName,
		@dt2g = dt2.DataTableGUID,
		@dt2schema = dt2.SQLSchemaName,
		@dt2name = dt2.SQLObjectName
	from 
		ScoreComposite sc
		left join ScoreDataTable dt1 on sc.DataTableGUID1 = dt1.DataTableGUID
		left join ScoreDataTable dt2 on sc.DataTableGUID2 = dt2.DataTableGUID
	where
		sc.CompositeGUID = @compositeGUID
		
	--delete scorecomposite record
	delete from ScoreComposite where CompositeGUID = @compositeGUID
	print 'deleted composite reg'
	
	--delete dt1 if unused by any composites
	delete from ScoreDataTable where DataTableGUID = @dt1g and not exists (select 1 from ScoreComposite sc where sc.DataTableGUID1 = @dt1g or sc.DataTableGUID2 = @dt1g)
	print 'deleted dt1 reg'

	--delete dt2 if unused by any composites
	delete from ScoreDataTable where DataTableGUID = @dt2g and not exists (select 1 from ScoreComposite sc where sc.DataTableGUID1 = @dt2g or sc.DataTableGUID2 = @dt2g)
	print 'deleted dt2 reg'
	
	declare @sql varchar(max)

	--drop dt1 table if it exists
	if dbo.TableExists(@dt1schema, @dt1name) = 1 begin
		set @sql = 'drop table [' + @dt1schema + '].[' + @dt1name + ']'
		exec (@sql)
		print 'dropped dt1'
	end

	--drop dt2 table if it exists
	if dbo.TableExists(@dt2schema, @dt2name) = 1 begin
		set @sql = 'drop table [' + @dt2schema + '].[' + @dt2name + ']'
		exec (@sql)
		print 'dropped dt2'
	end
	
	commit
end try
begin catch
	rollback
	print 'error: ' + error_message()
	exec procSysRethrowError
end catch
GO


---------------------------------------------

-- dbo.procScoreDeleteDataTable
CREATE Procedure [dbo].[procScoreDeleteDataTable]
(
	@DataTableGUID uniqueidentifier,
	@IsHardDelete bit = 0 ,
	@DeleteInUse bit = 0
)
AS
	declare @SchemaName nvarchar(128);
	declare @ObjectName nvarchar(max);
		select 
			@SchemaName = SQLSchemaName,
			@ObjectName = SQLObjectName
		from ScoreDataTable where DataTableGUID = @DataTableGUID;
	
	if @SchemaName is null RETURN
	if @objectname is null RETURN
	
	IF ([dbo].[ScoreIsDataTableInUse](@DataTableGUID) = 1 AND @DeleteInUse = 0)
	BEGIN
		--  Do NOT allow this to happen under any circumstances
		RAISERROR ('DataTable is in use. Cannot delete.',15,1);
		RETURN
	END

	IF @DeleteInUse = 1 begin
		print 'Deleting composites that use this datatable';
		DELETE FROM ScoreComposite where DataTableGUID1 = @DataTableGUID
		DELETE FROM ScoreComposite where DataTableGUID2 = @DataTableGUID
	end 
	
	print 'Deleting DataTableKeyLinks';
	DELETE FROM ScoreDataTableKeyLink where DataTableGUID = @DataTableGUID;
	
	print 'Deleting Measures';
	DELETE FROM ScoreMeasure where DataTableGUID = @DataTableGUID
	
	print ' Deleting DataTable';
	DELETE FROM ScoreDataTable where DataTableGUID = @DataTableGUID

	if (@IsHardDelete = 1)
	BEGIN

		if ([dbo].[IsView](@SchemaName, @ObjectName) = 1)
		BEGIN
			print ' Cannot hard delete a view. Skipping. ';
		END
		ELSE
		BEGIN
			print ' Hard deleting datatable.';
			declare @sql varchar(max);
			set @sql = '
				DELETE FROM ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @ObjectName)) + ';
				DROP TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @ObjectName)) + ';
			';
			print @sql
			print @schemaname
			print @objectname
			exec (@sql);
		END
	END
GO


---------------------------------------------

-- dbo.procScoreDeleteDimension
CREATE Procedure [dbo].[procScoreDeleteDimension]
(
	@DimensionGUID uniqueidentifier,
	@IsHardDelete bit = 0, --Hard Delete will remove the table as well.
	@DeleteInUse bit = 0
)
AS

	declare @SQLSchemaName nvarchar(128);
	declare @SQLObjectName nvarchar(max);
		select 
			@SQLSchemaName = SQLSchemaName,
			@SQLObjectName = SQLObjectName
		from ScoreDimension where DimensionGUID = @DimensionGUID;
	
	IF ([dbo].[ScoreIsDimensionInUse](@DimensionGUID) = 1 and @DeleteInUse = 0)
	BEGIN
		--  Do NOT allow this to happen under any circumstances
		RAISERROR ('Dimension is in use. Cannot delete.',15,1);
		RETURN
	END

	print ' Deleting Hierarchy Records ';
	DELETE FROM ScoreHierarchy where DimensionGUID = @DimensionGUID;



	print ' Resetting FKs and DefaultSortAtts ';
	--FKs and DefaultSortAttributeGUIDS
	DECLARE AttributeCursor CURSOR FOR
		SELECT A.AttributeGUID  FROM ScoreAttribute A
			inner join ScoreDimensionGroup G on G.DimensionGroupGUID = A.DimensionGroupGUID
			inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID
		 where D.DimensionGUID = @DimensionGUID

	OPEN AttributeCursor
	DECLARE @AttGuid_i uniqueidentifier

	FETCH NEXT FROM AttributeCursor INTO @AttGuid_i;
	WHILE (@@FETCH_STATUS = 0)
	BEGIN
		UPDATE ScoreAttribute 
			SET DefaultSortAttributeGUID = '00000000-0000-0000-0000-000000000000'
			WHERE DefaultSortAttributeGUID = @AttGuid_i;
		UPDATE ScoreAttribute
			SET ForeignKeyGUID = '00000000-0000-0000-0000-000000000000'
			WHERE ForeignKeyGUID = @AttGuid_i;
		FETCH NEXT FROM AttributeCursor INTO @AttGuid_i;
	END
	CLOSE AttributeCursor;
	DEALLOCATE AttributeCursor;

	Print ' Deleting Attribute Records ';
	--Note: Hierarchy Attribute links handled by Foreign Key delete in ScoreAttribute
	DELETE A
		FROM ScoreAttribute A
			inner join ScoreDimensionGroup G on G.DimensionGroupGUID = A.DimensionGroupGUID
	where G.DimensionGUID = @DimensionGUID;
	--DELETE FROM ScoreAttribute where DimensionGUID = @DimensionGUID;
	
	
	if (@IsHardDelete = 1) 
	begin
		print 'Dropping Group Tables/Views';
		declare @GroupSchema nvarchar(128);
		declare @GroupObject nvarchar(128);
		declare GroupCursor CURSOR LOCAL FAST_FORWARD FOR
			SELECT SchemaName, ObjectName  from ScoreDimensionGroup where DimensionGUID = @DimensionGUID;
		
		OPEN GroupCursor 
		FETCH NEXT FROM GroupCursor INTO @GroupSchema,@GroupObject;
		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			if ([dbo].[IsView](@GroupSchema,@GroupObject) = 1)
			begin
				exec procSysDropView @GroupSchema, @GroupObject;
			end
			else
			begin
				exec procSysDropTable @GroupSchema, @GroupObject;
			end
			FETCH NEXT FROM GroupCursor INTO @GroupSchema,@GroupObject;
		END
	CLOSE GroupCursor;
	DEALLOCATE GroupCursor;
	end
	
	Print ' Deleting Group Records';	
	DELETE FROM ScoreDimensionGroup where DimensionGUID = @DimensionGUID;
	
	if (@IsHardDelete = 1)
	BEGIN

		if ([dbo].[IsView](@SQLSchemaName, @SQLObjectName) = 1)
		BEGIN
			print ' Hard Deleting Dimension View ';
			exec procSysDropView @SQLSchemaName, @SQLObjectName;
		END
		ELSE
		BEGIN
			print ' Hard deleting dimension Table.';
			exec procSysDropTable @SQLSchemaName, @SQLObjectName;
		END
	END

	DELETE FROM dbo.ScoreDimensionFramework
	WHERE DimensionGUID = @DimensionGUID;
	
	print 'Deleting Dimension Record';
	DELETE FROM ScoreDimension where DimensionGUID = @DimensionGUID;
GO


---------------------------------------------

-- dbo.procScoreDeleteOrphanedSecurityTriggers
create procedure [dbo].[procScoreDeleteOrphanedSecurityTriggers] ( 
	@IsDebugOnly bit = 0
)
AS

BEGIN

--ORPHANED Triggers
declare crsCursor CURSOR FAST_FORWARD FOR
	
select 
	T.Name, 
	T.SchemaName 
from viewSysTriggers T
	left join ScoreDimension D on SUBSTRING(T.Name, 20, 32) = REPLACE(D.DimensionGUID,'-','')
where 
	T.Name like 'trg_ScoreDimension_%_LootRefresh%'
	and D.FriendlyName is null

print 'The Following Score Loot Refresh Triggers are Orphaned (Dimension no longer exists):
';

open crsCursor;

DECLARE @triggerName nvarchar(128);
DECLARE @schemaName nvarchar(128);

declare @sql varchar(max);
set @sql = '';
FETCH NEXT FROM crsCursor into @triggerName, @schemaName
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		
		PRINT '   [' + @schemaName + '].[' +   @triggerName + ']';	
		set @sql = @sql + 'DROP TRIGGER [' + @schemaName + '].[' +   @triggerName + '];
';
		FETCH NEXT FROM crsCursor into @triggerName, @schemaName;
	END
close crsCursor;
DEALLOCATE crsCursor;

print '';
print @sql;

if (@IsDebugOnly = 0) 
BEGIN
	exec (@sql);
END

END
GO


---------------------------------------------

-- dbo.procScoreDimensionCacheRefresh
CREATE proc [dbo].[procScoreDimensionCacheRefresh]
	@dimensionGUID uniqueidentifier,
	@whereClause nvarchar(max) = '',
	@isDebug bit = 0,
	@isNoRecurse bit = 0,
	@isSecurityDirty bit = 0
AS
	set nocount on
	
	--caching not used by v2 dimensions
	IF (exists (SELECT 1 FROM ScoreDimension with (readuncommitted) WHERE DimensionGUID = @dimensionGUID AND DimensionVersion = 3)) BEGIN
		--grab basic dimension info
		declare @sourceSchema nvarchar(100)
		declare @sourceName nvarchar(450)
		declare @cacheSchema nvarchar(100)
		declare @cacheName nvarchar(450)
		declare @objectid int
		declare @isSecured bit
		select 
			@sourceSchema = D.SQLSchemaName, 
			@sourceName = D.SQLObjectName + '_source',
			@cacheSchema = DG.SchemaName,
			@cacheName = DG.ObjectName,
			@objectid = T.object_id,
			@isSecured = D.IsSecured
		from 
			ScoreDimension D with (readuncommitted)
			inner join ScoreDimensionGroup DG with (readuncommitted) on DG.DimensionGroupGUID = D.PrimaryGroupGUID
			inner join sys.tables T with (readuncommitted) on T.name = DG.ObjectName
			inner join sys.schemas S with (readuncommitted) on S.name = DG.SchemaName and S.schema_id = T.schema_id
		where 
			D.DimensionGUID = @dimensionGUID

		declare @isUsingVersionColumn bit
		if ((select COUNT(*) from sys.columns with (readuncommitted) where object_id = @objectid and name = 'Version') > 0) begin
			set @isUsingVersionColumn = 1
		end else begin
			set @isUsingVersionColumn = 0
		end

		--get column info
		declare @colName nvarchar(100)
		declare crsColumns cursor fast_forward for
			select 
				C.name
			from 
				sys.columns C with (readuncommitted)
				inner join sys.tables T with (readuncommitted) on T.object_id = C.object_id 
				inner join sys.schemas S with (readuncommitted) on S.schema_id = T.schema_id 
				inner join viewScoreAttribute A on A.SQLColumnName = C.name
			where 
				T.name = @cacheName
				and S.name = @cacheSchema
				and A.DimensionGUID = @dimensionGUID
				and A.IsWrittenToDB = 0
				and A.AttributeType != 1
				and A.SQLColumnName not in('MemberGUID', 'HistoryItemGUID')
				and C.is_computed = 0

		declare @colCount int
		set @colCount = 0

		--build the update script to populate non-editable columns in the cache
		declare @fillSQL nvarchar(max) = ''
		if (@isSecured = 1) begin
			set @fillSQL = 'update dbo.ScoreDimension set IsSecurityTriggersEnabled = 0 where DimensionGUID = ''' + cast(@dimensionGUID as nvarchar(36)) + ''';
	'
		end
		set @fillSQL = @fillSQL + 'update C set '
		open crsColumns
		fetch next from crsColumns into @colName
		while (@@FETCH_STATUS = 0) begin
			set @fillSQL = @fillSQL + 'C.[' + @colName + '] = S.[' + @colName + '],'
			set @colCount = @colCount + 1
			fetch next from crsColumns into @colName
		end
		close crsColumns
		deallocate crsColumns
		set @fillSQL = LEFT(@fillSQL, len(@fillSQL) - 1)
		set @fillSQL = @fillSQL + '
		from 
			' + @cacheSchema + '.' + @cacheName + ' C
			inner join ' + @sourceSchema + '.' + @sourceName + ' S on S.MemberGUID = C.MemberGUID'
		if (@whereClause != '') begin
			set @fillSQL = @fillSQL + ' where ' + @whereClause
		end
		set @fillSQL = @fillSQL + ';
	'
		declare @rollbackSQL nvarchar(1000) = ''
		if (@isSecured = 1) begin
			set @fillSQL = @fillSQL + 'update dbo.ScoreDimension set IsSecurityTriggersEnabled = 1 where DimensionGUID = ''' + cast(@dimensionGUID as nvarchar(36)) + ''';'
			set @rollbackSQL = 'update dbo.ScoreDimension set IsSecurityTriggersEnabled = 1 where DimensionGUID = ''' + cast(@dimensionGUID as nvarchar(36)) + ''';'
		end

		--fill the cache table
		if (@colCount > 0) begin 
			if (@isDebug = 0) begin
				begin try
					exec(@fillSQL)
				end try
				begin catch
					--don't leave triggers in a bad state
					exec(@rollbackSQL)
				end catch
			end else begin
				print @fillSQL
			end
		end
	END

	--refresh dependent members, going up to 2 dependency levels deep
	if (@isNoRecurse = 0) begin
		declare @FKsql nvarchar(max)
		set @FKsql = ''
		declare @FKdimensionGUID uniqueidentifier
		declare crsFKDimensions cursor fast_forward for
			select distinct
				d.ChildDimensionGUID
			from 
				dbo.viewScoreDimensionDependency d
			where 
				(d.ParentDimensionGUID = @dimensionGUID or d.ParentDimensionGUID in(select c.ChildDimensionGUID from dbo.viewScoreDimensionDependency c where c.ParentDimensionGUID = @dimensionGUID))
				and d.ChildDimensionGUID != @dimensionGUID
		open crsFKDimensions
		fetch next from crsFKDimensions into @FKdimensionGUID
		while(@@FETCH_STATUS = 0) begin
			--have to use dynamic sql because otherwise the recursion fails because we use the same cursor name
			set @FKsql = @FKsql + 'exec procScoreDimensionCacheRefresh ''' + CAST(@FKdimensionGUID as nvarchar(36)) + ''', '''', ' + cast(@isDebug as nvarchar(1)) + ', 1, ' + cast(@isSecurityDirty as nvarchar(1)) + '
'
			fetch next from crsFKDimensions into @FKdimensionGUID
		end
		close crsFKDimensions
		deallocate crsFKDimensions
		exec(@FKsql)
	end
	
	--refresh security if any inferred/calculated attributes drive security
	if ((@isDebug = 0) and (@isSecured = 1) and (@isSecurityDirty = 1)) begin
		INSERT INTO [dbo].[S3UserACLRegenRequest] ([RequestGUID], [IssuedAt]) VALUES (NEWID(), GETDATE())
		exec procScoreSetDimensionSecurity30 @dimensionGUID, @isDebug, @isUsingVersionColumn, 0, 'procScoreDimensionCacheRefresh'
	end
GO


---------------------------------------------

-- dbo.procScoreDimensionCacheRefreshAll
--Forward
create proc procScoreDimensionCacheRefreshAll
as
	set nocount on

	declare @dimensionGUID uniqueidentifier
	declare crsDimensions cursor fast_forward for select DimensionGUID from ScoreDimension
	
	open crsDimensions
	fetch next from crsDimensions into @dimensionGUID
	
	while(@@FETCH_STATUS = 0) begin
		exec procScoreDimensionCacheRefresh @dimensionGUID
	
		fetch next from crsDimensions into @dimensionGUID
	end
	
	close crsDimensions
	deallocate crsDimensions
GO


---------------------------------------------

-- dbo.procScoreDimensionLastModified
CREATE proc [dbo].[procScoreDimensionLastModified]
	@dimensionguid uniqueidentifier
as

declare @datemodified datetime

select coalesce((select MAX(datemodified) from 
	(
		select datemodified from ScoreDimension where DimensionGUID = @dimensionguid
		union all select datemodified from ScoreAttribute where DimensionGroupGUID in (select dimensiongroupguid from scoredimensiongroup where dimensionguid = @dimensionguid)
		union all select datemodified from ScoreDimensionGroup where DimensionGUID = @dimensionguid
		union all select datemodified from ScoreHierarchy where DimensionGUID = @dimensionguid	
		union all select datemodified from ScoreHierarchyAttributeLink shal 
			where shal.HierarchyGUID in (select HierarchyGUID from ScoreHierarchy where DimensionGUID = @dimensionguid)
	) x
), getdate())	--return current date if invalid guid passedd
GO


---------------------------------------------

-- dbo.procScoreEnsureDefaultFramework
create proc dbo.procScoreEnsureDefaultFramework
AS
begin

	 --ensure that fw.DimFramework contains the general framework
	if not exists(select 1 from fw.DimFramework where FrameworkID = 0) begin
		set identity_insert fw.DimFramework ON;
		insert into fw.DimFramework (FrameworkID, Name) VALUES (0, 'General');
		set identity_insert fw.DimFramework OFF;
	end
	
	--insert into ScoreDimensionFramework any dimensions that aren't tagged at all (linked to General)
	insert into ScoreDimensionFramework (DimensionGUID, FrameworkID)
	select D.DimensionGUID, 0 as [FrameworkID] from ScoreDimension D
		left join ScoreDimensionFramework F on F.DimensionGUID = D.DimensionGUID
	group by D.DimensionGUID
	having SUM(case when F.FrameworkID is null then 0 else 1 end) = 0

end
GO


---------------------------------------------

-- dbo.procScoreEnsureDimensionTableSetup
CREATE proc [dbo].[procScoreEnsureDimensionTableSetup] (
	@DimensionGUID uniqueidentifier,
	@DebugMode bit
)
AS

	declare @SchemaName nvarchar(128);
	declare @ObjectName nvarchar(max);
	select 
		@SchemaName = SQLSchemaName, 
		@ObjectName = SQLObjectName
	from ScoreDimension where DimensionGUID = @DimensionGUID;
	
	if ([dbo].[IsView](@SchemaName, @ObjectName) = 1)
	BEGIN
		print ('Table is view-backed. Cannot add Columns. Exiting.');
		RETURN;
	END
		
	exec procEnsureColumnInTable @SchemaName, @ObjectName, 'IsDeleted', 'bit', '0', @DebugMode;
	exec procEnsureColumnInTable @SchemaName, @ObjectName, 'HistoryItemGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
	exec procEnsureColumnInTable @SchemaName, @ObjectName, 'MemberGUID', 'uniqueidentifier', 'newid()', @DebugMode
GO


---------------------------------------------

-- dbo.procScoreEnsureLootRefreshTrigger
--#notran#
CREATE PROC [dbo].[procScoreEnsureLootRefreshTrigger](
	@aDimensionGUID uniqueidentifier
)
AS

    --get schema and object
    declare @Schema varchar(128);
    declare @Object varchar(128);
	select @Schema = Sqlschemaname, @Object = SQLObjectname from ScoreDimension where DimensionGUID = @aDimensionGUID;
	if (exists(select 1 from scoredimension d where d.dimensionguid = @aDimensionGUID and d.dimensionversion = 3 and exists(select 1 from sys.views v where v.name = d.sqlobjectname + '_source'))) begin
		set @Object = @Object + '_source'
	end
    
    if ([dbo].[IsView](@Schema, @Object) = 1)
    BEGIN
		declare @TableSchema varchar(128);
		declare @TableName varchar(128);
		declare @TableTriggerName varchar(128);
		print 'Adding Triggers to Underlying Tables';

		DECLARE TableCursor CURSOR LOCAL FAST_FORWARD
		FOR select TableName, TableSchema from viewSysViewBaseTables where ViewName = @Object and ViewSchema = @Schema and TableType = 'BASE TABLE' and TableName like 'Dim%' and TableSchema <> 'dbo' order by [Level]
		--FOR select * from [dbo].GetViewUnderlyingTables(@Schema, @Object)		
		OPEN TableCursor;
		Fetch Next from TableCursor INTO  @TableName, @TableSchema;
		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			if (@TableSchema = 'dbo')
			BEGIN
				print 'Skipping dbo schema underlying table.';
			END
			ELSE
			BEGIN
				set @TableTriggerName = Substring((select [dbo].GetScoreLootRefreshTriggerName(@aDimensionGUID)) + '_' + @TableName, 0, 128);
				exec [dbo].procScoreEnsureLootRefreshTriggerHelper @aDimensionGUID, @TableSchema,@TableName,@TableTriggerName,0;
			END
			
			Fetch Next from TableCursor INTO  @TableName, @TableSchema;
		END
		CLOSE TableCursor;
		DEALLOCATE TableCursor;
    END
    ELSE
	BEGIN
		 --Add the Trigger directly to the Table
		declare @triggerName varchar(max);
		select @triggerName = (select [dbo].GetScoreLootRefreshTriggerName(@aDimensionGUID));
		exec [dbo].procScoreEnsureLootRefreshTriggerHelper @aDimensionGUID, @Schema, @Object, @triggerName,1;
	END
GO


---------------------------------------------

-- dbo.procScoreEnsureLootRefreshTriggerHelper
CREATE PROC [dbo].[procScoreEnsureLootRefreshTriggerHelper](
	@aDimensionGUID uniqueidentifier,
	@TargetSchemaName varchar(128),
	@TargetObjectName varchar(128),
	@TriggerName varchar(128),
	@IsDirect bit
)
AS

declare @isself bit = 0
if(exists(select 1 from [dbo].[ScoreDimension] D inner join [dbo].[ScoreDimensionGroup] DG on DG.DimensionGroupGUID = D.PrimaryGroupGUID where D.DimensionGUID = @aDimensionGUID and DG.SchemaName = @TargetSchemaName and DG.ObjectName = @TargetObjectName)) begin
	set @isself = 1
end

declare @targetDimensionGUID uniqueidentifier
select @targetDimensionGUID = D.DimensionGUID from [dbo].[ScoreDimension] D inner join [dbo].[ScoreDimensionGroup] DG on DG.DimensionGroupGUID = D.PrimaryGroupGUID where D.IsSecured = 1 and DG.SchemaName = @TargetSchemaName and DG.ObjectName = @TargetObjectName
if (@targetDimensionGUID is null) begin
	return
end

------IF THE TRIGGER EXISTS, THEN DROP IT, WE NEED TO RECREATE
if ([dbo].IsTriggerExist(@TriggerName)= 1)
 BEGIN
	declare @dropSQL varchar(max);
	set @dropSQL = '
		DROP TRIGGER [' + @TargetSchemaName + '].[' + @TriggerName + '];
	';
	print @dropSQL;
	exec(@dropSQL) 
 END
 
 -----SEE IF THERES A VERSION COLUMN , will be 1 OR 0
declare @IsVersion int;
select 
	@IsVersion = COUNT(*) 
from viewSysColumns COL 
where 
	COL.ObjectName = @TargetObjectName 
	and COL.SchemaName = @TargetSchemaName
	and COL.ColumnName = 'Version'
	and COL.ColumnTypeValue = 189  --timestamp

if (@IsDirect = 0) 
begin
	set @IsVersion = 0 --don't use version if we are not direct
end
	
if (not exists(select 1 from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where s.name = @TargetSchemaName and t.name = @TargetObjectName)) 
begin
	return
end

declare @sql varchar(max);
set @sql = '
	
	CREATE TRIGGER [' + @TargetSchemaName + '].[' + @TriggerName + ']
		ON  ' + (select [dbo].[GetSQLTableExpression](@TargetSchemaName, @TargetObjectName)) + '
		AFTER UPDATE, INSERT
	AS 
	BEGIN
		SET NOCOUNT ON;

		if (exists(select 1 from dbo.ScoreDimension with (readuncommitted) where DimensionGUID = ''' + cast(@targetDimensionGUID as nvarchar(36)) + ''' and IsSecurityTriggersEnabled = 0)) begin
			return
		end
'

if (@isself = 1) begin
	set @sql = @sql + '
		declare @memberguid uniqueidentifier

		--handle single member insert specially
		if (((select count(MemberGUID) from inserted) = 1) and ((select count(MemberGUID) from deleted) = 0)) begin
			select top 1 @memberguid = MemberGUID from inserted
			EXEC procScoreSetDimensionSecurity30InsertNew ''' + cast(@aDimensionGUID as varchar(max)) + ''', @memberguid, 0, ' + CAST(@IsVersion as nvarchar(8)) + '
			return
		end

		--handle single member update specially
		if (((select count(MemberGUID) from inserted) = 1) and ((select count(MemberGUID) from deleted) = 1) and (isnull((select top 1 MemberGUID from inserted), ''00000000-0000-0000-0000-000000000000'') = isnull((select top 1 MemberGUID from deleted), ''00000000-0000-0000-0000-000000000000''))) begin 
			select top 1 @memberguid = MemberGUID from deleted
			EXEC procScoreSetDimensionSecurity30UpdateSingle ''' + cast(@aDimensionGUID as varchar(max)) + ''', @memberguid, 0, ' + CAST(@IsVersion as nvarchar(8)) + '							
			return
		end'
end else begin
	set @sql = @sql + '
		if ((exists(select 1 from inserted)) and (not exists(select 1 from deleted))) begin
			--no dependents to refresh since this is a straight insert
			return
		end'
end
	
set @sql = @sql + '
	
		--handle all other cases
		EXEC procScoreSetDimensionSecurity30 ''' + cast(@aDimensionGUID as varchar(max)) + ''', 0, ' + CAST(@IsVersion as nvarchar(8)) + '
	END
';
print @sql;
exec (@sql);

--hack: drop unwanted project->requisition trigger
declare @reqdimguid uniqueidentifier
select @reqdimguid = DimensionGUID from ScoreDimension where FriendlyName = 'CAP Requisition'
if (@reqdimguid is not null) begin
	declare @reqdimsql nvarchar(max)
	set @reqdimsql = '
		IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[cap].[trg_ScoreDimension_' + replace(cast(@reqdimguid as nvarchar(36)), '-', '') + '_LootRefresh_DimProject]''))
		DROP TRIGGER [cap].[trg_ScoreDimension_' + replace(cast(@reqdimguid as nvarchar(36)), '-', '') + '_LootRefresh_DimProject]'
	exec(@reqdimsql)
end
GO


---------------------------------------------

-- dbo.procScoreEnsureLootRefreshTriggers
create procedure [dbo].[procScoreEnsureLootRefreshTriggers]
AS
BEGIN

	declare dimCursor CURSOR LOCAL FAST_FORWARD FOR
		select DimensionGUID, IsSecured from ScoreDimension
		
	open dimCursor;

	DECLARE @DimGUID uniqueidentifier;
	DECLARE @IsSecured bit;

	FETCH NEXT FROM dimCursor into @DimGUID, @IsSecured
	WHILE (@@FETCH_STATUS = 0) 
		BEGIN
			
			if (@IsSecured = 1) 
			begin
				exec procScoreEnsureLootRefreshTrigger @DimGUID;
			end
			
			FETCH NEXT FROM dimCursor into @DimGUID, @IsSecured
		END
	close dimCursor;
	DEALLOCATE dimCursor;

END
GO


---------------------------------------------

-- dbo.procScoreEnsureSecurity
create procedure [dbo].[procScoreEnsureSecurity]
AS
BEGIN

	exec procScoreDeleteOrphanedSecurityTriggers;
	exec procScoreEnsureLootRefreshTriggers;

END
GO


---------------------------------------------

-- dbo.procScoreEnsureSystemSectionDimension
--/****** Object:  StoredProcedure [dbo].[procScoreEnsureSystemSectionDimension]    Script Date: 03/22/2011 11:25:58 ******/
--SET ANSI_NULLS ON
--GO

--SET QUOTED_IDENTIFIER ON
--GO



CREATE proc [dbo].[procScoreEnsureSystemSectionDimension] (
    @IsForceRebuild bit = 0
)
as
	
	
declare @DeletedDimensionGUID uniqueidentifier;	
	
-- check existing
declare @cnt int
select @cnt = count(*) from ScoreDimension where FriendlyName = 'System Sections'
if @cnt = 1 begin

    if @IsForceRebuild = 1 begin
		print 'Forcing Rebuild...';
		select @DeletedDimensionGUID = DimensionGUID from ScoreDimension where FriendlyName = 'System Sections';
		exec procScoreDeleteDimension @DeletedDimensionGUID, 1,1;
    end
    else begin
		print 'System Section dimension already exists.'
		return
    end
	
end

-- get schema
declare @schema varchar(10)
select @schema = name from sys.schemas where name = 'fw'
if @schema is null begin
	select @schema = name from sys.schemas where name = 'data'
	if @schema is null begin
		set @schema = 'dbo'
	end
end

-- create view
declare @sql varchar(max)
set @sql = '
	create view [' + @schema + '].[viewDimSystemSection]
	as
	select
		SS.SYSTEMSECTIONGUID as MemberGUID,
		SS.Name,
		SS.ImageName,
		coalesce(nullif(replace(replace(replace(substring(replace(SS.FullPath, ''SYSTEM\'', ''''), 1, patindex(''%\%'', replace(SS.FullPath, ''SYSTEM\'', ''''))), ''\'', ''''), ''TOOLBAR_'', ''''), ''MENU_'', ''''), ''''), ''System'') as Area,
		coalesce(nullif(replace(substring(replace(SS.FullPath, ''SYSTEM\'', ''''), 1, patindex(''%\%'', replace(SS.FullPath, ''SYSTEM\'', ''''))), ''\'', ''''), ''''), ''System'') as Section,
		coalesce(nullif(replace(replace(replace(substring(replace(SS.FullPath, ''SYSTEM\'', ''''), 1, patindex(''%\%'', replace(SS.FullPath, ''SYSTEM\'', ''''))), ''\'', ''''), ''TOOLBAR_'', ''''), ''MENU_'', ''''), ''''), ''System'') 
		+ '' - '' +
		coalesce(nullif(replace(substring(replace(SS.FullPath, ''SYSTEM\'', ''''), 1, patindex(''%\%'', replace(SS.FullPath, ''SYSTEM\'', ''''))), ''\'', ''''), ''''), ''System'') 
		+ '' - '' + SS.Name as [FullName],
		SS.ID,
		SS.LootID,
		coalesce(PSS.Name, ''System'') as Parent,
		coalesce(PSS.LootID, ''1F30ED4A-DFA5-4EA6-8457-20D23DB372C3'') as ParentLootID,
		cast(0 as bit) as IsDeleted,
		dbo.ZeroGUID() as HistoryItemGUID
	from SystemSection SS
	left join SystemSection PSS on PSS.SystemSectionGUID = SS.ParentGUID
	--inner join S3Loot L on L.LootID = SS.LootID
	--inner join S3PermissionSet PS on PS.PermissionSetID = L.PermissionSetID  --why do we do this? AJK
	--where PS.Name like ''%System%''
	'
exec(@sql)

-- get permissionsetid
declare @PermissionSetID int
select @PermissionSetID = PermissionSetID from S3PermissionSet where Name like '%System%'

-- create dimension
insert into ScoreDimension
(FriendlyName, SQLTableAlias, DefaultKeyGUID, DefaultHierarchyGUID, DefaultLookupKeyGUID, IsSecured, PermissionSetID, SQLSchemaName, SQLObjectName, DefaultMemberGUID, IsSysAdminOnly)
values (
	'System Sections',			-- FriendlyName
	'SS',										-- SQLTableAlias
	dbo.ZeroGUID(),					-- DefaultKeyGUID
	dbo.ZeroGUID(),					-- DefaultHierarchyGUID
	dbo.ZeroGUID(),					-- DefaultLookupKeyGUID
	1,											-- IsSecured
	@PermissionSetID,				-- PermissionSetID
	@schema,									-- SQLSchemaName
	'viewDimSystemSection',	-- SQLObjectName
	dbo.ZeroGUID(),					-- DefaultMemberGUID
	0												-- IsSysAdminOnly
)

-- get dimensionguid
declare @DimensionGUID uniqueidentifier
select @DimensionGUID = DimensionGUID from ScoreDimension where FriendlyName = 'System Sections'



-- create dimension group
insert into ScoreDimensionGroup
(DimensionGUID, Name, Description, IsStock, SchemaName, ObjectName, DateModified)
values (
	@DimensionGUID,				--DimensionGUID
	'System Sections',			--Name
	'',							--Description
	1,							--IsStock
	@schema,					--SchemaName
	'viewDimSystemSection',     --ObjectName
	GETDATE()					--DateModified
);

declare @DimensionGroupGUID uniqueidentifier;
select @DimensionGroupGUID = G.DimensionGroupGUID from ScoreDimensionGroup G
	inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID
where G.Name = 'System Sections' and D.DimensionGUID = @DimensionGUID

--update primary group
UPDATE ScoreDimension Set PrimaryGroupGUID = @DimensionGroupGUID 
	where DimensionGUID = @DimensionGUID
	
--get COLUMN attribute type
declare @ColumnType int;
select @ColumnType = T.ScoreAttributeTypeID from ScoreAttributeType T where T.Name = 'Column';

-- create memberguid attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'MemberGUID',		-- FriendlyName
	36,							-- ColumnType
	0,							-- IsWrittenToDB
	1,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'MemberGUID',		-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)
	
-- create fullname attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'FullName',					-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	1,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'FullName',					-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)
	
-- create name attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'Name',					-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	0,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'Name',					-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)

-- create imagename attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'ImageName',		-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	0,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'ImageName',		-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)

-- create area attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'Area',					-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	0,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	1,							-- IsSecuredLootGroupID
	'SS',						-- SecuredLootGroupPrefix
	'Area',					-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)

-- create section attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'Section',			-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	0,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	1,							-- IsSecuredLootGroupID
	'SS',						-- SecuredLootGroupPrefix
	'Section',			-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)

-- create id attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'ID',						-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	0,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'ID',						-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)

-- create lootid attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'LootID',				-- FriendlyName
	167,						-- ColumnType
	0,							-- IsWrittenToDB
	1,							-- IsKey
	1,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	1,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'LootID',				-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)

-- create parent attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'Parent',				-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	0,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'Parent',				-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)

-- create parentlootid attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'ParentLootID',	-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	0,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	1,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'ParentLootID',	-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	0,							-- isHidden
	@ColumnType					--AttributeType
)

-- create hierarchy
insert into ScoreHierarchy
(DimensionGUID, FriendlyName, PathAlias)
values (@DimensionGUID, 'System Sections', 'SS')

-- get hierarchyguid
declare @HierarchyGUID uniqueidentifier
select @HierarchyGUID = HierarchyGUID from ScoreHierarchy where FriendlyName = 'System Sections'

-- create parentlootid hierarchyattributelink
insert into ScoreHierarchyAttributeLink
(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild)
select
	@HierarchyGUID,		-- HierarchyGUID
	A.AttributeGUID,	-- AttributeGUID
	DA.AttributeGUID,	-- DisplayAttributeGUID
	1,								-- SortOrder
	0									-- IsDependentOnChild
from ScoreAttribute A
inner join ScoreAttribute DA on DA.DimensionGroupGUID = A.DimensionGroupGUID
where A.FriendlyName = 'ParentLootID'
	and DA.FriendlyName = 'Parent'
	and A.DimensionGroupGUID = @DimensionGroupGUID

-- create area hierarchyattributelink
insert into ScoreHierarchyAttributeLink
(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild)
select
	@HierarchyGUID,		-- HierarchyGUID
	A.AttributeGUID,	-- AttributeGUID
	A.AttributeGUID,	-- DisplayAttributeGUID
	2,								-- SortOrder
	0									-- IsDependentOnChild
from ScoreAttribute A
where A.FriendlyName = 'Area'
	and A.DimensionGroupGUID = @DimensionGroupGUID

-- create section hierarchyattributelink
insert into ScoreHierarchyAttributeLink
(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild)
select
	@HierarchyGUID,		-- HierarchyGUID
	A.AttributeGUID,	-- AttributeGUID
	A.AttributeGUID,	-- DisplayAttributeGUID
	3,								-- SortOrder
	0									-- IsDependentOnChild
from ScoreAttribute A
where A.FriendlyName = 'Section'
	and A.DimensionGroupGUID = @DimensionGroupGUID

-- create lootid hierarchyattributelink
insert into ScoreHierarchyAttributeLink
(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild)
select
	@HierarchyGUID,		-- HierarchyGUID
	A.AttributeGUID,	-- AttributeGUID
	DA.AttributeGUID,	-- DisplayAttributeGUID
	4,								-- SortOrder
	0									-- IsDependentOnChild
from ScoreAttribute A
inner join ScoreAttribute DA on DA.DimensionGroupGUID = A.DimensionGroupGUID
where A.FriendlyName = 'LootID'
	and DA.FriendlyName = 'FullName' 
	and A.DimensionGroupGUID = @DimensionGroupGUID

-- create default hierarchyguid
update D
	set D.DefaultHierarchyGUID = @HierarchyGUID
from ScoreDimension D
where D.DimensionGUID = @DimensionGUID

-- create default keyguid
update D
	set D.DefaultKeyGUID = A.AttributeGUID
from ScoreDimension D
inner join ScoreDimensionGroup G on G.DimensionGUID = D.DimensionGUID
inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID
where A.FriendlyName = 'MemberGUID'
	and D.DimensionGUID = @DimensionGUID

-- create default lookupkeyguid
update D
	set D.DefaultLookupKeyGUID = A.AttributeGUID
from ScoreDimension D
inner join ScoreDimensionGroup G on D.DimensionGUID = G.DimensionGUID
inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID
where A.FriendlyName = 'FullName'
	and D.DimensionGUID = @DimensionGUID

-- update loot
exec procScoreSetDimensionSecurity30 @DimensionGUID

print 'System Section dimension created.'
print 'View: [' + @schema + '].[viewDimSystemSection]'
print 'Dimension: System Sections (' + cast(@DimensionGUID as varchar(36)) +')'
print 'PermissionSet: ' + cast(@PermissionSetID as varchar(10))


-- If rebuilding, fix simple security
if @IsForceRebuild = 1 begin
	update S3SimplePermission set LootID = @DimensionGUID where LootID = @DeletedDimensionGUID
end

exec procScoreAttributeSchemaUpdateAll;
GO


---------------------------------------------

-- dbo.procScoreEnsureUserProfileDimension
--==========================================================================================


CREATE proc [dbo].[procScoreEnsureUserProfileDimension] (
    @IsForceRebuild bit = 0
)
as
	
	
declare @DeletedDimensionGUID uniqueidentifier;	
	
-- check existing
declare @cnt int
select @cnt = count(*) from ScoreDimension where FriendlyName = 'User Profiles'
if @cnt = 1 begin

    if @IsForceRebuild = 1 begin
		print 'Forcing Rebuild...';
		select @DeletedDimensionGUID = DimensionGUID from ScoreDimension where FriendlyName = 'User Profiles';
		exec procScoreDeleteDimension @DeletedDimensionGUID, 1,1;
    end
    else begin
		print 'User Profile dimension already exists.'
		return
    end
	
end

-- get schema
declare @schema varchar(10)
select @schema = name from sys.schemas where name = 'fw'
if @schema is null begin
	select @schema = name from sys.schemas where name = 'data'
	if @schema is null begin
		set @schema = 'dbo'
	end
end

-- create view
declare @sql varchar(max)
set @sql = '
	create view [' + @schema + '].[viewDimUserProfile]
	as
	select 
		up.UserGUID as MemberGUID,
		up.UserGUID,
		up.UserName,
		up.NameFull,
		ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin,
		CAST (0 as bit) as IsDeleted,
		dbo.ZeroGUID() as HistoryItemGUID,
		CAST(UserGUID as varchar(36)) as LootID
	from UserProfile up
	left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = ''GEN - User Administrator'')
	where up.IsDisabled = 0
	'
exec(@sql)

----------------------------------------


-- get permissionsetid
declare @PermissionSetExists int
declare @PermissionSetID int
select @PermissionSetExists = COUNT(*) from S3PermissionSet where MetaForUpgrade='090D3991-D019-48A9-B501-0AC52402EDFC'

if (@PermissionSetExists = 0)
begin
	insert into dbo.S3PermissionSet (Name, MetaForUpgrade)
	values (
		'UP - ReadOnly',
		'090D3991-D019-48A9-B501-0AC52402EDFC'
	)
	
	select @PermissionSetID = PermissionSetID from S3PermissionSet where MetaForUpgrade='090D3991-D019-48A9-B501-0AC52402EDFC'
	insert into dbo.S3Permission (PermissionSetID, RoleID, Weight, ReadValue)
		select 
			@PermissionSetID,
			ur.RoleID,
			0,
			CAST (1 as bit)
		from UserRole ur
end

select @PermissionSetID = PermissionSetID from S3PermissionSet where MetaForUpgrade='090D3991-D019-48A9-B501-0AC52402EDFC'


-- create dimension
insert into ScoreDimension
(FriendlyName, SQLTableAlias, DefaultKeyGUID, DefaultHierarchyGUID, DefaultLookupKeyGUID, IsSecured, PermissionSetID, SQLSchemaName, SQLObjectName, DefaultMemberGUID, IsSysAdminOnly, IsAllowMemberAdd, IsAllowMemberDelete)
values (
	'User Profiles',			-- FriendlyName
	'USERPROF',										-- SQLTableAlias
	dbo.ZeroGUID(),					-- DefaultKeyGUID
	dbo.ZeroGUID(),					-- DefaultHierarchyGUID
	dbo.ZeroGUID(),					-- DefaultLookupKeyGUID
	1,											-- IsSecured
	@PermissionSetID,				-- PermissionSetID
	@schema,									-- SQLSchemaName
	'viewDimUserProfile',	-- SQLObjectName
	dbo.ZeroGUID(),					-- DefaultMemberGUID
	0,												-- IsSysAdminOnly
	0,						-- IsAllowMemberAdd
	0						-- IsAllowMemberDelete
)

-- get dimensionguid
declare @DimensionGUID uniqueidentifier
select @DimensionGUID = DimensionGUID from ScoreDimension where FriendlyName = 'User Profiles'



-- create dimension group
insert into ScoreDimensionGroup
(DimensionGUID, Name, Description, IsStock, SchemaName, ObjectName, DateModified)
values (
	@DimensionGUID,				--DimensionGUID
	'User Profiles',			--Name
	'',							--Description
	1,							--IsStock
	@schema,					--SchemaName
	'viewDimUserProfile',     --ObjectName
	GETDATE()					--DateModified
);

declare @DimensionGroupGUID uniqueidentifier;
select @DimensionGroupGUID = G.DimensionGroupGUID from ScoreDimensionGroup G
	inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID
where G.Name = 'User Profiles' and D.DimensionGUID = @DimensionGUID

--update primary group
UPDATE ScoreDimension Set PrimaryGroupGUID = @DimensionGroupGUID 
	where DimensionGUID = @DimensionGUID
	
--get COLUMN attribute type
declare @ColumnType int;
select @ColumnType = T.ScoreAttributeTypeID from ScoreAttributeType T where T.Name = 'Column';

-- create memberguid attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGroupGUID
	'MemberGUID',		-- FriendlyName
	36,							-- ColumnType
	0,							-- IsWrittenToDB
	1,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'MemberGUID',		-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	@ColumnType					--AttributeType
)

-- create userguid attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGroupGUID
	'UserGUID',		-- FriendlyName
	36,							-- ColumnType
	0,							-- IsWrittenToDB
	1,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'UserGUID',		-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	@ColumnType					--AttributeType
)
	
-- create NameFull attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'NameFull',					-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	1,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'NameFull',					-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	@ColumnType					--AttributeType
)
	
-- create UserName attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'UserName',					-- FriendlyName
	231,						-- ColumnType
	0,							-- IsWrittenToDB
	0,							-- IsKey
	0,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	0,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'UserName',					-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	@ColumnType					--AttributeType
)

-- create lootid attribute
insert into ScoreAttribute
(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType)
values (
	@DimensionGroupGUID,	-- DimensionGUID
	'LootID',				-- FriendlyName
	167,						-- ColumnType
	0,							-- IsWrittenToDB
	1,							-- IsKey
	1,							-- IsSecuredLootID
	0,							-- IsSecuredLootConfigID
	1,							-- IsSecuredLootGroupID
	'',							-- SecuredLootGroupPrefix
	'LootID',				-- SQLColumnName
	dbo.ZeroGUID(),	-- DefaultSortAttributeGUID
	dbo.ZeroGUID(),	-- ForeignKeyGUID
	1,							-- IsRequired
	0,							-- SpecialAttributeIndex
	1,							-- IsCopiedWithPlan
	0,							-- DisplayOrder
	@ColumnType					--AttributeType
)


-- create hierarchy
insert into ScoreHierarchy
(DimensionGUID, FriendlyName, PathAlias)
values (@DimensionGUID, 'User Profiles', 'USERPROF')

-- get hierarchyguid
declare @HierarchyGUID uniqueidentifier
select @HierarchyGUID = HierarchyGUID from ScoreHierarchy where FriendlyName = 'User Profiles'

-- create lootid/namefull hierarchyattributelink
insert into ScoreHierarchyAttributeLink
(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild)
select
	@HierarchyGUID,		-- HierarchyGUID
	A.AttributeGUID,	-- AttributeGUID
	DA.AttributeGUID,	-- DisplayAttributeGUID
	4,								-- SortOrder
	0									-- IsDependentOnChild
from ScoreAttribute A
inner join ScoreAttribute DA on DA.DimensionGroupGUID = A.DimensionGroupGUID
where A.FriendlyName = 'LootID'
	and DA.FriendlyName = 'NameFull' 
	and A.DimensionGroupGUID = @DimensionGroupGUID

-- create default hierarchyguid
update D
	set D.DefaultHierarchyGUID = @HierarchyGUID
from ScoreDimension D
where D.DimensionGUID = @DimensionGUID

-- create default keyguid
update D
	set D.DefaultKeyGUID = A.AttributeGUID
from ScoreDimension D
inner join ScoreDimensionGroup G on G.DimensionGUID = D.DimensionGUID
inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID
where A.FriendlyName = 'UserGUID'
	and D.DimensionGUID = @DimensionGUID

-- create default lookupkeyguid
update D
	set D.DefaultLookupKeyGUID = A.AttributeGUID
from ScoreDimension D
inner join ScoreDimensionGroup G on D.DimensionGUID = G.DimensionGUID
inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID
where A.FriendlyName = 'NameFull'
	and D.DimensionGUID = @DimensionGUID

-- update loot
exec procScoreSetDimensionSecurity30 @DimensionGUID

print 'User Profile dimension created.'
print 'View: [' + @schema + '].[viewDimUserProfile]'
print 'Dimension: User Profiles (' + cast(@DimensionGUID as varchar(36)) +')'
print 'PermissionSet: ' + cast(@PermissionSetID as varchar(10))


-- If rebuilding, fix simple security
if @IsForceRebuild = 1 begin
	update S3SimplePermission set LootID = @DimensionGUID where LootID = @DeletedDimensionGUID
end

exec procScoreAttributeSchemaUpdateAll;
GO


---------------------------------------------

-- dbo.procScoreFillInCopy
CREATE proc [dbo].[procScoreFillInCopy]
	@oldmodelguid uniqueidentifier,
	@newmodelguid uniqueidentifier
as

declare @higuid uniqueidentifier
set @higuid = NEWID()

declare @cnt int
set @cnt = 0

--UPDATE EVERYTHING THAT IS ALREADY THERE 
UPDATE ScoreFillin 
	SET 
		--PlaceholderSectionMemberGUID = OLD.PlaceholderSectionMemberGUID,
		--PlaceholderIndex = OLD.PlaceholderIndex,
		FillinMemberGUID = OLD.FillinMemberGUID,
		FillinMemberName = OLD.FillinMemberName,
		HistoryItemGUID = @higuid,
		IsSystemSet = OLD.IsSystemSet
FROM ScoreFillin 
	inner join ScoreFillin OLD
		 on 
			 OLD.PlaceholderSectionMemberGUID = ScoreFillin.PlaceholderSectionMemberGUID
				and
				OLD.PlaceholderIndex = ScoreFillin.PlaceholderIndex
where
	ScoreFillin.ModelGUID = @newmodelguid
	and OLD.ModelGUID = @oldmodelguid
	and ScoreFIllin.FillinMemberGUID <> OLD.FillinMemberGUID
	
set @cnt = @cnt + @@ROWCOUNT
		
--INSERT ANYTHING THAT ISNT 
insert into ScoreFillin(FillinGUID,	ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID, IsSystemSet)
select
	NewID() as FillinGUID,	@newmodelguid, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, @higuid, IsSystemSet
from
	ScoreFillin
where 
	modelguid = @oldmodelguid
	AND NOT EXISTS (
		select 1
		from 
			ScoreFillin NEW 
		where
			NEW.PlaceholderSectionMemberGUID = ScoreFillin.PlaceholderSectionMemberGUID
			and NEW.PlaceholderIndex = ScoreFillin.PlaceholderIndex
			and NEW.ModelGUID = @newmodelguid
	)

set @cnt = @cnt + @@ROWCOUNT

if @cnt > 0 begin

	exec [procLogObjectHistoryItemGUIDObjectType] 'Strata.EMF.Biz.Data.ScoreDataHistoryItem, Strata.EMF.Biz', @newmodelguid, 'Copied fillins', @cnt, @higuid
end
	--AND FillinGUID NOT IN
	--	(select OLD.FillinGUID from ScoreFillin NEW
	--			inner join ScoreFillin OLD on 
	--				OLD.PlaceholderSectionMemberGUID = NEW.PlaceholderSectionMemberGUID
	--				and
	--				OLD.PlaceholderIndex = NEW.PlaceholderIndex
	--		where
	--			NEW.ModelGUID = @newmodelguid
	--			and OLD.ModelGUID = @oldmodelguid)


--fix "self" fillins
exec procScoreFillinSetByTemplateDefault @newmodelguid, 1

--refresh cache
exec [dbo].[procScoreFillinTableRefresh] @newmodelguid
GO


---------------------------------------------

-- dbo.procScoreFillInDelete
create proc [dbo].[procScoreFillInDelete]
	@modelguid uniqueidentifier,
	@phSectionMemberGUID uniqueidentifier,
	@fillInMemberGUID uniqueidentifier
as

delete from ScoreFillin
where
	ModelGUID = @modelguid
	and PlaceholderSectionMemberGUID = @phSectionMemberGUID
	and FillinMemberGUID = @fillInMemberGUID
GO


---------------------------------------------

-- dbo.procScoreFillInInsert
CREATE proc [dbo].[procScoreFillInInsert]
	@modelguid uniqueidentifier,
	@phSectionMemberGUID uniqueidentifier,
	@fillInMemberGUID uniqueidentifier
as

declare @cnt int
declare @maxIndex int

select 
	@cnt = SUM(case when fi.FillinMemberGUID  = @fillInMemberGUID then 1 else 0 end),
	@maxIndex = MAX(fi.PlaceholderIndex)
from
	ScoreFillin fi
where
	fi.ModelGUID = @modelguid
	and fi.PlaceholderSectionMemberGUID = @phSectionMemberGUID

if @cnt = 0 begin
	insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID )
	values (@modelguid, @phSectionMemberGUID, @maxIndex + 1, @fillInMemberGUID)
end
GO


---------------------------------------------

-- dbo.procScoreFillInSetByTemplate
CREATE proc [dbo].[procScoreFillInSetByTemplate] 
	@modelGUID uniqueidentifier,
	@fillInTemplateName nvarchar(100)
as
--FITGUID		PlaceholderSectionMemberGUID	Auto-Fillin-Method
--x			{my department}					use current planmemberguid
--x			{accounts}						query: all accounts where attribute x = y sort by attribute z
--x			{payors}						specific member: {bcbs}

-- Fill in Current Model fit items
declare @modelName nvarchar(max)
select @modelName = name from xplan where planguid = @modelGUID

declare @higuid uniqueidentifier
set @higuid = NEWID()
declare @cnt int
set @cnt = 0

insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID)
select
	@modelGUID,
	PlaceholderSectionMemberGUID,
	isnull((select max(placeholderindex) from scorefillin fi where fi.modelguid = @modelguid and fi.placeholdersectionmemberguid = fit.PlaceholderSectionMemberGUID),0)
	+ PlaceholderSectionIndex,
	@modelGUID,
	left(isnull(@modelName,'Current Model') ,50),
	@higuid
from	
	ScoreFillInTemplateItem fit (readuncommitted)
where
	fillInTemplateName = @fillInTemplateName
	and IsCurrentModelGUID = 1
	and not exists (select 1 from ScoreFillin fi where fi.ModelGUID = @modelGUID and fi.PlaceholderSectionMemberGUID = fit.PlaceholderSectionMemberGUID and fi.FillinMemberGUID = @modelGUID)

set @cnt = @@ROWCOUNT

--Fill in constant fit items
insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID)
select
	@modelGUID,
	PlaceholderSectionMemberGUID,
	isnull((select max(placeholderindex) from scorefillin fi where fi.modelguid = @modelguid and fi.placeholdersectionmemberguid = fit.PlaceholderSectionMemberGUID),0)
	+ PlaceholderSectionIndex,
	ConstantMemberGUID,
	'Constant Member', --isnull(sdm.MemberName,'Constant Member' ),
	@higuid
from	
	ScoreFillInTemplateItem fit (readuncommitted)
	--left join data.viewScoreDimensionMember sdm on fit.ConstantMemberGUID = sdm.MemberGUID
where
	fillInTemplateName = @fillInTemplateName
	and IsConstantMemberGUID = 1
	and not exists (select 1 from ScoreFillin fi where fi.ModelGUID = @modelGUID and fi.PlaceholderSectionMemberGUID = fit.PlaceholderSectionMemberGUID and fi.FillinMemberGUID = ConstantMemberGUID)

set @cnt = @cnt + @@ROWCOUNT

declare @PlaceholderSectionMemberGUID uniqueidentifier
declare @query varchar(max)

declare crsFITQ  CURSOR LOCAL READ_ONLY FAST_FORWARD FOR 
	select
		PlaceholderSectionMemberGUID,
		Query
	from	
		ScoreFillInTemplateItem (readuncommitted)
	where
		fillInTemplateName = @fillInTemplateName
		and isquery = 1
	
			
open crsFITQ;

declare @minrow int

FETCH NEXT FROM crsFITQ into @PlaceholderSectionMemberGUID, @query
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		create table #members (rownum int, memberguid uniqueidentifier, memberName nvarchar(max))
		
		set @query = REPLACE(@query, '{modelguid}',@modelguid)
		
		insert into #members (rownum, memberguid, memberName)
		exec (@query)
		
		select @minrow = MIN(rownum) from #members
		if @minrow = 1 begin
			update #members set rownum = rownum - 1
		end
		
		insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID)
		select
			@modelGUID,
			@PlaceholderSectionMemberGUID,
			isnull((select max(placeholderindex) from scorefillin fi where fi.modelguid = @modelguid and fi.placeholdersectionmemberguid = @PlaceholderSectionMemberGUID),0)
			+ rownum,
			memberguid,
			left(memberName,50),
			@higuid
		from	
			#members fit
		where
			not exists (select 1 from ScoreFillin fi where fi.ModelGUID = @modelGUID and fi.PlaceholderSectionMemberGUID = @PlaceholderSectionMemberGUID and fi.FillinMemberGUID = fit.MemberGUID)
		order by
			rownum
			
		set @cnt = @cnt + @@ROWCOUNT
		drop table #members

		FETCH NEXT FROM crsFITQ into  @PlaceholderSectionMemberGUID, @query
	END
close crsFITQ;
DEALLOCATE crsFITQ;

declare @msg Nvarchar(max)
set @msg = 'Set Fillin Template ' + @fillInTemplateName

if @cnt > 0 begin
	exec [procLogObjectHistoryItemGUIDObjectType] 'Strata.EMF.Biz.Data.ScoreDataHistoryItem, Strata.EMF.Biz', @modelguid, @msg, @cnt, @higuid
end

--select
--	@isQuery = IsQuery
--from
--	ScoreFillInTemplateItem
--where
--	FillInTemplateItemID = @fillInTemplateItemID 

exec [dbo].[procScoreFillinTableRefresh] @modelGUID
GO


---------------------------------------------

-- dbo.procScoreFillInSetByTemplateJustSelf
CREATE proc [dbo].[procScoreFillInSetByTemplateJustSelf] 
	@modelGUID uniqueidentifier,
	@fillInTemplateName nvarchar(max)
as
--FITGUID		PlaceholderSectionMemberGUID	Auto-Fillin-Method
--x			{my department}					use current planmemberguid
--x			{accounts}						query: all accounts where attribute x = y sort by attribute z
--x			{payors}						specific member: {bcbs}


--delete existing iscurrentmodelguid = 1 fillins for this model 
delete fi from ScoreFillin fi
where
	ModelGUID = @modelGUID
	and exists (
		select 1 
		from
			ScoreFillInTemplateItem fit
		where
			fit.IsCurrentModelGUID = 1
			and fit.PlaceholderSectionMemberGUID = fi.PlaceholderSectionMemberGUID
			and fit.PlaceholderSectionIndex = fi.PlaceholderIndex
			)
	
declare @modelName nvarchar(max)
select @modelName = left(name, 50) from Xplan where PlanGUID = @modelGUID

declare @higuid uniqueidentifier
set @higuid = NEWID()

declare @cnt int

-- Fill in Current Model fit items
insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID)
select
	@modelGUID,
	PlaceholderSectionMemberGUID,
	isnull((select max(placeholderindex) from scorefillin fi where fi.modelguid = @modelguid and fi.placeholdersectionmemberguid = fit.PlaceholderSectionMemberGUID),0)
	+ PlaceholderSectionIndex,
	@modelGUID,
	isnull(@modelName,'Current Model'),
	@higuid
from	
	ScoreFillInTemplateItem fit
where
	fillInTemplateName = @fillInTemplateName
	and IsCurrentModelGUID = 1
	and not exists (select 1 from ScoreFillin fi where fi.ModelGUID = @modelGUID and fi.PlaceholderSectionMemberGUID = fit.PlaceholderSectionMemberGUID and fi.FillinMemberGUID = @modelGUID)
	
set @cnt = @@ROWCOUNT

if @cnt > 0 begin
	exec [procLogObjectHistoryItemGUIDObjectType] 'Strata.EMF.Biz.Data.ScoreDataHistoryItem, Strata.EMF.Biz', @modelguid,'Set Self Fillins',@cnt,@higuid
end

exec [dbo].[procScoreFillinTableRefresh] @modelGUID
GO


---------------------------------------------

-- dbo.procScoreFillInSetManyClearThoseBeingSet
--Forward


CREATE proc [dbo].[procScoreFillInSetManyClearThoseBeingSet]
	@iguid uniqueidentifier
as
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));


	WITH tgt (ModelGUID,
			PlaceholderSectionMemberGUID,
			PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName)
	AS
	(
   		select 
			ModelGUID,
			PlaceholderSectionMemberGUID ,
			PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName
		from
			ScoreFillin
		where
			ModelGUID in (select ModelGUID from ScoreFillinSetManyStaging where InstanceGUID = @iguid)
			and PlaceholderSectionMemberGUID in (select PlaceholderSectionMemberGUID from ScoreFillinSetManyStaging where InstanceGUID=@iguid) --Changed
			and IsDeleted = 0
	)
	MERGE tgt as target
	USING(
		select 
			ModelGUID,
			PlaceholderSectionMemberGUID,
			row_number() over (partition by modelguid, placeholdersectionmemberguid order by sortorder) - 1 as PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName
		from
			(
			select
				modelguid,
				placeholdersectionmemberguid,
				min(sortorder)as SortOrder,
				fillinmemberguid,
				min(fillinmembername) as fillinmembername
			from
				ScoreFillinSetManyStaging
			where InstanceGUID=@iguid  -- Changed
			group by
				modelguid,
				placeholdersectionmemberguid,
				FillInMemberGUID,
				MakeUnique
			) src
		) as source
	ON	(
			target.ModelGUID = source.ModelGUID
			and target.PlaceholderSectionMemberGUID = source.PlaceholderSectionMemberGUID
			and target.PlaceholderIndex = source.PlaceholderIndex
			and target.FillInMemberGUID = source.FillInMemberGUID
		)
	WHEN MATCHED AND target.FillinMemberName <> source.FillinMemberName THEN
		UPDATE SET target.FillinMemberName = source.FillinMemberName
	WHEN NOT MATCHED BY TARGET THEN 
		INSERT (	ModelGUID,
			PlaceholderSectionMemberGUID,
			PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName)
		VALUES (
			ModelGUID,
			PlaceholderSectionMemberGUID,
			PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName)
	WHEN NOT MATCHED BY SOURCE THEN
		DELETE --UPDATE SET target.IsDeleted = 1
	OUTPUT $action INTO @SummaryOfChanges;
	
	select Change, COUNT(*) from @SummaryOfChanges group by change

RETURN
GO


---------------------------------------------

-- dbo.procScoreFillInSetManyClearThoseBeingSetNoDeletes
create proc [dbo].[procScoreFillInSetManyClearThoseBeingSetNoDeletes]
	@iguid uniqueidentifier
as
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));


	WITH tgt (ModelGUID,
			PlaceholderSectionMemberGUID,
			PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName)
	AS
	(
   		select 
			ModelGUID,
			PlaceholderSectionMemberGUID ,
			PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName
		from
			ScoreFillin
		where
			ModelGUID in (select ModelGUID from ScoreFillinSetManyStaging where InstanceGUID = @iguid)
			and PlaceholderSectionMemberGUID in (select PlaceholderSectionMemberGUID from ScoreFillinSetManyStaging where InstanceGUID=@iguid) --Changed
			and IsDeleted = 0
	)
	MERGE tgt as target
	USING(
		select 
			ModelGUID,
			PlaceholderSectionMemberGUID,
			row_number() over (partition by modelguid, placeholdersectionmemberguid order by sortorder) - 1 as PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName
		from
			(
			select
				modelguid,
				placeholdersectionmemberguid,
				min(sortorder)as SortOrder,
				fillinmemberguid,
				min(fillinmembername) as fillinmembername
			from
				ScoreFillinSetManyStaging
			where InstanceGUID=@iguid  -- Changed
			group by
				modelguid,
				placeholdersectionmemberguid,
				FillInMemberGUID,
				MakeUnique
			) src
		) as source
	ON	(
			target.ModelGUID = source.ModelGUID
			and target.PlaceholderSectionMemberGUID = source.PlaceholderSectionMemberGUID
			and target.PlaceholderIndex = source.PlaceholderIndex
			and target.FillInMemberGUID = source.FillInMemberGUID
		)
	WHEN MATCHED AND target.FillinMemberName <> source.FillinMemberName THEN
		UPDATE SET target.FillinMemberName = source.FillinMemberName
	WHEN NOT MATCHED BY TARGET THEN 
		INSERT (	ModelGUID,
			PlaceholderSectionMemberGUID,
			PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName)
		VALUES (
			ModelGUID,
			PlaceholderSectionMemberGUID,
			PlaceholderIndex,
			FillInMemberGUID,
			FillinMemberName)
	OUTPUT $action INTO @SummaryOfChanges;
	
	select Change, COUNT(*) from @SummaryOfChanges group by change
GO


---------------------------------------------

-- dbo.procScoreFillinCompressIndices
CREATE proc [dbo].[procScoreFillinCompressIndices]
	@modelguid uniqueidentifier
as
select	
	fi.FillinGUID,
	ROW_NUMBER() over (partition by fi.modelguid, fi.placeholdersectionmemberguid order by fi.placeholderindex ) -1 as PlaceholderIndex
	into #CompressedIndices
from
	ScoreFillin fi
where
	fi.ModelGUID = @modelguid
	
declare @higuid uniqueidentifier
set @higuid = NEWID()

declare @cnt int

update
	ScoreFillin
set
	PlaceholderIndex = CI.PlaceholderIndex,
	HistoryItemGUID = @higuid
from
	ScoreFillin 
	inner join #CompressedIndices ci on ScoreFillin.FillinGUID = ci.fillInGUID
where
	ScoreFillin.PlaceholderIndex <> ci.PlaceholderIndex

set @cnt = @@ROWCOUNT

drop table #CompressedIndices

if @cnt > 0 begin
	exec [procLogObjectHistoryItemGUIDObjectType] 'Strata.EMF.Biz.Data.ScoreDataHistoryItem, Strata.EMF.Biz', @modelguid, 'Compressed Fillin Indices', @cnt, @higuid
end
GO


---------------------------------------------

-- dbo.procScoreFillinExclusivityLogMemberNameRefresh
CREATE proc [dbo].[procScoreFillinExclusivityLogMemberNameRefresh]
    @modelGuidCsv nvarchar(max),
    @isDebug bit = 0
AS
    DECLARE @dimobj nvarchar(max)
    DECLARE @keyname nvarchar(64)
    DECLARE @sql nvarchar(max)

DECLARE @DimensionsByModel TABLE(dimobj varchar(max), keyname nvarchar(64))

INSERT INTO @DimensionsByModel (dimobj, keyname)
SELECT DISTINCT sa.DimensionSQLObjectExpression, dk.SQLColumnName
FROM [dbo].[viewScoreAttribute] sa
     INNER JOIN [dbo].[ScoreDimension] d on d.DimensionGUID = sa.DimensionGUID
     INNER JOIN [dbo].[viewScoreAttribute] dk on dk.AttributeGUID = d.DefaultLookupKeyGUID and dk.SQLColumnName like '%Name'
WHERE EXISTS(
            SELECT TOP 1 1
            FROM [dbo].[ScoreCompositeLink] cl WITH (readuncommitted) 
            INNER JOIN [dbo].[EMFModelTemplateLinkSource] ls WITH (readuncommitted) ON ls.ParentScoreCompositeTableGUID = cl.CompositeGUID 
            INNER JOIN [dbo].[XPlan] p WITH (readuncommitted) ON p.ModelTemplateGUID = ls.ModelTemplateGUID and p.PlanGUID in(SELECT GUID FROM dbo.ConvertCSGuidsToTable(@modelGuidCsv, ','))
            WHERE 
              cl.Key2GUID = sa.AttributeGUID 
              AND cl.IsPlaceholder = 1
            )

DECLARE @COUNT INT
SELECT @COUNT = COUNT(1) FROM @DimensionsByModel

WHILE(@COUNT > 0)
  BEGIN
    SELECT TOP 1 @dimobj = dimobj, @keyname = keyname FROM @DimensionsByModel

	set @sql = '
        UPDATE SF
        SET Message = REPLACE(SF.Message, SF.FillinMemberGUID, D.' + @keyname + ')
        FROM ScoreFillinExclusivityLogItem SF
        INNER JOIN '+ @dimobj + ' D ON D.MemberGUID = SF.FillinMemberGUID
        WHERE
		    SF.ModelGUID IN (SELECT guid FROM dbo.ConvertCSGuidsToTable(''' + @modelGuidCsv + ''', '',''))
		    AND D.' + @keyname + ' != ''''
            AND SF.Message LIKE ''%''+CAST(SF.FillinMemberGUID AS nvarchar(36))+''%''
'

    IF (@isDebug = 0) BEGIN
	  EXEC(@sql)
    END ELSE BEGIN
	  PRINT @sql
    END

	SET @COUNT -= 1

	DELETE FROM @DimensionsByModel
	WHERE dimobj = @dimobj AND keyname = @keyname
  END
GO


---------------------------------------------

-- dbo.procScoreFillinMemberNameRefresh
CREATE proc dbo.procScoreFillinMemberNameRefresh
    @modelGuidCsv nvarchar(max) = '',
    @isDebug bit = 0
as
  set nocount on

  declare @dimobj nvarchar(450)
  declare @keyname nvarchar(450)
  declare @sql nvarchar(max)

  if (@modelGuidCsv = '') begin
    if(exists(select 1 from [dbo].[ScoreFillin] with (readuncommitted) where FillinMemberName in('', 'default'))) begin
      declare crsDimensions cursor fast_forward for
        select distinct
          sa.DimensionSQLObjectExpression,
          dk.SQLColumnName
        from
          [dbo].[viewScoreAttribute] sa
          inner join [dbo].[ScoreDimension] d on d.DimensionGUID = sa.DimensionGUID
          inner join [dbo].[viewScoreAttribute] dk on dk.AttributeGUID = d.DefaultLookupKeyGUID and dk.SQLColumnName like '%Name'
        where
          exists(select 1 from [dbo].[ScoreCompositeLink] cl with (readuncommitted) where cl.Key2GUID = sa.AttributeGUID and cl.IsPlaceholder = 1)

      open crsDimensions
      fetch next from crsDimensions into @dimobj, @keyname

      while(@@fetch_status = 0) begin
        set @sql = '
					update SF set SF.FillinMemberName = D.' + @keyname + '
					from
						ScoreFillin SF
						inner join ' + @dimobj + ' D on D.MemberGUID = SF.FillinMemberGUID
					where
						SF.FillinMemberName in('''', ''default'')
				'
        if (@isDebug = 0) begin
          exec(@sql)
        end else begin
          print @sql
        end

        set @sql = '
					update SF set SF.FillinMemberName = D.' + @keyname + '
					from
						ScoreFillinRefreshLogItem SF
						inner join ' + @dimobj + ' D on D.MemberGUID = SF.FillinMemberGUID
					where
						SF.FillinMemberName in('''', ''default'')
				'
        if (@isDebug = 0) begin
          exec(@sql)
        end else begin
          print @sql
        end

        fetch next from crsDimensions into @dimobj, @keyname
      end

      close crsDimensions
      deallocate crsDimensions
    end

    --handle self fillins specially
    if (@isDebug = 0) begin
      update sf set sf.FillinMemberName = xp.Name
      from
        [dbo].[ScoreFillin] sf
        inner join [dbo].[XPlan] xp with (readuncommitted) on xp.PlanGUID = sf.ModelGUID and sf.FillinMemberGUID = xp.PlanGUID
      where
        sf.FillinMemberName <> xp.Name
        and xp.Name != ''
    end else begin
      print '
			update sf set sf.FillinMemberName = xp.Name
			from
				[dbo].[ScoreFillin] sf
				inner join [dbo].[XPlan] xp with (readuncommitted) on xp.PlanGUID = sf.ModelGUID and sf.FillinMemberGUID = xp.PlanGUID
			where
				sf.FillinMemberName <> xp.Name
				and xp.Name != '''''
    end
  end else begin
    if(exists(select 1 from [dbo].[ScoreFillin] with (readuncommitted) where FillinMemberName in ('', 'default') and ModelGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGuidCsv, ',')))) begin
      declare crsDimensionsByModel cursor fast_forward for
        select distinct
          sa.DimensionSQLObjectExpression,
          dk.SQLColumnName
        from
          [dbo].[viewScoreAttribute] sa
          inner join [dbo].[ScoreDimension] d on d.DimensionGUID = sa.DimensionGUID
          inner join [dbo].[viewScoreAttribute] dk on dk.AttributeGUID = d.DefaultLookupKeyGUID and dk.SQLColumnName like '%Name'
        where
          exists(
              select 1
              from
                [dbo].[ScoreCompositeLink] cl with (readuncommitted)
                inner join [dbo].[EMFModelTemplateLinkSource] ls with (readuncommitted) on ls.ParentScoreCompositeTableGUID = cl.CompositeGUID
                inner join [dbo].[XPlan] p with (readuncommitted) on p.ModelTemplateGUID = ls.ModelTemplateGUID and p.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGuidCsv, ','))
              where
                cl.Key2GUID = sa.AttributeGUID
                and cl.IsPlaceholder = 1
          )

      open crsDimensionsByModel
      fetch next from crsDimensionsByModel into @dimobj, @keyname

      while(@@fetch_status = 0) begin
        set @sql = '
					update SF set SF.FillinMemberName = D.' + @keyname + '
					from
						ScoreFillin SF
						inner join ' + @dimobj + ' D on D.MemberGUID = SF.FillinMemberGUID
					where
						SF.FillinMemberName in('''', ''default'')
						and ModelGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @modelGuidCsv + ''', '',''))
				'
        if (@isDebug = 0) begin
          exec(@sql)
        end else begin
          print @sql
        end

        set @sql = '
					update SF set SF.FillinMemberName = D.' + @keyname + '
					from
						ScoreFillinRefreshLogItem SF
						inner join ' + @dimobj + ' D on D.MemberGUID = SF.FillinMemberGUID
					where
						SF.FillinMemberName in('''', ''default'')
						and ModelGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @modelGuidCsv + ''', '',''))
				'
        if (@isDebug = 0) begin
          exec(@sql)
        end else begin
          print @sql
        end

        fetch next from crsDimensionsByModel into @dimobj, @keyname
      end

      close crsDimensionsByModel
      deallocate crsDimensionsByModel
    end

    --handle self fillins specially
    if (@isDebug = 0) begin
      update sf set sf.FillinMemberName = xp.Name
      from
        [dbo].[ScoreFillin] sf
        inner join [dbo].[XPlan] xp with (readuncommitted) on xp.PlanGUID = sf.ModelGUID and sf.FillinMemberGUID = xp.PlanGUID
      where
        sf.FillinMemberName <> xp.Name
        and xp.Name != ''
        and xp.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGuidCsv, ','))
    end else begin
      print '
			update sf set sf.FillinMemberName = xp.Name
			from
				[dbo].[ScoreFillin] sf
				inner join [dbo].[XPlan] xp with (readuncommitted) on xp.PlanGUID = sf.ModelGUID and sf.FillinMemberGUID = xp.PlanGUID
			where
				sf.FillinMemberName <> xp.Name
				and xp.Name != ''''
				and xp.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGuidCsv, '',''))'
    end
  end
GO


---------------------------------------------

-- dbo.procScoreFillinSetByTemplateDefault
CREATE proc [dbo].[procScoreFillinSetByTemplateDefault]
	@planguid uniqueidentifier
	,@isCopy as bit = 0
as

declare @fillInTemplateName nvarchar(100)
select @fillInTemplateName  = scoredefaultfillInTemplateName from PlanType 
where PlanTypeGUID = (select PlanTypeGUID from XPlan where PlanGUID = @planguid)

if @fillInTemplateName  is null return
if @fillInTemplateName = '' return

if @isCopy = 1 begin
	exec procScoreFillInSetByTemplateJustSelf @planguid, @fillInTemplateName
end else begin
	exec procScoreFillInSetByTemplate @planguid, @fillInTemplateName
end
GO


---------------------------------------------

-- dbo.procScoreFillinTableAudit
CREATE proc [dbo].[procScoreFillinTableAudit]
	@modelGUID uniqueidentifier,
	@isAutoFixing bit = 1
as
	set nocount on

	declare @rowid int = -1
	if((select count(*) from [data].[ScoreFillinCacheAudit] (readuncommitted)) > 0) begin
		select @rowid = max(RowID) from [data].[ScoreFillinCacheAudit] (readuncommitted)
	end

	declare @tableName nvarchar(150)
	declare @phKeyName nvarchar(100)
	declare @phDimTable nvarchar(450)
	declare @fillinKeyName nvarchar(100)
	declare @fillinDimTable nvarchar(450)
	declare @fillinDimGUID uniqueidentifier
	declare crsInfo cursor fast_forward for 
		select distinct
			'ScoreFillin_' + replace(A2.DimensionName, ' ', '') as TableName,
			A1.SQLColumnName as PHKeyName,
			A1.DimensionSQLObjectExpression as PHDimTable,
			A2.SQLColumnName as FillinKeyName,
			A2.DimensionSQLObjectExpression as FillinDimTable,
			A2.DimensionGUID as FillinDimGUID
		from
			ScoreCompositeLink CL (readuncommitted)
			inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID
			inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID
			inner join EMFModelTemplateLinkSource LS (readuncommitted) on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID
			inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID
			inner join sys.tables t on t.Name = 'ScoreFillin_' + replace(A2.DimensionName, ' ', '')
			inner join dbo.XPlan p on p.ModelTemplateGUID = MT.ModelTemplateGUID
		where
			CL.IsPlaceholder = 1
			and MT.IsScoreFillinAdvancedMode = 1
			and p.PlanGUID = @modelGUID

	open crsInfo
	fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID
	
	declare @sql nvarchar(max)
	while(@@FETCH_STATUS = 0) begin
		set @sql = '
			insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem])
			select [FillinGUID], [ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin exists, ' + @tableName + ' missing'' 
			from ScoreFillin (readuncommitted)
			where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk)
			and FillinGUID not in(select c.FillinGUID from [data].[' + @tableName + '] c (readuncommitted))
			and ModelGUID = ''' + cast(@modelGUID as nvarchar(36)) + ''';

			insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem])
			select [FillinGUID], [ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin missing, ' + @tableName + ' exists'' 
			from [data].[' + @tableName + '] (readuncommitted)
			where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk)
			and FillinGUID not in(select l.FillinGUID from ScoreFillin l (readuncommitted))
			and ModelGUID = ''' + cast(@modelGUID as nvarchar(36)) + ''';
			
			insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem])
			select fi.[FillinGUID], fi.[ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin order '' + cast(fi.PlaceholderIndex as nvarchar(8)) + '', ' + @tableName + ' '' + cast(c.PlaceholderIndex as nvarchar(8))
			from ScoreFillin fi (readuncommitted)
			inner join [data].[' + @tableName + '] c (readuncommitted) on c.FillinGUID = fi.FillinGUID
			where fi.PlaceholderIndex != c.PlaceholderIndex
			and fi.ModelGUID = ''' + cast(@modelGUID as nvarchar(36)) + ''';
'
		exec(@sql)
	
		fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID
	end

	close crsInfo
	deallocate crsInfo

	if ((@isAutoFixing = 1) and (exists(select 1 from [data].[ScoreFillinCacheAudit] (readuncommitted) where RowID > @rowid and ModelGUID = @modelGUID))) begin
		exec [dbo].[procScoreFillinTableRefresh] @modelGUID
		exec [dbo].[procInvalidateModelWorkbookCache] @modelGUID, 0, 0, 'procScoreFillinTableAudit'
	end
GO


---------------------------------------------

-- dbo.procScoreFillinTableAuditAll
/************************************************************
** Author: gforeman
** Create Date: 2012
** Description: 
**		This proc serves as a safeguard against fillin
**		cache tables getting out of sync with ScoreFillin.
**		Theoretically, if all Jazz functions and custom scripts
**		are setup and working correctly, this should be
**		unnecessary.  But if anything forgets to refresh
**		cache after updating members, you have problems.
** Usage:		
**		Run and then inspect the returned contents of 
**		data.ScoreFillinCacheAudit for a listing of issues that 
**		were encountered.
*************************************************************/
CREATE proc procScoreFillinTableAuditAll
	@isAutoFixing bit = 0
as
	set nocount on

	declare @rowid int = -1
	if((select count(*) from [data].[ScoreFillinCacheAudit] (readuncommitted)) > 0) begin
		select @rowid = max(RowID) from [data].[ScoreFillinCacheAudit] (readuncommitted)
	end

	declare @tableName nvarchar(150)
	declare @phKeyName nvarchar(100)
	declare @phDimTable nvarchar(450)
	declare @fillinKeyName nvarchar(100)
	declare @fillinDimTable nvarchar(450)
	declare @fillinDimGUID uniqueidentifier
	declare crsInfo cursor fast_forward for 
		select distinct
			'ScoreFillin_' + replace(A2.DimensionName, ' ', '') as TableName,
			A1.SQLColumnName as PHKeyName,
			A1.DimensionSQLObjectExpression as PHDimTable,
			A2.SQLColumnName as FillinKeyName,
			A2.DimensionSQLObjectExpression as FillinDimTable,
			A2.DimensionGUID as FillinDimGUID
		from
			ScoreCompositeLink CL (readuncommitted)
			inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID
			inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID
			inner join EMFModelTemplateLinkSource LS (readuncommitted) on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID
			inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID
			inner join sys.tables t on t.Name = 'ScoreFillin_' + replace(A2.DimensionName, ' ', '')
		where
			CL.IsPlaceholder = 1
			and MT.IsScoreFillinAdvancedMode = 1

	open crsInfo
	fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID
	
	declare @sql nvarchar(max)
	while(@@FETCH_STATUS = 0) begin
		set @sql = '
			insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem])
			select [FillinGUID], [ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin exists, ' + @tableName + ' missing'' 
			from ScoreFillin (readuncommitted)
			where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk)
			and FillinGUID not in(select c.FillinGUID from [data].[' + @tableName + '] c (readuncommitted))
			and ModelGUID in(select p.PlanGUID from XPlan p (readuncommitted) inner join EMFModelTemplate t (readuncommitted) on t.ModelTemplateGUID = p.ModelTemplateGUID and t.IsScoreFillinAdvancedMode = 1);

			insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem])
			select [FillinGUID], [ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin missing, ' + @tableName + ' exists'' 
			from [data].[' + @tableName + '] (readuncommitted)
			where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk)
			and FillinGUID not in(select l.FillinGUID from ScoreFillin l (readuncommitted))
			and ModelGUID in(select p.PlanGUID from XPlan p (readuncommitted) inner join EMFModelTemplate t (readuncommitted) on t.ModelTemplateGUID = p.ModelTemplateGUID and t.IsScoreFillinAdvancedMode = 1);
			
			insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem])
			select fi.[FillinGUID], fi.[ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin order '' + cast(fi.PlaceholderIndex as nvarchar(8)) + '', ' + @tableName + ' '' + cast(c.PlaceholderIndex as nvarchar(8))
			from ScoreFillin fi (readuncommitted)
			inner join [data].[' + @tableName + '] c (readuncommitted) on c.FillinGUID = fi.FillinGUID
			where fi.PlaceholderIndex != c.PlaceholderIndex;
'
		exec(@sql)
	
		fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID
	end

	close crsInfo
	deallocate crsInfo
	
	if (@isAutoFixing = 1) begin
		declare @dimensionGUID uniqueidentifier
		declare crsDimensions cursor fast_forward for select distinct DimensionGUID from [data].[ScoreFillinCacheAudit] (readuncommitted) where RowID > @rowid
		open crsDimensions
		fetch next from crsDimensions into @dimensionGUID
		while(@@fetch_status = 0) begin
			exec [dbo].[procScoreFillinTableRefreshByDimension] @dimensionGUID
			fetch next from crsDimensions into @dimensionGUID
		end
		close crsDimensions
		deallocate crsDimensions

		declare @invwhere nvarchar(max)
		set @invwhere = 'PlanGUID in(select ModelGUID from [data].[ScoreFillinCacheAudit] (readuncommitted) where RowID > ' + cast(@rowid as nvarchar(16)) + ')'
		exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @invwhere, 0, 'procScoreFillinTableAuditAll'
	end
	
	select * from [data].[ScoreFillinCacheAudit] where RowID > @rowid
GO


---------------------------------------------

-- dbo.procScoreFillinTableRebuild
CREATE proc [dbo].[procScoreFillinTableRebuild]
	@phDimensionGUID uniqueidentifier,
	@fillinDimensionGUID uniqueidentifier,
	@isDebug bit = 0
as
	set nocount on

	declare @tableName nvarchar(150)
	select @tableName = 'ScoreFillin_' + replace(FriendlyName, ' ', '') from ScoreDimension where DimensionGUID = @fillinDimensionGUID

	declare @phKeyName nvarchar(100)
	declare @phKeyType int
	select @phKeyName = A.SQLColumnName, @phKeyType = A.ColumnType from viewScoreAttribute A inner join ScoreDimension D on D.DimensionGUID = A.DimensionGUID and D.DefaultKeyGUID = A.AttributeGUID and D.DimensionGUID = @phDimensionGUID

	declare @fillinKeyName nvarchar(100)
	declare @fillinKeyType int
	select @fillinKeyName = A.SQLColumnName, @phKeyType = A.ColumnType from viewScoreAttribute A inner join ScoreDimension D on D.DimensionGUID = A.DimensionGUID and D.DefaultKeyGUID = A.AttributeGUID and D.DimensionGUID = @fillinDimensionGUID

	declare @error nvarchar(450)
	if (@phKeyType != 48 and @phKeyType != 52 and @phKeyType != 56 and @phKeyType != 127) begin
		set @error = 'Fillin table ' + @tableName + ' cannot be created because the placeholder dimension has a non-integer default key.'
		RAISERROR (@error, 18, 0)  
		return
	end
	if (@fillinKeyType != 48 and @fillinKeyType != 52 and @fillinKeyType != 56 and @fillinKeyType != 127) begin
		set @error = 'Fillin table ' + @tableName + ' cannot be created because the fillin dimension has a non-integer default key.'
		RAISERROR (@error, 18, 0)  
		return
	end

	declare @sql nvarchar(max)

	--drop any existing instance of the table
	set @sql = '
		if ((select count(*) from sys.tables where name = ''' + @tableName + ''') > 0) begin
			drop table data.' + @tableName + '
		end'
	if (@isDebug = 1) begin	print @sql end else begin exec(@sql) end

	--create the table
	set @sql = '
		CREATE TABLE [data].[' + @tableName + '] (
			[RowID] [int] IDENTITY(1,1) NOT NULL,
			[FillinGUID] [uniqueidentifier] NOT NULL,
			[ModelGUID] [uniqueidentifier] NOT NULL,
			[PlaceholderSectionMemberGUID] [uniqueidentifier] NOT NULL,
			[PlaceholderIndex] [int] NOT NULL,
			[FillinMemberGUID] [uniqueidentifier] NOT NULL,
			[FillinMemberName] [nvarchar](max) NOT NULL,
			[IsDeleted] [bit] NOT NULL,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL,
			[' + @phKeyName + '] [int] NOT NULL,
			[' + @fillinKeyName + '] [int] NOT NULL,
			CONSTRAINT [PK_' + @tableName + '] PRIMARY KEY NONCLUSTERED 
			( [RowID] ASC ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
		) ON [PRIMARY]'
	if (@isDebug = 1) begin	print @sql end else begin exec(@sql) end

	--add default values
	set @sql = '
		ALTER TABLE [data].[' + @tableName + '] ADD  CONSTRAINT [DF_' + @tableName + '_' + @phKeyName + ']  DEFAULT ((0)) FOR [' + @phKeyName + ']
		ALTER TABLE [data].[' + @tableName + '] ADD  CONSTRAINT [DF_' + @tableName + '_' + @fillinKeyName + ']  DEFAULT ((0)) FOR [' + @fillinKeyName + ']'
	if (@isDebug = 1) begin	print @sql end else begin exec(@sql) end

	--create clustered index
	set @sql = '
		CREATE CLUSTERED INDEX [IX_' + @tableName + '_Cluster] ON [data].[' + @tableName + '] (
			[ModelGUID] ASC
		) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]'
	if (@isDebug = 1) begin	print @sql end else begin exec(@sql) end

	--create index on ID columns
	set @sql = '
		CREATE NONCLUSTERED INDEX [IX_' + @tableName + '_ByIDs] ON [data].[' + @tableName + '] (
			[ModelGUID] ASC,
			[PlaceholderIndex] ASC,
			[' + @phKeyName + '] ASC,
			[' + @fillinKeyName + '] ASC
		) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]'
	if (@isDebug = 1) begin	print @sql end else begin exec(@sql) end
	
	--prevent duplicate fillins
	set @sql = '
		CREATE UNIQUE NONCLUSTERED INDEX IX_' + @tableName + '_ByFillinGUID ON [data].[' + @tableName + '] (
			FillinGUID
		) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]'
	if (@isDebug = 1) begin	print @sql end else begin exec(@sql) end
GO


---------------------------------------------

-- dbo.procScoreFillinTableRebuildAll
--Author: gforeman
--Branch: Earwig
--Forward
create proc procScoreFillinTableRebuildAll
	@isDebug bit = 0
as
	if ((select COUNT(*) from EMFModelTemplate where IsScoreFillinAdvancedMode = 1) = 0) begin return end

	declare @phDimensionGUID uniqueidentifier
	declare @fillinDimensionGUID uniqueidentifier
	declare crsDimensions cursor fast_forward for 
		select distinct
			A1.DimensionGUID as PHDimensionGUID,
			A2.DimensionGUID as FillinDimensionGUID
		from
			ScoreCompositeLink CL
			inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID
			inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID
			inner join EMFModelTemplateLinkSource LS on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID
			inner join EMFModelTemplate MT on MT.ModelTemplateGUID = LS.ModelTemplateGUID
		where
			CL.IsPlaceholder = 1
			and MT.IsScoreFillinAdvancedMode = 1

	open crsDimensions
	fetch next from crsDimensions into @phDimensionGUID, @fillinDimensionGUID
	
	while(@@FETCH_STATUS = 0) begin
		exec procScoreFillinTableRebuild @phDimensionGUID, @fillinDimensionGUID, @isDebug

		fetch next from crsDimensions into @phDimensionGUID, @fillinDimensionGUID
	end
	
	close crsDimensions
	deallocate crsDimensions
	
	exec procScoreFillinTableRefreshAll @isDebug
GO


---------------------------------------------

-- dbo.procScoreFillinTableRefresh
CREATE proc [dbo].[procScoreFillinTableRefresh]
	@modelGUIDList nvarchar(max),
	@isDebug bit = 0
as
	set nocount on

	declare @mtguid uniqueidentifier
	declare @whereClause nvarchar(max)
	
	declare crsTemplates cursor fast_forward for select distinct MT.ModelTemplateGUID from [dbo].[EMFModelTemplate] MT (readuncommitted) inner join [dbo].[XPlan] P (readuncommitted) on P.ModelTemplateGUID = MT.ModelTemplateGUID where P.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGUIDList, ','))
	open crsTemplates
	fetch next from crsTemplates into @mtguid
	
	while(@@FETCH_STATUS = 0) begin
		set @whereClause = 'in (select xp.PlanGUID from XPlan xp (readuncommitted) inner join dbo.ConvertCSGuidsToTable(''' + @modelGUIDList + ''', '','') cs on cs.guid = xp.PlanGUID where xp.ModelTemplateGUID = ''' + CAST(@mtguid as nvarchar(36)) + ''')'
		exec procScoreFillinTableRefreshWorker @mtguid, @whereClause, @isDebug

		fetch next from crsTemplates into @mtguid
	end
	
	close crsTemplates
	deallocate crsTemplates
GO


---------------------------------------------

-- dbo.procScoreFillinTableRefreshAll
CREATE proc procScoreFillinTableRefreshAll
	@isDebug bit = 0
as
	declare @ptguid uniqueidentifier
	declare crsTypes cursor fast_forward for select PlanTypeGUID from [dbo].[PlanType] (readuncommitted)
		
	open crsTypes
	fetch next from crsTypes into @ptguid
	
	while (@@FETCH_STATUS = 0) begin
		exec procScoreFillinTableRefreshByPlanType @ptguid, @isDebug
		fetch next from crsTypes into @ptguid
	end
	
	close crsTypes
	deallocate crsTypes
GO


---------------------------------------------

-- dbo.procScoreFillinTableRefreshByDimension
CREATE proc [dbo].[procScoreFillinTableRefreshByDimension]
	@dimensionGUID uniqueidentifier,
	@isDebug bit = 0,
	@whereClause nvarchar(max) = ''
as
	set nocount on
	
	declare @tableName nvarchar(150)
	declare @phKeyName nvarchar(100)
	declare @phDimTable nvarchar(450)
	declare @fillinKeyName nvarchar(100)
	declare @fillinDimTable nvarchar(450)
	declare @fillinDimGUID uniqueidentifier
	declare crsInfo cursor fast_forward for 
		select distinct
			'ScoreFillin_' + replace(A2.DimensionName, ' ', '') as TableName,
			A1.SQLColumnName as PHKeyName,
			A1.DimensionSQLObjectExpression as PHDimTable,
			A2.SQLColumnName as FillinKeyName,
			A2.DimensionSQLObjectExpression as FillinDimTable,
			A2.DimensionGUID
		from
			ScoreCompositeLink CL (readuncommitted)
			inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID
			inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID
			inner join EMFModelTemplateLinkSource LS (readuncommitted) on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID
			inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID
		where
			CL.IsPlaceholder = 1
			and MT.IsScoreFillinAdvancedMode = 1
			and (A1.DimensionGUID = @dimensionGUID or A2.DimensionGUID = @dimensionguid)

	open crsInfo
	fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID
	
	declare @sql nvarchar(max)
	while(@@FETCH_STATUS = 0) begin
		if ((@dimensionGUID = @fillinDimGUID) and (len(@whereClause) > 0)) begin
			set @sql = '
				begin tran
				
				delete from data.' + @tableName + ' where FillinMemberGUID in(select C.MemberGUID from ' + @fillinDimTable + ' C where ' + @whereClause + ');
				delete from data.' + @tableName + ' where FillinMemberGUID not in(select C.MemberGUID from ' + @fillinDimTable + ' C);
				
				insert into [data].[' + @tableName + '] ([FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID])
				select [FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID] 
				from ScoreFillin (readuncommitted)
				where FillinMemberGUID in (select C.MemberGUID from ' + @fillinDimTable + ' C where ' + @whereClause + ');
				
				update FI set FI.' + @phKeyName + ' = PH.' + @phKeyName + ' from data.' + @tableName + ' FI inner join ' + @phDimTable + ' PH on PH.MemberGUID = FI.PlaceholderSectionMemberGUID where FI.FillinMemberGUID in (select C.MemberGUID from ' + @fillinDimTable + ' C where ' + @whereClause + ');
				update FI set FI.' + @fillinKeyName + ' = PH.' + @fillinKeyName + ' from data.' + @tableName + ' FI inner join ' + @fillinDimTable + ' PH on PH.MemberGUID = FI.FillinMemberGUID where FI.FillinMemberGUID in (select C.MemberGUID from ' + @fillinDimTable + ' C where ' + @whereClause + ');
				
				commit tran
'
		end else begin
			set @sql = '
				begin tran
				
				truncate table data.' + @tableName + ';
				
				insert into [data].[' + @tableName + '] ([FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID])
				select [FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID] 
				from ScoreFillin (readuncommitted)
				where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk);
				
				update FI set FI.' + @phKeyName + ' = PH.' + @phKeyName + ' from data.' + @tableName + ' FI inner join ' + @phDimTable + ' PH on PH.MemberGUID = FI.PlaceholderSectionMemberGUID;
				update FI set FI.' + @fillinKeyName + ' = PH.' + @fillinKeyName + ' from data.' + @tableName + ' FI inner join ' + @fillinDimTable + ' PH on PH.MemberGUID = FI.FillinMemberGUID;
				
				commit tran
'
		end
		
		if (@isDebug = 1) begin print @sql end else begin exec(@sql) end
	
		fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID
	end

	close crsInfo
	deallocate crsInfo
GO


---------------------------------------------

-- dbo.procScoreFillinTableRefreshByPlanType
CREATE proc procScoreFillinTableRefreshByPlanType
	@planTypeGUID uniqueidentifier,
	@isDebug bit = 0
as
	declare @templateGUID uniqueidentifier
	declare crsTemplates cursor fast_forward for
		select distinct
			P.ModelTemplateGUID
		from
			XPlan P (readuncommitted)
		where
			P.PlanTypeGUID = @planTypeGUID
			and exists(select 1 from EMFModelTemplateLinkSource LS (readuncommitted) inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID where LS.ModelTemplateGUID = P.ModelTemplateGUID and LS.ParentScoreCompositeTableGUID != dbo.ZeroGUID() and MT.IsScoreFillinAdvancedMode = 1)
		
	open crsTemplates
	fetch next from crsTemplates into @templateGUID
	
	declare @whereClause nvarchar(max) = ''
	while (@@FETCH_STATUS = 0) begin
		set @whereClause = ' in(select xp.PlanGUID from XPlan xp (readuncommitted) where xp.PlanTypeGUID = ''' + cast(@planTypeGUID as nvarchar(36)) + ''' and xp.ModelTemplateGUID = ''' + cast(@templateGUID as nvarchar(36)) + ''')'
		exec [dbo].[procScoreFillinTableRefreshWorker] @templateGUID, @whereClause, @isDebug
		
		fetch next from crsTemplates into @templateGUID
	end
	
	close crsTemplates
	deallocate crsTemplates
GO


---------------------------------------------

-- dbo.procScoreFillinTableRefreshWorker
create proc [dbo].[procScoreFillinTableRefreshWorker]
	@modelTemplateGUID uniqueidentifier,
	@modelGUIDWhereClause nvarchar(max),
	@isDebug bit = 0
as
	set nocount on
	
	declare @tableName nvarchar(150)
	declare @phKeyName nvarchar(100)
	declare @phDimTable nvarchar(450)
	declare @fillinKeyName nvarchar(100)
	declare @fillinDimTable nvarchar(450)
	declare crsInfo cursor fast_forward for 
		select distinct
			'ScoreFillin_' + replace(A2.DimensionName, ' ', '') as TableName,
			A1.SQLColumnName as PHKeyName,
			A1.DimensionSQLObjectExpression as PHDimTable,
			A2.SQLColumnName as FillinKeyName,
			A2.DimensionSQLObjectExpression as FillinDimTable
		from
			ScoreCompositeLink CL (readuncommitted)
			inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID
			inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID
			inner join EMFModelTemplateLinkSource LS (readuncommitted) on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID
			inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID
		where
			MT.ModelTemplateGUID = @modelTemplateGUID
			and CL.IsPlaceholder = 1
			and MT.IsScoreFillinAdvancedMode = 1

	open crsInfo
	fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable
	
	declare @sql nvarchar(max)
	while(@@FETCH_STATUS = 0) begin
		set @sql = '
			begin tran
			
			delete from data.' + @tableName + ' where ModelGUID ' + @modelGUIDWhereClause + ';
			
			insert into [data].[' + @tableName + '] ([FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID])
			select [FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID] 
			from ScoreFillin (readuncommitted)
			where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk) and ModelGUID ' + @modelGUIDWhereClause + ';
			
			update FI set FI.' + @phKeyName + ' = PH.' + @phKeyName + ' from data.' + @tableName + ' FI inner join ' + @phDimTable + ' PH on PH.MemberGUID = FI.PlaceholderSectionMemberGUID where FI.ModelGUID ' + @modelGUIDWhereClause + ';
			update FI set FI.' + @fillinKeyName + ' = PH.' + @fillinKeyName + ' from data.' + @tableName + ' FI inner join ' + @fillinDimTable + ' PH on PH.MemberGUID = FI.FillinMemberGUID where FI.ModelGUID ' + @modelGUIDWhereClause + ';
			
			commit tran
'
		if (@isDebug = 1) begin print @sql end else begin exec(@sql) end
	
		fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable
	end

	close crsInfo
	deallocate crsInfo
GO


---------------------------------------------

-- dbo.procScoreFixMeasureAggTypes
CREATE proc [dbo].[procScoreFixMeasureAggTypes]
AS

--AggType 1 = COUNT, safe for all score measures

--Fix Sums = 0
update ScoreMeasure set AggType = 1
	where AggType = 0
		AND (dbo.IsSQLNumericType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0)

--Fix Avg = 2
update ScoreMeasure set AggType = 1
	where AggType = 2
		AND (dbo.IsSQLNumericType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0)
		
--Fix Min = 3
update ScoreMeasure set AggType = 1
where AggType = 3
		AND (dbo.IsSQLNumericType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0)
		AND (dbo.IsSQLCharacterType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0)	
		AND (dbo.IsSQLDateTimeType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0)
	
--Fix Max = 4
update ScoreMeasure set AggType = 1
where AggType = 4
		AND (dbo.IsSQLNumericType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0)
		AND (dbo.IsSQLCharacterType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0)	
		AND (dbo.IsSQLDateTimeType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0)
GO


---------------------------------------------

-- dbo.procScoreGetDefaultAttributeValue
CREATE PROCEDURE [dbo].[procScoreGetDefaultAttributeValue](
	@AttributeGUID uniqueidentifier,
	@MemberGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
)
AS

--parameter(s)
--declare @AttributeGUID uniqueidentifier;
--set @AttributeGUID = 'A0965292-E374-4407-9C07-EE613A2F69D0';

----------------------------------------------------
-- Get all necessary values and save to variables
----------------------------------------------------
declare @DimensionExp varchar(256);
declare @KeyColumn varchar(128);
declare @AttColumn varchar(128);
declare @DefaultMemberGUID uniqueidentifier;

select 
	    @KeyColumn = K.SQLColumnName,
	    @AttColumn = Att.SQLColumnName,
	   @DimensionExp = [dbo].[GetSQLTableExpression](DIM.SQLSchemaName, DIM.SQLObjectName),
	   @DefaultMemberGUID = DIM.DefaultMemberGUID
	from dbo.ScoreAttribute K
		inner join ScoreDimensionGroup GK on GK.DimensionGroupGUID = K.DimensionGroupGUID
		inner join ScoreDimension DIM on GK.DimensionGUID = DIM.DimensionGUID
		inner join ScoreAttribute ATT on ATT.AttributeGUID = DIM.DefaultLookupKeyGUID
	where K.AttributeGUID = @AttributeGUID

print @DimensionExp;
print @AttColumn;

if (@MemberGUID <> '00000000-0000-0000-0000-000000000000') begin
	set @DefaultMemberGUID = @MemberGUID
end
----------------------------------------------------
--BUILD SQL
--   Note: Ignoring Security for Default Members
----------------------------------------------------
declare @sql varchar(max);
set @sql = '

	select 
		DIM.[' + @KeyColumn + '] as KeyValue,
		DIM.[' + @AttColumn + '] as AttributeValue
	from ' + @DimensionExp + ' DIM
	where
	   MemberGUID = ''' + CAST(@DefaultMemberGUID as nvarchar(64)) + '''
';
print @sql;
exec (@sql);
GO


---------------------------------------------

-- dbo.procScoreHierarchyPathGetQuery
create proc dbo.procScoreHierarchyPathGetQuery
	@hpath nvarchar(max),
	@isWhereOnly bit,
	@sql nvarchar(max) OUT
as
	select 
		@sql = dbo.straggr(a.SQLColumnName + ' = ''' + lvls.val + '''', ' AND ', '')
	from 
		viewScoreHierarchy h 
		inner join ScoreDimension d on d.DimensionGUID = h.DimensionGUID
		inner join viewScoreAttribute a on a.AttributeGUID = h.AttributeGUID
		inner join (select parts.pos - 2 as pos, parts.val from dbo.ConvertCSValuesToTable(@hpath, '|') parts where parts.pos > 2) lvls on lvls.pos = h.SortOrder
	where 
		d.SQLTableAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 1)
		and h.PathAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 2)

	declare @filter nvarchar(max)
	select 
		@filter = max(a.SQLColumnName + ' = ''' + al.FilterString + '''')
	from 
		ScoreHierarchy h
		inner join ScoreHierarchyAttributeLink al on al.HierarchyGUID = h.HierarchyGUID
		inner join ScoreDimension d on d.DimensionGUID = h.DimensionGUID
		inner join viewScoreAttribute a on a.AttributeGUID = al.FilterAttributeGUID
	where 
		d.SQLTableAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 1)
		and h.PathAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 2)
		and al.IsAttributeFiltered = 1
	if (@filter is not null and @filter != '') begin
		set @sql = @sql + ' AND ' + @filter
	end

	if (@isWhereOnly = 0) begin
		select
			@sql = 'select ' + a.SQLColumnName + ' from ' + d.SQLSchemaName + '.' + d.SQLObjectName + ' where ' + @sql
		from
			ScoreDimension d
			inner join viewScoreAttribute a on a.AttributeGUID = d.DefaultKeyGUID
		where
			d.SQLTableAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 1)
	end
GO


---------------------------------------------

-- dbo.procScoreLoadPlanGUIDForSecuredLootID
CREATE PROCEDURE [dbo].[procScoreLoadPlanGUIDForSecuredLootID](
	@SecuredID nvarchar(128)	
)
AS
BEGIN
	select coalesce((select top 1 PlanGUID from XPlan PLN where PLN.CachedLootID = @SecuredID), dbo.ZeroGUID())
END
GO


---------------------------------------------

-- dbo.procScoreLoadSecuredConfigIDForPlan
CREATE PROC [dbo].[procScoreLoadSecuredConfigIDForPlan](
	@PlanGUID uniqueidentifier
)
AS
	select CachedLootID from XPlan where PlanGUID = @PlanGUID

	--declare @SQLSchemaName nvarchar(128);
	--declare @SQLObjectName nvarchar(max);
	--declare @AttributeColumn nvarchar(4000);
	--declare @Prefix nvarchar(128);

	--select top 1 
	--	@SQLSchemaName = DIM.SQLSchemaName,
	--	@SQLObjectName = DIM.SQLObjectName,
	--	@AttributeColumn =  coalesce(OATTR.SQLColumnName, ATTR.SQLColumnName),
	--	@Prefix = coalesce(OATTR.SecuredLootGroupPrefix, ATTR.SecuredLootGroupPrefix)
	--from XPLan PLN
	--	inner join PlanType PLNTYPE on PLN.PlanTypeGUID = PLNTYPE.PlanTypeGUID
	--	inner join ScoreDimension DIM on DIM.DimensionGUID = PLNTYPE.DimensionGUID
	--	inner join ScoreAttribute ATTR on ATTR.DimensionGUID = DIM.DimensionGUID
	--	left join ScoreAttribute OATTR on OATTR.DimensionGUID = DIM.DimensionGUID
	--		and OATTR.IsSecuredLootConfigID = 1
	--where ATTR.IsSecuredLootID = 1
	--	and PLN.PlanGUID = @PlanGUID

	--declare @sql varchar(max);
	--if(@Prefix = '') begin
	--	set @sql = '
	--		select cast(' + @AttributeColumn + ' as nvarchar) as LootID from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' 
	--		where MemberGUID = ''' + cast(@PlanGUID as nvarchar(36)) + '''

	--	';
	--end else begin
	--	set @sql = '
	--		select ''' + @Prefix + ''' + ''|'' + cast(' + @AttributeColumn + ' as nvarchar) as LootID from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' 
	--		where MemberGUID = ''' + cast(@PlanGUID as nvarchar(36)) + '''

	--	';
	--end

	--exec (@sql);
GO


---------------------------------------------

-- dbo.procScoreLoadSecuredLootIDForPlan
CREATE PROC [dbo].[procScoreLoadSecuredLootIDForPlan] (
	@PlanGUID uniqueidentifier
)
AS

select CachedLootID from XPlan where PlanGUID = @PlanGUID

--declare @SQLSchemaName nvarchar(128);
--declare @SQLObjectName nvarchar(max);
--declare @AttributeColumn nvarchar(4000);
--declare @Prefix nvarchar(128);

--select top 1 
--	@SQLSchemaName = DIM.SQLSchemaName,
--	@SQLObjectName = DIM.SQLObjectName,
--	@AttributeColumn =  ATTR.SQLColumnName,
--	@Prefix = ATTR.SecuredLootGroupPrefix 
--from XPLan PLN
--	inner join PlanType PLNTYPE on PLN.PlanTypeGUID = PLNTYPE.PlanTypeGUID
--	inner join ScoreDimension DIM on DIM.DimensionGUID = PLNTYPE.DimensionGUID
--	inner join ScoreDimensionGroup DIMG on DIMG.DimensionGUID = DIM.DimensionGUID
--	inner join ScoreAttribute ATTR on ATTR.DimensionGroupGUID = DIMG.DimensionGroupGUID
--where PLN.PlanGUID = @PlanGUID and ATTR.IsSecuredLootID = 1

	
--declare @sql varchar(max);

--if(@Prefix = '') begin
--	set @sql = '
--		select cast(' + @AttributeColumn + ' as nvarchar) as LootID from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' 
--		where MemberGUID = ''' + CAST(@PlanGUID as varchar(max)) + '''

--	';
--end else begin
--	set @sql = '
--		select ''' + @Prefix + ''' + ''|'' + cast(' + @AttributeColumn + ' as nvarchar) as LootID from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' 
--		where MemberGUID = ''' + CAST(@PlanGUID as varchar(max)) + '''

--	';
--end

--print @sql;
--exec (@sql);
GO


---------------------------------------------

-- dbo.procScoreLoadSecuredLootIDForPlanShortcut
CREATE PROC [dbo].[procScoreLoadSecuredLootIDForPlanShortcut](
  @EntityGUID UNIQUEIDENTIFIER
)
AS
	--check xplan first because viewWFEntity filters out deleted plans
	if (exists(select 1 from dbo.XPlan where PlanGUID = @EntityGUID)) begin
		SELECT TOP 1 CachedLootID
		FROM [dbo].[XPlan]
		WHERE PlanGUID = @EntityGUID
	end else begin
		SELECT TOP 1 CachedLootID
		FROM [dbo].[viewWFEntity]
		WHERE EntityGUID = @EntityGUID
	end
GO


---------------------------------------------

-- dbo.procScoreLoadSecuredLootIDForPlansShortcut
CREATE PROC [dbo].[procScoreLoadSecuredLootIDForPlansShortcut](
	@PlanGUIDListCSV varchar(max)
)
AS
	select 
		PLN.PlanGUID as MemberGUID,
		PLN.CachedLootID as LootID
	from 
		XPLan PLN
	where 
		PLN.PlanGUID in (select * from dbo.CSVGuidsToTable (@PlanGUIDListCSV))
GO


---------------------------------------------

-- dbo.procScoreMeasureSchemaUpdate
create proc [dbo].[procScoreMeasureSchemaUpdate]
	@datatableguid uniqueidentifier = '00000000-0000-0000-0000-000000000000'
as

update
	obj
set
	obj.ColumnID = objschema.ColumnID,
	obj.ColumnTypeValue = objschema.ColumnTypeValue,
	obj.ColumnName = objschema.ColumnName,
	obj.ComputedValueDefinition = objschema.ComputedValueDefinition,
	obj.DefaultValueDefinition = objschema.DefaultValueDefinition,
	obj.ForeignKeyColumn = objschema.ForeignKeyColumn,
	obj.ForeignKeyOnDelete = objschema.ForeignKeyOnDelete,
	obj.ForeignKeySchema = objschema.ForeignKeySchema,
	obj.ForeignKeyTable = objschema.ForeignKeyTable,
	obj.IdentityIncrement = objschema.IdentityIncrement,
	obj.IdentitySeed = objschema.IdentitySeed,
	obj.IsComputed = objschema.IsComputed,
	obj.IsForeignKeyed = objschema.IsForeignKeyed,
	obj.IsIdentity = objschema.IsIdentity,
	obj.IsNullable = objschema.IsNullable,
	obj.IsPartOfPrimaryKey = objschema.IsPartOfPrimaryKey,
	obj.IsPartOfUniqueIndex = objschema.IsPartOfUniqueIndex,
	obj.IsPrimaryKey = objschema.IsPrimaryKey,
	obj.IsUniqueIndex = objschema.IsUniqueIndex,
	obj.MaxLength = objschema.MaxLength,
	obj.ObjectID = objschema.ObjectID,
	obj.ObjectName = objschema.ObjectName,
	obj.ObjectType = objschema.ObjectType,
	obj.Precision = objschema.Precision,
	obj.Scale = objschema.Scale,
	obj.SchemaName = objschema.SchemaName	
from
	ScoreMeasure obj
	inner join viewScoreMeasureSchemaInfo objschema on obj.MeasureGUID = objschema.MeasureGUID
where
	@datatableguid in (obj.datatableguid, dbo.zeroguid())
	and (
		obj.ColumnID <> objschema.ColumnID or
		obj.ColumnTypeValue <> objschema.ColumnTypeValue or
		obj.ColumnName <> objschema.ColumnName or
		obj.ComputedValueDefinition <> objschema.ComputedValueDefinition or
		obj.DefaultValueDefinition <> objschema.DefaultValueDefinition or
		obj.ForeignKeyColumn <> objschema.ForeignKeyColumn or
		obj.ForeignKeyOnDelete <> objschema.ForeignKeyOnDelete or
		obj.ForeignKeySchema <> objschema.ForeignKeySchema or
		obj.ForeignKeyTable <> objschema.ForeignKeyTable or
		obj.IdentityIncrement <> objschema.IdentityIncrement or
		obj.IdentitySeed <> objschema.IdentitySeed or
		obj.IsComputed <> objschema.IsComputed or
		obj.IsForeignKeyed <> objschema.IsForeignKeyed or
		obj.IsIdentity <> objschema.IsIdentity or
		obj.IsNullable <> objschema.IsNullable or
		obj.IsPartOfPrimaryKey <> objschema.IsPartOfPrimaryKey or
		obj.IsPartOfUniqueIndex <> objschema.IsPartOfUniqueIndex or
		obj.IsPrimaryKey <> objschema.IsPrimaryKey or
		obj.IsUniqueIndex <> objschema.IsUniqueIndex or
		obj.MaxLength <> objschema.MaxLength or
		obj.ObjectID <> objschema.ObjectID or
		obj.ObjectName <> objschema.ObjectName or
		obj.ObjectType <> objschema.ObjectType or
		obj.Precision <> objschema.Precision or
		obj.Scale <> objschema.Scale or
		obj.SchemaName <> objschema.SchemaName
	)
GO


---------------------------------------------

-- dbo.procScoreRebuildDimensionMemberView
--#notran#
CREATE proc [dbo].[procScoreRebuildDimensionMemberView]
	@isDebugOnly bit = 0
as
exec dbo.procRefreshViews --broken views will not be included in these debug views

declare @viewSQL varchar(max)
set @viewSQL = ''

declare @dropSql varchar(max)

set @dropSql ='
if dbo.ViewExists(''data'',''viewScoreDimensionMember'') = 1 begin
	drop view data.viewScoreDimensionMember
end

if dbo.ViewExists(''data'',''viewScoreFillInDetail'') = 1 begin
	drop view data.viewScoreFillInDetail
end

if dbo.ViewExists(''data'',''viewScoreFillInTemplateItemDetail'') = 1 begin
	drop view data.viewScoreFillInTemplateItemDetail
end

'
if (@isDebugOnly = 0) begin exec (@dropsql) end else begin exec dbo.procPrintLongText @dropsql end

--secured system sections
set @viewSQL = @viewSQL +'

create view data.viewScoreDimensionMember as
'

--secured dimensions
declare crsScoreDim CURSOR FOR
	select '
SELECT 
	cast(''' + cast(SD.DimensionGUID as varchar(36)) + ''' as uniqueidentifier) as DimensionGUID,
	''' + SD.FriendlyName + ''' as DimensionName,
	MemberGUID, 
	cast([' + sadlk.sqlcolumnname + '] as varchar(max)) as MemberName,
	cast([' + sadk.sqlcolumnname + '] as varchar(max)) as DefaultKey,
	''' + isnull(salid.securedlootgroupprefix,'Unsecure') +  '|'' + cast([' + isnull(salid.sqlcolumnname, sadk.sqlcolumnname) + '] as varchar(max)) as LootID
FROM [' + sd.sqlschemaname + '].[' + sd.sqlobjectname + ']'
	from 
		ScoreDimension SD
		inner join viewSysColumns col on sd.sqlschemaname = col.schemaname and sd.sqlobjectname = col.objectname and col.columnname = 'memberguid'
		
		inner join viewScoreAttributeCore30 SADLK on sd.dimensionguid = sadlk.dimensionguid and sd.defaultlookupkeyguid = sadlk.attributeguid
		inner join viewSysColumns SADLKcol on sd.sqlschemaname = SADLKcol.schemaname and sd.sqlobjectname = SADLKcol.objectname and SADLKcol.columnname = sadlk.sqlcolumnname
		
		inner join viewScoreAttributeCore30 SADK on sd.dimensionguid = sadk.dimensionguid and sd.defaultkeyguid = SADK.attributeguid
		inner join viewSysColumns sadkcol on sd.sqlschemaname = sadkcol.schemaname and sd.sqlobjectname = sadkcol.objectname and sadkcol.columnname = sadk.sqlcolumnname
		
		left join viewScoreAttributeCore30 SALID on sd.dimensionguid = salid.dimensionguid and salid.issecuredlootid = 1
	where
		(dbo.viewexists(sd.sqlschemaname,sd.sqlobjectname) = 1
		or dbo.tableexists(sd.sqlschemaname,sd.sqlobjectname) = 1)
		and sd.sqlschemaname + '.' + sd.sqlobjectname not in(select replace(replace(brokenviewname, '[', ''), ']', '') from dbo.RefreshViewsLog)

open crsScoreDim;

declare @dimsql varchar(max)
declare @cnt int
set @cnt = 0

FETCH NEXT FROM crsScoreDim into @dimsql
WHILE (@@FETCH_STATUS = 0) 	BEGIN

	if @cnt > 0 begin	
		set @viewSQL = @viewSQL  + '
		UNION ALL
		'
	end
	set @cnt = @cnt + 1
	set @viewSQL = @viewSQL  + '
	' + @dimsql
	FETCH NEXT FROM crsScoreDim into @dimsql
end

close crsscoredim
deallocate crsscoredim

if @cnt > 0 begin
	if (@isDebugOnly = 0) begin exec (@viewsql) end else begin exec dbo.procPrintLongText @viewsql end

	set @viewSQL = '

create view data.[viewScoreFillInTemplateItemDetail] as
select	
	fit.*,
	secmem.DimensionName as SectionDimensionName,
	secmem.MemberName as SectionMemberName,
	conmem.DimensionName as ConstantDimensionName,
	conmem.MemberName as ConstantMemberName
from
	ScoreFillInTemplateItem fit
	left join data.viewScoreDimensionMember secmem on fit.PlaceholderSectionMemberGUID = secmem.MemberGUID
	left join data.viewScoreDimensionMember conmem on fit.ConstantMemberGUID = conmem.MemberGUID'
	
	if (@isDebugOnly = 0) begin exec (@viewsql) end else begin exec dbo.procPrintLongText @viewsql end
	
	set @viewSQL = '
create view [data].[viewScoreFillinDetail] as
select
	fi.ModelGUID,
	sdmm.MemberName as ModelName,
	fi.PlaceholderSectionMemberGUID,
	sdmph.DimensionName as PlaceholderSectionDimensionName,
	sdmph.DefaultKey as PlaceholderSectionDefaultKey,
	sdmph.LootID as PlaceholderSectionLootID,
	sdmph.MemberName as PlaceholderSectionMemberName,
	fi.PlaceholderIndex,
	fi.FillinMemberGUID,
	sdmfi.DimensionName as FillInDimensionName,
	sdmfi.DefaultKey as FillInDefaultKey,
	sdmfi.LootID as FillInLootID,
	sdmfi.MemberName as FillInMemberName
from
	ScoreFillin fi
	left join data.viewScoreDimensionMember sdmm on fi.ModelGUID = sdmm.MemberGUID
	left join data.viewScoreDimensionMember sdmph on fi.PlaceholderSectionMemberGUID = sdmph.MemberGUID
	left join data.viewScoreDimensionMember sdmfi on fi.FillinMemberGUID = sdmfi.MemberGUID
	'
	if (@isDebugOnly = 0) begin exec (@viewsql) end else begin exec dbo.procPrintLongText @viewsql end
end
GO


---------------------------------------------

-- dbo.procScoreRemoveDeletedAll
CREATE proc procScoreRemoveDeletedAll
as
exec [procScoreRunForManyStructures] 'delete from [{schema}].[{object}] where isdeleted = 1', 'where iswrittentodb = 1', 1
GO


---------------------------------------------

-- dbo.procScoreRemoveLootRefreshTrigger
CREATE proc [dbo].[procScoreRemoveLootRefreshTrigger](
	@aDimensionGUID uniqueidentifier
)
AS

    --get schema and object
    declare @Schema varchar(128);
    declare @Object varchar(128);
    
    select @Schema = Sqlschemaname, @Object = SQLObjectName from ScoreDimension where DimensionGUID = @aDimensionGUID;
    
    declare @triggerName varchar(max);
    select @triggerName = (select [dbo].GetScoreLootRefreshTriggerName(@aDimensionGUID));
     
    if ([dbo].[IsView](@Schema, @Object) = 1)
    BEGIN
		print 'Removing Triggers from Underlying Tables';
		declare @TableSchema varchar(128);
		declare @TableName varchar(128);
		declare @TableTriggerName varchar(128);
		
		DECLARE TableCursor  CURSOR
		FOR select * from [dbo].GetViewUnderlyingTables(@Schema, @Object)
		
		OPEN TableCursor;
		Fetch Next from TableCursor INTO  @TableName, @TableSchema;
		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			set @TableTriggerName = Substring((select [dbo].GetScoreLootRefreshTriggerName(@aDimensionGUID)) + '_' + @TableName, 0, 128);
			if ([dbo].IsTriggerExist(@TableTriggerName) = 1)
			BEGIN
				declare @tablesql varchar(max);
				set @tablesql = '
					DROP TRIGGER [' + @TableSchema + '].[' + @TableTriggerName + ']
					';
				print @tablesql;
				exec (@tablesql);
			END
			Fetch Next from TableCursor INTO  @TableName, @TableSchema;
		END
		CLOSE TableCursor;
		DEALLOCATE TableCursor;
    END
    
    if ([dbo].IsTriggerExist(@triggerName)= 1)
    BEGIN
    
		declare @sql varchar(max);
		set @sql = '
			DROP TRIGGER [' + @Schema + '].[' + @triggerName + ']
		';
		print @sql;
		exec (@sql);
	END
	ELSE
		print 'Trigger does not exist.'
GO


---------------------------------------------

-- dbo.procScoreRunForManyStructures
CREATE proc [dbo].[procScoreRunForManyStructures]
	@execsql varchar(max)
	,@structurefiltersql varchar(max) = ''
	,@exec bit = 0
	,@allTogether bit = 0
as

--set @execsql = '
--	select ''{mdcname}'', count(*) from zzemfmodeldata_{mdcguidfriendly}
--'
--set @structurefiltersql = '
--where friendlyname like ''lrfp%''
--'

declare @structuresql varchar(max)

set @structuresql = '
select
	datatableguid, friendlyname, sqlschemaname, sqlobjectname, sqltablealias
from
	scoredatatable
' + @structurefiltersql

create table #mdcs (datatableguid uniqueidentifier, friendlyname nvarchar(64), sqlschemaname nvarchar(max), sqlobjectname nvarchar(max), sqltablealias nvarchar(max))

insert into #mdcs
exec (@structuresql)	

declare @sdtguid uniqueidentifier
declare @sdtguidfriendly varchar(36)
declare @sdtname nvarchar(64)
declare @sdtnamefriendly nvarchar(64)
declare @sqlschemaname nvarchar(max)
declare @sqlobjectname nvarchar(max)
declare @sqltablealias nvarchar(max)
declare @sql varchar(max)

	declare crsMDC CURSOR FOR
		select *
		from #mdcs
		
	open crsMDC;
	
	set @sql = ''
	
	FETCH NEXT FROM crsMDC into @sdtguid, @sdtname, @sqlschemaname, @sqlobjectname, @sqltablealias
	WHILE (@@FETCH_STATUS = 0) 
		BEGIN
		
			set @sdtguidfriendly = replace(cast(@sdtguid as varchar(36)),'-','_')
			set @sdtnamefriendly = REPLACE(@sdtname,' ','')
			set @sdtnamefriendly = REPLACE(@sdtnamefriendly,'-','')
			set @sdtnamefriendly = REPLACE(@sdtnamefriendly,'.','')
			
			if @allTogether = 1 begin
				set @sql = @sql + replace(replace(replace(replace(replace(replace(replace(@execsql,'{mdcguid}',cast(@sdtguid as varchar(36))), '{mdcname}',@sdtname),'{mdcguidfriendly}',@sdtguidfriendly),'{mdcnamefriendly}',@sdtnamefriendly),'{schema}',@sqlschemaname),'{object}',@sqlobjectname),'{alias}',@sqltablealias)
			end else begin
				set @sql = replace(replace(replace(replace(replace(replace(replace(@execsql,'{mdcguid}',cast(@sdtguid as varchar(36))), '{mdcname}',@sdtname),'{mdcguidfriendly}',@sdtguidfriendly),'{mdcnamefriendly}',@sdtnamefriendly),'{schema}',@sqlschemaname),'{object}',@sqlobjectname),'{alias}',@sqltablealias)
				if @exec = 1 begin
					exec(@sql)
				end else begin
					print @sql
				end
			end

			
			

			FETCH NEXT FROM crsMDC into  @sdtguid, @sdtname, @sqlschemaname, @sqlobjectname, @sqltablealias
		END
	close crsMDC;
	DEALLOCATE crsMDC;

			if @allTogether = 1 begin
				if @exec = 1 begin
					exec(@sql)
				end else begin
					print @sql
				end
			end


	
drop table #mdcs
GO


---------------------------------------------

-- dbo.procScoreSecurityTriggersGet
create proc procScoreSecurityTriggersGet
	@dimensionSchema nvarchar(10),
	@dimensionTableName nvarchar(100)
as
	select 
		d.FriendlyName as RefreshDimension, 
		'exec procScoreSetDimensionSecurity30 ''' + cast(d.DimensionGUID as nvarchar(36)) + ''',0,0' as RefreshSQL,
		'drop trigger fw.' + tg.Name as DropSQL 
	from 
		sys.triggers tg 
		inner join [dbo].[ScoreDimension] d on tg.name like '%' + replace(cast(d.DimensionGUID as nvarchar(36)),'-', '') + '%' where tg.parent_id in(select t.object_id from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where t.name = @dimensionTableName and s.name = @dimensionSchema) 
		and name like '%ScoreDimension%'
GO


---------------------------------------------

-- dbo.procScoreSetDimensionSecurity30
CREATE proc [dbo].[procScoreSetDimensionSecurity30]
(
	@aDimensionGUID UNIQUEIDENTIFIER,
	@IsDebugOnly bit = 0,
	@IsUsingVersionColumn bit = 0,
	@IsOverrideSharedLoot bit = 0,
	@source nvarchar(100) = 'procScoreSetDimensionSecurity30'
)
AS
BEGIN
	set nocount on
	IF (
	   (
		   SELECT
			   COUNT(*)
		   FROM
			   [dbo].[ScoreDimension] (READUNCOMMITTED)
		   WHERE
			   DimensionGUID = @aDimensionGUID AND
			   IsSecurityTriggersEnabled = 1
	   ) = 0
	   )
	BEGIN
		RETURN;
	END;
	ELSE
	BEGIN
		
		DECLARE @json VARCHAR(1000) = '{' +
			'"DimensionGuid":"' + CAST(@aDimensionGUID AS VARCHAR(50)) + '"' +
			',"IsDebugOnly":' + CAST(@IsDebugOnly AS VARCHAR(1)) + 
			',"IsUsingVersionColumn":' + CAST(@IsUsingVersionColumn AS VARCHAR(1)) + 
			',"IsOverrideSharedLoot":' + CAST(@IsOverrideSharedLoot AS VARCHAR(1)) + 
		'}';
		
		DECLARE @statusCode INT;
		EXEC dbo.procCreateTask
			@taskTypeName = 'Strata.CS.Jazz.Biz.Security.Tasks.ScoreSetDimensionSecurityTask, Strata.CS.Jazz.Biz', -- varchar(1000)
			@contextXML = @json,                                                                                   -- varchar(1000)
			@userName = 'Strata',
			@statusCode = @statusCode OUTPUT,
			@taskSource = @source;

	END;
END;
GO


---------------------------------------------

-- dbo.procScoreSetDimensionSecurity30InsertNew
CREATE proc [dbo].[procScoreSetDimensionSecurity30InsertNew]
(
	@aDimensionGUID uniqueidentifier,
	@aMemberGUID uniqueidentifier,
	@IsDebugOnly bit = 0,
	@IsUsingVersionColumn bit = 0,
	@IsOverrideSharedLoot bit = 0
)
AS

declare @sql nvarchar(max);
set @sql = '';

declare @SQLSchemaName nvarchar(128);
declare @SQLObjectName nvarchar(max);
declare @IsSecured bit;
declare @IsSharingSecurity bit;
select 
	@SQLSchemaName = SQLSchemaName, 
	@SQLObjectName = SQLObjectName,
	@IsSecured = IsSecured,
	@IsSharingSecurity = IsSharingSecurity
from ScoreDimension (readuncommitted) where DimensionGUID = @aDimensionGUID;


if (@SQLObjectName is null) begin
	--declare @err nvarchar(max);
	--set @err = 'Dimension with GUID ' + cast(@aDimensionGUID as nvarchar(64)) + ' does not exist. Cannot set security on dimension.';
	--RAISERROR (@err,15,1);
	RETURN;
end
if (@IsSecured = 0)
BEGIN
	--NOT SECURED, DO NOTHING
	RETURN;
END
if (@IsSharingSecurity = 1 and @IsOverrideSharedLoot = 0) 
BEGIN
	--LOOTS are handled from another dimension. No Need to refresh
	RETURN;
END

declare @lootIDColumn nvarchar(128)
declare @lootIDExpression nvarchar(128)
select @lootIDColumn = 'START.' + SQLColumnName, @lootIDExpression = SecuredLootGroupPrefix from viewScoreAttributeCore30 where DimensionGUID = @aDimensionGUID and IsSecuredLootID = 1

if @lootIDExpression = '' begin
	set @lootIDExpression  = 'cast(' + @lootIDColumn + ' as nvarchar(128))'
end
else begin
	set @lootIDExpression  = '''' + @lootIDExpression + '|'' + cast(' + @lootIDColumn + ' as nvarchar(128))'
end

set @sql = @sql + '
	IF (SELECT COUNT(*) FROM ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' WHERE MemberGUID = ''' + CAST(@aMemberGUID as nvarchar(36)) + ''') = 0 BEGIN
		RETURN
	END

	--DELETE FROM S3Loot WHERE LootID IN (SELECT ' + @lootIDExpression + ' FROM ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START) AND PermissionSetID <> (SELECT SD.PermissionSetID FROM ScoreDimension SD WHERE SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + ''')
	INSERT INTO S3Loot (LootID, PermissionSetID)
	SELECT DISTINCT
		' + @lootIDExpression + ', SD.PermissionSetID
	FROM
		' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START
		CROSS JOIN ScoreDimension (readuncommitted) SD 
	WHERE
		SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + '''
		AND NOT EXISTS (SELECT 1 FROM S3Loot LX WHERE LX.LootID = ' + @lootIDExpression  + ')
		AND START.MemberGUID = ''' + CAST(@aMemberGUID as nvarchar(36)) + '''
'

set @sql = @sql + '
	CREATE TABLE #S3LootGroup (LootID nvarchar(128), LootGroupID nvarchar(128))
	
	INSERT INTO #S3LootGroup (LootID, LootGroupID)
	
	
';

DECLARE AttributeCursor  CURSOR
FOR select 'START.' + SQLColumnName as ColumnName, SecuredLootGroupPrefix
	from viewScoreAttributeCore30 ATT 
	where ATT.IsSecuredLootGroupID = 1 and ATT.DimensionGUID = @aDimensionGUID;

declare @ColName nvarchar(max);
declare @Prefix nvarchar(128);
declare @expression nvarchar(128);
declare @expressionWithPrefix nvarchar(128);

declare @i int;
set @i = 0;
OPEN AttributeCursor;
Fetch Next from AttributeCursor INTO  @ColName, @Prefix;
WHILE (@@FETCH_STATUS = 0)
BEGIN
	if (@i <> 0) begin
		set @sql = @sql + 'UNION ALL
		';
	end
	set @expression = 'ltrim(rtrim(cast(' + @ColName + ' as nvarchar(128))))'
	if @Prefix = '' begin
		set @expressionWithPrefix = @expression
	end
	else begin
		set @expressionWithPrefix = '''' + @Prefix + '|'' + ' + @expression
	end
	
	set @sql = @sql + '	
		select ' + @lootIDExpression  + ', ' + @expressionWithPrefix + ' from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START
		WHERE
			MemberGUID = ''' + CAST(@aMemberGUID as nvarchar(36)) + ''' AND
			' + @expression + ' <> ''''
			'

			--and not exists (select 1 from dbo.S3LootGroup LOOTGROUP 
			--				where LOOTGROUP.LootID = ' + @lootIDExpression + '
			--						and LOOTGROUP.LootGroupID = ' + @expressionWithPrefix + '
			--			)
								
	
	
	set @i = @i + 1;
	Fetch Next from AttributeCursor INTO  @ColName, @Prefix;
END;
CLOSE AttributeCursor;
DEALLOCATE AttributeCursor;

set @sql = @sql + '
--create index idx_lootid on #s3lootgroup(lootid)

--add valid ones
INSERT INTO S3LootGroup (LootID, LootGroupID)
SELECT DISTINCT
	lootid, lootgroupid
FROM	
	#S3LootGroup nlg
WHERE
	NOT EXISTS (
		SELECT 1
		FROM S3LootGroup lg
		WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid
	)	
'

set @sql = @sql + '
DROP TABLE #S3LootGroup
'

if @IsDebugOnly = 0 begin
	exec (@sql)
end else begin
	print @sql
end
GO


---------------------------------------------

-- dbo.procScoreSetDimensionSecurity30Sync
CREATE proc [dbo].[procScoreSetDimensionSecurity30Sync]
(
	@aDimensionGUID uniqueidentifier,
	@IsDebugOnly bit = 0,
	@IsUsingVersionColumn bit = 0,
	@IsOverrideSharedLoot bit = 0
)
AS
set nocount on

declare @sql nvarchar(max);
set @sql = '';

declare @SQLSchemaName nvarchar(128);
declare @SQLObjectName nvarchar(max);
declare @IsSecured bit;
declare @IsSharingSecurity bit;
declare @IsSecurityReadOnly bit;
select 
	@SQLSchemaName = SQLSchemaName, 
	@SQLObjectName = SQLObjectName,
	@IsSecured = IsSecured,
	@IsSharingSecurity = IsSharingSecurity,
	@IsSecurityReadOnly = IsSecurityReadOnly
from ScoreDimension (readuncommitted) where DimensionGUID = @aDimensionGUID;

--if security is read only, we assume another dimension is maintaining the security for us
if (@IsSecurityReadOnly = 1) begin
	return
end

if (@SQLObjectName is null) begin
	--declare @err nvarchar(max);
	--set @err = 'Dimension with GUID ' + cast(@aDimensionGUID as nvarchar(64)) + ' does not exist. Cannot set security on dimension.';
	--RAISERROR (@err,15,1);
	RETURN;
end
if (@IsSecured = 0)
BEGIN
	--NOT SECURED, DO NOTHING
	RETURN;
END
if (@IsSharingSecurity = 1 and @IsOverrideSharedLoot = 0) 
BEGIN
	--LOOTS are handled from another dimension. No Need to refresh
	RETURN;
END

declare @eventName varchar(64)
set @eventName = 'SBS' + CAST(@aDimensionGUID as varchar(36))
declare @lastRunVersion timestamp
select @lastRunVersion = dbo.GetEventVersion(@eventName)

declare @lootIDColumn nvarchar(128)
declare @lootIDExpression nvarchar(128)
select @lootIDColumn = 'START.' + SQLColumnName, @lootIDExpression = SecuredLootGroupPrefix from viewScoreAttributeCore30 where DimensionGUID = @aDimensionGUID and IsSecuredLootID = 1

if @lootIDExpression = '' begin
	set @lootIDExpression  = 'cast(' + @lootIDColumn + ' as nvarchar(128))'
end
else begin
	set @lootIDExpression  = '''' + @lootIDExpression + '|'' + cast(' + @lootIDColumn + ' as nvarchar(128))'
end

set @sql = @sql + '
	--DELETE FROM S3Loot WHERE LootID IN (SELECT ' + @lootIDExpression + ' FROM ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START) AND PermissionSetID <> (SELECT SD.PermissionSetID FROM ScoreDimension SD WHERE SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + ''')
	INSERT INTO S3Loot (LootID, PermissionSetID)
	SELECT DISTINCT
		' + @lootIDExpression + ', SD.PermissionSetID
	FROM
		' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START
		CROSS JOIN ScoreDimension SD (readuncommitted)
	WHERE
		SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + '''
		AND NOT EXISTS (SELECT 1 FROM S3Loot LX WHERE LX.LootID = ' + @lootIDExpression  + ')
'
if @IsUsingVersionColumn = 1 begin
		set @sql = @sql + ' AND START.Version > @lastRunVersion'
end


set @sql = @sql + '
	CREATE TABLE #S3LootGroup (LootID nvarchar(128), LootGroupID nvarchar(128))
	
	INSERT INTO #S3LootGroup (LootID, LootGroupID)
	
	
';

DECLARE AttributeCursor  CURSOR
FOR select 'START.' + SQLColumnName as ColumnName, SecuredLootGroupPrefix
	from viewScoreAttributeCore30 ATT 
	where ATT.IsSecuredLootGroupID = 1 and ATT.DimensionGUID = @aDimensionGUID;

declare @ColName nvarchar(max);
declare @Prefix nvarchar(128);
declare @expression nvarchar(128);
declare @expressionWithPrefix nvarchar(128);

declare @i int;
set @i = 0;
OPEN AttributeCursor;
Fetch Next from AttributeCursor INTO  @ColName, @Prefix;
WHILE (@@FETCH_STATUS = 0)
BEGIN
	if (@i <> 0) begin
		set @sql = @sql + 'UNION ALL
		';
	end
	set @expression = 'ltrim(rtrim(cast(' + @ColName + ' as nvarchar(128))))'
	if @Prefix = '' begin
		set @expressionWithPrefix = @expression
	end
	else begin
		set @expressionWithPrefix = '''' + @Prefix + '|'' + ' + @expression
	end
	
	set @sql = @sql + '	
		select ' + @lootIDExpression  + ', ' + @expressionWithPrefix + ' from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START
		WHERE
			' + @expression + ' <> ''''
			'
if @IsUsingVersionColumn = 1 begin
		set @sql = @sql + ' AND START.Version > @lastRunVersion
		'
end

			--and not exists (select 1 from dbo.S3LootGroup LOOTGROUP 
			--				where LOOTGROUP.LootID = ' + @lootIDExpression + '
			--						and LOOTGROUP.LootGroupID = ' + @expressionWithPrefix + '
			--			)
								
	
	
	set @i = @i + 1;
	Fetch Next from AttributeCursor INTO  @ColName, @Prefix;
END;
CLOSE AttributeCursor;
DEALLOCATE AttributeCursor;

set @sql = @sql + '
create index idx_lootid on #s3lootgroup(lootid)

--delete invalid ones
while (1 = 1) begin
	DELETE top(1000) lg FROM S3LootGroup lg WHERE
		lg.LootID IN (select nlg.LootID from #S3LootGroup nlg)
		and NOT EXISTS (
			SELECT 1
			FROM #S3LootGroup  nlg
			WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid
		)

	if (@@rowcount = 0) break
end

--add valid ones
CREATE TABLE #S3LootGroupInsert (RowID int primary key identity, LootID nvarchar(128), LootGroupID nvarchar(128))
INSERT INTO	#S3LootGroupInsert (LootID, LootGroupID)
SELECT DISTINCT
	lootid, lootgroupid
FROM	
	#S3LootGroup nlg
WHERE
	NOT EXISTS (
		SELECT 1
		FROM S3LootGroup lg
		WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid
	)	
declare @inscount int = 1
declare @insmax int
select @insmax = max(RowID) from #S3LootGroupInsert
while(@inscount <= @insmax) begin
	INSERT INTO S3LootGroup (LootID, LootGroupID)
	select nlg.LootID, nlg.LootGroupID from #S3LootGroupInsert nlg where nlg.RowID >= @inscount and nlg.RowID < @inscount + 1000
		and NOT EXISTS (
			SELECT 1
			FROM S3LootGroup lg
			WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid
		)	
	
	set @inscount = @inscount + 1000
end
'

set @sql = @sql + '
DROP TABLE #S3LootGroup
DROP TABLE #S3LootGroupInsert
'

if @IsDebugOnly = 0 begin
	--exec (@sql);
	exec sp_executesql @sql,N'@lastRunVersion timestamp', @lastRunVersion = @lastRunVersion--
	
	exec procEventupdate @eventName	
end else begin
	print @sql
end
GO


---------------------------------------------

-- dbo.procScoreSetDimensionSecurity30UpdateSingle
CREATE proc [dbo].[procScoreSetDimensionSecurity30UpdateSingle]
(
	@aDimensionGUID uniqueidentifier,
	@aMemberGUID uniqueidentifier,
	@IsDebugOnly bit = 0,
	@IsUsingVersionColumn bit = 0,
	@IsOverrideSharedLoot bit = 0
)
AS
set nocount on

declare @sql nvarchar(max);
set @sql = '';

declare @SQLSchemaName nvarchar(128);
declare @SQLObjectName nvarchar(max);
declare @IsSecured bit;
declare @IsSharingSecurity bit;
declare @IsSecurityReadOnly bit;
select 
	@SQLSchemaName = SQLSchemaName, 
	@SQLObjectName = SQLObjectName,
	@IsSecured = IsSecured,
	@IsSharingSecurity = IsSharingSecurity,
	@IsSecurityReadOnly = IsSecurityReadOnly
from ScoreDimension (readuncommitted) where DimensionGUID = @aDimensionGUID;

--if security is read only, we assume another dimension is maintaining the security for us
if (@IsSecurityReadOnly = 1) begin
	return
end

if (@SQLObjectName is null) begin
	--declare @err nvarchar(max);
	--set @err = 'Dimension with GUID ' + cast(@aDimensionGUID as nvarchar(64)) + ' does not exist. Cannot set security on dimension.';
	--RAISERROR (@err,15,1);
	RETURN;
end
if (@IsSecured = 0)
BEGIN
	--NOT SECURED, DO NOTHING
	RETURN;
END
if (@IsSharingSecurity = 1 and @IsOverrideSharedLoot = 0) 
BEGIN
	--LOOTS are handled from another dimension. No Need to refresh
	RETURN;
END

declare @lootIDColumn nvarchar(128)
declare @lootIDExpression nvarchar(128)
select @lootIDColumn = 'START.' + SQLColumnName, @lootIDExpression = SecuredLootGroupPrefix from viewScoreAttributeCore30 where DimensionGUID = @aDimensionGUID and IsSecuredLootID = 1

if @lootIDExpression = '' begin
	set @lootIDExpression  = 'cast(' + @lootIDColumn + ' as nvarchar(128))'
end
else begin
	set @lootIDExpression  = '''' + @lootIDExpression + '|'' + cast(' + @lootIDColumn + ' as nvarchar(128))'
end

set @sql = @sql + '
	INSERT INTO S3Loot (LootID, PermissionSetID)
	SELECT DISTINCT
		' + @lootIDExpression + ', SD.PermissionSetID
	FROM
		' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START
		CROSS JOIN ScoreDimension SD (readuncommitted)
	WHERE
		SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + '''
		AND START.MemberGUID = ''' + cast(@aMemberGUID as varchar(36)) + '''
		AND NOT EXISTS (SELECT 1 FROM S3Loot LX WHERE LX.LootID = ' + @lootIDExpression  + ')
'

set @sql = @sql + '
	CREATE TABLE #S3LootGroup (LootID nvarchar(128), LootGroupID nvarchar(128))
	
	INSERT INTO #S3LootGroup (LootID, LootGroupID)
	
	
';

DECLARE AttributeCursor  CURSOR
FOR select 'START.' + SQLColumnName as ColumnName, SecuredLootGroupPrefix
	from viewScoreAttributeCore30 ATT 
	where ATT.IsSecuredLootGroupID = 1 and ATT.DimensionGUID = @aDimensionGUID;

declare @ColName nvarchar(max);
declare @Prefix nvarchar(128);
declare @expression nvarchar(128);
declare @expressionWithPrefix nvarchar(128);

declare @i int;
set @i = 0;
OPEN AttributeCursor;
Fetch Next from AttributeCursor INTO  @ColName, @Prefix;
WHILE (@@FETCH_STATUS = 0)
BEGIN
	if (@i <> 0) begin
		set @sql = @sql + 'UNION ALL
		';
	end
	set @expression = 'ltrim(rtrim(cast(' + @ColName + ' as nvarchar(128))))'
	if @Prefix = '' begin
		set @expressionWithPrefix = @expression
	end
	else begin
		set @expressionWithPrefix = '''' + @Prefix + '|'' + ' + @expression
	end
	
	set @sql = @sql + '	
		select ' + @lootIDExpression  + ', ' + @expressionWithPrefix + ' from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START
		WHERE
			' + @expression + ' <> ''''
			AND START.MemberGUID = ''' + cast(@aMemberGUID as varchar(36)) + '''
			'

			--and not exists (select 1 from dbo.S3LootGroup LOOTGROUP 
			--				where LOOTGROUP.LootID = ' + @lootIDExpression + '
			--						and LOOTGROUP.LootGroupID = ' + @expressionWithPrefix + '
			--			)
								
	
	
	set @i = @i + 1;
	Fetch Next from AttributeCursor INTO  @ColName, @Prefix;
END;
CLOSE AttributeCursor;
DEALLOCATE AttributeCursor;

set @sql = @sql + '
create index idx_lootid on #s3lootgroup(lootid)

--delete invalid ones
while (1 = 1) begin
	DELETE top(1000) lg FROM S3LootGroup lg WHERE
		lg.LootID IN (select nlg.LootID from #S3LootGroup nlg)
		and NOT EXISTS (
			SELECT 1
			FROM #S3LootGroup  nlg
			WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid
		)

	if (@@rowcount = 0) break
end

--add valid ones
CREATE TABLE #S3LootGroupInsert (RowID int primary key identity, LootID nvarchar(128), LootGroupID nvarchar(128))
INSERT INTO	#S3LootGroupInsert (LootID, LootGroupID)
SELECT DISTINCT
	lootid, lootgroupid
FROM	
	#S3LootGroup nlg
WHERE
	NOT EXISTS (
		SELECT 1
		FROM S3LootGroup lg
		WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid
	)	
declare @inscount int = 1
declare @insmax int
select @insmax = max(RowID) from #S3LootGroupInsert
while(@inscount <= @insmax) begin
	INSERT INTO S3LootGroup (LootID, LootGroupID)
	select LootID, LootGroupID from #S3LootGroupInsert where RowID >= @inscount and RowID < @inscount + 1000
	
	set @inscount = @inscount + 1000
end
'

set @sql = @sql + '
DROP TABLE #S3LootGroup
DROP TABLE #S3LootGroupInsert
'

if @IsDebugOnly = 0 begin
	exec (@sql)
end else begin
	print @sql
end
GO


---------------------------------------------

-- dbo.procScoreSyncDimensionGroups
CREATE proc [dbo].[procScoreSyncDimensionGroups] (
	@DimensionGUID uniqueidentifier,
	@IsDebugOnly bit = 0
)
AS
BEGIN


declare @PrimarySchema sysname;
declare @PrimaryObject sysname;

select 
	@PrimaryObject = DG.ObjectName,
	@PrimarySchema = DG.SchemaName
from ScoreDimension D
	inner join ScoreDimensionGroup DG on DG.DimensionGUID = D.DimensionGUID 
where DG.DimensionGroupGUID = D.PrimaryGroupGUID and D.DimensionGUID = @DimensionGUID;

if (@PrimarySchema is null or @PrimaryObject is null)
begin
	print 'Unable to find Primary Group';
	return;
end

--cursor over secondaries
declare @GroupSchema sysname;
declare @GroupObject sysname;

declare crsCursor CURSOR LOCAL FAST_FORWARD FOR
	select 
		DG.SchemaName,
		DG.ObjectName
	from ScoreDimension D
		inner join ScoreDimensionGroup DG on DG.DimensionGUID = D.DimensionGUID 
	where DG.DimensionGroupGUID <> D.PrimaryGroupGUID and D.DimensionGUID = @DimensionGUID
				and dbo.IsView(DG.SchemaName,DG.ObjectName) = 0; -- don't sync view-backed dimension groups
	
open crsCursor;

FETCH NEXT FROM crsCursor into @GroupSchema, @GroupObject
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		
		declare @sql varchar(max);
		set @sql = '
			INSERT INTO [' + @GroupSchema + '].[' + @GroupObject +  '] ([MemberGUID])
				select P.[MemberGUID] from [' + @PrimarySchema + '].[' + @PrimaryObject +  '] P
					left join [' + @GroupSchema + '].[' + @GroupObject +  '] S on S.[MemberGUID] = P.[MemberGUID]
				where S.[MemberGUID] is null;
				
			DELETE FROM [' + @GroupSchema + '].[' + @GroupObject +  '] 
				where [MemberGUID] not in (Select [MemberGUID] from [' + @PrimarySchema + '].[' + @PrimaryObject +  ']);
		';	
		if (@IsDebugOnly = 1) begin
			print @sql;
		end
		else begin
			exec (@sql);
		end
		
		FETCH NEXT FROM crsCursor into @GroupSchema, @GroupObject
	END
close crsCursor;
DEALLOCATE crsCursor;




END
GO


---------------------------------------------

-- dbo.procScoreTruncateDimension
CREATE proc [dbo].[procScoreTruncateDimension] (
	@DimensionGUID uniqueidentifier,
	@IsDebugOnly bit = 0
)
AS
BEGIN

	declare @sql varchar(max);
	set @sql = '';
	declare @schema sysname;
	declare @object sysname;
	
	
	declare crsCursor CURSOR LOCAL FAST_FORWARD FOR
	select G.SchemaName, G.ObjectName from ScoreDimension D 
		inner join ScoreDimensionGroup G on G.DimensionGUID = D.DimensionGUID
	where D.DimensionGUID = @DimensionGUID
	
	
	open crsCursor;

	set @sql = 'BEGIN TRANSACTION TRUNCATE_DIMENSION;
';
	FETCH NEXT FROM crsCursor into @schema, @object
	WHILE (@@FETCH_STATUS = 0) 
		BEGIN
			
			set @sql = @sql + 'TRUNCATE TABLE [' + @schema + '].[' + @object + '];
';
			
			FETCH NEXT FROM crsCursor into @schema, @object
		END
	close crsCursor;
	DEALLOCATE crsCursor;
	set @sql = @sql + 'COMMIT TRANSACTION TRUNCATE_DIMENSION;';
	
	if (@IsDebugOnly = 1) begin
		print @sql;
	end
	else begin
		exec (@sql);
	end
	


END
GO


---------------------------------------------

-- dbo.procScoreUpdateLootPermissionSets
CREATE procedure [dbo].[procScoreUpdateLootPermissionSets] (
	@DimensionGUID uniqueidentifier
)
AS
BEGIN
	
	if not exists (select top 1 DimensionGUID from ScoreDimension where DimensionGUID =@DimensionGUID and IsSecured=1)
	begin
		print 'Dimension doesn''t exist, or it isn''t secured!'
		return;
	end
	
	declare @SecuredColumn nvarchar(128);
	declare @SecuredPrefix nvarchar(128);
	declare @SQLSchema nvarchar(128);
	declare @SQLObject nvarchar(128);
	declare @PSetID smallint;
		
	select
		@SQLSchema = SQLSchemaName,
		@SQLObject = SQLObjectName,
		@PSetID = PermissionSetID
	from ScoreDimension 
	where DimensionGUID = @DimensionGUID
	
	
	select  @SecuredColumn = A.SQLColumnName,
			@SecuredPrefix = A.SecuredLootGroupPrefix
		from ScoreDimension D
			inner join [dbo].[ScoreDimensionGroup] sdg on d.DimensionGuid = sdg.DimensionGUID
			inner join ScoreAttribute A on a.DimensionGroupGuid = sdg.DimensionGroupGUID
		where D.DimensionGUID = @DimensionGUID  and A.IsSecuredLootID = 1
	if (@SecuredColumn is null)
	begin
		print 'SecuredLootID column doesn''t exist!'
		return;
	end
	
	declare @sql varchar(max);
	set @sql = '
	
		UPDATE LOOT
			SET LOOT.PermissionSetID = ' + cast(@PSetID as nvarchar(128)) + '
		FROM S3Loot LOOT
		INNER JOIN ' + dbo.GetSQLTableExpression(@SQLSchema, @SQLObject) + ' DIM
			ON LOOT.[LootID] = ''' + @SecuredPrefix  +'|'' + cast(DIM.[' + @SecuredColumn + '] as nvarchar(128))
		WHERE LOOT.PermissionSetID != ' + cast(@PSetID as nvarchar(128)) + '
	
	';
	
	print @sql;
	exec (@sql);
END
GO


---------------------------------------------

-- dbo.procScoreValidateConfig
CREATE proc [dbo].[procScoreValidateConfig]
	@commit bit = 0
as


set nocount on
declare @cnt int
declare @results as table (Result varchar(max))
declare @sql nvarchar(max)

--these should be done no matter what
exec procScoreFixMeasureAggTypes
exec procScoreAttributeSchemaUpdateAll

begin try
	begin tran
	
	--

	--INVALID MODELGUID IN SCOREFILLIN
	insert into @results 
	select distinct 'Deleted fillins for invalid modelguid: ' + isnull(CAST(modelguid as varchar(36)),'') from ScoreFillin where not modelguid in (select planguid from xplan)
	
	delete from ScoreFillin where not modelguid in (select planguid from xplan)


	----secured dimension with invalid permissionset
	--insert into @results
	--select 'Updated secured score dimension to have a valid permissionsetid: ' + isnull(FriendlyName,'')
	--from 
	--	ScoreDimension 
	--where 
	--	IsSecured = 1
	--	and not PermissionSetID in (select PermissionSetID from S3PermissionSet)

	--update
	--	ScoreDimension 
	--set
	--	PermissionSetID = (select top 1 PermissionSetID from S3PermissionSet) --gotta pick 1!
	--where 
	--	IsSecured = 1
	--	and not PermissionSetID in (select PermissionSetID from S3PermissionSet)

	--insert into @results
	--select 
	--	'NO AUTOFIX: Invalid dimension (' + isnull(SD.FriendlyName,'Missing') + ') attribute (' + isnull(SA.FriendlyName,'Missing') + ') for plantype (' + isnull(PT.Name,'Null') + ') ' 
	--	+ case when isnull(SA.SecuredLootGroupPrefix,'') <> 'P' then 'No P Prefix, ' else '' end
	--	+ case when isnull(SA.ColumnType,0) <> 56 then 'Not integer, ' else '' end
	--from
	--	PlanType PT
	--	left join ScoreDimension SD on PT.DimensionGUID = SD.DimensionGUID
	--	left join ScoreAttribute SA on SD.DimensionGUID = SA.DimensionGUID
	--where
	--	SA.IsSecuredLootID = 1
	--	and (
	--		SA.AttributeGUID is null
	--		or SA.SecuredLootGroupPrefix <> 'P'
	--		or SA.ColumnType <> 56
	--		)
			
	
	insert into @results
	select
		'NO AUTOFIX: exec dbo.procScoreDeleteDimension ''' + isnull(cast(sd.dimensionguid as varchar(36)),'') + ''' --Dimension "' + isnull(sd.FriendlyName,'') + '" (' + isnull(cast(sd.DimensionGUID as varchar(36)),'') + ') is missing source object: [' + isnull(sd.SQLSchemaName,'') + '].[' + isnull(sd.SQLObjectName,'') + ']'
	from
		scoredimension sd
	where not
			(
				dbo.viewexists(sd.sqlschemaname,sd.sqlobjectname) = 1
				or dbo.tableexists(sd.sqlschemaname,sd.sqlobjectname) = 1
			)
	
	
	insert into @results
	select
		'Deleted ScoreDimensionGroup (' + sd.FriendlyName + '.' + sdg.Name + ') (and its attributes) because its sql object does not exist [' + sdg.SchemaName + '].[' + sdg.ObjectName + ']'
	from 
		ScoreDimensionGroup sdg
		inner join ScoreDimension sd on sdg.DimensionGUID = sd.DimensionGUID
		
	where not	
		(	
			dbo.ViewExists(SchemaName, ObjectName) = 1
			or dbo.TableExists(SchemaName, ObjectName) = 1
		)

	delete from ScoreAttribute where DimensionGroupGUID in (
		select DimensionGroupGUID from ScoreDimensionGroup where not	
			(	
				dbo.ViewExists(SchemaName, ObjectName) = 1
				or dbo.TableExists(SchemaName, ObjectName) = 1
			)
		)

	delete from ScoreDimensionGroup where not	
		(	
			dbo.ViewExists(SchemaName, ObjectName) = 1
			or dbo.TableExists(SchemaName, ObjectName) = 1
		)
			
	insert into @results
	select
		'NO AUTOFIX: exec dbo.procScoreDeleteDataTable ''' + isnull(cast(DataTableGUID as varchar(36)),'') + '''--,0,1 --DataTable "' + isnull(FriendlyName,'') + '" (' + isnull(cast(DataTableGUID as varchar(36)),'') + ') is missing source object: [' + isnull(SQLSchemaName,'') + '].[' + isnull(SQLObjectName,'') + ']'
	from
		ScoreDataTable dt
	where not
		(
				dbo.viewexists(sqlschemaname,sqlobjectname) = 1
				or dbo.tableexists(sqlschemaname,sqlobjectname) = 1
		)
	order by FriendlyName
	
	insert into @results
	select
		'Deleted ScoreMeasure, MeasureGUID = ''' + isnull(cast(MeasureGUID as varchar(36)),'') + ''' --  Missing column: [' + isnull(SQLSchemaName,'') + '].[' + isnull(SQLObjectName,'') + '].[' + ISNULL(sqlcolumnname,'') + ']'
	from
		ScoreMeasure sm
		inner join ScoreDataTable dt on sm.DataTableGUID = dt.DataTableGUID
	where not
		(
			dbo.ColumnExists(SQLSchemaName, SQLObjectName, SQLColumnName) = 1
		)
	order by
		SQLSchemaName, SQLObjectName, SQLColumnName

	delete sm from ScoreMeasure sm
		inner join ScoreDataTable dt on sm.DataTableGUID = dt.DataTableGUID
	where not
		(
			dbo.ColumnExists(SQLSchemaName, SQLObjectName, SQLColumnName) = 1
		)
	
	insert into @results
	select	
		'Deleted Invalid attribute (and its CompositeLinks and DataTableKeyLinks) (not in viewScoreAttributeCore30): ' + isnull(cast(sa.AttributeGUID as varchar(36)),'') + ' ' + isnull(sa.FriendlyName,'')
	from
		ScoreAttribute sa
	where not AttributeGUID in (select AttributeGUID from viewScoreAttributeCore30)

	delete from ScoreDataTableKeyLink 			
	where not KeyGUID in (select AttributeGUID from viewScoreAttributeCore30)
	
	delete from ScoreCompositeLink 
	where not Key1GUID in (select AttributeGUID from viewScoreAttributeCore30)

	delete from ScoreCompositeLink 
	where not Key2GUID in (select AttributeGUID from viewScoreAttributeCore30)
	
	delete from ScoreAttribute
	where not AttributeGUID in (select AttributeGUID from viewScoreAttributeCore30)

	insert into @results
	select	
		'Deleted Invalid attribute (and its CompositeLinks and DataTableKeyLinks) (column does not exist): ' + cast(sa.AttributeGUID as varchar(36)) + ' ' + sa.DimensionName + ' ' + isnull(sa.FriendlyName,'')
	from
		viewScoreAttributeCore30 sa
	where	
		IsColumnExist = 0

	delete from ScoreDataTableKeyLink 
	where KeyGUID in (select AttributeGUID from viewScoreAttributeCore30 where IsColumnExist = 0)
			
	delete from ScoreCompositeLink 
	where Key1GUID in (select AttributeGUID from viewScoreAttributeCore30 where IsColumnExist = 0)

	delete from ScoreCompositeLink 
	where Key2GUID in (select AttributeGUID from viewScoreAttributeCore30 where IsColumnExist = 0)
			
	delete from ScoreAttribute
	where AttributeGUID in (select AttributeGUID from viewScoreAttributeCore30 where IsColumnExist = 0)
		
	insert into @results
	select
		'Updated (' + isnull(SD.FriendlyName,'Missing')  + ') to not be secured, since it has no SecuredLootID'
	from
		ScoreDimension sd
	where
		IsSecured = 1 and
		not exists (
			select 1 from
				ScoreDimensionGroup sdg 
				inner join ScoreAttribute sa on sdg.DimensionGroupGUID = sa.DimensionGroupGUID
			where
				sd.DimensionGUID = sdg.DimensionGUID
				and sa.IsSecuredLootID = 1
		)
			
	update ScoreDimension 
	set IsSecured = 0
	where 
		IsSecured = 1 and
		not exists (
			select 1 from
				ScoreDimensionGroup sdg 
				inner join ScoreAttribute sa on sdg.DimensionGroupGUID = sa.DimensionGroupGUID
			where
				ScoreDimension.DimensionGUID = sdg.DimensionGUID
				and sa.IsSecuredLootID = 1
		)
			
	declare @total int
	select @total = COUNT(*) from @results

	if @commit = 1 begin
		commit
		insert into @results select 'Changes committed.'
	end else begin
		rollback
		insert into @results select 'Changes rolled back.'
	end
	
	select * 
	from @results 
	
end try
begin catch
	rollback
	print error_message()
	print 'Rollback rolled back.  No changes have been applied.'
end catch
GO


---------------------------------------------

-- dbo.procSetIdentityInsert
CREATE PROCEDURE [dbo].[procSetIdentityInsert]
(
	@SQLTableExpression varchar(max),
	@IsOn bit
)
AS

declare @sql varchar(max);
declare @ONorOFF varchar(8);

if (@IsOn = 1)
BEGIN
	set @ONorOFF = 'ON';
END
ELSE
	set @ONorOFF = 'OFF';

set @sql = 'set Identity_insert ' + @SQLTableExpression +  ' ' + @ONorOFF;
print @sql;
exec (@sql)
GO


---------------------------------------------

-- dbo.procSetUserSecurityLastModifiedDate
-- =============================================
-- Author:		<Jacky Chau>
-- Create date: <6/24/2008>
-- Description:	<Update the security last modified date for an user>
-- =============================================
CREATE PROCEDURE procSetUserSecurityLastModifiedDate
	-- Add the parameters for the stored procedure here
	@UserGUID uniqueidentifier, 
	@LastModifiedDate DateTime = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	-- Make sure date time is set
	IF @LastModifiedDate IS NULL SET @LastModifiedDate = GetDate()

	-- Attempt update
	UPDATE UserSecurityLastModifiedDate 
	SET LastModifiedDate = @LastModifiedDate 
	WHERE UserGUID = @UserGUID

    -- If userguid doesn't exist, insert
	IF @@ROWCOUNT=0
    INSERT INTO UserSecurityLastModifiedDate VALUES (@UserGUID, @LastModifiedDate)
   
END
GO


---------------------------------------------

-- dbo.procShowGUIDsMB
CREATE PROC procShowGUIDsMB AS

CREATE table #space (name varchar(100), rows int, reserved varchar(50),
                                  data varchar(50), index_size varchar(50), unused varchar(50))

exec sp_MSforeachtable 'insert into #space exec sp_spaceused ''?'';'

--
--SELECT 
--	name, 
--	rows,
--	cast(replace(reserved, ' KB', '') as int) / 1000 as reserved,
--	cast(replace(data, ' KB', '') as int) / 1000 as data,
--	cast(replace(index_size, ' KB', '') as int) / 1000 as index_size,
--	cast(replace(unused, ' KB', '') as int) / 1000 as unused
-- from #space order by reserved DESC

DECLARE @val FLOAT

SELECT 
	--sysobjects.name, syscolumns.name, #space.rows, 
	@val = sum(#space.rows * 16.0) / 1000000.0
FROM sysobjects 
	INNER JOIN syscolumns ON sysobjects.id = syscolumns.id 
	INNER JOIN #space ON #space.name = sysobjects.name
WHERE sysobjects.xtype='U' AND syscolumns.xtype = 36

PRINT 'All: ' + cast(@val AS varchar(max)) + ' MB'

SELECT 
	--sysobjects.name, syscolumns.name, #space.rows, 
	@val = sum(#space.rows * 16.0) / 1000000.0
FROM sysobjects 
	INNER JOIN syscolumns ON sysobjects.id = syscolumns.id 
	INNER JOIN #space ON #space.name = sysobjects.name
WHERE sysobjects.xtype='U' AND syscolumns.xtype = 36 AND sysobjects.name LIKE 'zz%'

PRINT 'zzTables: ' + cast(@val AS varchar(max))  + ' MB'

DROP TABLE #space
GO


---------------------------------------------

-- dbo.procShowLargestModels
CREATE PROC [dbo].[procShowLargestModels] AS
	SET NOCOUNT ON;

	DECLARE @zzMDCGUID uniqueidentifier
	DECLARE @mdcName nvarchar(max)
	DECLARE @zzMDCtablename nvarchar(36)
--	DECLARE @zzDIMcursor nvarchar(256)
--	DECLARE @zzDIMcolumnname nvarchar(256)
	DECLARE @modelTemplateMappingTableName nvarchar(256)
	DECLARE @modelDataTableName nvarchar(256)
--	DECLARE @dimensionName as nvarchar(256)
--	DECLARE @dimensionGUID as uniqueidentifier
--	DECLARE @fixSQL as nvarchar(max)
	DECLARE @sql varchar(max)

	CREATE TABLE #Biggest (IsTemplate BIT , name varchar(max), rows int)

	DECLARE zztable CURSOR LOCAL FAST_FORWARD
		FOR SELECT NAME, MODELDATACONFIGGUID FROM EMFModelDataConfig
	OPEN zztable
	FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID
	WHILE @@FETCH_STATUS = 0
	BEGIN


		--SET @zztable_query = 'ALTER TABLE ' + @zztable_name + ' ADD [MAPPINGTYPE] int NOT NULL Default(0) WITH VALUES'
		--EXECUTE sp_executesql @zztable_query
		SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_')

		SET @modelTemplateMappingTableName = 'zzEMFModelTemplateMapping_' + @zzMDCtablename
		if (select count(*) from sysobjects where xtype='u' and name like @modelTemplateMappingTableName) <> 0  BEGIN
			SET @sql = 'DECLARE @name varchar(max); DECLARE @cnt int; SELECT TOP 1 @name = MT.NAME, @cnt = COUNT(*) FROM ' + @modelTemplateMappingTableName + ' MAP INNER JOIN EMFMODELTEMPLATE MT ON MT.MODELTEMPLATEGUID = MAP.MODELTEMPLATEGUID GROUP BY MT.NAME ORDER BY COUNT(*) DESC
			; INSERT INTO #Biggest (IsTemplate, name, Rows) VALUES (1, @name, @cnt)'
			EXEC (@sql)
		END


--		SET @modelDataTableName = 'zzEMFModelData_' + @zzMDCtablename
--		if (select count(*) from sysobjects where xtype='u' and name like @modelDataTableName) = 0
--			PRINT @modelDataTableName + ' table is not present'
--		else begin
--			--exec procEnsureColumnInTable @modelDataTableName ,'MODELGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
--			exec procEnsureDimensionColumnsInTable @modelDataTableName, @zzMDCGUID, @DebugMode, 0
--			exec procEnsureColumnInTable @modelDataTableName ,'MEASUREGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
--			exec procEnsureColumnInTable @modelDataTableName ,'VALUE', 'float', '0', @DebugMode
--			exec procEnsureColumnInTable @modelDataTableName ,'FORMULA', 'varchar(1024)', '''''', @DebugMode
--			exec procEnsureColumnInTable @modelDataTableName ,'STRINGVALUE', 'varchar(1024)', '''''', @DebugMode
--			exec procEnsureColumnInTable @modelDataTableName ,'RISKVARIABLEGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
--			exec procEnsureColumnInTable @modelDataTableName ,'HISTORYITEMGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode
--		end
		

--		DECLARE zzdimensions CURSOR LOCAL FAST_FORWARD
--		FOR SELECT SLM.LISTGUID, SLM.NAME, UPPER('G' + REPLACE(cast(SLM.LISTGUID as varchar(36)),'-','_')) FROM dbo.EMFModelDataConfigDimensionLink MDCDL JOIN SECURELIST SLM ON MDCDL.DIMENSIONGUID=SLM.LISTGUID WHERE MDCDL.MODELDATACONFIGGUID = @zzMDCGUID
--		OPEN zzdimensions
--		FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor
--		WHILE @@FETCH_STATUS = 0
--		BEGIN
--			SET @zzDIMcolumnname = @zzDIMcursor --+ 'GUID'
--			SET @fixSQL = 'DELETE FROM emfmodeldataconfigdimensionlink WHERE DIMENSIONGUID = ''' + cast(@dimensionGUID as varchar(36)) + ''' and MODELDATACONFIGGUID = ''' + cast(@zzMDCGUID as varchar(36)) + ''''
--			IF (SELECT count(*) FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype='U' AND (sysobjects.name like @modelDataTableName or sysobjects.name like @modelMappingTableName or sysobjects.name like @modelTemplateMappingTableName)and syscolumns.name like @zzDIMcolumnname) <> 3
--				--PRINT '   ' + @zzDIMcolumnname + ' is present'
--			--ELSE
--				PRINT @fixSQL + ' --' + cast(@zzMDCGUID as varchar(36)) + ' (' + @mdcName + ') - ' + @zzDIMcolumnname + ' (' + @dimensionName + ') is not present in both ModelData and ModelMapping'
--				
--
--			FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor
--		END
--		CLOSE zzdimensions
--		DEALLOCATE zzdimensions
--			
		FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID
	END
	CLOSE zztable
	DEALLOCATE zztable


	SELECT TOP 10 * FROM #Biggest ORDER BY rows DESC
	DROP TABLE #Biggest
GO


---------------------------------------------

-- dbo.procShowTableSizes
CREATE procedure [dbo].[procShowTableSizes] 
	@orderByColumn varchar(max) = ''
as
create table #space (name varchar(100), rows int, reserved varchar(50),
                                  data varchar(50), index_size varchar(50), unused varchar(50))

exec sp_MSforeachtable 'insert into #space exec sp_spaceused ''?'';'

select 
	name, 
	rows,
	cast(replace(reserved, ' KB', '') as int) / 1000 as reserved,
	cast(replace(data, ' KB', '') as int) / 1000 as data,
	cast(replace(index_size, ' KB', '') as int) / 1000 as index_size,
	cast(replace(unused, ' KB', '') as int) / 1000 as unused,
	round(case when rows = 0 then 0 else cast(replace(reserved, ' KB', '') as float) / rows end,2) as KBperrow
from #space 
order by reserved desc

drop table #space
GO


---------------------------------------------

-- dbo.procStrataCLRDrop
CREATE PROCEDURE dbo.procStrataCLRDrop 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	
	--First we need to drop all the Wrapper objects that are dependent on the Assembly which include CLR { Aggregates, Scalars, Stored Procedures, Table Value Functions & Triggers }
	DECLARE @asmname NVARCHAR(1000);
	DECLARE @d_sql NVARCHAR(MAX);
	DECLARE @drop_type VARCHAR(100)

	--****Don't forget to set the correct *OLD* (NOT NEW) assembly name.
	SET @asmname = N'StrataCLR';

	-- CURSOR VARIABLES --

	DECLARE @wname NVARCHAR(1000);
	DECLARE @wtype NVARCHAR(1000);

	-- CURSOR VARIABLES (END) --

	DECLARE dCursor CURSOR FAST_FORWARD FOR
	SELECT '[' + ss.name + '].[' + o.name + ']'  AS wraper_name, o.type
	FROM sys.assembly_modules am
	JOIN sys.objects o ON am.object_id = o.object_id
	JOIN sys.assemblies sas ON sas.assembly_id = am.assembly_id
	JOIN sys.schemas ss ON ss.schema_id = o.schema_id
	WHERE sas.name = @asmname

	OPEN dCursor

	FETCH NEXT FROM dCursor INTO @wname, @wtype

	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		SET @drop_type = '';
		
		IF @wtype IN ('PC', 'P')
			SELECT @drop_type = 'PROCEDURE'

		IF @wtype IN ('FN', 'FS', 'FT', 'IF', 'TF')
			SELECT @drop_type = 'FUNCTION'
	    
		IF @wtype = 'AF'
			SELECT @drop_type = 'AGGREGATE'
	    
		IF @wtype = 'U'
			SELECT @drop_type = 'TABLE'
	    
		IF @wtype = 'V'
			SELECT @drop_type = 'VIEW'
			
		IF @drop_type <> ''
		BEGIN
			SET @d_sql = 'DROP '+ @drop_type + ' ' + @wname 
			EXEC(@d_sql);
		END

		FETCH NEXT FROM dCursor INTO @wname, @wtype
	END

	CLOSE dCursor
	DEALLOCATE dCursor

	--Finally drop the Assembly
	SET @d_sql = N'IF  EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = ''' + @asmname + ''' AND is_user_defined = 1) DROP ASSEMBLY [StrataCLR]'
				   
	EXEC(@d_sql)
	
END
GO


---------------------------------------------

-- dbo.procSyncEMFDimensionWithScore
CREATE procedure [dbo].[procSyncEMFDimensionWithScore]  
 @listGUID uniqueidentifier,  
 @dimGUID uniqueidentifier,  
 @updateMemberGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000',  
 @nameCol nvarchar(64) = 'Name',  
 @sortCol nvarchar(64) = 'Name',  
 @scoreWhereClause nvarchar(4000) = '(1 = 1)',  
 @isdebug bit = 0  
as  
 set nocount on  
  
 --verify dimension integrity  
 if((select COUNT(*) from SecureList where ListGUID = @listGUID) = 0) begin  
  RAISERROR ('EMF dimension not found.', 18, 0)  
  return  
 end  
 if((select COUNT(*) from ScoreDimension where DimensionGUID = @dimGUID) = 0) begin  
  RAISERROR ('Score dimension not found.', 18, 0)  
  return  
 end  
 if((select COUNT(*) from SecureListProperty LP left join viewScoreAttributeCore30 SA on SA.FriendlyName = LP.Name and SA.DimensionGUID = @dimGUID where LP.ListGUID = @listGUID and SA.AttributeGUID is null) > 0) begin  
  RAISERROR ('Attribute names don''t match.', 18, 0)  
  return  
 end  
 if((select COUNT(*) from SecureListLevel where ListGUID = @listGUID) > 2) begin  
  RAISERROR ('Dimensions with more than 2 levels are not supported.', 18, 0)  
  return  
 end  
 if((select COUNT(*) from SecureListLevel where ListGUID = @listGUID) > 1) begin  
  if((select COUNT(*) from SecureListLevel LL left join viewScoreAttributeCore30 SA on SA.FriendlyName = LL.Name and SA.DimensionGUID = @dimGUID where LL.LevelIndex = 0 and LL.ListGUID = @listGUID and SA.AttributeGUID is null) > 0) begin  
   RAISERROR ('Level names don''t match.', 18, 0)  
   return  
  end  
 end  
 
  
 --get score dimension table name  
 declare @dimTable nvarchar(100)  
 select @dimTable = SQLSchemaName + '.' + SQLObjectName from ScoreDimension where DimensionGUID = @dimGUID  
  
 --get emf cache table name  
 declare @cacheTable nvarchar(100)  
 set @cacheTable = 'zzList_' + REPLACE(cast(@listGUID as nvarchar(36)), '-', '_')  
   
 --get emf levels  
 declare @levelLeaf uniqueidentifier  
 declare @levelCategory uniqueidentifier  
 if((select COUNT(*) from SecureListLevel where ListGUID = @listGUID) > 1) begin  
  select @levelLeaf = ListLevelGUID from SecureListLevel where ListGUID = @listGUID and LevelIndex = 1  
  select @levelCategory = ListLevelGUID from SecureListLevel where ListGUID = @listGUID and LevelIndex = 0  
 end else begin  
  select @levelLeaf = ListLevelGUID from SecureListLevel where ListGUID = @listGUID and LevelIndex = 0  
  select @levelCategory = dbo.ZeroGUID()  
 end  
 declare @levelCategoryName nvarchar(100)  
 
select 
	@levelCategoryName = SA.SQLColumnName
from SecureListLevel LL
left join viewScoreAttributeCore30 SA on SA.FriendlyName = LL.Name and SA.DimensionGUID = @dimGUID
where 
	LL.ListLevelGUID = @levelCategory
 --select @levelCategoryName = Name from SecureListLevel where ListLevelGUID = @levelCategory  
   
 --get lootid info  
 declare @lootidPrefix nvarchar(100)  
 declare @lootidColName nvarchar(100)  
 set @lootidPrefix = coalesce((select SecuredLootGroupPrefix from viewScoreAttributeCore30 where IsSecuredLootID = 1 and DimensionGUID = @dimGUID), '')  
 set @lootidColName = coalesce((select SQLColumnName from viewScoreAttributeCore30 where IsSecuredLootID = 1 and DimensionGUID = @dimGUID), 'MemberGUID')  
 if(@lootidPrefix != '') begin  
  set @lootidPrefix = @lootidPrefix + '|'  
 end  
    
 --delete missing emf members  
 declare @deletesql nvarchar(max)  
 set @deletesql = 'delete from SecureListMember where ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' and ListMemberGUID not in(select MemberGUID from ' + @dimTable + ' where ' + @scoreWhereClause + ')'  
 if(@levelCategory != dbo.ZeroGUID()) begin  
  --don't delete parent members  
  set @deletesql = @deletesql + ' and ParentListMemberGUID != dbo.ZeroGUID()'  
 end  
 if(@updateMemberGUID != dbo.ZeroGUID()) begin  
  --only delete specified member  
  set @deletesql = @deletesql + ' and ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
 end  
    
 --delete from list cache also  
 set @deletesql = @deletesql + '; delete from ' + @cacheTable + ' where ListMemberGUID not in(select MemberGUID from ' + @dimTable + ' where ' + @scoreWhereClause + ')'  
 if(@levelCategory != dbo.ZeroGUID()) begin  
  --don't delete parent members  
  set @deletesql = @deletesql + ' and coalesce(L' + replace(CAST(@levelLeaf as nvarchar(36)), '-', '_') + ', dbo.ZeroGUID()) != dbo.ZeroGUID()'  
 end  
 if(@updateMemberGUID != dbo.ZeroGUID()) begin  
  --only delete specified member  
  set @deletesql = @deletesql + ' and ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
 end  
 
    
 --commit deletes  
 if(@isdebug = 1) begin  
  print @deletesql  
 end else begin  
  exec(@deletesql)  
 end  
  
 --create missing members  
 declare @insertsql nvarchar(max)  
 set @insertsql = '  
  INSERT INTO [SecureListMember] ([ListMemberGUID], [ListGUID], [ParentListMemberGUID], [Name], [Description], [FullPath], [DisplayOrder], [OutlineLevel], [ListMemberID], [SortOrderFullPath], [DateCreated], [DateModified], [LootIDOverride])  
  select  
   MemberGUID,  
   ''' + cast(@listGUID as nvarchar(36)) + ''',  
   dbo.ZeroGUID(),  
   ' + @nameCol + ',  
   '''',  
   ''' + cast(@listGUID as nvarchar(36)) + '\'' + CAST(MemberGUID as nvarchar(36)) + ''\'',  
   0,  
   0,  
   cast(MemberGUID as nvarchar(36)),  
   ''00000000\'',  
   GETDATE(),  
   GETDATE(),  
   ''' + @lootidPrefix + ''' + cast(' + @lootidColName + ' as nvarchar(100))  
  from  
   ' + @dimTable + '  
  where  
   ' + @scoreWhereClause + '  
   and MemberGUID not in(select ListMemberGUID from SecureListMember where ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''')'  
 if(@updateMemberGUID != dbo.ZeroGUID()) begin  
  --only create specified member  
  set @insertsql = @insertsql + ' and MemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
 end  
   
 --create missing parents  
 if(@levelCategory != dbo.ZeroGUID()) begin  
  set @insertsql = @insertsql + ';  
   declare @parentName nvarchar(100)  
   declare crsParents cursor for select distinct ' + @levelCategoryName + ' from ' + @dimTable + ' where ' + @scoreWhereClause + ' and ' + @levelCategoryName + ' not in(select Name from SecureListMember where ParentListMemberGUID = dbo.ZeroGUID() and ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''')'  
  if(@updateMemberGUID != dbo.ZeroGUID()) begin  
   --only create parent of specified member  
   set @insertsql = @insertsql + ' and MemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
  end  
     
  set @insertsql = @insertsql + '  
   open crsParents  
   fetch next from crsParents into @parentName  
     
   declare @parentGUID uniqueidentifier  
   while(@@fetch_status = 0) begin  
    select @parentGUID = newid()  
     
    INSERT INTO [SecureListMember] ([ListMemberGUID], [ListGUID], [ParentListMemberGUID], [Name], [Description], [FullPath], [DisplayOrder], [OutlineLevel], [ListMemberID], [SortOrderFullPath], [DateCreated], [DateModified], [LootIDOverride])  
    select  
     @parentGUID,  
     ''' + cast(@listGUID as nvarchar(36)) + ''',  
     dbo.ZeroGUID(),  
     @parentName,  
     '''',  
     ''' + cast(@listGUID as nvarchar(36)) + '\'' + CAST(@parentGUID as nvarchar(36)) + ''\'',  
     0,  
     0,  
     cast(@parentGUID as nvarchar(36)),  
     ''00000000\'',  
     GETDATE(),  
     GETDATE(),  
     ''''  
       
    fetch next from crsParents into @parentName  
   end  
     
   close crsParents  
   deallocate crsParents'  
 end  
   
 --fix parents  
 if(@levelCategory != dbo.ZeroGUID()) begin  
  set @insertsql = @insertsql + ';  
   update LM set LM.ParentListMemberGUID = PLM.ListMemberGUID, LM.FullPath = PLM.FullPath + cast(LM.ListMemberGUID as nvarchar(36)) + ''\'', SortOrderFullPath = ''00000000\00000000\'', OutlineLevel=1  
   from  
    SecureListMember LM  
    inner join ' + @dimTable + ' SD on SD.MemberGUID = LM.ListMemberGUID  
    inner join SecureListMember PLM on PLM.Name = SD.' + @levelCategoryName + ' and PLM.OutlineLevel = 0  
   where  
    ' + @scoreWhereClause + '  
    and LM.ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + '''  
    and LM.ParentListMemberGUID != PLM.ListMemberGUID  
  '  
  if(@updateMemberGUID != dbo.ZeroGUID()) begin  
   --only fix specified member  
   set @insertsql = @insertsql + ' and LM.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
  end  
 end  
   
 --add missing parents in cache  
 if(@levelCategory != dbo.ZeroGUID()) begin  
  set @insertsql = @insertsql + ';  
   INSERT INTO ' + @cacheTable + ' (L' + replace(CAST(@levelCategory as nvarchar(36)), '-', '_') + ', Name, ListMemberGUID)  
   select ListMemberGUID, Name, ListMemberGUID  
   from SecureListMember  
   where OutlineLevel = 0 and ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' and ListMemberGUID not in(select ListMemberGUID from ' + @cacheTable + ')'  
 end  
   
 --add other new members to list cache  
 set @insertsql = @insertsql + ';  
  INSERT INTO ' + @cacheTable + ' (L' + replace(CAST(@levelLeaf as nvarchar(36)), '-', '_') + ', Name, ListMemberGUID)  
  select ListMemberGUID, Name, ListMemberGUID  
  from SecureListMember  
  where ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' and ListMemberGUID not in(select ListMemberGUID from ' + @cacheTable + ')'  
 if(@updateMemberGUID != dbo.ZeroGUID()) begin  
  --only create specified member  
  set @insertsql = @insertsql + ' and ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
 end   
   
 --fix parents of leaf members in cache  
 if(@levelCategory != dbo.ZeroGUID()) begin  
  set @insertsql = @insertsql + ';  
   update LC set LC.L' + replace(cast(@levelCategory as nvarchar(36)), '-', '_') + ' = LM.ParentListMemberGUID  
   from  
    ' + @cacheTable + ' LC  
    inner join SecureListMember LM on LC.ListMemberGUID = LM.ListMemberGUID  
   where  
    LM.ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + '''  
    and LM.OutlineLevel = 1  
    and coalesce(LC.L' + replace(cast(@levelCategory as nvarchar(36)), '-', '_') + ', dbo.ZeroGUID()) != LM.ParentListMemberGUID  
  '  
  if(@updateMemberGUID != dbo.ZeroGUID()) begin  
   --only fix specified member  
   set @insertsql = @insertsql + ' and LC.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
  end   
 end  
   
 --commit inserts    
 if(@isdebug = 1) begin  
  print @insertsql  
 end else begin  
  exec(@insertsql)  
 end  
   
 --create missing membervalue records  
 declare @valsyncsql nvarchar(max)  
 set @valsyncsql = '  
  insert into SecureListMemberValue(ListMemberValueGUID, ListMemberGUID, ListGUID, Type, ValueFloat, ValueText, ValueIndex)  
  select   
   NEWID(),  
   LM.ListMemberGUID,  
   LM.ListGUID,  
   case when LP.PropertyType = 1 then 1 else 0 end,  
   0,  
   '''',  
   LP.PropertyIndex  
  from   
   SecureListMember LM   
   inner join SecureListProperty LP on LP.ListGUID = LM.ListGUID  
   left join SecureListMemberValue LMV on LMV.ListMemberGUID = LM.ListMemberGUID and LMV.ValueIndex = LP.PropertyIndex  
  where  
   LM.ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + '''  
   and LMV.ListMemberValueGUID is null'  
 if(@updateMemberGUID != dbo.ZeroGUID()) begin  
  --only create for specified member  
  set @valsyncsql = @valsyncsql + ' and LM.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
 end  
 if(@isdebug = 1) begin  
  print @valsyncsql  
 end else begin  
  exec(@valsyncsql)  
 end  
   
 --update member name  
 declare @updatesql nvarchar(max)  
 set @updatesql = '  
  update LM set LM.Name = SD.' + @nameCol + '  
  from  
   SecureListMember LM  
   inner join ' + @dimTable + ' SD on SD.MemberGUID = LM.ListMemberGUID  
  where  
   ' + @scoreWhereClause + '  
   and LM.Name != SD.' + @nameCol + '  
   and LM.ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''''  
 if(@updateMemberGUID != dbo.ZeroGUID()) begin  
  --only update specified member  
  set @updatesql = @updatesql + ' and LM.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
 end  
   
 --iterate through properties  
 declare @emfpropGUID uniqueidentifier  
 declare @emfpropType int  
 declare @scorepropName nvarchar(100)  
 declare crsAttributes cursor for select LP.ListPropertyGUID, LP.PropertyType, '[' + SA.SQLColumnName + ']' from SecureListProperty LP left join viewScoreAttributeCore30 SA on SA.FriendlyName = LP.Name and SA.DimensionGUID = @dimGUID where LP.ListGUID = @listGUID  
 open crsAttributes  
 fetch next from crsAttributes into @emfpropGUID, @emfpropType, @scorepropName  
   
 --update property values  
 while(@@FETCH_STATUS = 0) begin  
  --member value table updates  
  if(@emfpropType = 1) begin  
   --numeric property update  
   set @updatesql = @updatesql + ';   
    update LMV set LMV.ValueFloat = SD.' + @scorepropName + ', LMV.ValueText = ''''  
    from  
     SecureListMemberValue LMV  
     inner join SecureListProperty LP on LP.ListGUID = LMV.ListGUID and LP.PropertyIndex = LMV.ValueIndex  
     inner join ' + @dimTable + ' SD on SD.MemberGUID = LMV.ListMemberGUID  
    where  
     ' + @scoreWhereClause + '  
     and LMV.ListGUID = ''' + cast(@listGUID as nvarchar(36)) + '''  
     and LP.ListPropertyGUID = ''' + CAST(@emfpropGUID as nvarchar(36)) + '''  
     and LMV.ValueFloat != SD.' + @scorepropName  
  end else begin  
   --text property update  
   set @updatesql = @updatesql + ';   
    update LMV set LMV.ValueFloat = 0, LMV.ValueText = SD.' + @scorepropName + '  
    from  
     SecureListMemberValue LMV  
     inner join SecureListProperty LP on LP.ListGUID = LMV.ListGUID and LP.PropertyIndex = LMV.ValueIndex  
     inner join ' + @dimTable + ' SD on SD.MemberGUID = LMV.ListMemberGUID  
    where  
     ' + @scoreWhereClause + '  
     and LMV.ListGUID = ''' + cast(@listGUID as nvarchar(36)) + '''  
     and LP.ListPropertyGUID = ''' + CAST(@emfpropGUID as nvarchar(36)) + '''  
     and LMV.ValueText != cast(SD.' + @scorepropName + ' as nvarchar(1000))'
  end  
  if(@updateMemberGUID != dbo.ZeroGUID()) begin  
   --only update specified member  
   set @updatesql = @updatesql + ' and LMV.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
  end  
  
  --list cache (cheat and update name here too)  
  set @updatesql = @updatesql + ';   
   update LC set LC.Name = SD.' + @nameCol + ', LC.P' + replace(CAST(@emfpropguid as nvarchar(36)), '-', '_') + ' = SD.' + @scorepropName + '  
   from  
    ' + @cacheTable + ' LC  
    inner join ' + @dimTable + ' SD on SD.MemberGUID = LC.ListMemberGUID  
   where  
    ' + @scoreWhereClause + '  
    and (LC.Name != SD.' + @nameCol + ' or LC.P' + replace(CAST(@emfpropguid as nvarchar(36)), '-', '_') + ' is null or LC.P' + replace(CAST(@emfpropguid as nvarchar(36)), '-', '_') + ' != SD.' + @scorepropName + ')'  
  if(@updateMemberGUID != dbo.ZeroGUID()) begin  
   --only update specified member  
   set @updatesql = @updatesql + ' and LC.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + ''''  
  end  
   
  fetch next from crsAttributes into @emfpropGUID, @emfpropType, @scorepropName  
 end  
  
 --update display orders for the whole dimension  
 declare @tmpname nvarchar(50)  
 select @tmpname = '##tmp' + replace(cast(newid() as nvarchar(36)), '-', '')  
 set @updatesql = @updatesql + ';  
  select MemberGUID, rank() over (order by ' + @sortCol + ') as [Rank] into ' + @tmpname + ' from ' + @dimTable + ';  
    
  update SLM set SLM.DisplayOrder = O.Rank, SLM.SortOrderFullPath = (SUBSTRING(''00000000'', 1, 8 - len(O.Rank)) + CAST(O.Rank as nvarchar(8)) + ''\'')  
  from  
   SecureListMember SLM  
   inner join ' + @tmpname + ' O on O.MemberGUID = SLM.ListMemberGUID and SLM.DisplayOrder != O.Rank  
  where  
   SLM.ListGUID = ''' + cast(@listGUID as nvarchar(36)) + ''';  
     
  drop table ' + @tmpname  
   
 --commit updates  
 close crsAttributes  
 deallocate crsAttributes  
 if(@isdebug = 1) begin  
  print @updatesql  
 end else begin  
  exec(@updatesql)  
 end
GO


---------------------------------------------

-- dbo.procSyncEMFDimensionWithScoreCreate
CREATE procedure [dbo].[procSyncEMFDimensionWithScoreCreate]
	@listGUID uniqueidentifier,
	@dimGUID uniqueidentifier,
	@dimTableSchema nvarchar(64),
	@dimTableName nvarchar(64),
	@nameCol nvarchar(64) = 'Name',
	@sortCol nvarchar(64) = 'Name',
	@tolerance int = 200,
	@isdebug bit = 0
as
	declare @sql nvarchar(max)
	
	set @sql = '
		CREATE TRIGGER ' + @dimTableSchema + '.[' + replace(replace(@dimTableName, '[', ''), ']', '') + 'Sync]
		   ON  ' + @dimTableSchema + '.[' + replace(replace(@dimTableName, '[', ''), ']', '') + ']
		   AFTER INSERT, DELETE, UPDATE
		AS 
		BEGIN
			SET NOCOUNT ON;

			declare @memberGUID uniqueidentifier

			--short-circuit and just refresh everything if there were a lot of updates
			if(((select count(*) from INSERTED) + (select count(*) from DELETED)) > ' + CAST(@tolerance as nvarchar(8)) + ') begin
				exec procSyncEMFDimensionWithScore ''' + cast(@listGUID as nvarchar(36)) + ''', ''' + cast(@dimGUID as nvarchar(36)) + ''', ''00000000-0000-0000-0000-000000000000'', ''' + @nameCol + ''', ''' + @sortCol + '''
				return
			end

			--process deleted
			declare crsDeleted cursor for select MemberGUID from DELETED where MemberGUID not in(select MemberGUID from INSERTED)
			open crsDeleted
			fetch next from crsDeleted into @memberGUID
			while(@@fetch_status = 0) begin
				exec procSyncEMFDimensionWithScore ''' + cast(@listGUID as nvarchar(36)) + ''', ''' + cast(@dimGUID as nvarchar(36)) + ''', @memberGUID, ''' + @nameCol + ''', ''' + @sortCol + '''
				fetch next from crsDeleted into @memberGUID
			end
			close crsDeleted
			deallocate crsDeleted
			
			--process inserted
			declare crsInserted cursor for select MemberGUID from INSERTED where MemberGUID not in(select MemberGUID from DELETED)
			open crsInserted
			fetch next from crsInserted into @memberGUID
			while(@@fetch_status = 0) begin
				exec procSyncEMFDimensionWithScore ''' + cast(@listGUID as nvarchar(36)) + ''', ''' + cast(@dimGUID as nvarchar(36)) + ''', @memberGUID, ''' + @nameCol + ''', ''' + @sortCol + '''
				fetch next from crsInserted into @memberGUID
			end
			close crsInserted
			deallocate crsInserted
			
			--process updated
			declare crsUpdated cursor for select MemberGUID from INSERTED where MemberGUID in(select MemberGUID from DELETED)
			open crsUpdated
			fetch next from crsUpdated into @memberGUID
			while(@@fetch_status = 0) begin
				exec procSyncEMFDimensionWithScore ''' + cast(@listGUID as nvarchar(36)) + ''', ''' + cast(@dimGUID as nvarchar(36)) + ''', @memberGUID, ''' + @nameCol + ''', ''' + @sortCol + '''
				fetch next from crsUpdated into @memberGUID
			end
			close crsUpdated
			deallocate crsUpdated
		END
	'

	if(@isdebug = 1) begin
		print @sql
	end else begin
		exec(@sql)
	end
GO


---------------------------------------------

-- dbo.procSyncEMFDimensionWithScoreDrop
CREATE procedure [dbo].[procSyncEMFDimensionWithScoreDrop]
	@dimTableSchema nvarchar(64),
	@dimTableName nvarchar(64),
	@isdebug bit = 0
as
	declare @sql nvarchar(max)

	set @sql = 'DROP TRIGGER ' + @dimTableSchema + '.[' + REPLACE(REPLACE(@dimTableName, '[', ''), ']', '') + 'Sync]'

	if(@isdebug = 1) begin
		print @sql
	end else begin
		exec(@sql)
	end
GO


---------------------------------------------

-- dbo.procSysDisableChangeTrackingOnTable
CREATE   PROCEDURE [dbo].[procSysDisableChangeTrackingOnTable] 
(
	@schemaName NVARCHAR(128), 
	@tableName NVARCHAR(128)
)
AS
BEGIN
	DECLARE @fulltablename NVARCHAR(256) = @schemaName + '.' + @tableName;
	DECLARE @SQL VARCHAR(MAX);
	SET @SQL = 'IF EXISTS (SELECT 1 FROM sys.change_tracking_tables 
                                WHERE object_id = OBJECT_ID(N''' + @fulltablename + '''))
                                BEGIN
                                    ALTER TABLE  ' + @fulltablename + '  DISABLE CHANGE_TRACKING
                                END'
                                
	Exec(@SQL);
END
GO


---------------------------------------------

-- dbo.procSysDropAllColumnConstraints
CREATE procedure [dbo].[procSysDropAllColumnConstraints] (
	@schema sysname,
	@object sysname
)
AS
BEGIN

declare @tableexpression sysname;
set @tableexpression = dbo.GetSQLTableExpression(@schema, @object);


declare colCursor CURSOR local FAST_FORWARD FOR
	select ColumnName from viewSysColumns where ObjectID = OBJECT_ID(@tableexpression);
	
open colCursor;

DECLARE @column nvarchar(128);

FETCH NEXT FROM colCursor into @column
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		exec procSysDropColumnConstraints @schema, @object, @column;
		--print 'exec procSysDropColumnConstraints @schema, @table, @column';
		FETCH NEXT FROM colCursor into @column
	END
close colCursor;
DEALLOCATE colCursor;


END
GO


---------------------------------------------

-- dbo.procSysDropClusteredIndex
create procedure [dbo].[procSysDropClusteredIndex] (@schema sysname,	@table sysname)
AS
BEGIN

	--DROP CLUSTERED INDEX
	declare @tableexpression sysname;
	set @tableexpression = dbo.GetSQLTableExpression(@schema, @table);

	declare @ClusteredIndexName varchar(200)
	set @ClusteredIndexName = (select i.name from sys.indexes i 
									inner join sys.tables t on i.object_id=t.object_id
									inner join sys.schemas s on t.schema_id=s.schema_id
								where t.type = 'u' and t.name = @table and s.name = @schema and i.type = 1)

	declare @sql nvarchar(max);
	set @sql = '
	IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N''[' + @schema + '].[' + @table + ']'') AND name = N''' + @ClusteredIndexName + ''' and is_primary_key = 1)
		ALTER TABLE ' + @tableexpression + ' DROP CONSTRAINT [' + @ClusteredIndexName + ']
	IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N''[' + @schema + '].[' + @table + ']'') AND name = N''' + @ClusteredIndexName + ''' and is_primary_key = 0)
		DROP INDEX ' + @ClusteredIndexName + ' ON ' + @tableexpression + ' WITH ( ONLINE = OFF )'
	exec sp_executesql @sql;

END


RETURN
GO


---------------------------------------------

-- dbo.procSysDropColumnAndDefault
CREATE PROC [dbo].[procSysDropColumnAndDefault]
    @schema SYSNAME,
    @table  SYSNAME,
    @column SYSNAME
AS

  DECLARE @sql VARCHAR(MAX)
  SET @sql = '
    ALTER TABLE [{0}].[{1}] DROP COLUMN [{2}]
  '

  IF (dbo.ColumnExists(@schema, @table, @column) = 1)
    BEGIN
      SET @sql = REPLACE(@sql, '{0}', @schema)
      SET @sql = REPLACE(@sql, '{1}', @table)
      SET @sql = REPLACE(@sql, '{2}', @column)

      BEGIN TRY
      EXEC procSysDropColumnConstraints @schema, @table, @column
      EXEC (@sql)
      END TRY
      BEGIN CATCH
      PRINT 'Column drop not successful: ' + @schema + '.' + @table + '.' + @column
      EXEC procSysRethrowError
      END CATCH
    END
GO


---------------------------------------------

-- dbo.procSysDropColumnConstraints
CREATE proc [dbo].[procSysDropColumnConstraints]  
 @schemaName sysname,  
 @tableName sysname,  
 @columnName sysname,  
 @includeCheck bit = 1,  
 @includeFK bit = 1,  
 @includePK bit = 1,  
 @includeUnique bit = 1,  
 @includeDefault bit = 1  
as  
  
  
declare crsCursor CURSOR local FAST_FORWARD FOR  
select  'ALTER TABLE [' + @schemaName + '].[' +@tableName + '] DROP CONSTRAINT [' + so.name + ']'  
 from  sysobjects so  
 inner join sys.sysconstraints sc on so.id = sc.constid 
 left join sys.key_constraints kc on kc.object_id = so.id
 left join sys.syscolumns scol on sc.colid = scol.colid and scol.id = so.parent_obj  
 left join sys.indexes i on i.index_id = kc.unique_index_id and i.object_id = object_id( '[' + @schemaName + '].[' +@tableName + ']' )
 left join sys.index_columns ic on ic.index_id = i.index_id and ic.object_id = object_id( '[' + @schemaName + '].[' +@tableName + ']' )
 left join sys.columns icol on icol.column_id = ic.column_id and icol.object_id = object_id( '[' + @schemaName + '].[' +@tableName + ']' )
where  
 ((@includeCheck = 1 and so.xtype = 'C')  
 or  
 (@includeFK = 1 and so.xtype = 'F')  
 or   
 (@includePK = 1 and so.xtype = 'PK')  
 or  
 (@includeUnique = 1 and so.xtype = 'UQ')  
 or  
 (@includeDefault = 1 and so.xtype = 'D'))   
 and (so.status & 64) = 0  
 and     parent_obj = object_id( '[' + @schemaName + '].[' +@tableName + ']' )  
 and (scol.name = @columnName  or icol.name = @columnName)
    
open crsCursor;  
  
DECLARE @SQL NVARCHAR(MAX)  
  
FETCH NEXT FROM crsCursor into @sql  
WHILE (@@FETCH_STATUS = 0)   
 BEGIN  
    
  exec(@sql)  
    
  FETCH NEXT FROM crsCursor into @sql  
 END  
close crsCursor;  
DEALLOCATE crsCursor;
GO


---------------------------------------------

-- dbo.procSysDropColumnDefault
CREATE proc [dbo].[procSysDropColumnDefault]
	@schemaName sysname,
	@tableName sysname,
	@columnName sysname
as


exec dbo.procSysDropColumnConstraints @schemaName,@tableName,@columnName,0,0,0,0,1;
GO


---------------------------------------------

-- dbo.procSysDropForeignKeyConstraint
CREATE PROC dbo.procSysDropForeignKeyConstraint 
	@SchemaName NVARCHAR(10),
	@TableName NVARCHAR(100),
	@ColumnName NVARCHAR(256)
AS
BEGIN
	DECLARE @command NVARCHAR(MAX)
	select @Command = 'ALTER TABLE ' + @SchemaName + '.[' + @TableName + '] DROP CONSTRAINT ' + d.name
	 from sys.tables t
	  join sys.default_constraints d on d.parent_object_id = t.object_id
	  join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
	 where t.name = @TableName
	  and t.schema_id = schema_id(@SchemaName)
	  and c.name = @ColumnName;
	EXEC sp_executesql @command
END
GO


---------------------------------------------

-- dbo.procSysDropIndex
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2021-12-16  KF	    JAZZ-31105	Created
** 2    2022-01-20	HV	    JAZZ-32256   Add possibility to drop index for views 
*************************************************************/
CREATE PROCEDURE dbo.procSysDropIndex (@schema sysname, @table sysname, @indexName sysname, @isView bit = 0)
AS

DECLARE @indexExists bit

IF @isView = 0
	BEGIN
	SET @indexExists =
		CASE WHEN EXISTS
			(select 1 from sys.indexes i
				inner join sys.tables t on t.object_id = i.object_id
				inner join sys.schemas s on s.schema_id = t.schema_id
				where s.name = @schema and t.name = @table and i.name = @indexName)
		THEN 1 ELSE 0
		END        
	END
ELSE -- @isView = 1
	BEGIN
	SET @indexExists = 
		CASE WHEN EXISTS
			(select 1 from sys.indexes i
			 inner join sys.views t on t.object_id = i.object_id
			 inner join sys.schemas s on s.schema_id = t.schema_id
			 where s.name = @schema and t.name = @table and i.name = @indexName)
		THEN 1 ELSE 0
		END
	END

IF (@indexExists = 1)
	BEGIN
		declare @sql nvarchar(max);
		set @sql = N'DROP INDEX ['+@indexName+'] ON ['+@schema+'].['+@table+']'

		exec sp_executesql @sql
	END
GO


---------------------------------------------

-- dbo.procSysDropPrimaryKeyConstraint
CREATE PROC dbo.procSysDropPrimaryKeyConstraint 
	@SchemaName NVARCHAR(10),
	@TableName NVARCHAR(100)
AS
BEGIN
	DECLARE @PKName NVARCHAR(MAX)
	SELECT @PKName = k.name
	FROM sys.key_constraints k
	INNER JOIN sys.tables t ON k.parent_object_id = t.object_id
	INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
	WHERE k.type = 'PK' AND t.name = @TableName and s.name = @SchemaName

	DECLARE @dropsql NVARCHAR(MAX) = 'ALTER TABLE ' + @SchemaName + '.' + @TableName + ' DROP CONSTRAINT ' + @PKName
	EXEC sp_executesql @dropsql
END
GO


---------------------------------------------

-- dbo.procSysDropProc
CREATE PROCEDURE [dbo].[procSysDropProc](
  @schema SYSNAME,
  @proc   SYSNAME
)
AS
  BEGIN

    DECLARE @tableexpression SYSNAME;
    SET @tableexpression = dbo.GetSQLTableExpression(@schema, @proc);
    DECLARE @sql VARCHAR(MAX);
    SET @sql = 'DROP PROCEDURE ' + @tableexpression;

    -- NOW DROP THE VIEW ---------------------------------------------------------------------
    IF EXISTS(SELECT * FROM sys.procedures WHERE name = @proc AND schema_name(schema_id) = @schema)
      EXEC (@sql);
    
  END
GO


---------------------------------------------

-- dbo.procSysDropTable
CREATE procedure [dbo].[procSysDropTable] (
	@schema sysname,
	@table sysname
)
AS
BEGIN

declare @tableexpression sysname;
set @tableexpression = dbo.GetSQLTableExpression(@schema, @table);

-- DROP CONSTRAINTS,TRIGGERS
exec procSysDropAllColumnConstraints @schema, @table
exec procSysDropTriggers @schema, @table;

-- NOW DROP THE TABLE ---------------------------------------------------------------------
declare @sql varchar(max);
set @sql = '

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[' + @schema + '].[' + @table + ']'') AND type in (N''U''))
	DROP TABLE ' + @tableexpression + ';
';

exec (@sql);

END
GO


---------------------------------------------

-- dbo.procSysDropTempTable
CREATE PROCEDURE [dbo].[procSysDropTempTable] (
  @tempTable  SYSNAME
)
AS
  BEGIN
    -- NOW DROP THE TEMP TABLE ---------------------------------------------------------------------
    DECLARE @sql VARCHAR(MAX);
    SET @sql = '
    IF OBJECT_ID(''tempdb..' + @tempTable + ''') IS NOT NULL
      DROP TABLE ' + @tempTable + ';
    ';

    EXEC (@sql);
  END
GO


---------------------------------------------

-- dbo.procSysDropTrigger
CREATE procedure [dbo].[procSysDropTrigger] (
	@schema sysname,
	@trigger sysname
)
AS
BEGIN

declare @triggerexpression sysname;
set @triggerexpression = dbo.GetSQLTableExpression(@schema, @trigger);

-- NOW DROP THE TABLE ---------------------------------------------------------------------
declare @sql varchar(max);
set @sql = '

if (OBJECT_ID(''[' + @schema + '].[' + @trigger + ']'', ''TRIGGER'') is not null)
	DROP TRIGGER ' + @triggerexpression + ';
';

print @sql;
exec (@sql);

END
GO


---------------------------------------------

-- dbo.procSysDropTriggers
CREATE procedure [dbo].[procSysDropTriggers] (
	@schema sysname,
	@object sysname,
	@IncludeAfter bit = 1,
	@IncludeInsteadOf bit = 1
)
AS
BEGIN

declare @tableexpression sysname;
set @tableexpression = dbo.GetSQLTableExpression(@schema, @object);


declare tCursor CURSOR FAST_FORWARD FOR
	select Name from sys.triggers T where T.parent_id = OBJECT_ID(@tableexpression)
	and
		((@IncludeAfter=1 and T.is_instead_of_trigger = 0) OR (@IncludeInsteadOf=1 and T.is_instead_of_trigger=1));
	
	
open tCursor;

DECLARE @trigger nvarchar(128);

FETCH NEXT FROM tCursor into @trigger
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		declare @sql varchar(max);
		set @sql =  'DROP TRIGGER [' + @schema + '].[' + @trigger + ']';
		exec (@sql);
		FETCH NEXT FROM tCursor into @trigger
	END
close tCursor;
DEALLOCATE tCursor;


END
GO


---------------------------------------------

-- dbo.procSysDropView
CREATE procedure [dbo].[procSysDropView] (
	@schema sysname,
	@view sysname
)
AS
BEGIN

declare @tableexpression sysname;
set @tableexpression = dbo.GetSQLTableExpression(@schema, @view);

-- DROP TRIGGERS
exec procSysDropTriggers @schema, @view;

-- NOW DROP THE VIEW ---------------------------------------------------------------------
declare @sql varchar(max);
set @sql = '

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[' + @schema + '].[' + @view + ']'') AND type in (N''V''))
	DROP VIEW ' + @tableexpression + ';
';

exec (@sql);

END
GO


---------------------------------------------

-- dbo.procSysGetUniqueObjectName
create procedure procSysGetUniqueObjectName (
	 @schema sysname,
	 @desiredName sysname
)
AS
BEGIN
	declare @testname sysname;
	declare @index int;

	set @testname = @desiredName;
	set @index = 0;

	if ( 0 = (select COUNT(O.object_id) from sys.objects O inner join sys.schemas S on S.schema_id = O.schema_id where S.name = @schema  and O.name = @desiredName))
	BEGIN
		select @desiredName
		return;
	END

	WHILE (1=1)
	BEGIN
		set @testname = @desiredName + '_' + CAST(@index as nvarchar(max));
		
		if ( 0 = (select COUNT(O.object_id) from sys.objects O inner join sys.schemas S on S.schema_id = O.schema_id where S.name = @schema  and O.name = @testname))
		BEGIN
			select @testname
			return;
		END
		set @index = @index + 1;
	END
END
GO


---------------------------------------------

-- dbo.procSysGetUniqueObjectNameForCopy
CREATE procedure [dbo].[procSysGetUniqueObjectNameForCopy] (
	 @schema sysname,
	 @desiredName sysname
)
AS
BEGIN
	declare @testname sysname;
	declare @index int;

	set @testname = @desiredName;
	set @index = 0;

	if ( 0 = (select COUNT(O.object_id) from sys.objects O inner join sys.schemas S on S.schema_id = O.schema_id where S.name = @schema  and O.name = @desiredName))
	BEGIN
		select @desiredName
		return;
	END

	WHILE (1=1)
	BEGIN
		set @testname = @desiredName + ' - Copy' + ISNULL(  
															(case when @index = 0 then null else ' (' + CAST(@index as nvarchar(max)) + ')' end), 
															'');
		
		if ( 0 = (select COUNT(O.object_id) from sys.objects O inner join sys.schemas S on S.schema_id = O.schema_id where S.name = @schema  and O.name = @testname))
		BEGIN
			select @testname
			return;
		END
		set @index = @index + 1;
	END
END
GO


---------------------------------------------

-- dbo.procSysRefreshView
CREATE procedure [dbo].[procSysRefreshView] (
	@viewName nvarchar(256)
)
AS
BEGIN

	-- NOW REFRESH THE VIEW ---------------------------------------------------------------------
	declare @sql varchar(max);
	set @sql = '

	IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''' + @viewName + ''') AND type in (N''V''))
			EXEC sp_refreshview ''' + @viewName + ''';
	';

	EXEC (@sql);

END
GO


---------------------------------------------

-- dbo.procSysRethrowError
-- Create the stored procedure to generate an error using 
-- RAISERROR. The original error information is used to
-- construct the msg_str for RAISERROR.
CREATE PROCEDURE procSysRethrowError AS
    -- Return if there is no error information to retrieve.
    IF ERROR_NUMBER() IS NULL
        RETURN;

    DECLARE 
        @ErrorMessage    NVARCHAR(4000),
        @ErrorNumber     INT,
        @ErrorSeverity   INT,
        @ErrorState      INT,
        @ErrorLine       INT,
        @ErrorProcedure  NVARCHAR(200);

    -- Assign variables to error-handling functions that 
    -- capture information for RAISERROR.
    SELECT 
        @ErrorNumber = ERROR_NUMBER(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE(),
        @ErrorLine = ERROR_LINE(),
        @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');

    -- Build the message string that will contain original
    -- error information.
    SELECT @ErrorMessage = 
        N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + 
            'Message: '+ ERROR_MESSAGE();

    -- Raise an error: msg_str parameter of RAISERROR will contain
    -- the original error information.
    RAISERROR 
        (
        @ErrorMessage, 
        @ErrorSeverity, 
        1,               
        @ErrorNumber,    -- parameter: original error number.
        @ErrorSeverity,  -- parameter: original error severity.
        @ErrorState,     -- parameter: original error state.
        @ErrorProcedure, -- parameter: original error procedure name.
        @ErrorLine       -- parameter: original error line number.
        );
GO


---------------------------------------------

-- dbo.procSysSetColumnIdentity
CREATE proc [dbo].[procSysSetColumnIdentity] (      
 @schema varchar(max),       
 @table varchar(max),      
 @column varchar(max),      
 @isDebug bit = 0)       
as      
      
      
      
-- Helper Variables      
declare @tempTable varchar(max)      
declare @columnType varchar(max)      
declare @source varchar(max)      
      
-- SQL      
declare @backupSQL varchar(max)      
declare @dropConstraintsSQL varchar(max)      
declare @fixTableSQL varchar(max)      
declare @reloadValuesSQL varchar(max)      
declare @addConstraintsSQL varchar(max)      
          
set @tempTable = '#zzTemp' + @table + 'Fix'      
set @source = '[' + @schema + '].[' + @table + ']'      
      
      
      
-- Validate Input      
if ((select object_id from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where s.name like @schema and t.name like @table) is null) begin      
 print 'Unable to find table: ' + @source + '.'      
 return      
end      
      
if ((select c.object_id from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name like @schema and t.name like @table and c.name like @column) is null) begin      
 print 'Unable to find column: [' + @column + '] in table: ' + @source + '.'      
 return      
end      
      
select @columnType = ty.name from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id inner join sys.types ty on ty.system_type_id = c.system_type_id where s.name like @schema and t.name
  
    
 like @table and c.name like @column;      
if (@columnType is null or @columnType not in ('tinyint', 'smallint', 'int', 'bigint')) begin      
 print 'Invalid column type: ''' + @columnType + '''. Expecting an integer.'      
 return      
end      
      
      
      
declare @columns as varchar(max)    
set @columns = ''    
select @columns = @columns + ',[' + c.name + ']'    
from sys.columns c    
inner join sys.tables t on t.object_id = c.object_id    
inner join sys.schemas s on s.schema_id = t.schema_id    
inner join sys.types ct on ct.system_type_id = c.system_type_id and ct.user_type_id = c.user_type_id    
where s.name = @schema and t.name = @table and ct.name not in ('timestamp')    
if (LEN(@columns) > 0) set @columns = SUBSTRING(@columns, 2, len(@columns) - 1)    
      
-- Save the values SQL      
set @backupSQL = '      
select ' + @columns + ' into ' + @tempTable + ' from ' + @source + ';    
'      
      
-- Reload Values SQL      
set @reloadValuesSQL = '      
set identity_insert ' + @source + ' ON;      
truncate table ' + @source + ';    
insert into ' + @source + '(' + @columns + ') select ' + @columns + ' from ' + @tempTable + ';    
set identity_insert ' + @source + ' OFF;      
drop table ' + @tempTable + ';      
'      
      
      
-- Fix Table      
set @fixTableSQL = '      
alter table ' + @source + ' drop column [' + @column + '];      
alter table ' + @source + ' add [' + @column + '] ' + @columnType + ' not null identity(1,1);      
'      
      
-- Constraints      
declare @defvalueName varchar(max)      
declare @defvalue varchar(max)      
      
select @defvalueName = d.name, @defvalue = d.definition      
from sys.default_constraints d      
      
inner join sys.tables t on t.object_id = d.parent_object_id      
inner join sys.schemas s on t.schema_id = t.schema_id      
inner join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id      
      
where s.name like @schema and t.name like @table and c.name like @column      
      
if (@defvalue is not null and @defvalueName is not null) begin      
 set @dropConstraintsSQL = '      
alter table ' + @source + ' drop constraint ' + @defvalueName + ';'      
 -- Default cannot be re-added because it will be an identity  
end      
      
set @dropConstraintsSQL = ISNULL(@dropConstraintsSQL, '')      
set @addConstraintsSQL = ISNULL(@addConstraintsSQL, '')      
    
    
declare @fkName varchar(max)      
declare @deleteAction varchar(max)      
declare @updateAction varchar(max)      
declare @pSchema varchar(max)      
declare @pTable varchar(max)      
declare @pColumn varchar(max)        
      
declare @pSource varchar(max)      
      
declare fkCursor CURSOR LOCAL FAST_FORWARD FOR      
 select      
  fk.name, fk.delete_referential_action_desc, fk.update_referential_action_desc, psch.name as parent_schema, ptbl.name as parent_table, pcol.name as parent_table_column      
 from sys.foreign_keys fk      
      
 inner join sys.foreign_key_columns fkc on fkc.constraint_object_id = fk.object_id      
      
 inner join sys.tables fktbl on fktbl.object_id = fk.referenced_object_id      
 inner join sys.schemas fksch on fksch.schema_id = fktbl.schema_id      
 inner join sys.columns fkcol on fkcol.object_id = fktbl.object_id and fkcol.column_id = fkc.referenced_column_id      
      
 inner join sys.tables ptbl on ptbl.object_id = fk.parent_object_id      
 inner join sys.schemas psch on psch.schema_id = ptbl.schema_id      
 inner join sys.columns pcol on pcol.object_id = fk.parent_object_id and pcol.column_id = fkc.parent_column_id      
      
 where fksch.name like @schema and fktbl.name like @table and fkcol.name like @column      
       
open fkCursor;      
fetch next from fkCursor into @fkName, @deleteAction, @updateAction, @pSchema, @pTable, @pColumn      
      
while (@@FETCH_STATUS <> -1) begin      
      
 set @pSource = '[' + @pSchema + '].[' + @pTable + ']'      
 set @updateAction = REPLACE(@updateAction, '_', ' ')      
 set @deleteAction = REPLACE(@deleteAction, '_', ' ')      
       
 set @dropConstraintsSQL = @dropConstraintsSQL + '      
alter table ' + @pSource + ' drop constraint ' + @fkName + ';'      
 set @addConstraintsSQL = @addConstraintsSQL + '      
alter table ' + @pSource + ' add constraint ' + @fkName + ' foreign key ([' + @pColumn + '])       
 references ' + @source + '([' + @column + '])       
 on update ' + @updateAction + '       
 on delete ' + @deleteAction + ';      
'      
      
 fetch next from fkCursor into @fkName, @deleteAction, @updateAction, @pSchema, @pTable, @pColumn      
end       
      
close fkCursor      
deallocate fkCursor      
      
      
      
      
        
      
declare @pkname varchar(max)      
declare @pkcolumns varchar(max)      
      
select @pkname = c.CONSTRAINT_NAME      
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc      
inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c on c.CONSTRAINT_NAME = tc.CONSTRAINT_NAME      
where tc.TABLE_SCHEMA like @schema and tc.TABLE_NAME like @table and tc.CONSTRAINT_TYPE = 'PRIMARY KEY'      
      
if (@pkname is not null) begin      
 set @pkcolumns = ''      
 select @pkcolumns = @pkcolumns + ', [' + c.COLUMN_NAME + ']' from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc      
 inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c on c.CONSTRAINT_NAME = tc.CONSTRAINT_NAME      
 where tc.TABLE_SCHEMA like @schema and tc.TABLE_NAME like @table and tc.CONSTRAINT_TYPE = 'PRIMARY KEY'      
 if (len(@pkcolumns) > 0) set @pkcolumns = SUBSTRING(@pkcolumns, 3, len(@pkcolumns) - 2)      
       
 set @dropConstraintsSQL = @dropConstraintsSQL + '      
alter table ' + @source + ' drop constraint ' + @pkname + ';'      
 set @addConstraintsSQL = '    
alter table ' + @source + ' add constraint ' + @pkname + ' primary key (' + @pkcolumns + ');' + @addConstraintsSQL      
    
end      
      
      
      
      
--- Print/Exec      
if (@isDebug = 1) begin      
      
 print 'begin transaction;'      
 print 'begin try      
-- Backing up values: ' + @backupSQL      
 print '      
-- Dropping Constraints: ' + @dropConstraintsSQL      
 print '      
-- Fixing Table: ' + @fixTableSQL      
 print '      
-- Reloading values: ' + @reloadValuesSQL      
 print '      
-- Re-Adding Constraints: ' + @addConstraintsSQL      
 print '  
end try  
begin catch  
 print cast(ERROR_NUMBER() as varchar(max)) + '' : '' + ERROR_MESSAGE()  
 if @@TRANCOUNT > 0  
  rollback transaction;  
end catch;  
if @@TRANCOUNT > 0  
 commit transaction;'  
end      
else begin      
 begin transaction;  
 begin try  
  exec (@backupSQL + @dropConstraintsSQL + @fixTableSQL + @reloadValuesSQL + @addConstraintsSQL)  
 end try  
 begin catch  
  print cast(ERROR_NUMBER() as varchar(max)) + ' : ' + ERROR_MESSAGE()  
  if @@TRANCOUNT > 0  
   rollback transaction;  
 end catch;  
 if @@TRANCOUNT > 0  
  commit transaction;  
end
GO


---------------------------------------------

-- dbo.procSysUpdateColumnType
CREATE proc [dbo].[procSysUpdateColumnType]
	@schema sysname,
	@table sysname,
	@column sysname,
	@newtype varchar(100),
	@meta varchar(100) = 'NOT NULL DEFAULT (0)'
as


begin try
		exec ('
		alter table ' + @schema + '.' + @table + ' add ' + @column + '__New ' + @newtype + ' ' + @meta+ '
		exec (''update ' + @schema + '.' + @table + ' set ' + @column + '__New = ' + @column + ''')
		exec procSysDropColumnAndDefault ''' + @schema + ''', ''' + @table + ''', ''' + @column + '''
		exec sp_rename ''' + @schema + '.' + @table + '.' + @column + '__New'', ''' + @column + ''', ''COLUMN'';
		')
end try
begin catch
	print 'Column type change failed.'
	exec [dbo].[procSysRethrowError]	
end catch
GO


---------------------------------------------

-- dbo.procTEEvictModelCache
CREATE PROCEDURE [dbo].[procTEEvictModelCache]
(
	@PlanWhereClause nvarchar(max),
    @IsDebugOnly bit = 0
)
AS
	DECLARE @json NVARCHAR(max) 
	
	if (exists(select 1 from fw.systemsetting where name = 'Use TaskEngine' and value = '1')) begin
		set @json = '{' +
			'"PlanWhereClause":"' + replace(@PlanWhereClause, '''', '''''') + '"' +
		'}';
	end else begin
		set @json = '{' +
			'"PlanWhereClause":"' + @PlanWhereClause + '"' +
		'}';
	end
		
	if (@IsDebugOnly = 0) begin
		DECLARE @statusCode INT;
		EXEC dbo.procCreateTask
			@taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.EvictModelCacheTask, Strata.CS.Jazz.Biz',
			@contextXML = @json,                                                                                   
			@taskSource = 'procTEEvictModelCache',
			@statusCode = @statusCode OUTPUT;

		IF @statusCode < 200 OR @statusCode > 299
		BEGIN
			RAISERROR('Failed to insert to Hangfire',16,1);
		END;
	end else begin
		print 'DECLARE @statusCode INT;
		EXEC dbo.procCreateTask
			@taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.EvictModelCacheTask, Strata.CS.Jazz.Biz'',
			@contextXML = ''' + @json + ''',                                                                                   
			@taskSource = ''procTEEvictModelCache'',
			@statusCode = @statusCode OUTPUT;'
	end
GO


---------------------------------------------

-- dbo.procTEGetLinkedServerFullName
CREATE PROCEDURE dbo.procTEGetLinkedServerFullName(
	@ReturnVal nvarchar(256) OUTPUT
)
AS
BEGIN

	declare @SMC_SERVER nvarchar(128);
	declare @SMC_DB nvarchar(128);
	declare @TE_GUID nvarchar(36);

	select @SMC_SERVER = Setting from DBSetting where Name = 'SMC_PRIMARY_SERVER'
	select @SMC_DB = setting from DBSetting where Name = 'SMC_PRIMARY_DATABASE'
	select @TE_GUID = setting from DBSetting where Name = 'TASKENGINE_CONNECTIONKEY'
	DECLARE @TE_FULLNAME nvarchar(256);

	declare @sql nvarchar(max);
	set @sql = '
	select 
		@TE_FULLNAMEOUT = LinkedServerFullName
	from [' + @SMC_SERVER + '].[' + @SMC_DB + '].[dbo].[viewDatabaseInfo]
		 where DatabaseGUID = ''' + @TE_GUID + '''
	'

	EXECUTE sp_executesql
	@sql,
	N'@TE_FULLNAMEOUT nvarchar(256) OUTPUT',
	@TE_FULLNAMEOUT=@TE_FULLNAME OUTPUT;

    SELECT @ReturnVal = @TE_FULLNAME;
END
GO


---------------------------------------------

-- dbo.procTEPartialModelRefresh
CREATE PROCEDURE [dbo].[procTEPartialModelRefresh]
(
	@compositeGUID uniqueidentifier,
    @ModelGUIDList nvarchar(max),
    @IsDebugOnly bit = 0
)
AS
begin
	if (@IsDebugOnly = 1) begin
		print 'EXEC dbo.procCreateTask
			@taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz'',
			@contextXML = '''',                                                                                   
			@taskSource = ''procTEPartialModelRefresh'';'
		return
	end

	--add to refresh queue, converting any requests that were already in queue into full refreshes
	update q set q.CompositeGUID = dbo.ZeroGUID() from [dbo].[MEModelRefreshQueue] q inner join [dbo].[XPlan] P (readuncommitted) on P.PlanGUID = q.ModelGUID where P.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@ModelGUIDList, ',')) and q.CompositeGUID != dbo.ZeroGUID() and q.CompositeGUID != @compositeGUID;
	insert into [dbo].[MEModelRefreshQueue] (ModelGUID, Source, CompositeGUID) 
    select 
        P.PlanGUID, 
        'procTEPartialModelRefresh', 
        case when mt.IsMemoryCachable = 1 
            then @compositeGUID 
            else dbo.ZeroGUID() 
        end 
    from [dbo].[XPlan] P (readuncommitted) 
        inner join [dbo].[EMFModelTemplate] mt on mt.ModelTemplateGUID = P.ModelTemplateGUID 
    where 1=1
    and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' --filter GM Blank template
    and P.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@ModelGUIDList, ',')) 
    and not exists(select 1 from [dbo].[MEModelRefreshQueue] ex where ex.ModelGUID = P.PlanGUID);

	--invalidate cache for requests that turned into full refreshes
	exec procInvalidateModelWorkbookCacheByWhereClause 'PlanGUID in(select ModelGUID from dbo.MEModelRefreshQueue where CompositeGUID = dbo.ZeroGUID())', 0, 'procTEPartialModelRefresh'
		
	--create task
	DECLARE @statusCode INT;
	EXEC dbo.procCreateTask
		@taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz',
		@contextXML = '',                                                                                   
		@taskSource = 'procTEPartialModelRefresh',
		@statusCode = @statusCode OUTPUT;

	IF @statusCode < 200 OR @statusCode > 299
	BEGIN
		RAISERROR('Failed to insert to Hangfire',16,1);
	END;
end
GO


---------------------------------------------

-- dbo.procTERefreshFillins
CREATE PROCEDURE [dbo].[procTERefreshFillins]
(
	@planTypeGUID uniqueidentifier,
	@modelTemplateGUID uniqueidentifier,
	@placeholderSectionGUIDList nvarchar(max),
    @IsDebugOnly bit = 0
)
AS
	if (@IsDebugOnly = 1) begin
		print 'EXEC dbo.procCreateTask
			@taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Fillins20.FillinRefreshTask, Strata.CS.Jazz.Biz'',
			@contextXML = '''',                                                                                   
			@taskSource = ''procTERefreshFillins'';'
		return
	end

	--insert refresh requests
	if(@placeholderSectionGUIDList <> '')
	begin
		INSERT INTO [dbo].[FillinRefreshRequest] ([PlanTypeGUID], [ModelTemplateGUID], [PlaceHolderSectionGUID])
		SELECT @planTypeGUID, @modelTemplateGUID, guid FROM CSVGuidsToTable(@placeholderSectionGUIDList)
	end
	else
	begin
		if(@modelTemplateGUID <> '00000000-0000-0000-0000-000000000000')
		begin
			INSERT INTO [dbo].[FillinRefreshRequest] ([ModelTemplateGUID]) VALUES (@modelTemplateGUID)
		end
		else
		begin
			INSERT INTO [dbo].[FillinRefreshRequest] ([PlanTypeGUID]) VALUES (@planTypeGUID)
		end
	end

	--create task
	DECLARE @statusCode INT;
	EXEC dbo.procCreateTask
		@taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Fillins20.FillinRefreshTask, Strata.CS.Jazz.Biz',
		@contextXML = '',                                                                                   
		@taskSource = 'procTERefreshFillins',
		@statusCode = @statusCode OUTPUT;

	IF @statusCode < 200 OR @statusCode > 299
	BEGIN
		RAISERROR('Failed to insert to Hangfire',16,1);
	END;
GO


---------------------------------------------

-- dbo.procTERefreshFillinsByPlan
CREATE PROCEDURE [dbo].[procTERefreshFillinsByPlan]
(
	@planGUIDList nvarchar(max),
	@placeholderSectionGUIDList nvarchar(max),
    @IsDebugOnly bit = 0
)
AS
	if (@IsDebugOnly = 1) begin
		print 'EXEC dbo.procCreateTask
			@taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Fillins20.FillinRefreshTask, Strata.CS.Jazz.Biz'',
			@contextXML = '''',                                                                                   
			@taskSource = ''procTERefreshFillinsByPlan'';'
		return
	end

	--insert refresh requests
	if(@placeholderSectionGUIDList = '')
	begin
		INSERT INTO [dbo].[FillinRefreshRequest] ([PlanGUID])
		SELECT guid FROM CSVGuidsToTable(@planGUIDList)
	end
	else
	begin
		INSERT INTO [dbo].[FillinRefreshRequest] ([PlaceHolderSectionGUID], [PlanGUID])
		SELECT phs.guid, p.guid FROM CSVGuidsToTable(@planGUIDList) p cross apply CSVGuidsToTable(@placeholderSectionGUIDList) phs  
	end
            
	--create task
	DECLARE @statusCode INT;
	EXEC dbo.procCreateTask
		@taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Fillins20.FillinRefreshTask, Strata.CS.Jazz.Biz',
		@contextXML = '',                                                                                   
		@taskSource = 'procTERefreshFillins',
		@statusCode = @statusCode OUTPUT;

	IF @statusCode < 200 OR @statusCode > 299
	BEGIN
		RAISERROR('Failed to insert to Hangfire',16,1);
	END;
GO


---------------------------------------------

-- dbo.procTERefreshModel
CREATE PROCEDURE [dbo].[procTERefreshModel]
(
    @ModelGUID uniqueidentifier,
    @IsIgnoreLock bit = 0, --obsolete
    @UseDependencies bit = 0, --obsolete
    @IsDebugOnly bit = 0
)
AS
begin
	if (@IsDebugOnly = 1) begin
		print 'EXEC dbo.procCreateTask
			@taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz'',
			@contextXML = '''',                                                                                   
			@taskSource = ''procTERefreshModel'';'
		return
	end

	--add to refresh queue
	insert into [dbo].[MEModelRefreshQueue] (ModelGUID, Source)
	select 
        P.PlanGUID, 
        'procTERefreshModel' 
    from [dbo].[XPlan] P (readuncommitted) 
    where 1=1
    and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' --filter GM Blank template
    and P.PlanGUID = @ModelGUID 
    and not exists(select 1 from [dbo].[MEModelRefreshQueue] ex where ex.ModelGUID = P.PlanGUID)

	--invalidate cache
	exec procInvalidateModelWorkbookCache @ModelGUID, 0, 0, 'procTERefreshModel'

	--create task
	DECLARE @statusCode INT;
	EXEC dbo.procCreateTask
		@taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz',
		@contextXML = '',                                                                                   
		@taskSource = 'procTERefreshModel',
		@statusCode = @statusCode OUTPUT;

	IF @statusCode < 200 OR @statusCode > 299
	BEGIN
		RAISERROR('Failed to insert to Hangfire',16,1);
	END;
end
GO


---------------------------------------------

-- dbo.procTERefreshModelList
CREATE PROCEDURE [dbo].[procTERefreshModelList]
(
    @ModelGUIDList nvarchar(max),
    @IsDebugOnly bit = 0
)
AS
begin
	if (@IsDebugOnly = 1) begin
		print 'EXEC dbo.procCreateTask
			@taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz'',
			@contextXML = '''',                                                                                   
			@taskSource = ''procTERefreshModelList'';'
		return
	end

	--add to refresh queue
	insert into [dbo].[MEModelRefreshQueue] (ModelGUID, Source)
	select 
        P.PlanGUID, 
        'procTERefreshModelList' 
    from [dbo].[XPlan] P (readuncommitted) 
    where 1=1
    and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' --filter GM Blank template
    and P.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@ModelGUIDList, ',')) 
    and not exists(select 1 from [dbo].[MEModelRefreshQueue] ex where ex.ModelGUID = P.PlanGUID)

	--invalidate cache
	declare @invalidateWhere nvarchar(max)
	set @invalidateWhere = 'PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @ModelGUIDList + ''', '',''))'
	exec procInvalidateModelWorkbookCacheByWhereClause @invalidateWhere, 0, 'procTERefreshModelList'
		
	--create task
	DECLARE @statusCode INT;
	EXEC dbo.procCreateTask
		@taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz',
		@contextXML = '',                                                                                   
		@taskSource = 'procTERefreshModelList',
		@statusCode = @statusCode OUTPUT;

	IF @statusCode < 200 OR @statusCode > 299
	BEGIN
		RAISERROR('Failed to insert to Hangfire',16,1);
	END;
end
GO


---------------------------------------------

-- dbo.procTERefreshModelTemplate
CREATE PROCEDURE [dbo].[procTERefreshModelTemplate]
(
	@ModelTemplateGUID uniqueidentifier,
    @IsIgnoreLock bit = 0, --obsolete
    @IsDebugOnly bit = 0
)
AS
begin
    if (@ModelTemplateGUID = '7F792F1F-F32A-4053-9907-534A2D736D45') return --filter GM Blank template

	if (@IsDebugOnly = 1) begin
		print 'EXEC dbo.procCreateTask
			@taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz'',
			@contextXML = '''',                                                                                   
			@taskSource = ''procTERefreshModelTemplate'';'
		return
	end

	--add to refresh queue
	insert into [dbo].[MEModelRefreshQueue] (ModelGUID, Source)
	select P.PlanGUID, 'procTERefreshModelTemplate' 
		from [dbo].[XPlan] P (readuncommitted) 
		where 1=1 
		and P.ModelTemplateGUID = @ModelTemplateGUID 
		and not exists(select 1 from [dbo].[MEModelRefreshQueue] ex where ex.ModelGUID = P.PlanGUID)

	--invalidate cache
	exec procInvalidateModelWorkbookCache @ModelTemplateGUID, 1, 0, 'procTERefreshModelTemplate'

	--create task
	DECLARE @statusCode INT;
	EXEC dbo.procCreateTask
		@taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz',
		@contextXML = '',                                                                                   
		@taskSource = 'procTERefreshModelTemplate',
		@statusCode = @statusCode OUTPUT;

	IF @statusCode < 200 OR @statusCode > 299
	BEGIN
		RAISERROR('Failed to insert to Hangfire',16,1);
	END;
end
GO


---------------------------------------------

-- dbo.procTableReseedIdentity
CREATE PROCEDURE dbo.procTableReseedIdentity
@schemaName VARCHAR(100),
@tableName VARCHAR(100),
@seedValue INT = null AS 

BEGIN
	
	DECLARE @tableNameWithSchema VARCHAR(200)
	SET @tableNameWithSchema = @schemaName + '.' + @tableName

	IF OBJECTPROPERTY(OBJECT_ID(@tableNameWithSchema), 'TableHasIdentity') = 1 
	BEGIN
		SELECT @seedValue = ISNULL(@seedValue,IDENT_SEED(@tableNameWithSchema))

		DBCC CHECKIDENT(@tableNameWithSchema,'RESEED', @seedValue)
	END  

END
GO


---------------------------------------------

-- dbo.procTruncateTemplateMappingbyFramework
CREATE PROC [dbo].[procTruncateTemplateMappingbyFramework]
	@FrameworkID Int
as

DECLARE @SCHEMA nvarchar(256)
DECLARE @FactTableName nvarchar(256)
DECLARE @SQL nvarchar(1024)
DECLARE @SQL2 nvarchar(1024)
DECLARE @FrameworkSchemaName nvarchar(100) = (Select FrameworkSchemaName from [fw].[DimFramework] WHERE FrameworkID=@FrameworkID)
DECLARE @ClientSchemaName nvarchar(100) = (Select ClientSchemaName from [fw].[DimFramework]WHERE FrameworkID=@FrameworkID)
Declare @TemplateGUIDs nvarchar(max) 
		

DECLARE FactTableCursor CURSOR FOR 

	select 
		t.name
		, (select name from sys.schemas where schema_id = t.schema_id) 
		from sys.tables t 
		where 
			1=1
			and t.schema_id in(select schema_id from sys.schemas where name in(@FrameworkSchemaName, @ClientSchemaName) ) 
			and t.name like 'fact%' and t.name like '%map' and name not like '%FactWorkingHoursPerMonthMap'
			order by t.name
			
OPEN FactTableCursor
	
    FETCH NEXT FROM FactTableCursor 
    INTO @FactTableName, @SCHEMA
    WHILE @@FETCH_STATUS = 0
    BEGIN
        set @SQL = 'truncate table ' + @SCHEMA + '.' + @FactTableName
        set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)'
--        print @SQL
--        print @SQL2
        EXECUTE sp_executesql @SQL 
        EXECUTE sp_executesql @SQL2
        FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
    END
    CLOSE FactTableCursor
    DEALLOCATE FactTableCursor

select @TemplateGUIDs = dbo.straggr(a.ID, ',', '') from (
			select distinct cast(db.ModelTemplateGUID as nvarchar(36)) as ID from [dbo].[EMFModelTemplateFramework] db where FrameworkID=@FrameworkID
		) a
		
exec [dbo].[procRunForManyGUIDs] @sql = 'exec [dbo].[procEMFRemoveTemplateMappings] @modeltemplateguid ={guidq}  ,@includeprofiles = 1', @guids = @TemplateGUIDs, @isExecuting = 1



RETURN
GO


---------------------------------------------

-- dbo.procUpdateDefaultMemberGuid
--Author: rreimer
--Branch: DSSAdvancedCostingNoKoz
--Forward
create proc procUpdateDefaultMemberGuid
as
	set nocount on

	declare @dimGuid nvarchar(36)
	declare @tableName nvarchar(max)
	declare crsInfo cursor fast_forward for 
		select
			cast(DG.DimensionGUID as nvarchar(36)),
			DG.SchemaName + '.' + DG.ObjectName as SQLObjectName
		from
			[dbo].[ScoreDimension] D
			inner join [dbo].[ScoreDimensionGroup] DG on DG.DimensionGroupGUID = D.PrimaryGroupGUID
			inner join sys.tables T on T.Name = DG.ObjectName
			inner join sys.schemas S on S.Name = DG.SchemaName and T.schema_id = S.schema_id
		where
		D.DefaultMemberGUID ='00000000-0000-0000-0000-000000000000'
		and	exists(select 1 from sys.columns C where C.object_id = T.object_id and Name = 'Name')
			
		open crsInfo
		fetch next from crsInfo into @dimGuid,@tableName
		declare @sql nvarchar(max)
		while(@@FETCH_STATUS = 0) begin
		set @sql = '
			update [dbo].[ScoreDimension] set DefaultMemberGUID = 
				coalesce((select top 1 M.MemberGUID from '+@tableName+' M where M.Name like ''%Not Specified%''), dbo.ZeroGUID())
			where DimensionGUID = ''' + @dimGuid +''''
				exec (@sql)
				fetch next from crsInfo into @dimGuid, @tableName
		end
		close crsInfo
		deallocate crsInfo
GO


---------------------------------------------

-- dbo.procUpdateDefaultMemberGuid2
CREATE proc [dbo].[procUpdateDefaultMemberGuid2]
@dimGuid nvarchar(36),
@tableName nvarchar(max),
@nameColumn nvarchar(max)
as
declare @sql nvarchar(max)
set @sql = '
			update [dbo].[ScoreDimension] set DefaultMemberGUID = 
				coalesce((select top 1 M.MemberGUID from '+@tableName+' M where M.'+@nameColumn+' like ''%Not Specified%''), dbo.ZeroGUID())
			where DimensionGUID = ''' + @dimGuid +''''
				exec (@sql)

RETURN
GO


---------------------------------------------

-- dbo.procUpdateScheduledTaskIsDisabled
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2019-12-16	KF		B-24658 MR | Automatic Reminders
*************************************************************/
CREATE PROCEDURE [dbo].[procUpdateScheduledTaskIsDisabled]
@ScheduledTaskGUID uniqueidentifier,
@IsDisabled BIT
AS

UPDATE dbo.TEScheduledTask
SET IsDisabled = @IsDisabled
WHERE ScheduledTaskGUID = @ScheduledTaskGUID
GO


---------------------------------------------

-- dbo.procUserCheckPasswordHistory
-- =============================================
-- Author:		Eric Kretzer
-- Create date: 04/12/2011
-- Description:	Check to see if a password has been used in the last X iterations
-- =============================================
CREATE PROCEDURE [dbo].[procUserCheckPasswordHistory]
	@USERGUID as uniqueidentifier,
	@HASHEDPASSWORD as nvarchar(64),
	@ITERATIONS as tinyint
AS
BEGIN
	select case when COUNT(*) > 0 then 1 else 0 end as [IsUsedPassword] from passwordhistory where UserGUID = @UserGUID and Iteration <= @Iterations and HashedPassword = @HashedPassword
END
GO


---------------------------------------------

-- dbo.procUserGroupDelete
CREATE procedure [dbo].[procUserGroupDelete] 
	@UserGroupGUID uniqueidentifier,
	@Name nvarchar(64) = '',
	@Type int = 0,
	@Description nvarchar(4000) = '',
	@Category nvarchar(64) = '',
	@LootGUID uniqueidentifier = '00000000-0000-0000-0000-00000000000000',
	@UserRoleGUID uniqueidentifier = '00000000-0000-0000-0000-00000000000000'
as

--Role assignment groups should never be deleted manually
IF (@Type != 1) BEGIN
	DELETE FROM UserGroup WHERE UserGroupGUID = @UserGroupGUID
END
GO


---------------------------------------------

-- dbo.procUserGroupInsert
CREATE  procedure [dbo].[procUserGroupInsert]
	@UserGroupGUID uniqueidentifier,
	@Name nvarchar(64),
	@Type int,
	@Description nvarchar(4000),
	@Category nvarchar(64),
	@LootGUID uniqueidentifier,
	@UserRoleGUID uniqueidentifier
as

IF (@Type != 1) BEGIN
	INSERT INTO UserGroup (UserGroupGUID, Name, Type, Description, Category) 
		VALUES (@UserGroupGUID, @Name, @Type, @Description, @Category)	
END
GO


---------------------------------------------

-- dbo.procUserGroupUpdate
CREATE  procedure [dbo].[procUserGroupUpdate]
	@UserGroupGUID uniqueidentifier,
	@Name nvarchar(64),
	@Type int,
	@Description nvarchar(4000),
	@Category nvarchar(64),
	@LootGUID uniqueidentifier,
	@UserRoleGUID uniqueidentifier
as

IF (@Type != 1) BEGIN
	UPDATE UserGroup SET Name = @Name, Type = @Type, Description = @Description, Category = @Category WHERE UserGroupGUID = @UserGroupGUID
END
GO


---------------------------------------------

-- dbo.procUserSetPassword
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[procUserSetPassword]
	@USERGUID as uniqueidentifier,
	@HASHEDPASSWORD as nvarchar(64)
AS
BEGIN
	UPDATE	UserProfile 
	SET 
			HASHEDPASSWORD = @HASHEDPASSWORD 
	WHERE 
			USERGUID = @USERGUID
END
GO


---------------------------------------------

-- dbo.procUserSetPasswordAll
create proc dbo.procUserSetPasswordAll
	@UnhashedPassword nvarchar(64)
as
	set nocount on
	
	declare @userguid uniqueidentifier
	declare crsUsers cursor fast_forward for select UserGUID from [dbo].[UserProfile]

	open crsUsers
	fetch next from crsUsers into @userguid

	while (@@fetch_status = 0) begin
		update [dbo].[UserProfile] set HashedPassword = dbo.GetHashedPassword(UserGUID, @UnhashedPassword) where UserGUID = @userguid
		
		fetch next from crsUsers into @userguid
	end

	close crsUsers
	deallocate crsUsers
GO


---------------------------------------------

-- dbo.procUserSetPasswordSandbox
CREATE proc dbo.procUserSetPasswordSandbox
	@UnhashedPassword nvarchar(64)
as
	set nocount on
	
	declare @userguid uniqueidentifier
	declare crsUsers cursor fast_forward for select UserGUID from [dbo].[UserProfile] where UserName like 'sandbox%' or UserName like 'elearning%' 
		or userguid in (select UserGUID from [dbo].[DemoUser])  order by UserName
	open crsUsers
	fetch next from crsUsers into @userguid

	while (@@fetch_status = 0) begin
		update [dbo].[UserProfile] set HashedPassword = dbo.GetHashedPassword(UserGUID, @UnhashedPassword) where UserGUID = @userguid
		
		fetch next from crsUsers into @userguid
	end

	close crsUsers
	deallocate crsUsers
GO


---------------------------------------------

-- dbo.procUsersEnsureSimpleMode
CREATE procedure [dbo].[procUsersEnsureSimpleMode]
as
begin
	insert into UserProfileAppModeAccessLink (UserGUID, AccessLevel)
	select 
		UP.UserGUID, 1
	from 
		UserProfile UP
	where 
		not exists(select 1 from UserProfileAppModeAccessLink L where UP.UserGUID = L.UserGUID)
end
GO


---------------------------------------------

-- dbo.procValidateColumnsExists
create proc [dbo].[procValidateColumnsExists]
	@schema nvarchar(max),
	@object nvarchar(max),
	@column nvarchar(max)
as
	
if dbo.ColumnExists(@schema, @object, @column) = 0 
	print @schema + '.' + @object + '.' + @column + ' is missing.'
GO


---------------------------------------------

-- dbo.procValidateDimensionProperty
CREATE proc [dbo].[procValidateDimensionProperty] 
	@DimensionName nvarchar(450),
	@PropertyName nvarchar(450),
	@MatchDimensionName nvarchar(450),
	@MatchDimensionLevel int = -1
AS

DECLARE @DimensionGUID uniqueidentifier
DECLARE @PropertyIndex int
DECLARE @TargetDimensionGUID uniqueidentifier

SET @DimensionGUID = '00000000-0000-0000-0000-000000000000'
SELECT @DimensionGUID = ListGUID FROM SecureList WHERE [Name] = @DimensionName
IF(@DimensionGUID = '00000000-0000-0000-0000-000000000000') BEGIN
	PRINT 'Dimension not found.'
	RETURN
END

SET @PropertyIndex = -1
SELECT @PropertyIndex = PropertyIndex FROM SecureListProperty WHERE ListGUID = @DimensionGUID AND [Name] = @PropertyName
IF(@PropertyIndex = -1) BEGIN
	PRINT 'Property not found.'
	RETURN
END

SET @TargetDimensionGUID = '00000000-0000-0000-0000-000000000000'
SELECT @TargetDimensionGUID = ListGUID FROM SecureList WHERE [Name] = @MatchDimensionName
IF(@TargetDimensionGUID = '00000000-0000-0000-0000-000000000000') BEGIN
	PRINT 'Target dimension not found.'
	RETURN
END

SELECT
	SM.ListMemberGUID AS MemberGUID,
	SM.[Name] AS Member,
	SMV.ValueText AS MemberPropertyValue
FROM
	SecureListMember SM
	LEFT JOIN SecureListMemberValue SMV ON SM.ListMemberGUID = SMV.ListMemberGUID AND SMV.ValueIndex = @PropertyIndex
	LEFT JOIN SecureListMember TM ON TM.ListGUID = @TargetDimensionGUID AND (SMV.ValueText = TM.[Name] OR CAST(SMV.ValueFloat AS NVARCHAR(64)) = TM.[Name]) AND (@MatchDimensionLevel = -1 OR TM.OutlineLevel = @MatchDimensionLevel)
WHERE
	SM.ListGUID = @DimensionGUID
	AND TM.ListMemberGUID IS NULL	
ORDER BY
	SM.SortOrderFullPath
GO


---------------------------------------------

-- dbo.procValidateModelStructures
-- =============================================
-- Author:		Eric Kretzer
-- Create date: Nov 21, 2006
-- Description:	Validates the Model Structure dynamic tables zzEMFModelMapping & zzEMFModelData
-- =============================================
CREATE PROCEDURE [dbo].[procValidateModelStructures]
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @zzMDCGUID uniqueidentifier
	DECLARE @mdcName nvarchar(max)
	DECLARE @zzMDCtablename nvarchar(36)
	DECLARE @zzDIMcursor nvarchar(256)
	DECLARE @zzDIMcolumnname nvarchar(256)
	DECLARE @modelTemplateMappingTableName nvarchar(256)
	DECLARE @modelDataTableName nvarchar(256)
	DECLARE @dimensionName as nvarchar(256)
	DECLARE @dimensionGUID as uniqueidentifier
	DECLARE @fixSQL as nvarchar(max)

	DECLARE zztable CURSOR LOCAL FAST_FORWARD
		FOR SELECT NAME, MODELDATACONFIGGUID FROM EMFMODELDATACONFIG
	OPEN zztable
	FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID
	WHILE @@FETCH_STATUS = 0
	BEGIN


		--SET @zztable_query = 'ALTER TABLE ' + @zztable_name + ' ADD [MAPPINGTYPE] int NOT NULL Default(0) WITH VALUES'
		--EXECUTE sp_executesql @zztable_query
		SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_')
			--PRINT @zztablename + ' table is present'
		--else

		SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_')
		SET @modelDataTableName = 'zzEMFModelData_' + @zzMDCtablename
		if (select count(*) from sysobjects where xtype='u' and name like @modelDataTableName) = 0
			--PRINT @zztablename + ' table is present'
		--else
			PRINT @modelDataTableName + ' table is not present'

		SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_')
		SET @modelTemplateMappingTableName = 'zzEMFModelTemplateMapping_' + @zzMDCtablename
		if (select count(*) from sysobjects where xtype='u' and name like @modelDataTableName) = 0
			--PRINT @zztablename + ' table is present'
		--else
			PRINT @modelTemplateMappingTableName + ' table is not present'

--SELECT sysobjects.name, syscolumns.name,* FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype='U'  order by sysobjects.name, syscolumns.name
		DECLARE @type int
		DECLARE zzdimensions CURSOR LOCAL FAST_FORWARD
		FOR SELECT SLM.LISTGUID, SLM.NAME, UPPER('G' + REPLACE(cast(SLM.LISTGUID as varchar(36)),'-','_')) FROM dbo.EMFModelDataConfigDimensionLink MDCDL JOIN SECURELIST SLM ON MDCDL.DIMENSIONGUID=SLM.LISTGUID WHERE MDCDL.MODELDATACONFIGGUID = @zzMDCGUID
		OPEN zzdimensions
		FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT @type = LISTTYPE FROM SECURELIST WHERE LISTGUID = @dimensionGUID

			IF @type = 0 or @type = 3 BEGIN
				SET @zzDIMcolumnname = @zzDIMcursor --+ 'GUID'
				SET @fixSQL = 'DELETE FROM emfmodeldataconfigdimensionlink WHERE DIMENSIONGUID = ''' + cast(@dimensionGUID as varchar(36)) + ''' and MODELDATACONFIGGUID = ''' + cast(@zzMDCGUID as varchar(36)) + ''''
				IF (SELECT count(*) FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype='U' AND (sysobjects.name like @modelDataTableName  or sysobjects.name like @modelTemplateMappingTableName)and syscolumns.name like @zzDIMcolumnname) <> 2
					--PRINT '   ' + @zzDIMcolumnname + ' is present'
				--ELSE
					PRINT @fixSQL + ' --' + cast(@zzMDCGUID as varchar(36)) + ' (' + @mdcName + ') - ' + @zzDIMcolumnname + ' (' + @dimensionName + ') is not present in both ModelData and ModelMapping'
			END 

			FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor
		END
		CLOSE zzdimensions
		DEALLOCATE zzdimensions
			
		FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID
	END
	CLOSE zztable
	DEALLOCATE zztable

END
GO


---------------------------------------------

-- dbo.procVerifyReportFolder
CREATE PROC [dbo].[procVerifyReportFolder] (
	@sourcedb nvarchar(100),
	@folderGUID uniqueidentifier
)
AS
BEGIN

	IF EXISTS (SELECT 1 FROM [dbo].[Folder] WHERE FolderGuid = @folderGUID)
		BEGIN
			RETURN
		END

	DECLARE @sql nvarchar(4000) = 'INSERT INTO [dbo].[Folder] ([FolderGuid], [FolderSetGUID], [ParentFolderGUID], [Name], [Description], [DateCreated], [DateModified], [OutlineLevel], [DisplayOrder], [ImageType], [FolderType], [QueryRootXML], [IsDeletedFolder], [BasedOnFolderGUID], [UpgradeHierarchyPath], [GlobalID])
								   SELECT ''' + CAST(@folderGuid AS nvarchar(50)) + ''', [FolderSetGUID], [ParentFolderGUID], [Name], [Description], [DateCreated], [DateModified], [OutlineLevel], [DisplayOrder], [ImageType], [FolderType], [QueryRootXML], [IsDeletedFolder], ''00000000-0000-0000-0000-000000000000'', [UpgradeHierarchyPath], [GlobalID]
								   FROM ' + @sourceDB + '.[dbo].[Folder]
								   WHERE folderGUID = ''' + CAST(@folderGuid AS nvarchar(50)) + ''''
	EXEC sp_executeSql @sql

	DECLARE @parentFolderGUID uniqueidentifier
	SELECT @parentFolderGUID = ParentFolderGUID FROM [dbo].[Folder] WHERE FolderGuid = @folderGUID

	IF NOT EXISTS (SELECT 1 FROM [dbo].[Folder] WHERE FolderGuid = @parentFolderGUID)
		BEGIN
			EXEC [dbo].[procVerifyReportFolder] @sourcedb, @parentFolderGUID
		END

END
GO


---------------------------------------------

-- dbo.procWFBrokenConditionsFix
create proc [dbo].[procWFBrokenConditionsFix]
as
	if((select COUNT(*) from wfeventplanstatement where type=1 and statementguid not in(select conditionsetguid from wfconditionset)) > 0) begin
		declare crsStatements cursor for select statementguid from wfeventplanstatement where type=1 and statementguid not in(select conditionsetguid from wfconditionset)
		declare @statementguid uniqueidentifier
		declare @conditionguid uniqueidentifier

		open crsStatements
		fetch next from crsStatements into @statementguid

		while(@@FETCH_STATUS = 0) begin
			select @conditionguid = newid()

			insert into wfconditionset values(@statementguid, @conditionguid);
			insert into wfcondition values(@conditionguid, @statementguid, 1, '00000000-0000-0000-0000-000000000000', '', '', 'Always', '', '');

			fetch next from crsStatements into @statementguid
		end

		close crsStatements
		deallocate crsStatements
	end
GO


---------------------------------------------

-- dbo.procWFHistoryReport
CREATE PROCEDURE [dbo].[procWFHistoryReport]
	@workflowMapGUID uniqueidentifier,
	@planGUIDList nvarchar(max)
AS
	declare @tempTableName nvarchar(34)
	select @tempTableName = '#T' + replace(CAST(NEWID() as nvarchar(36)), '-', '')

	declare @allsql nvarchar(max)
	set @allsql = '
		declare @workflowMapGUID uniqueidentifier
		declare @planGUIDList nvarchar(max)
		
		set @workflowMapGUID = ''' + CAST(@workflowMapGUID as nvarchar(36)) + '''
		set @planGUIDList = ''' + @planGUIDList + '''
	
		--create empty records for all plan/step combinations
		select distinct
			e.EntityGUID,
			s.WorkflowStepGUID,
			CAST(''1900-01-01 12:00:00.000'' as datetime) as EnteredStep,
			CAST(''1900-01-01 12:00:00.000'' as datetime) as ExitedStep,
			0 as DaysInStep
		into ' + @tempTableName + '
		from
			WFWorkflowStep s
			cross join dbo.viewWFEntity e
		where
			s.WorkflowMapGUID = @workflowMapGUID
			and e.EntityGUID in (select entityguid from WFToken where WorkflowMapGUID = @workflowMapGUID)
			and e.EntityGUID in (select guid from dbo.ConvertCSGuidsToTable(@planGUIDList, '',''))
			and s.IsHidden = 0
			and s.IsHiddenInRouting = 0
			
		declare @planguid uniqueidentifier
		declare @stepguid uniqueidentifier
		declare crsPlan cursor for select EntityGUID, WorkflowStepGUID from ' + @tempTableName + '

		open crsPlan
		fetch next from crsPlan into @planguid, @stepguid

		declare @sql nvarchar(max)

		--fill in entered/exited step dates from history
		while(@@FETCH_STATUS = 0) begin
			set @sql = ''
				update ' + @tempTableName + ' set EnteredStep = coalesce(h.DateTimeStamp, ''''1900-01-01 12:00:00.000'''')
				from
					' + @tempTableName + ' wfh
					inner join historyitem h on wfh.EntityGUID = h.ObjectGUID and h.Category=''''Workflow'''' and (h.MetaXML.exist(''''//WORKFLOWCHANGE[TYPE = 1 and ITEMGUID = "'' + lower(cast(@stepguid as nvarchar(36))) + ''"]'''') = 1)
				where
					wfh.EntityGUID = '''''' + cast(@planguid as nvarchar(36)) + '''''' and wfh.WorkflowStepGUID = '''''' + cast(@stepguid as nvarchar(36)) + '''''';
					
				update ' + @tempTableName + ' set ExitedStep = coalesce(h.DateTimeStamp, ''''1900-01-01 12:00:00.000'''')
				from
					' + @tempTableName + ' wfh
					inner join historyitem h on wfh.EntityGUID = h.ObjectGUID and h.Category=''''Workflow'''' and (h.MetaXML.exist(''''//WORKFLOWCHANGE[(TYPE = 3 or TYPE = 10) and ITEMGUID = "'' + lower(cast(@stepguid as nvarchar(36))) + ''"]'''') = 1)
				where
					wfh.EntityGUID = '''''' + cast(@planguid as nvarchar(36)) + '''''' and wfh.WorkflowStepGUID = '''''' + cast(@stepguid as nvarchar(36)) + '''''';
			''
			exec(@sql)

			fetch next from crsPlan into @planguid, @stepguid
		end

		close crsPlan
		deallocate crsPlan
			
		--calculate time in step
		update ' + @tempTableName + ' set DaysInStep = cast((GETDATE() - EnteredStep) as int) where EnteredStep != ''1900-01-01 12:00:00.000'' and ExitedStep = ''1900-01-01 12:00:00.000'';
		update ' + @tempTableName + ' set DaysInStep = cast((ExitedStep - EnteredStep) as int) where EnteredStep != ''1900-01-01 12:00:00.000'' and ExitedStep != ''1900-01-01 12:00:00.000'';
			
		select * from ' + @tempTableName + '
			
		drop table ' + @tempTableName + '
	'
	exec(@allsql)
GO


---------------------------------------------

-- dbo.procWFMergeWorkflows
create proc procWFMergeWorkflows
	@sourceWorkflowGUID uniqueidentifier,
	@targetWorkflowGUID uniqueidentifier
as
	update WFComment set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID
	update WFHistory set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID
	update WFProcess set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID
	update WFProcessStepLink set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID
	update WFToken set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID
	update WFTransition set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID
	update WFWorkflowStep set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID
	delete from WFToken where WorkflowMapGUID = @targetWorkflowGUID
GO


---------------------------------------------

-- dbo.procWFPlanStepCacheRefresh
CREATE proc dbo.procWFPlanStepCacheRefresh
as
	set nocount on

	declare @currentPlanGUID uniqueidentifier
	declare @lastPlanGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
	declare @stepName nvarchar(64)
	declare @stepGUID uniqueidentifier
	declare @stepList nvarchar(max) = ''
	declare @stepGUIDList nvarchar(max) = ''

	declare crsTokens cursor fast_forward for select distinct T.EntityGUID, S.WorkflowStepGUID, S.Name from [dbo].[WFToken] T (readuncommitted) inner join [dbo].[WFWorkflowStep] S on S.WorkflowStepGUID = T.WorkflowStepGUID where S.IsHidden = 0 and S.IsHiddenInRouting = 0 order by T.EntityGUID

	open crsTokens
	fetch next from crsTokens into @currentPlanGUID, @stepGUID, @stepName

	while (@@fetch_status = 0) begin
		if (@lastPlanGUID != @currentPlanGUID) begin
			if (len(@stepList) > 0) begin
				update [dbo].[XPlan] set CachedWorkflowStep = left(@stepList, 128), CachedWorkflowStepGUIDsCSV = left(@stepGUIDList, 400) where PlanGUID = @lastPlanGUID
			end
			
			set @stepList = ''
			set @stepGUIDList = ''
			set @lastPlanGUID = @currentPlanGUID
		end
		
		if (len(@stepList) > 0) begin
			set @stepList = @stepList + ', '
			set @stepGUIDList = @stepGUIDList + ','
		end
		set @stepList = @stepList + @stepName	
		set @stepGUIDList = @stepGUIDList + cast(@stepGUID as nvarchar(36))

		fetch next from crsTokens into @currentPlanGUID, @stepGUID, @stepName
	end

	if (@lastPlanGUID != '00000000-0000-0000-0000-000000000000') and (len(@stepList) > 0) begin
		update [dbo].[XPlan] set CachedWorkflowStep = left(@stepList, 128), CachedWorkflowStepGUIDsCSV = left(@stepGUIDList, 400) where PlanGUID = @lastPlanGUID
	end

	close crsTokens
	deallocate crsTokens
GO


---------------------------------------------

-- dbo.procWFSecurityRemoveInvalid
create proc dbo.procWFSecurityRemoveInvalid
	@entityGUID uniqueidentifier,
	@wfStepGUID uniqueidentifier
as
	delete ra
	from 
		WFToken t
		inner join viewWFEntity e on e.EntityGUID = t.EntityGUID
		inner join WFWorkflowStep s on s.WorkflowStepGUID = t.WorkflowStepGUID
		inner join UserRole r on r.Type = case when s.ReviewerAccess = 1 then 6 when s.ReviewerAccess = 2 then 8 else -1 end
		inner join S3RoleAssignment ra on ra.LootGroupID = e.CachedLootID and ra.RoleID = r.RoleID
		inner join UserProfile u on u.userGUID = ra.IdentityGUID --wf auto-security is always applied directly to users
	where
		s.ReviewerAccess in(1, 2) --read, write
		and s.ReviewerExitAccess != s.ReviewerAccess
		and not exists( --checks if assigned user is not a reviewer
			select 1
			from
				viewWFReviewerAssignmentIndexedAll ra
			where
				ra.WorkflowStepGUID = s.WorkflowStepGUID
				and ra.PlanGUID = e.EntityGUID
				and ra.UserGUID = u.UserGUID
		)
		and e.EntityGUID = @entityGUID
		and s.WorkflowStepGUID = @wfStepGUID
GO


---------------------------------------------

-- dbo.sp_alterdiagram
CREATE PROCEDURE dbo.sp_alterdiagram
	(
		@diagramname 	sysname,
		@owner_id	int	= null,
		@version 	int,
		@definition 	varbinary(max)
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
	
		declare @theId 			int
		declare @retval 		int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
		declare @ShouldChangeUID	int
	
		if(@diagramname is null)
		begin
			RAISERROR ('Invalid ARG', 16, 1)
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID();	 
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		revert;
	
		select @ShouldChangeUID = 0
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		
		if(@DiagId IS NULL or (@IsDbo = 0 and @theId <> @UIDFound))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1);
			return -3
		end
	
		if(@IsDbo <> 0)
		begin
			if(@UIDFound is null or USER_NAME(@UIDFound) is null) -- invalid principal_id
			begin
				select @ShouldChangeUID = 1 ;
			end
		end

		-- update dds data			
		update dbo.sysdiagrams set definition = @definition where diagram_id = @DiagId ;

		-- change owner
		if(@ShouldChangeUID = 1)
			update dbo.sysdiagrams set principal_id = @theId where diagram_id = @DiagId ;

		-- update dds version
		if(@version is not null)
			update dbo.sysdiagrams set version = @version where diagram_id = @DiagId ;

		return 0
	END
GO


---------------------------------------------

-- dbo.sp_creatediagram
CREATE PROCEDURE dbo.sp_creatediagram
	(
		@diagramname 	sysname,
		@owner_id		int	= null, 	
		@version 		int,
		@definition 	varbinary(max)
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
	
		declare @theId int
		declare @retval int
		declare @IsDbo	int
		declare @userName sysname
		if(@version is null or @diagramname is null)
		begin
			RAISERROR (N'E_INVALIDARG', 16, 1);
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID(); 
		select @IsDbo = IS_MEMBER(N'db_owner');
		revert; 
		
		if @owner_id is null
		begin
			select @owner_id = @theId;
		end
		else
		begin
			if @theId <> @owner_id
			begin
				if @IsDbo = 0
				begin
					RAISERROR (N'E_INVALIDARG', 16, 1);
					return -1
				end
				select @theId = @owner_id
			end
		end
		-- next 2 line only for test, will be removed after define name unique
		if EXISTS(select diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @diagramname)
		begin
			RAISERROR ('The name is already used.', 16, 1);
			return -2
		end
	
		insert into dbo.sysdiagrams(name, principal_id , version, definition)
				VALUES(@diagramname, @theId, @version, @definition) ;
		
		select @retval = @@IDENTITY 
		return @retval
	END
GO


---------------------------------------------

-- dbo.sp_drop_constraints
CREATE proc [dbo].[sp_drop_constraints]

	@tablename	sysname

as

-- name:   sp_drop_constraints
-- author: douglas bass
-- date:   06/19/2000

-- sp_drop_constraints will drop all constraints on the specified table, 
-- including CHECK, FOREIGN KEY, PRIMARY KEY, UNIQUE, and DEFAULT constraints.  
-- Compile it in your master database and use it from any user database.

set nocount on

declare @constname	sysname,
	@cmd		varchar(1024)

declare curs_constraints cursor LOCAL FAST_FORWARD for
	select 	name
	from 	sysobjects 
	where 	xtype in ('C', 'F', 'PK', 'UQ', 'D')
	and	(status & 64) = 0
	and     parent_obj = object_id(@tablename)

open curs_constraints

fetch next from curs_constraints into @constname
while (@@fetch_status = 0)
begin
	select @cmd = 'ALTER TABLE ' + @tablename + ' DROP CONSTRAINT ' + @constname
	exec(@cmd)
	fetch next from curs_constraints into @constname
end

close curs_constraints
deallocate curs_constraints

return 0
GO


---------------------------------------------

-- dbo.sp_dropdiagram
CREATE PROCEDURE dbo.sp_dropdiagram
	(
		@diagramname 	sysname,
		@owner_id	int	= null
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
		declare @theId 			int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
	
		if(@diagramname is null)
		begin
			RAISERROR ('Invalid value', 16, 1);
			return -1
		end
	
		EXECUTE AS CALLER;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		REVERT; 
		
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1)
			return -3
		end
	
		delete from dbo.sysdiagrams where diagram_id = @DiagId;
	
		return 0;
	END
GO


---------------------------------------------

-- dbo.sp_helpdiagramdefinition
CREATE PROCEDURE dbo.sp_helpdiagramdefinition
	(
		@diagramname 	sysname,
		@owner_id	int	= null 		
	)
	WITH EXECUTE AS N'dbo'
	AS
	BEGIN
		set nocount on

		declare @theId 		int
		declare @IsDbo 		int
		declare @DiagId		int
		declare @UIDFound	int
	
		if(@diagramname is null)
		begin
			RAISERROR (N'E_INVALIDARG', 16, 1);
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner');
		if(@owner_id is null)
			select @owner_id = @theId;
		revert; 
	
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname;
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId ))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1);
			return -3
		end

		select version, definition FROM dbo.sysdiagrams where diagram_id = @DiagId ; 
		return 0
	END
GO


---------------------------------------------

-- dbo.sp_helpdiagrams
CREATE PROCEDURE dbo.sp_helpdiagrams
	(
		@diagramname sysname = NULL,
		@owner_id int = NULL
	)
	WITH EXECUTE AS N'dbo'
	AS
	BEGIN
		DECLARE @user sysname
		DECLARE @dboLogin bit
		EXECUTE AS CALLER;
			SET @user = USER_NAME();
			SET @dboLogin = CONVERT(bit,IS_MEMBER('db_owner'));
		REVERT;
		SELECT
			[Database] = DB_NAME(),
			[Name] = name,
			[ID] = diagram_id,
			[Owner] = USER_NAME(principal_id),
			[OwnerID] = principal_id
		FROM
			sysdiagrams
		WHERE
			(@dboLogin = 1 OR USER_NAME(principal_id) = @user) AND
			(@diagramname IS NULL OR name = @diagramname) AND
			(@owner_id IS NULL OR principal_id = @owner_id)
		ORDER BY
			4, 5, 1
	END
GO


---------------------------------------------

-- dbo.sp_renamediagram
CREATE PROCEDURE dbo.sp_renamediagram
	(
		@diagramname 		sysname,
		@owner_id		int	= null,
		@new_diagramname	sysname
	
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
		declare @theId 			int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
		declare @DiagIdTarg		int
		declare @u_name			sysname
		if((@diagramname is null) or (@new_diagramname is null))
		begin
			RAISERROR ('Invalid value', 16, 1);
			return -1
		end
	
		EXECUTE AS CALLER;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		REVERT;
	
		select @u_name = USER_NAME(@owner_id)
	
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1)
			return -3
		end
	
		-- if((@u_name is not null) and (@new_diagramname = @diagramname))	-- nothing will change
		--	return 0;
	
		if(@u_name is null)
			select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @new_diagramname
		else
			select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @owner_id and name = @new_diagramname
	
		if((@DiagIdTarg is not null) and  @DiagId <> @DiagIdTarg)
		begin
			RAISERROR ('The name is already used.', 16, 1);
			return -2
		end		
	
		if(@u_name is null)
			update dbo.sysdiagrams set [name] = @new_diagramname, principal_id = @theId where diagram_id = @DiagId
		else
			update dbo.sysdiagrams set [name] = @new_diagramname where diagram_id = @DiagId
		return 0
	END
GO


---------------------------------------------

-- dbo.sp_upgraddiagrams
CREATE PROCEDURE dbo.sp_upgraddiagrams
	AS
	BEGIN
		IF OBJECT_ID(N'dbo.sysdiagrams') IS NOT NULL
			return 0;
	
		CREATE TABLE dbo.sysdiagrams
		(
			name sysname NOT NULL,
			principal_id int NOT NULL,	-- we may change it to varbinary(85)
			diagram_id int PRIMARY KEY IDENTITY,
			version int,
	
			definition varbinary(max)
			CONSTRAINT UK_principal_name UNIQUE
			(
				principal_id,
				name
			)
		);


		/* Add this if we need to have some form of extended properties for diagrams */
		/*
		IF OBJECT_ID(N'dbo.sysdiagram_properties') IS NULL
		BEGIN
			CREATE TABLE dbo.sysdiagram_properties
			(
				diagram_id int,
				name sysname,
				value varbinary(max) NOT NULL
			)
		END
		*/

		IF OBJECT_ID(N'dbo.dtproperties') IS NOT NULL
		begin
			insert into dbo.sysdiagrams
			(
				[name],
				[principal_id],
				[version],
				[definition]
			)
			select	 
				convert(sysname, dgnm.[uvalue]),
				DATABASE_PRINCIPAL_ID(N'dbo'),			-- will change to the sid of sa
				0,							-- zero for old format, dgdef.[version],
				dgdef.[lvalue]
			from dbo.[dtproperties] dgnm
				inner join dbo.[dtproperties] dggd on dggd.[property] = 'DtgSchemaGUID' and dggd.[objectid] = dgnm.[objectid]	
				inner join dbo.[dtproperties] dgdef on dgdef.[property] = 'DtgSchemaDATA' and dgdef.[objectid] = dgnm.[objectid]
				
			where dgnm.[property] = 'DtgSchemaNAME' and dggd.[uvalue] like N'_EA3E6268-D998-11CE-9454-00AA00A3F36E_' 
			return 2;
		end
		return 1;
	END
GO


---------------------------------------------

---------------------------------------------
--  FUNCTIONS
---------------------------------------------

-- dbo.CSVGuidsToTable
CREATE  FUNCTION [dbo].[CSVGuidsToTable] 
   (@CSVList varchar(max) )
RETURNS 
	@tPKList TABLE  ( guid uniqueidentifier)
AS
BEGIN
/*
	select * from dbo.[CSVGuidsToTable]('')
	select * from dbo.[CSVGuidsToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,')
	select * from dbo.[CSVGuidsToTable]('00000000-0000-0000-0000-000000000000')
	select * from dbo.[CSVGuidsToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000')
	DECLARE @list nvarchar(max)
	SET @list = '00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,'
	DECLARE @delimiter char(1)
	SET @delimiter = ','
	DECLARE @tbl TABLE (pos int IDENTITY(1, 1) NOT NULL, guid uniqueidentifier)
*/


		DECLARE @CSVCte  TABLE (startpos bigint, endpos bigint)


		DECLARE @startpos bigint
		SET @startpos = 1 
		DECLARE @endpos bigint
		SET @endpos = CHARINDEX(',' , @CSVList + ',') 

		IF @endpos = 0 RETURN

		INSERT INTO @CSVCte (startpos, endpos)
		SELECT @startpos, @endpos

		SET @startpos = @endpos + 1
		SET @endpos = CHARINDEX(',', @CSVList + ',', @endpos + 1) 
		
		WHILE @endpos <> 0 BEGIN
			INSERT INTO @CSVCte (startpos, endpos)
			SELECT @startpos, @endpos

			SET @startpos = @endpos + 1
			SET @endpos = CHARINDEX(',', @CSVList + ',', @endpos + 1) 
		END

		INSERT INTO @tPKList  
			   SELECT cast(rtrim(ltrim(SUBSTRING(@CSVList, StartPos,EndPos-StartPos))) as uniqueidentifier) FROM @CSVCte WHERE endpos - startpos >= 36



   RETURN 
END
GO


---------------------------------------------

-- dbo.CapitalizeEachWord
CREATE FUNCTION [dbo].[CapitalizeEachWord](
	@InputString varchar(8000)
)
RETURNS varchar(8000)
AS
BEGIN

declare @CurrentString varchar(8000);
declare @ReturnString varchar(8000);
set @ReturnString = '';

DECLARE BUILD CURSOR 
	FOR select Component from [dbo].[Split](@InputString, ' ')

Open BUILD
FETCH NEXT FROM BUILD INTO @CurrentString
WHILE (@@FETCH_STATUS <> - 1)
BEGIN
	set @ReturnString = @ReturnString + upper(substring(@currentString,1,1)) + lower(substring(@currentString, 2, Len(@currentString))) + ' '
	FETCH NEXT FROM BUILD INTO @CurrentString
END

set @ReturnString = RTRIM(@ReturnString)

CLOSE BUILD
DEALLOCATE BUILD


RETURN @ReturnString
END
GO


---------------------------------------------

-- dbo.ColumnExists
CREATE FUNCTION [dbo].[ColumnExists](
	@SchemaName NVARCHAR(128),
	@TableName NVARCHAR(MAX),
	@ColumnName NVARCHAR(128)
)
RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists.
AS
BEGIN
RETURN dbo.TableColumnExists(@SchemaName,@TableName,@columnname)
----See if the Table already contains the column.
--IF EXISTS
--(SELECT * FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID
--WHERE ObjectProperty(O.ID,'IsUserTable')=1
--AND O.Name=@TableName
--AND C.Name=@ColumnName)
--RETURN cast(1 as bit)
----Table does not contain the column.
--RETURN cast(0 as bit)
END
GO


---------------------------------------------

-- dbo.ColumnExistsByTableExpression
CREATE FUNCTION [dbo].[ColumnExistsByTableExpression](
	@TableExpression NVARCHAR(MAX),
	@ColumnName NVARCHAR(128)
)
RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists.
AS
BEGIN
RETURN dbo.TableColumnExistsByTableExpression(@TableExpression,@columnname)
----See if the Table already contains the column.
--IF EXISTS
--(SELECT * FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID
--WHERE ObjectProperty(O.ID,'IsUserTable')=1
--AND O.Name=@TableName
--AND C.Name=@ColumnName)
--RETURN cast(1 as bit)
----Table does not contain the column.
--RETURN cast(0 as bit)
END
GO


---------------------------------------------

-- dbo.ConstraintExists
create function dbo.ConstraintExists(
	@ConstraintName sysname
)
returns bit
AS
BEGIN
	declare @returnVal bit;
	set @returnVal = 0;
	
	if (exists(select 1 from sys.sysconstraints sc where OBJECT_NAME(sc.constid) = @ConstraintName))
	begin
		set @returnVal = 1
	end
	return @returnVal;
	
END
GO


---------------------------------------------

-- dbo.ConvertCSGuidsToTable
CREATE  FUNCTION [dbo].[ConvertCSGuidsToTable] 
   (@CSVList varchar(max), @delimiter char(1) = N',' )
RETURNS 
	@tPKList TABLE  ( listpos int IDENTITY(1, 1) NOT NULL, guid uniqueidentifier)
AS
BEGIN
/*
	select * from dbo.[ConvertCSGuidsToTable]('',',')
	select * from dbo.[ConvertCSGuidsToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,',',')
	select * from dbo.[ConvertCSGuidsToTable]('00000000-0000-0000-0000-000000000000',',')
	select * from dbo.[ConvertCSGuidsToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000',',')
	DECLARE @list nvarchar(max)
	SET @list = '00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,'
	DECLARE @delimiter char(1)
	SET @delimiter = ','
	DECLARE @tbl TABLE (pos int IDENTITY(1, 1) NOT NULL, guid uniqueidentifier)
*/


		DECLARE @startpos bigint
		SET @startpos = 1 
		DECLARE @endpos bigint
		SET @endpos = CHARINDEX(@delimiter , @CSVList + @delimiter) 

		IF @endpos = 0 RETURN

		IF @endpos - @startpos >= 36 BEGIN
			INSERT INTO @tPKList (guid) values (cast(rtrim(ltrim(SUBSTRING(@CSVList, @StartPos,@EndPos-@StartPos))) as uniqueidentifier))
		END

		SET @startpos = @endpos + 1
		SET @endpos = CHARINDEX(@delimiter, @CSVList + @delimiter, @endpos + 1) 
		
		WHILE @endpos <> 0 BEGIN
			IF @endpos - @startpos >= 36 BEGIN
				INSERT INTO @tPKList (guid) values (cast(rtrim(ltrim(SUBSTRING(@CSVList, @StartPos,@EndPos-@StartPos))) as uniqueidentifier))
			END

			SET @startpos = @endpos + 1
			SET @endpos = CHARINDEX(@delimiter, @CSVList + @delimiter, @endpos + 1) 
		END




   RETURN 
END
GO


---------------------------------------------

-- dbo.ConvertCSValuesToTable
CREATE  FUNCTION [dbo].[ConvertCSValuesToTable] 
   (@CSVList nvarchar(max), @delimiter char(1) = N',' )
RETURNS 
	@tPKList TABLE  ( pos int IDENTITY(1, 1) NOT NULL, val nvarchar(max))
AS
BEGIN
/*
	select * from dbo.[ConvertCSValuesToTable]('', ',')
	select * from dbo.[ConvertCSValuesToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,', ',')
	select * from dbo.[ConvertCSValuesToTable]('00000000-0000-0000-0000-000000000000', ',')
	select * from dbo.[ConvertCSValuesToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000', ',')
	DECLARE @list nvarchar(max)
	SET @list = '00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,'
	DECLARE @delimiter char(1)
	SET @delimiter = ','
	DECLARE @tbl TABLE (pos int IDENTITY(1, 1) NOT NULL, guid uniqueidentifier)
*/


		DECLARE @startpos bigint
		SET @startpos = 1 
		DECLARE @endpos bigint
		SET @endpos = CHARINDEX(@delimiter , @CSVList + @delimiter) 

		IF @endpos = 0 RETURN

		IF @endpos - @startpos >= 0 BEGIN
			INSERT INTO @tPKList (val) values ( rtrim(ltrim(SUBSTRING(@CSVList, @StartPos,@EndPos-@StartPos))))
		END

		SET @startpos = @endpos + 1
		SET @endpos = CHARINDEX(@delimiter, @CSVList + @delimiter, @endpos + 1) 
		
		WHILE @endpos <> 0 BEGIN
			--INSERT INTO @CSVCte (startpos, endpos)
			--SELECT @startpos, @endpos
			IF @endpos - @startpos >= 0 BEGIN
				INSERT INTO @tPKList (val) values ( rtrim(ltrim(SUBSTRING(@CSVList, @StartPos,@EndPos-@StartPos))))
			END

			SET @startpos = @endpos + 1
			SET @endpos = CHARINDEX(@delimiter, @CSVList + @delimiter, @endpos + 1) 
		END

		
			   --SELECT rtrim(ltrim(SUBSTRING(@CSVList, StartPos,EndPos-StartPos))) FROM @CSVCte WHERE endpos - startpos >= 0



   RETURN 
END
GO


---------------------------------------------

-- dbo.ConvertEMFFormatToScore
CREATE function [dbo].[ConvertEMFFormatToScore](@EMFFormat as nvarchar(max))
	returns nvarchar(max)
as
begin
	Return CASE @EMFFormat
		WHEN 'Percent 2' then '0.00%;(0.00%)'
		WHEN 'Dollars (Actual) 2' then '$#,##0.00;($#,##0.00)'
		WHEN 'Dollars (Thousands)' then '$#,##0;($#,##0)'
		WHEN 'Dollars (Thousands) 0' then '$#,##0;($#,##0)'
		WHEN 'Number 0' then '#,##0;(#,##0)'
		WHEN 'Number 1' then '#,##0.0;(#,##0.0)'
		WHEN 'Number 2' then '#,##0.00;(#,##0.00)'
		ELSE @EMFFormat
	END
END
GO


---------------------------------------------

-- dbo.DataIntegrationSchema
create function dbo.DataIntegrationSchema()
RETURNS sysname
BEGIN
	return 'int';
END
GO


---------------------------------------------

-- dbo.Divide
CREATE function [dbo].[Divide] (@left float, @right decimal(38,15))
returns decimal(38,15)
as
begin
return cast((@left / @right) as decimal(38,15))
end
GO


---------------------------------------------

-- dbo.DivideSafely
Create FUNCTION [dbo].[DivideSafely](@numeratoramount float, @denominatoramount float,  @isusingdenominator tinyint)
RETURNS float
AS
BEGIN
	
	if (@numeratoramount is null) begin
		return 0
	end 	
	
	if (@isusingdenominator = 0) begin
		return @numeratoramount
	end
	
	if (@denominatoramount is null) or (@denominatoramount = 0)	begin
		return 0
	end 
	
	return @numeratoramount / @denominatoramount

END
GO


---------------------------------------------

-- dbo.GUIDLEN
create function [dbo].[GUIDLEN]()
returns int
AS 
BEGIN
	declare @len int;
	select @len = LEN(dbo.ZeroGUID());
	return @len;
END
GO


---------------------------------------------

-- dbo.GetColumnDefaultValue
Create FUNCTION [dbo].[GetColumnDefaultValue](
	@SchemaName NVARCHAR(128),
	@TableName NVARCHAR(1000),
	@ColumnName NVARCHAR(128)
)
RETURNS nvarchar(4000)
AS
BEGIN

DECLARE @DefaultValue AS NVARCHAR(4000)

SET @DefaultValue = NULL

SELECT @DefaultValue = COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = @SchemaName
  AND TABLE_NAME = @TableName
  AND COLUMN_NAME = @ColumnName
 
IF @DefaultValue IS NOT NULL
BEGIN  
--Trim out the leading '(' and trailing ')'
--Leading '('
SET @DefaultValue = REPLACE(REPLACE(LTrim(RTrim(REPLACE(REPLACE(@DefaultValue,' ','~'),'(',' '))),' ','('),'~',' ')
--Trailing ')'
SET @DefaultValue = REPLACE(REPLACE(LTrim(RTrim(REPLACE(REPLACE(@DefaultValue,' ','~'),')',' '))),' ',')'),'~',' ')
END

RETURN @DefaultValue

END
GO


---------------------------------------------

-- dbo.GetCurrentFiscalYear
create function [dbo].[GetCurrentFiscalYear]()
RETURNS char(4) as begin

DECLARE @RET AS CHAR(4)
SELECT @RET = CAST(YEAR(dbo.getfiscaldate(getdate())) AS CHAR(4))

return @RET
end
GO


---------------------------------------------

-- dbo.GetCurrentMonthAmount
create FUNCTION [dbo].GetCurrentMonthAmount
(
	@currentMonthIndex tinyint,
	@amount01 money,
	@amount02 money,
	@amount03 money,
	@amount04 money,
	@amount05 money,
	@amount06 money,
	@amount07 money,
	@amount08 money,
	@amount09 money,
	@amount10 money,
	@amount11 money,
	@amount12 money
)
returns money with schemabinding
BEGIN

declare @amount money

if @currentMonthIndex = 1 set @amount = @amount01
if @currentMonthIndex = 2 set @amount = @amount02;
if @currentMonthIndex = 3 set @amount = @amount03; 
if @currentMonthIndex = 4 set @amount = @amount04; 
if @currentMonthIndex = 5 set @amount = @amount05; 
if @currentMonthIndex = 6 set @amount = @amount06; 
if @currentMonthIndex = 7 set @amount = @amount07; 
if @currentMonthIndex = 8 set @amount = @amount08; 
if @currentMonthIndex = 9 set @amount = @amount09; 
if @currentMonthIndex = 10 set @amount = @amount10; 
if @currentMonthIndex = 11 set @amount = @amount11; 
if @currentMonthIndex = 12 set @amount = @amount12; 


return @amount

END
GO


---------------------------------------------

-- dbo.GetDBSetting
CREATE FUNCTION [dbo].[GetDBSetting](@SettingName nvarchar(128))
										RETURNS nvarchar(4000)
									AS
									BEGIN
										DECLARE @Value nvarchar(4000)
										SET @Value = null
										
										if exists(select 1 from dbsetting where name = @SettingName) 
											set @Value = (select setting from DBSetting where Name = @SettingName)
										
										return @value
									END
GO


---------------------------------------------

-- dbo.GetDataIntSectionAcceptedTableName
create function dbo.GetDataIntSectionAcceptedTableName(
	@SectionId uniqueidentifier
)
returns varchar(max)
BEGIN
	return dbo.SanitizeNonDelimitedIdentifier('Import_' + cast(@SectionId as nvarchar(36)) + '_Accepted');
END
GO


---------------------------------------------

-- dbo.GetDataIntSectionAcceptedViewName
create function dbo.GetDataIntSectionAcceptedViewName(
	@SectionName nvarchar(128),
	@SectionId uniqueidentifier
)
returns varchar(max)
BEGIN
	return dbo.SanitizeNonDelimitedIdentifier('viewImport_' + @SectionName + '_' + cast(@SectionId as nvarchar(36)) + '_Accepted');
END
GO


---------------------------------------------

-- dbo.GetDataIntSectionRejectedTableName
create function dbo.GetDataIntSectionRejectedTableName(
	@SectionId uniqueidentifier
)
returns varchar(max)
BEGIN
	return dbo.SanitizeNonDelimitedIdentifier('Import_' + cast(@SectionId as nvarchar(36)) + '_Rejected');
END
GO


---------------------------------------------

-- dbo.GetDataIntSectionRejectedViewName
CREATE function dbo.GetDataIntSectionRejectedViewName(
	@SectionName nvarchar(128),
	@SectionId uniqueidentifier
)
returns varchar(max)
BEGIN
	return dbo.SanitizeNonDelimitedIdentifier('viewImport_' + @SectionName + '_' + cast(@SectionId as nvarchar(36)) + '_Rejected');
END
GO


---------------------------------------------

-- dbo.GetDaysInMonth
CREATE FUNCTION [dbo].[GetDaysInMonth] ( @pDate    DATETIME ) 
RETURNS INT
with schemabinding
AS
BEGIN

    --SET @pDate = CONVERT(VARCHAR(10), @pDate, 101)
    SET @pDate = dateadd(d, 1 - DAY(@pDate),@pdate)

    RETURN DATEDIFF(DD, @pDate, DATEADD(MM, 1, @pDate))
END
GO


---------------------------------------------

-- dbo.GetDaysInMonthsLoaded
CREATE FUNCTION [dbo].[GetDaysInMonthsLoaded] (@fiscalYearID int) 
RETURNS INT
AS
  BEGIN

	RETURN 
	(SELECT SUM(VALUE)
	 FROM [client].[viewFactWorkingHoursPerMonthUnpivoted] wh
		 INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = wh.FiscalMonthID
	 WHERE FiscalYearID = @FiscalYearID
		  AND fm.SortOrder <= (SELECT CAST(Setting AS int) FROM [dbo].[DBSetting] WHERE Name = 'OB_Months_Loaded'))

  END
GO


---------------------------------------------

-- dbo.GetDefaultConstraintName
CREATE FUNCTION [dbo].[GetDefaultConstraintName](
	@SQLSchemaName nvarchar(128),
	@SQLObjectName nvarchar(128),
	@ColumnName NVARCHAR(128)
)
returns nvarchar(128)
AS
BEGIN
	return [dbo].[GetDefaultConstraintNameByTableExpression](@SQLSchemaName + '.' + @SQLObjectName, @ColumnName);

END
GO


---------------------------------------------

-- dbo.GetDefaultConstraintNameByTableExpression
CREATE FUNCTION [dbo].[GetDefaultConstraintNameByTableExpression](
	@SQLObjectExpression VARCHAR(MAX),
	@ColumnName NVARCHAR(128)
)
returns nvarchar(128)
AS
BEGIN
	declare @defConstraint nvarchar(128);
		select top 1 @defConstraint = c.name from sys.default_constraints c
			inner join sys.columns col on col.default_object_id = c.object_id
			inner join sys.objects o  on o.object_id = c.parent_object_id
			inner join sys.schemas s on s.schema_id = o.schema_id
		where ('[' + s.name + '].[' + o.name + ']') = @SQLObjectExpression 
			and col.name = @ColumnName
	
	if (@defConstraint is null)
	begin
		select top 1 @defConstraint = c.name from sys.default_constraints c
			inner join sys.columns col on col.default_object_id = c.object_id
			inner join sys.objects o  on o.object_id = c.parent_object_id
			inner join sys.schemas s on s.schema_id = o.schema_id
		where (s.name + '.' + o.name) = @SQLObjectExpression 
			and col.name = @ColumnName
	end

	return @defConstraint;

END
GO


---------------------------------------------

-- dbo.GetDepreciationPart
CREATE FUNCTION [dbo].[GetDepreciationPart](
	@amount money
	,@amountYear int
	,@usefulLife int
	,@inserviceYear int
	,@inserviceMonth int
	,@resultYear int
	)
RETURNS Money
AS
BEGIN

if @amountYear > @inserviceYear set @inserviceYear = @amountYear

if @resultYear < @inserviceYear  begin
	return 0
end

if @resultYear > @inserviceYear + @usefulLife  begin
	return 0
end

declare @firstYearMonths int
set @firstYearMonths = 12 - @inserviceMonth

declare @lastYearMonths int
set @lastYearMonths = 12 - @firstYearMonths

declare @yearlyAmount money
set @yearlyAmount = @amount / @usefulLife

if @resultYear = @inserviceYear begin
	--handle first year
	--set @result = (@firstYearMonths / 12.0) * @yearlyAmount
	return (@firstYearMonths / 12.0) * @yearlyAmount
end


if @resultYear = @inserviceYear + @usefulLife  begin
	--handle last year
	--set @result = (@lastYearMonths / 12.0) * @yearlyAmount
	return (@lastYearMonths / 12.0) * @yearlyAmount
end

return @yearlyAmount

end
GO


---------------------------------------------

-- dbo.GetDirectoryCacheName
CREATE function [dbo].[GetDirectoryCacheName](@plantypeguid as uniqueidentifier)
	returns nvarchar(max)
as
begin
	declare @plantypename nvarchar(128)
	declare @tablename nvarchar(max)
	
	set @plantypename = (select name from PlanType where PlanTypeGUID=@planTypeGUID)
	set @tablename = 'data.DirectoryCache_' + replace(replace(replace(@plantypename, ' ', ''), '-', ''), '.', '')
	
	return @tablename
end
GO


---------------------------------------------

-- dbo.GetEscapedString
CREATE function [dbo].[GetEscapedString] (
	@expression varchar(max)
	)
returns varchar(max)
AS
BEGIN
	declare @ret varchar(max);
	set @ret = replace(replace(replace(replace(replace(@expression,'''',''),']',''),'[',''),'(',''),')','');
	return @ret;
END
GO


---------------------------------------------

-- dbo.GetEventVersion
create FUNCTION [dbo].[GetEventVersion](
	@EventName varchar(64)
	)
RETURNS varbinary(8)
AS
BEGIN
 	declare @ret timestamp
	select @ret = version from event where eventname = @eventname
	if @ret is null set @ret = 0
	return @ret
end
GO


---------------------------------------------

-- dbo.GetFillinMembersPastMaxIndex
CREATE FUNCTION [dbo].[GetFillinMembersPastMaxIndex] 
   (@modelGUID uniqueidentifier, @placeholderDimensionGUID uniqueidentifier, @maxIndex int)
RETURNS 
	@fillInMemberGUIDS TABLE  ( guid uniqueidentifier)
AS
BEGIN

	--declare @modelGUID uniqueidentifier
	--declare @structureDimensionGUID as uniqueidentifier --ph

	--declare @maxIndex int
	--set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77'
	--set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC'

	----select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid)
	--set @maxIndex = 1
	--declare @minIndex int

--delete fillins past index @maxIndex
	
	insert into @fillinMemberGUIDs
	select 
		FilledInMemberGUID
	FROM
		(
		select 
			--modelguid,dbo.getplanname(modelguid),
			row_number() over (order by slm.sortorderfullpath) as RowNum, 
			FilledInMemberGUID
		from
			EMFFillIn fi
			inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid
		where
			PlaceholderMemberGUID in 
				(	select slm.listmemberguid 
					from securelistmember slm 
					where slm.listguid = @placeholderDimensionGUID
				)
			and ModelGUID = @modelGUID
		) FillIns
	WHERE
		RowNum > @MaxIndex 
		
		
	

   RETURN 
END
GO


---------------------------------------------

-- dbo.GetFiscalDate
CREATE FUNCTION [dbo].[GetFiscalDate](
	@NonFiscalDate datetime 
	)
RETURNS DATETIME--Returns 0 if column does not exist. Returns 1 if column exists.
AS
BEGIN
--See if the Table already contains the column.


	declare @yeday varchar(2)
	select @yeday = setting from dbsetting where name = 'GENERAL_FISCALYEARENDDAY'
	declare @yemonth varchar(2)
	select @yemonth = setting from dbsetting where name = 'GENERAL_FISCALYEARENDMONTH'

	--set @yemonth = '04'
	--set @yeday = '30'

	declare @yedate datetime
	set @yedate =  @yemonth + '/' + @yeday + '/' + cast(year(@NonFiscalDate) as varchar(4))


	if datediff(dd, @yedate, @NonFiscalDate) > = 1 begin
		return dateadd(yy,1,@NonFiscalDate)
	end else begin
		return @NonFiscalDate
	end

	--needed because functions are weird
	return @NonFiscalDate
end

--Table does not contain the column.
GO


---------------------------------------------

-- dbo.GetFiscalDateNow
create function dbo.GetFiscalDateNow()
RETURNS DATETIME as begin
return dbo.getfiscaldate(getdate())
end
GO


---------------------------------------------

-- dbo.GetFiscalStartMonth
CREATE FUNCTION dbo.GetFiscalStartMonth()
RETURNS int
AS
BEGIN

	DECLARE @fiscalYearEndMonth INT;
	DECLARE @fiscalYearStartMonth INT;

	SET @fiscalYearEndMonth = CAST(dbo.GetDBSetting('GENERAL_FISCALYEARENDMONTH') AS INT);

	IF @fiscalYearEndMonth = 12
	BEGIN
		SET @fiscalYearStartMonth = 1;
	END
	ELSE 
	BEGIN
		SET @fiscalYearStartMonth = @fiscalYearEndMonth + 1;
	END  
	
	RETURN @fiscalYearStartMonth

END;
GO


---------------------------------------------

-- dbo.GetFiscalYearEndDate
CREATE FUNCTION dbo.GetFiscalYearEndDate()
	RETURNS Date
AS
BEGIN

	DECLARE @EndDate DATE;

	SET @EndDate = CONVERT(DATE, dbo.GetCurrentFiscalYear() + '/'+  dbo.GetDBSetting('GENERAL_FISCALYEARENDMONTH') + '/' +dbo.GetDBSetting('GENERAL_FISCALYEARENDDAY') );
	
	RETURN @EndDate

END;
GO


---------------------------------------------

-- dbo.GetFiscalYearForDate
CREATE FUNCTION [dbo].[GetFiscalYearForDate](@TestDate datetime) 

RETURNS int
AS
BEGIN

	declare @yeday varchar(2)
	select @yeday = setting from dbsetting where name = 'GENERAL_FISCALYEARENDDAY'
	declare @yemonth varchar(2)
	select @yemonth = setting from dbsetting where name = 'GENERAL_FISCALYEARENDMONTH'

	declare @FiscalYear int

	set @FiscalYear = (Select
	(CASE WHEN (DATEPART(month, @TestDate) = @yemonth) THEN
		 (CASE WHEN (DATEPART(day, @TestDate) > @yeday) 
            THEN (DATEPART(year, @TestDate) + 1) 
           ELSE (DATEPART(year, @TestDate)) END) 
           ELSE (CASE WHEN (DATEPART(month, @TestDate) 
            > @yemonth) THEN (DATEPART(year, @TestDate) + 1) ELSE (DATEPART(year, @TestDate)) END) END) AS FiscalYear)
            
  return @FiscalYear

END
GO


---------------------------------------------

-- dbo.GetFiscalYearStartDate
CREATE FUNCTION dbo.GetFiscalYearStartDate()
	RETURNS Date
AS
BEGIN

	DECLARE @StartDate DATE;

	SET @StartDate = DATEADD(DAY, 1, DATEADD(YEAR, -1, dbo.GetFiscalYearEndDate()));
	
	RETURN @StartDate

END;
GO


---------------------------------------------

-- dbo.GetFolderFullPath
create function GetFolderFullPath(@folderguid as uniqueidentifier)
	returns nvarchar(max)
as
begin
	--declare @folderguid uniqueidentifier
	--set @folderguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B'

	declare @parentfolderguid uniqueidentifier
	declare @folderfound bit
	declare @fullpath nvarchar(max)

	select @fullpath = name, @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @folderguid

	declare @currentfoldername nvarchar(450)

	while @folderfound = 1 begin
		set @folderfound = 0
		select @currentfoldername = name, @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @parentfolderguid

		if @folderfound = 1 begin
			set @fullpath = @currentfoldername + '\' + @fullpath
		end 
	end

	return @fullpath
end
GO


---------------------------------------------

-- dbo.GetFolderFullPathGUID
create function [dbo].[GetFolderFullPathGUID](@folderguid as uniqueidentifier)
	returns nvarchar(max)
as
begin
	--declare @folderguid uniqueidentifier
	--set @folderguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B'

	declare @parentfolderguid uniqueidentifier
	declare @folderfound bit
	declare @fullpath nvarchar(max)

	select @fullpath = cast(folderguid as varchar(36)), @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @folderguid

	declare @currentfoldername varchar(36)

	while @folderfound = 1 begin
		set @folderfound = 0
		select @currentfoldername = cast(folderguid as varchar(36)), @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @parentfolderguid

		if @folderfound = 1 begin
			set @fullpath = @currentfoldername + '\' + @fullpath
		end 
	end

	return @fullpath
end
GO


---------------------------------------------

-- dbo.GetFolderGUID
CREATE function [dbo].[GetFolderGUID](@fullpath as nvarchar(max))
	returns uniqueidentifier
as
begin
	
	declare @folderguid As uniqueidentifier

	set @folderguid = (select folderguid from folder where dbo.getfolderfullpath(folderguid) = cast('CHW\' + Left(@fullpath,Len(@fullpath) - 1) as nvarchar(Max)))

	If (@folderguid is null)
		set @folderguid = '00000000-0000-0000-0000-000000000000'

	return @folderguid

end
GO


---------------------------------------------

-- dbo.GetFolderName
Create function [dbo].[GetFolderName](@folderguid as uniqueidentifier)
	returns nvarchar(450)
as
begin
	
	declare @foldername As nvarchar(450)

	set @foldername = (select name from folder where folderguid = @folderguid)

	return @foldername

end
GO


---------------------------------------------

-- dbo.GetFolderSortorderFullPath
CREATE function [dbo].[GetFolderSortorderFullPath](@folderguid as uniqueidentifier)
	returns nvarchar(max)
as
begin
/*
	select dbo.GetFolderSortorderFullPath(folderguid),* from folder where foldersetguid = 'BFB042E0-119C-4CFB-9C65-787275EEDB93' order by dbo.[GetFolderSortorderFullPath](folderguid)
*/
	--declare @folderguid uniqueidentifier
	--set @folderguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B'

	declare @parentfolderguid uniqueidentifier
	declare @folderfound bit
	declare @fullpath nvarchar(max)

	select @fullpath = replace(space(10 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0'), @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @folderguid

	declare @currentfoldername nvarchar(450)

	while @folderfound = 1 begin
		set @folderfound = 0
		select @currentfoldername = replace(space(10 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0'), @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @parentfolderguid

		if @folderfound = 1 begin
			set @fullpath = @currentfoldername + '\' + @fullpath
		end 
	end

	return @fullpath
end


--select replace(space(5 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0') from folder
GO


---------------------------------------------

-- dbo.GetFoldersRecursive
CREATE FUNCTION [dbo].[GetFoldersRecursive] 
   (@folderguid uniqueidentifier)
RETURNS 
	@folderguids TABLE  ( guid uniqueidentifier)
AS
BEGIN
/*
	select * from dbo.GetFoldersRecursive('2F4DEF7F-26F4-41AD-9A6E-8570A3AE78B9')
*/
	DECLARE @ISDELETED bit
	SELECT @ISDELETED = COALESCE(ISDELETEDFOLDER, CAST(0 AS BIT)) FROM FOLDER WHERE FOLDERGUID = @folderguid

	INSERT INTO @folderguids
	SELECT FOLDERGUID FROM FOLDER WHERE FOLDERGUID = @folderguid

	WHILE @@ROWCOUNT > 0 BEGIN
		INSERT INTO @folderguids
		SELECT FOLDERGUID FROM FOLDER WHERE ISDELETEDFOLDER = @ISDELETED AND PARENTFOLDERGUID IN (select guid from @folderguids) AND NOT FOLDERGUID IN (select guid from @folderguids)
	END

   RETURN 
END
GO


---------------------------------------------

-- dbo.GetFormFieldGUID
CREATE function [dbo].[GetFormFieldGUID](@aFormFieldName as nvarchar(64)) returns uniqueidentifier
as
BEGIN
	declare @ret as uniqueidentifier
	select top 1 @ret = formfieldguid from feformfield where name like @aFormFieldName
	return @ret
END
GO


---------------------------------------------

-- dbo.GetFormFieldTypeColumn
CREATE function [dbo].[GetFormFieldTypeColumn](@aFormFieldType as int) returns varchar(64)
as
BEGIN
	declare @ret as varchar(64)
	
	select @ret = case
		when @aFormFieldType = 1 then 'ValueFloat'
		when @aFormFieldType = 2 then 'ValueFloat'
		when @aFormFieldType = 3 then 'ValueFloat'
		when @aFormFieldType = 5 then 'ValueDate'
		when @aFormFieldType = 12 then 'ValueBit'
		when @aFormFieldType = 15 then 'ValueBit'
		else 'ValueVarChar' end
	
	return @ret
END
GO


---------------------------------------------

-- dbo.GetFormFieldValue
CREATE function [dbo].[GetFormFieldValue](@aFormFieldGUID as uniqueidentifier, @aPlanGUID as uniqueidentifier) returns varchar(Max)
as
BEGIN
	declare @ret as varchar(Max)
	select top 1 @ret = valuevarchar from feformdata where feformdata.entityguid = @aPlanGUID AND formfieldguid = @aFormFieldGUID		
	return @ret
END
GO


---------------------------------------------

-- dbo.GetHangfireApiEndpoint
CREATE 
     
  FUNCTION [dbo].[GetHangfireApiEndpoint]() 
       RETURNS  varchar(200) 
    AS 
 BEGIN 
                  
       DECLARE @domain nvarchar(100); 
                  
        SELECT @domain = [ds].[Setting] 
          FROM [dbo].[DBSetting] AS [ds] 
         WHERE [ds].[Name] = 'SECURITY_TA_IMPERSONATE_DOMAIN'; 
                  
                  
       ------- Declare the return variable here 
       DECLARE @smc           varchar(50), 
               @appVersion    varchar(20); 
                  
        SELECT @smc = [Setting] 
          FROM [dbo].[DBSetting] 
         WHERE [Name] = 'SMC_PRIMARY_DATABASE'; 
                  
        SELECT @appVersion = REPLACE([ds].[Setting], '.', '') 
          FROM [dbo].[DBSetting] AS [ds] 
         WHERE [ds].[Name] = 'GENERAL_APPVERSION'; 
                  
                  
            IF @domain IS NOT NULL AND @domain = 'strataeudev' 
         BEGIN 
               RETURN 'https://deuw1websrv-01.ad.strataeudev.net/HangfireManagement' + @appVersion + '/api'; 
           END; 
                  
                  
       DECLARE @apiEnpoint varchar(100); 
                  
        SELECT @apiEnpoint =  CASE @smc 
                              WHEN 'smc dev'      THEN 'https://hangfire-dev.sdt.local/HangfireManagement' 
                              WHEN 'smc qa'       THEN 'https://qoakwebsrv01.sdt.local/HangfireManagement' 
                              WHEN 'smc training' THEN 'https://noakwebsrv01.sdt.local/HangfireManagement' 
                              WHEN 'smc prod'     THEN 'https://hangfire-prod.sdt.local/HangfireManagement' 
                              WHEN 'smc dr'       THEN 'https://hangfire-dr.sdt.local/HangfireManagement' 
                              ELSE '' 
                               END; 
                  
        RETURN @apiEnpoint + @appVersion + '/api'; 
            
   END;
GO


---------------------------------------------

-- dbo.GetHashedPassword
CREATE function [dbo].[GetHashedPassword](@userguid as uniqueidentifier, @pw as varchar(max)) returns varchar(max)
as
BEGIN
	declare @ret as varchar(max)

	declare @converter as xml
	set @ret = @pw + lower(cast(@userguid as varchar(36))) +  'Strata Decision Technology SDT' 


	declare @i int
	set @i = 0
	
	while @i <100001 begin
		set @converter = (SELECT HASHBYTES('SHA1',@ret) as "T"   FOR XML RAW, BINARY BASE64, TYPE)
		select @ret = @converter.value('row[1]/@T', 'varchar(max)')
		set @i = @i + 1
	end
	
	
	

	return @ret
END
GO


---------------------------------------------

-- dbo.GetImageColumnHTML
CREATE FUNCTION dbo.GetImageColumnHTML
(
	@imgurl varchar(128),
	@value varchar(64)
)
RETURNS varchar(400)
AS
BEGIN
	declare @result varchar(400)

	select @result = '<table><tr><td><img src="' + @imgurl + '" /></td><td><span>' + @value + '</span></td></tr></table>'
	
	return @result

END
GO


---------------------------------------------

-- dbo.GetInsertCommandForDataDictionaryFieldValueExample
-- =============================================
-- Author:		Yaroslav Dembitskyi
-- Create date: 7/20/2017
-- Description:	Generates insert command for score item to populate DataDictionary
-- =============================================
CREATE FUNCTION [dbo].[GetInsertCommandForDataDictionaryFieldValueExample]
(
	@scoreGuid uniqueidentifier,
	@columnName nvarchar(128),
	@schemaName nvarchar(128),
	@objectName nvarchar(128),
	@columnType tinyint,
	@idColumnName nvarchar(128) = null
)
RETURNS nvarchar(max)
AS
BEGIN
	if([dbo].ColumnExists(@schemaName, @objectName, @columnName) = 0)
	BEGIN
		return ''
	END
	
	declare @result nvarchar(max)
	declare @fromWhereClause nvarchar(max) = ' from [' + @schemaName + '].[' + @objectName + '] where CONVERT(NVARCHAR(4000),[' + @columnName + ']) <> '''' '
	declare @scoreGuidAsText nvarchar(50) = CONVERT(NVARCHAR(50), @scoreGuid)
	if(@idColumnName is not null AND [dbo].ColumnExists(@schemaName, @objectName, @idColumnName) = 1 AND 
		(select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS IC where TABLE_NAME = @objectName and TABLE_SCHEMA=@schemaName and COLUMN_NAME = @idColumnName) like '%int')
	BEGIN
		set @fromWhereClause = @fromWhereClause + ' and [' + @idColumnName + '] <> 0 '
	END
	IF(TYPE_NAME(@columnType) = 'bit')
		BEGIN
			set @result = 'insert into [dbo].[DataDictionaryFieldValueExample] (ScoreGUID, ExampleValue) values (''' + @scoreGuidAsText + ''', ''True/False'')'
		END
	ELSE IF (TYPE_NAME(@columnType) = 'datetime' OR TYPE_NAME(@columnType) = 'datetime2' OR TYPE_NAME(@columnType) = 'smalldatetime')
		BEGIN
			set @result = 'insert into [dbo].[DataDictionaryFieldValueExample] (ScoreGUID, ExampleValue)  select top 1 ''' + @scoreGuidAsText + ''', 
			 CONVERT(CHAR(10), ['+ @columnName + '], 103) + SUBSTRING(CONVERT(varchar, [' + @columnName + '], 0),12, 8) ' + @fromWhereClause 
		END
	ELSE
		BEGIN
			set @result = 'insert into [dbo].[DataDictionaryFieldValueExample] (ScoreGUID, ExampleValue)  select top 1 ''' + @scoreGuidAsText + ''', 
					CONVERT(NVARCHAR(4000),['+ @columnName + '])' + @fromWhereClause 
		END
	return @result
END
GO


---------------------------------------------

-- dbo.GetLastFiscalYearEndDate
CREATE FUNCTION dbo.GetLastFiscalYearEndDate()
	RETURNS Date
AS
BEGIN

	DECLARE @EndDate DATE;
	DECLARE @CurrentFiscalYearEndDate DATE;

	SET @CurrentFiscalYearEndDate = CONVERT(DATE, dbo.GetCurrentFiscalYear() + '/'+  dbo.GetDBSetting('GENERAL_FISCALYEARENDMONTH') + '/' +dbo.GetDBSetting('GENERAL_FISCALYEARENDDAY') );
	SET @EndDate = DATEADD(YEAR, -1, @CurrentFiscalYearEndDate);
	
	RETURN @EndDate

END;
GO


---------------------------------------------

-- dbo.GetLastFiscalYearStartDate
CREATE FUNCTION dbo.GetLastFiscalYearStartDate()
	RETURNS Date
AS
BEGIN

	DECLARE @StartDate DATE;

	SET @StartDate = DATEADD(DAY, 1, DATEADD(YEAR, -1, dbo.GetLastFiscalYearEndDate()));
	
	RETURN @StartDate

END;
GO


---------------------------------------------

-- dbo.GetLinkedServerDefinition
CREATE FUNCTION [dbo].[GetLinkedServerDefinition]()
returns nvarchar(512)
AS
BEGIN

	declare @retval nvarchar(512)
	select @retval = '[' + @@ServerName + '].[' + db_Name() + ']'
	return @retval
END
GO


---------------------------------------------

-- dbo.GetMainFolderSetGUID
create function GetMainFolderSetGUID() returns uniqueidentifier
as
BEGIN
	declare @ret as uniqueidentifier
	select @ret = foldersetguid from folderset where type = 1
	return @ret
END
GO


---------------------------------------------

-- dbo.GetModelDependencyTree
CREATE  FUNCTION [dbo].[GetModelDependencyTree] 
   (@ModelGUID uniqueidentifier, @MaxRecursionLevel int)
RETURNS 
	@ModelTree TABLE  ( [ModelGUID] uniqueidentifier, [Level] int)
AS
BEGIN

 	declare @Level int;
	declare @Counter int;
	set @Level = 0;
	set @Counter = 1;
	
	declare @Models TABLE
	(
		ModelGUID uniqueidentifier,
		ParentModelGUID uniqueidentifier,
		[Level] int,
		unique clustered (ModelGUID, ParentModelGUID, [Level])
	)
	declare @UsedParents TABLE
	(
		ModelGUID uniqueidentifier primary key clustered
	)

	--Base Query
	insert into @Models select @ModelGUID, @ModelGUID, @Level;
	insert into @UsedParents select @ModelGUID
	
	set @Level=@Level+1;
	
	insert into @Models
	select distinct ModelGUID, ParentModelGUID, @Level from dbo.viewModelDependencies
	where ParentModelGUID = @ModelGUID and ModelGUID <> @ModelGUID
	
	-- Begin Recursion		
	WHILE @@ROWCOUNT > 0
	BEGIN
		--handle max recursion
		if (@Counter > @MaxRecursionLevel)
		BEGIN
			BREAK;
		END
		
		--update state
		set @Level = @Level + 1;
		insert into @UsedParents
		select distinct M.ModelGUID from @Models M
			where not exists(select 1 from @UsedParents where ModelGUID = M.ModelGUID) and M.MODELGUID <> null
		
		--recursive query
		insert into @Models	
			select DISTINCT NEW.ModelGUID, NEW.ParentModelGUID, @Level from viewModelDependencies NEW
				left join @Models OLD	on OLD.ModelGUID = NEW.ParentModelGUID
					where not exists (select 1 from @UsedParents where ModelGUID = NEW.ParentModelGUID)
						and NEW.ModelGUID <> NEW.ParentModelGUID and OLD.MODELGUID <> null
						
		set @Counter = @Counter + 1;
	END

	insert into @ModelTree select distinct ModelGUID, [Level] from @Models order by [Level] DESC
	
	return
END
GO


---------------------------------------------

-- dbo.GetModelFirstFillIn
CREATE function [dbo].[GetModelFirstFillIn](@modelGUID as uniqueidentifier, @structureDimensionGUID as uniqueidentifier)
	returns uniqueidentifier
as
begin
	
/*
declare @modelGUID uniqueidentifier
declare @structureDimensionGUID as uniqueidentifier --ph

declare @maxIndex int
set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77'
set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC'

select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid)
*/

--delete fillins past index @maxIndex
	declare @out uniqueidentifier
	select top 1 
		@out = FilledInMemberGUID
	FROM
		(
		select 
			--modelguid,dbo.getplanname(modelguid),
			row_number() over (order by slm.sortorderfullpath) as RowNum, 
			FilledInMemberGUID
		from
			EMFFillIn fi
			inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid
		where
			(
				PlaceholderMemberGUID in 
					(	select listmemberguid 
						from securelistmember
						where listguid = @structureDimensionGUID
					) or
				FilledInMemberGUID in 
					(	select listmemberguid 
						from securelistmember
						where listguid = @structureDimensionGUID
					)	
			)			
			and ModelGUID = @modelGUID
		) FillIns
	ORDER BY RowNum

	if @out is null  set @out = '00000000-0000-0000-0000-000000000000'
	
	return @out
end
GO


---------------------------------------------

-- dbo.GetModelFirstFillInSection
create function [dbo].[GetModelFirstFillInSection](@modelGUID as uniqueidentifier,  @PHSectionGUID as uniqueidentifier)
	returns uniqueidentifier
as
begin
	
/*
declare @modelGUID uniqueidentifier
declare @structureDimensionGUID as uniqueidentifier --ph

declare @maxIndex int
set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77'
set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC'

select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid)
*/

--delete fillins past index @maxIndex
	declare @out uniqueidentifier
	select top 1 
		@out = FilledInMemberGUID
	FROM
		(
		select 
			--modelguid,dbo.getplanname(modelguid),
			row_number() over (order by slm.sortorderfullpath) as RowNum, 
			FilledInMemberGUID
		from
			EMFFillIn fi
			inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid
		where
			(
				PlaceholderMemberGUID in 
					(	select listmemberguid 
						from securelistmember
						where parentlistmemberguid = @PHSectionGUID
								
					)
				--FilledInMemberGUID in 
				--	(	select listmemberguid 
				--		from securelistmember
				--		where listguid = @structureDimensionGUID
				--	)	
			)			
			and ModelGUID = @modelGUID
		) FillIns
	ORDER BY RowNum

	if @out is null  set @out = '00000000-0000-0000-0000-000000000000'
	
	return @out
end
GO


---------------------------------------------

-- dbo.GetModelLastFillInIndex
CREATE function [dbo].[GetModelLastFillInIndex](@modelGUID as uniqueidentifier, @structureDimensionGUID as uniqueidentifier)
	returns bigint
as
begin
	
/*
declare @modelGUID uniqueidentifier
declare @structureDimensionGUID as uniqueidentifier --ph

declare @maxIndex int
set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77'
set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC'

select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid)
*/

--delete fillins past index @maxIndex
	declare @out bigint
	select top 1 
		@out = RowNum -1
	FROM
		(
		select 
			--modelguid,dbo.getplanname(modelguid),
			row_number() over (order by slm.sortorderfullpath) as RowNum, 
			FilledInMemberGUID
		from
			EMFFillIn fi
			inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid
		where
			PlaceholderMemberGUID in 
				(	select slm.listmemberguid 
					from securelistmember slm
					where slm.listguid = @structureDimensionGUID
				)
			and ModelGUID = @modelGUID
		) FillIns
	ORDER BY RowNum desc

	if @out is null  set @out = 0
	
	return @out
end
GO


---------------------------------------------

-- dbo.GetModelLastFillInIndexSection
CREATE function [dbo].[GetModelLastFillInIndexSection](@modelGUID as uniqueidentifier, @SectionmemberGUID as uniqueidentifier)
	returns bigint
as
begin
	

/*
declare @modelGUID uniqueidentifier
declare @structureDimensionGUID as uniqueidentifier --ph

declare @maxIndex int
set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77'
set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC'

select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid)
*/

--delete fillins past index @maxIndex
	declare @out bigint

		select 
			@out = count(*) -1
		from
			EMFFillIn fi
			inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid
		where
			slm.parentlistmemberguid = @SectionmemberGUID
			and ModelGUID = @modelGUID
			
	if @out is null  set @out = 0
	
	return @out
end
GO


---------------------------------------------

-- dbo.GetPlanGUID
CREATE function [dbo].[GetPlanGUID](@aPlanName as nvarchar(max)) returns uniqueidentifier
as
BEGIN
	declare @ret as uniqueidentifier
	select top 1 @ret = planguid from xplan where dbo.getplanname(planguid) like @aPlanName
	return @ret
END
GO


---------------------------------------------

-- dbo.GetPlanLastModified
CREATE function [dbo].[GetPlanLastModified](@PLANGUID as uniqueidentifier) returns nvarchar(450)
as
BEGIN
	declare @ret as nvarchar(450)

	SELECT @ret = CONVERT(VARCHAR(10), coalesce((select MAX(datetimestamp) from HistoryItem (readuncommitted) where OBJECTGUID = @planguid), '2000-01-01 12:00:00.000'), 101)

	if(@ret = '2000-01-01 12:00:00.000') begin
		set @ret = ''
	end
	
	return @ret
END
GO


---------------------------------------------

-- dbo.GetPlanName
CREATE function [dbo].[GetPlanName](@PLANGUID as uniqueidentifier) returns nvarchar(450)
as
BEGIN
	declare @ret as nvarchar(450)

	SELECT @ret = Name FROM XPlan (readuncommitted) WHERE PlanGUID = @PLANGUID

	return @ret
END
GO


---------------------------------------------

-- dbo.GetSQLColumnFullType
CREATE FUNCTION [dbo].[GetSQLColumnFullType]
(
	@type_id int,
	@maxlength int,
	@scale int,
	@precision int
)
RETURNS nvarchar(128)
AS
BEGIN
	DECLARE @typeToReturn nvarchar(128) = TYPE_NAME(@type_id)
	IF @typeToReturn = 'char'OR @typeToReturn ='varchar' OR @typeToReturn = 'binary' OR @typeToReturn = 'varbinary'
	BEGIN	
		SET @typeToReturn = @typeToReturn + '(' + case @maxlength when -1 then 'max' else cast(@maxlength as nvarchar(10)) end + ')'
	END
	ELSE IF @typeToReturn = 'nchar'OR @typeToReturn ='nvarchar' OR @typeToReturn = 'nbinary' OR @typeToReturn = 'nvarbinary'
	BEGIN
		SET @typeToReturn = @typeToReturn + '(' + case @maxlength when -1 then 'max' else cast(@maxlength / 2 as nvarchar(10)) end + ')'
	END
	ELSE IF @typeToReturn = 'decimal' or @typeToReturn = 'numeric'
	BEGIN
		SET @typeToReturn = @typeToReturn + '(' + cast(@scale as nvarchar(10)) + ', ' + cast(@precision as nvarchar(10)) + ')'
	END

	RETURN @typeToReturn;
END
GO


---------------------------------------------

-- dbo.GetSQLColumnSafeGuid
CREATE FUNCTION [dbo].[GetSQLColumnSafeGuid] (@guid uniqueidentifier) RETURNS varchar(37) 
AS
BEGIN
	DECLARE @tmpstr varchar(37)

	SELECT @tmpstr = upper(cast(@guid as varchar(37)))
	SELECT @tmpstr = replace(@tmpstr, '-', '_')
	SELECT @tmpstr = 'G' + @tmpstr

	RETURN @tmpstr
END
GO


---------------------------------------------

-- dbo.GetSQLFullyQualifiedType
CREATE FUNCTION dbo.GetSQLFullyQualifiedType 
(
	@type_id int,
	@maxlength int,
	@scale int,
	@precision int
)
RETURNS nvarchar(128)
AS
BEGIN
	DECLARE @typeToReturn nvarchar(128);
	select @typeToReturn = TYPE_NAME(@type_id);
	
	IF @typeToReturn like '%varchar%' 
	BEGIN
		SET @typeToReturn = @typeToReturn + '(' + cast(@maxlength as nvarchar(10)) + ')'
	END	
	ELSE IF @typeToReturn like '%decimal%'
	BEGIN
		SET @typeToReturn = @typeToReturn + '(' + cast(@scale as nvarchar(10)) + ',' + cast(@precision as nvarchar(10)) + ')'
	END

	RETURN @typeToReturn;
END
GO


---------------------------------------------

-- dbo.GetSQLTableExpression
CREATE FUNCTION [dbo].[GetSQLTableExpression](
	@SchemaName nvarchar(128),
	@ObjectName nvarchar(Max)
)
RETURNS varchar(max)
AS
BEGIN

	declare @SchemaExp varchar(max);
	declare @ObjectExp varchar(max);
	declare @returnval varchar(max)
	
	set @SchemaExp = '';
	set @ObjectExp = '';
	
	--Build Schema Expression
	if (SUBSTRING(@SchemaName,1,1) <> '[')
		set @SchemaExp = '['
	
	set @SchemaExp = @SchemaExp + @SchemaName;
	
	if (SUBSTRING(@SchemaName,LEN(@SchemaName),1) <> ']')
		set @SchemaExp = @SchemaExp + ']';
		
	--Build Object Expression
	if (SUBSTRING(@ObjectName,1,1) <> '[')
		set @ObjectExp = '['
	
	set @ObjectExp = @ObjectExp + @ObjectName;
	
	if (SUBSTRING(@ObjectName,LEN(@ObjectName),1) <> ']')
		set @ObjectExp = @ObjectExp + ']';
		
	--Combine
	select @returnval = @SchemaExp + '.' + @ObjectExp;
	return @returnval;
END
GO


---------------------------------------------

-- dbo.GetScoreLootRefreshTriggerName
CREATE Function [dbo].[GetScoreLootRefreshTriggerName](
	@aDimensionGUID uniqueidentifier
)
returns varchar(max)
AS
BEGIN	
	declare @TriggerName varchar(max);
	set @TriggerName =  'trg_ScoreDimension_' + Replace(cast(@aDimensionGUID as varchar(64)),'-','') + '_LootRefresh';
	return @TriggerName;
END
GO


---------------------------------------------

-- dbo.GetSecureListMemberFullPath
create function [dbo].[GetSecureListMemberFullPath](@listmemberguid as uniqueidentifier)
	returns nvarchar(max)
as
begin
	--declare @listmemberguid uniqueidentifier
	--set @listmemberguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B'

	declare @parentlistmemberguid uniqueidentifier	declare @SecureListMemberfound bit
	declare @fullpath nvarchar(max)

	select @fullpath = name, @SecureListMemberfound = 1, @parentlistmemberguid = parentlistmemberguid from SecureListMember where listmemberguid = @listmemberguid

	declare @currentSecureListMembername nvarchar(450)

	while @SecureListMemberfound = 1 begin
		set @SecureListMemberfound = 0
		select @currentSecureListMembername = name, @SecureListMemberfound = 1, @parentlistmemberguid = parentlistmemberguid from SecureListMember where listmemberguid = @parentlistmemberguid

		if @SecureListMemberfound = 1 begin
			set @fullpath = @currentSecureListMembername + '\' + @fullpath
		end 
	end

	return @fullpath
end
GO


---------------------------------------------

-- dbo.GetSecureListOffsetMember
CREATE function [dbo].[GetSecureListOffsetMember](@oldmemberguid as uniqueidentifier, @offset int)
	returns uniqueidentifier
as
begin
	--select * from securelist where name = 'year 20'
/*	declare @oldmemberguid uniqueidentifier
	declare @offset int
	set @offset = 3
	set @oldmemberguid = 'B95F36CB-970B-4E44-8382-81A12F1D3C06'
*/

	declare @dimensionguid uniqueidentifier
	
	select @dimensionguid = listguid 
	from securelistmember 
	where listmemberguid = @oldmemberguid

	declare @ret as uniqueidentifier
	select 
		@ret = cast(coalesce(slmnew.listmemberguid, '11111111-1111-1111-1111-111111111111') as uniqueidentifier)
	from 
		securelistmember slmOld
		left join SecureListMember slmNew on slmOld.listguid = slmNew.listguid
				and slmNew.displayorder = slmOld.displayorder + @offset
				and slmnew.ParentListMemberGUID = slmold.ParentListMemberGUID
	where
		slmold.listmemberguid = @oldmemberguid	
	
	if @ret is null set @ret = '11111111-1111-1111-1111-111111111111'
	return @ret
end
GO


---------------------------------------------

-- dbo.GetSecureListSortorderFullPath
create function [dbo].[GetSecureListSortorderFullPath](@listmemberguid as uniqueidentifier)
	returns nvarchar(max)
as
begin
/*
	select dbo.GetSecureListSortorderFullPath(listmemberguid),* from folder order by dbo.[GetFolderSortorderFullPath](listmemberguid)
*/
	--declare @listmemberguid uniqueidentifier
	--set @listmemberguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B'

	declare @parentlistmemberguid uniqueidentifier
	declare @folderfound bit
	declare @fullpath nvarchar(max)

	select @fullpath = replace(space(10 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0'), @folderfound = 1, @parentlistmemberguid = parentlistmemberguid from securelistmember where listmemberguid = @listmemberguid

	declare @currentfoldername nvarchar(450)

	while @folderfound = 1 begin
		set @folderfound = 0
		select @currentfoldername = replace(space(10 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0'), @folderfound = 1, @parentlistmemberguid = parentlistmemberguid from securelistmember where listmemberguid = @parentlistmemberguid

		if @folderfound = 1 begin
			set @fullpath = @currentfoldername + '\' + @fullpath
		end 
	end

	return @fullpath
end


--select replace(space(5 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0') from folder
GO


---------------------------------------------

-- dbo.GetSecureListVersion
CREATE function [dbo].[GetSecureListVersion](@LISTGUID as uniqueidentifier) returns binary(8)
AS
BEGIN
	declare @maxversion as binary(8)
	declare @tempversion as binary(8)

	select @maxversion = max(l.version)
	from securelist l where l.listguid = @LISTGUID;

	select @tempversion = max(lm.version)
	from securelistmember lm where lm.listguid = @LISTGUID;
	if(@tempversion > @maxversion) begin
		SET @maxversion = @tempversion
	end

	select @tempversion = max(lmv.version)
	from securelistmembervalue lmv where lmv.listguid = @LISTGUID;
	if(@tempversion > @maxversion) begin
		SET @maxversion = @tempversion
	end

	select @tempversion = max(ll.version)
	from securelistlevel ll where ll.listguid = @LISTGUID;
	if(@tempversion > @maxversion) begin
		SET @maxversion = @tempversion
	end

	select @tempversion = max(lp.version)
	from securelistproperty lp where lp.listguid = @LISTGUID;
	if(@tempversion > @maxversion) begin
		SET @maxversion = @tempversion
	end

	return @maxversion
END
GO


---------------------------------------------

-- dbo.GetSuperUserGUID
create function [dbo].[GetSuperUserGUID]()
RETURNS uniqueidentifier
AS
BEGIN
	declare @val uniqueidentifier;
	set @val = '10101010-1111-0000-1111-101010101010'

	return @val;
END
GO


---------------------------------------------

-- dbo.GetSystemSectionFullPath
CREATE function [dbo].[GetSystemSectionFullPath](@SystemSectionguid as uniqueidentifier)
	returns nvarchar(max)
as
begin
	--declare @SystemSectionguid uniqueidentifier
	--set @SystemSectionguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B'

	declare @parentSystemSectionguid uniqueidentifier
	declare @SystemSectionfound bit
	declare @fullpath nvarchar(max)

	select	@fullpath = name, 
			@SystemSectionfound = 1, 
			@parentSystemSectionguid = parentguid 
			from SystemSection where SystemSectionguid = @SystemSectionguid

	declare @currentSystemSectionname nvarchar(450)

	while @SystemSectionfound = 1 begin
		set @SystemSectionfound = 0
		select @currentSystemSectionname = name, @SystemSectionfound = 1, @parentSystemSectionguid = parentguid from SystemSection where SystemSectionguid = @parentSystemSectionguid

		if @SystemSectionfound = 1 and @currentSystemSectionname  <> 'System' begin
			set @fullpath = @currentSystemSectionname + '\' + @fullpath
		end 
	end

	set @fullpath = replace(@fullpath,'~Tool_','')
	set @fullpath = replace(@fullpath,'~Title_','')
	set @fullpath = replace(@fullpath,'~Group_','')
	set @fullpath = replace(@fullpath,'~Main_Generic','')
	return @fullpath
end
GO


---------------------------------------------

-- dbo.GetTrueFalseString
create Function dbo.GetTrueFalseString( 
	@Bit bit
	)
	returns nvarchar(10)
AS
BEGIN
declare @returnval nvarchar(10)
if (@Bit = 1)
	begin
		set @returnval = 'True'
	end
	else
	begin
		set @returnval = 'False'
	end
	return @returnval
END
GO


---------------------------------------------

-- dbo.GetUpdateCommandForDataDictionaryFieldValueExample
-- =============================================
-- Author:		Yaroslav Dembitskyi
-- Create date: 7/20/2017
-- Description:	Generates update command for score item to populate DataDictionary
-- =============================================
CREATE FUNCTION [dbo].[GetUpdateCommandForDataDictionaryFieldValueExample]
(
	@scoreGuid uniqueidentifier,
	@columnName nvarchar(128),
	@schemaName nvarchar(128),
	@objectName nvarchar(128),
	@columnType tinyint,
	@idColumnName nvarchar(128) = null
)
RETURNS nvarchar(max)
AS
BEGIN
	if([dbo].ColumnExists(@schemaName, @objectName, @columnName) = 0)
	BEGIN
		return ''
	END
	
	declare @result nvarchar(max)
	declare @valueToUpdateSelectQuery nvarchar(max)
	declare @fromWhereClause nvarchar(max) = ' from [' + @schemaName + '].[' + @objectName + '] where CONVERT(NVARCHAR(4000),[' + @columnName + ']) <> '''' '
	declare @scoreGuidAsText nvarchar(50) = CONVERT(NVARCHAR(50), @scoreGuid)
	if(@idColumnName is not null AND [dbo].ColumnExists(@schemaName, @objectName, @idColumnName) = 1 AND 
		(select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS IC where TABLE_NAME = @objectName and TABLE_SCHEMA=@schemaName and COLUMN_NAME = @idColumnName) like '%int')
	BEGIN
		set @fromWhereClause = @fromWhereClause + ' and [' + @idColumnName + '] <> 0 '
	END
	IF(TYPE_NAME(@columnType) = 'bit')
		BEGIN
			set @valueToUpdateSelectQuery = 'select ''True/False'''
		END
	ELSE IF (TYPE_NAME(@columnType) = 'datetime' OR TYPE_NAME(@columnType) = 'datetime2' OR TYPE_NAME(@columnType) = 'smalldatetime')
		BEGIN
			set @valueToUpdateSelectQuery = 'select top 1 CONVERT(CHAR(10), ['+ @columnName + '], 103) + SUBSTRING(CONVERT(varchar, [' + @columnName + '], 0),12, 8) ' + @fromWhereClause
		END
	ELSE
		BEGIN
			set @valueToUpdateSelectQuery = 'select top 1 CONVERT(NVARCHAR(4000), ['+ @columnName + '])' + @fromWhereClause
		END

		set @result = 'if(exists(' + @valueToUpdateSelectQuery + '))
							update [dbo].[DataDictionaryFieldValueExample] set ExampleValue = (' + @valueToUpdateSelectQuery + ') where ScoreGUID = ''' + @scoreGuidAsText + '''
					   else 
						     delete from [dbo].[DataDictionaryFieldValueExample] where ScoreGUID = ''' + @scoreGuidAsText + ''''

	return @result
END
GO


---------------------------------------------

-- dbo.GetUserGUID
CREATE function GetUserGUID(@aUsername as nvarchar(max)) returns uniqueidentifier
as
BEGIN
	declare @ret as uniqueidentifier
	select top 1 @ret = userguid from userprofile where username like @ausername
	return @ret
END
GO


---------------------------------------------

-- dbo.GetUserGroupGUID
CREATE function [dbo].[GetUserGroupGUID](@agroupname as nvarchar(max)) returns uniqueidentifier
as
BEGIN
	declare @ret as uniqueidentifier
	select top 1 @ret = usergroupguid from usergroup where name like @agroupname
	return @ret
END
GO


---------------------------------------------

-- dbo.GetUserRoleAssignmentCSV
CREATE FUNCTION [dbo].[GetUserRoleAssignmentCSV] ( 
		@ENTITYGUID uniqueidentifier, 
		@ALIASGUIDLIST text,
		@IDENTITYNAMES bit = 0
	)
    RETURNS NVARCHAR(MAX)
AS
BEGIN
	DECLARE @tbl TABLE ( MemberGUID uniqueidentifier ) 
	DECLARE @ALIASGUID uniqueidentifier

	DECLARE crsAliases CURSOR LOCAL FAST_FORWARD FOR
	SELECT GUID FROM dbo.ConvertCSGuidsToTable(@ALIASGUIDLIST, ',')
	OPEN crsAliases

	FETCH NEXT FROM crsAliases INTO @ALIASGUID
	WHILE @@FETCH_STATUS = 0 BEGIN
		INSERT @tbl 

		SELECT DISTINCT 
			RA.UserGUID
		FROM
			viewS3RoleAssignmentDetail RA
			inner join UserRole R on R.RoleID = RA.RoleID
			inner join XPlan P on P.CachedLootID = RA.LootID
		WHERE
			R.UserRoleGUID = @ALIASGUID
			AND P.PlanGUID = @EntityGUID
					

/*		SELECT DISTINCT 
			IDENTITYGUID 
		FROM 
			IdentityAlias 
		WHERE 
			ALIASGUID = @ALIASGUID 
			AND IDENTITYGUID NOT IN (SELECT IDENTITYGUID FROM @tbl)
			AND ((ENTITYGUID = @ENTITYGUID) OR (ENTITYGUID = '00000000-0000-0000-0000-000000000000')) 
*/
		FETCH NEXT FROM crsAliases INTO @ALIASGUID

	END

	CLOSE crsAliases
	DEALLOCATE crsAliases

	DECLARE @csv NVARCHAR(MAX)
	SET @csv = ''

	IF (@IDENTITYNAMES = 1) BEGIN
		select @csv = @csv + namelast + ', ' + namefirst + '; ' from userprofile where userguid in(select memberguid from @tbl)
		IF (len(@csv) > 1) BEGIN
			select @csv = left(@csv, len(@csv) - 1)
		END
	END ELSE BEGIN
		select @csv = @csv + cast(memberguid as varchar(36)) + ',' from @tbl
		IF (len(@csv) > 1) BEGIN
			select @csv = left(@csv, len(@csv) - 1)
		END
	END

	RETURN @csv
END
GO


---------------------------------------------

-- dbo.GetValidDimensionTupleXML
create function GetValidDimensionTupleXML(@tuplexml xml, @mdcguid uniqueidentifier)
	returns xml
as begin
	declare @goodtuplexml xml

	set @goodtuplexml = (select lower(cast(dimensionguid as varchar(36))) as DIMENSIONGUID from emfmodeldataconfigdimensionlink DIMENSIONALITY where modeldataconfigguid = @mdcguid for xml auto, elements)

	declare @combinedxml xml
	set @combinedxml = '<DT>' + cast(@tuplexml as varchar(max)) + cast(@goodtuplexml as varchar(max)) + '</DT>'

	declare @goodmembers xml

	select @goodmembers = @combinedxml.query('//DIMENSIONTUPLEMEMBER[DIMENSIONGUID = //DIMENSIONALITY/DIMENSIONGUID]')

	declare @ots xml
	select @ots = @tuplexml.query('/DIMENSIONTUPLE/OBJECTTYPESTRATA')

	declare @mg xml
	select @mg = @tuplexml.query('/DIMENSIONTUPLE/MEASUREGUID')

	declare @goodxml xml
	set @goodxml = '<DIMENSIONTUPLE>' + cast(@ots as varchar(max)) + cast(@mg as varchar(max)) + cast(@goodmembers as varchar(max)) + '</DIMENSIONTUPLE>'

	return @goodxml
end
GO


---------------------------------------------

-- dbo.GetViewUnderlyingTables
CREATE function [dbo].[GetViewUnderlyingTables](@ViewSchema varchar(128), @ViewName varchar(128))
Returns Table
AS
	return (select distinct(TABLE_NAME) TableName, TABLE_SCHEMA as TableSchema  from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE
	where VIEW_SCHEMA = @ViewSchema AND VIEW_NAME = @ViewName);
GO


---------------------------------------------

-- dbo.GetWebSafeString
CREATE function [dbo].[GetWebSafeString](@input as nvarchar(max)) returns nvarchar(max)
as
BEGIN
	declare @ret as nvarchar(max)
	select @ret = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@input, '<', ''), '>', ''), '''', ''), '&', ''), '"', ''), '\', ''), '/', '')
	return @ret
END
GO


---------------------------------------------

-- dbo.GetWebSafeStringFullTrim
CREATE function [dbo].[GetWebSafeStringFullTrim](@input as nvarchar(max)) returns nvarchar(max)
as
BEGIN
	declare @ret as nvarchar(max)
	select @ret = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@input, '<', ''), '>', ''), '''', ''), '&', ''), '"', ''), '\', ''), '/', ''), '  ', ' ')))
	return @ret
END
GO


---------------------------------------------

-- dbo.GetZZModelDataTableName
create function GetZZModelDataTableName(@mdcguid uniqueidentifier)
returns varchar(max)
as begin

	return 'zzEMFModelData_' + replace(cast(@mdcguid as varchar(36)), '-','_')
end
GO


---------------------------------------------

-- dbo.GetZZModelDataViewName
CREATE function [dbo].[GetZZModelDataViewName](@mdcguid uniqueidentifier)
	returns varchar(max)
as begin
	declare @mdcName as nvarchar(64)
	declare @ret as nvarchar(max)
	
	SELECT
		@mdcName = Name
	FROM
		EMFModelDataConfig
	WHERE
		ModelDataConfigGUID = @mdcguid

	set @ret = replace(@mdcName, ' ', '')
	set @ret = replace(@ret, '(', '')
	set @ret = replace(@ret, ')', '')
	
	set @ret = 'zzviewModelData_' + @ret

	return @ret
end
GO


---------------------------------------------

-- dbo.GetZZModelTemplateMappingTableName
create function GetZZModelTemplateMappingTableName(@mdcguid uniqueidentifier)
returns varchar(max)
as begin

	return 'zzEMFModelTemplateMapping_' + replace(cast(@mdcguid as varchar(36)), '-','_')
end
GO


---------------------------------------------

-- dbo.GetZeroGUID
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[GetZeroGUID] ()
RETURNS uniqueidentifier
AS
BEGIN
	-- Declare the return variable here
	DECLARE @ZEROGUID uniqueidentifier
	select @ZEROGUID = [dbo].[ZeroGUID]();
	RETURN @ZEROGUID

END
GO


---------------------------------------------

-- dbo.IntToGUID
CREATE Function [dbo].[IntToGUID](
	@objectID int
)
returns UNIQUEIDENTIFIER
AS
BEGIN	
	declare @GUIDSTR nvarchar(36);
	set @GUIDSTR = cast(dbo.ZeroGUID() as nvarchar(36));
	
	declare @obj nvarchar(11);
	if (@objectID >= 0) begin
		set @obj = '0' + cast(@objectID as nvarchar(10));
	end
	else begin
		set @obj = '1' + substring(cast(@objectID as nvarchar(11)), 2,10);
	end
	return cast(
			STUFF('00000000', 1, LEN(SUBSTRING(@obj,1,8)),SUBSTRING(@obj, 1,8))
			+ '-' +
			STUFF('0000',1, LEN(SUBSTRING(@obj,9,3)),SUBSTRING(@obj,9,3))
			+ '-0000-0000-000000000000' as uniqueidentifier)
END
GO


---------------------------------------------

-- dbo.IsClusteredIndexExist
-- =============================================
-- Author:		AI
-- Create date: 8/03/2017
-- Description:	Checks if clustered index exist.
-- Parameters:
--     @schema: Table schema
--     @table: Table name
--     @isPrimaryKey: Optional parameter. Checks if it's has primary key index. If parameter has default value then checks for clustered indexes with primary key and not.
-- Example:
-- Check for indexes with primary key and not
--     select dbo.IsClusteredIndexExist(@schema, @table, DEFAULT)
-- Check only primary key indexes
--     select dbo.IsClusteredIndexExist(@schema, @table, 1)
-- =============================================
CREATE FUNCTION [dbo].[IsClusteredIndexExist] (
	@schema SYSNAME
	,@table SYSNAME
	,@isPrimaryKey BIT = NULL
	)
RETURNS BIT
AS
BEGIN
	DECLARE @result BIT

	SET @result = (
			SELECT CASE 
					WHEN count(*) > 0
						THEN 1
						ELSE 0
					END
			FROM sys.indexes i
			INNER JOIN sys.tables t ON i.object_id = t.object_id
			INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
			WHERE t.type = 'u'
				AND t.NAME = @table
				AND s.NAME = @schema
				AND i.type = 1
				AND (
					@isPrimaryKey IS NULL
					OR i.is_primary_key = @isPrimaryKey
					)
			)

	RETURN @result
END
GO


---------------------------------------------

-- dbo.IsLetter
CREATE function dbo.IsLetter(
	@char varchar
)
returns bit
BEGIN

	declare @returnVal bit;
	declare @ascii int;
	
	select @ascii = ASCII(@char);

	if ((@ascii >= 65 and @ascii <= 90) or (@ascii >= 97 and @ascii <= 122)) begin
		set @returnVal = 1;
	end
	else begin
		set @returnVal = 0;
	end

	return @returnVal;
END
GO


---------------------------------------------

-- dbo.IsLetterOrDigit
CREATE function [dbo].[IsLetterOrDigit](
	@char varchar
)
returns bit
BEGIN

	declare @returnVal bit;
	declare @ascii int;

	select @ascii = ASCII(@char);

	if (
			(@ascii >= 48 and @ascii <= 57)  
			or (@ascii >= 65 and @ascii <= 90) 
			or (@ascii >= 97 and @ascii <= 122)) 
	begin
		set @returnVal = 1;
	end
	else begin
		set @returnVal = 0;
	end

	return @returnVal;
END
GO


---------------------------------------------

-- dbo.IsSQLCharacterType
CREATE Function [dbo].[IsSQLCharacterType](
	@eSQLDataType int
)
RETURNS bit
AS
BEGIN
	declare @returnval bit;
	set @returnval = 0;
	if (@eSQLDataType in (175,239,35,99,167,231))
	begin
		set @returnval = 1;
	end
	
	return @returnval;
END
GO


---------------------------------------------

-- dbo.IsSQLDateTimeType
CREATE Function [dbo].[IsSQLDateTimeType](
	@eSQLDataType int
)
RETURNS bit
AS
BEGIN
	declare @returnval bit;
	set @returnval = 0;
	if (@eSQLDataType in (58,61))
	begin
		set @returnval = 1;
	end
	
	return @returnval;
END
GO


---------------------------------------------

-- dbo.IsSQLNumericType
CREATE Function [dbo].[IsSQLNumericType](
	@eSQLDataType int
)
RETURNS bit
AS
BEGIN
	declare @returnval bit;
	set @returnval = 0;
	if (@eSQLDataType in (48,52,56,58,59,60,62,106,122,127))
	begin
		set @returnval = 1;
	end
	
	return @returnval;
END
GO


---------------------------------------------

-- dbo.IsScoreObjectSQLForeignKeyedToTarget
CREATE FUNCTION dbo.IsScoreObjectSQLForeignKeyedToTarget
(
	@dimToCheckAgainst UNIQUEIDENTIFIER,
	@fkDimGUID UNIQUEIDENTIFIER
)
RETURNS BIT
AS 
BEGIN
	DECLARE	@tableToFKCheck nvarchar(400)
	DECLARE	@tableToCheckAgainst nvarchar(400)
	SELECT 
		@tableToCheckAgainst = a.DimensionGroupSQLObjectName, -- we check against this one to see if this table has a FK
		@tableToFKCheck = A2.DimensionGroupSQLObjectName --this is the table we check if it is foreign keyed from
	from viewscoreattribute a
	INNER JOIN viewscoreattribute a2 ON a2.AttributeGUID = a.CachedFKDefaultLookupKeyGUID
	where a.DimensionGUID =  @dimToCheckAgainst AND a.CachedFKDimensionGUID =@fkDimGUID

	DECLARE @result BIT
	IF @tableToFKCheck is null OR  @tableToCheckAgainst is null
	BEGIN 
		SET @result = 0
	END
	ELSE
	BEGIN
		SET @result = dbo.IsTableForeignKeyedToTarget(@tableToFKCheck, @tableToCheckAgainst)
	END

	RETURN @RESULT
END
GO


---------------------------------------------

-- dbo.IsTableForeignKeyedToTarget
CREATE FUNCTION dbo.IsTableForeignKeyedToTarget (
	@tableToFKCheck nvarchar(400),
	@tableToCheckAgainst nvarchar(400)
)
RETURNS BIT
AS
BEGIN
	declare @returnval as bit

	IF (
		SELECT 
		COUNT(1)
		FROM 
		   sys.foreign_keys (nolock) AS f
		INNER JOIN 
		   sys.foreign_key_columns (nolock) AS fc 
			  ON f.OBJECT_ID = fc.constraint_object_id
		INNER JOIN 
		   sys.tables (nolock) t 
			  ON t.OBJECT_ID = fc.referenced_object_id
		WHERE 
		   OBJECT_NAME (f.referenced_object_id) = 'dimpatienttype' AND OBJECT_NAME(f.parent_object_id) = 'dimaccount'
	   ) > 0
	BEGIN
		SET @returnval = 1
	END
	ELSE
	BEGIN
		SET @returnval = 0
	END

	RETURN @returnval
END
GO


---------------------------------------------

-- dbo.IsTriggerExist
CREATE Function [dbo].[IsTriggerExist](
	@TriggerName varchar(128)
)
returns bit
BEGIN
	
	declare @retval bit;
	declare @count int;
	select @count = count(*) from ViewSysTriggers where
		Name = @TriggerName
	if (@count >= 1)
		set @retval = 1
	ELSE
		set @retval = 0
	return @retval;
END
GO


---------------------------------------------

-- dbo.IsTupleXMLValidForStructure
CREATE function IsTupleXMLValidForStructure (@tuplexml xml, @mdcguid uniqueidentifier)
	returns bit
as begin
	declare @cnt int
	select
		@cnt = count(*)
	from
		(
			(select 
				T.c.query('DIMENSIONGUID').value('.', 'uniqueidentifier') as dimensionguid
			from
				@tuplexml.nodes('//DIMENSIONTUPLEMEMBER') T(c))
		) xmld 
		left join emfmodeldataconfigdimensionlink mdcd on  mdcd.dimensionguid = xmld.dimensionguid and modeldataconfigguid = @mdcguid
	where 
		mdcd.dimensionguid is null

	declare @retval bit
	if @cnt = 0 
		set @retval = 1
	else
		set @retval = 0
	return @retval
end
GO


---------------------------------------------

-- dbo.IsUniqueIndexColumnExist
Create Function [dbo].[IsUniqueIndexColumnExist](
	@SchemaName nvarchar(128),
	@ObjectName nvarchar(128),
	@ColumnName nvarchar(128)
)
Returns bit
AS
BEGIN

declare @Count int;

select @Count = COUNT(IND0.Name)  from sys.objects O0 
	inner join sys.schemas S0 on S0.schema_id = O0.schema_id
	inner join sys.indexes IND0 on O0.object_id = IND0.object_id	
	inner join sys.index_columns ICOL0 on ICOL0.object_id = O0.object_id and IND0.index_id = ICOL0.index_id
	inner join sys.columns COL0 on COL0.object_id = O0.object_id and ICOL0.column_id = COL0.column_id
Group By IND0.name, S0.name, O0.name

HAVING S0.name = @SchemaName and O0.name = @ObjectName and COUNT(IND0.Name) = 1

and
IND0.name in (

select IND.name from sys.objects O 
	inner join sys.schemas S on S.schema_id = O.schema_id
	inner join sys.indexes IND on O.object_id = IND.object_id	
	inner join sys.index_columns ICOL on ICOL.object_id = O.object_id and IND.index_id = ICOL.index_id
	inner join sys.columns COL on COL.object_id = O.object_id and ICOL.column_id = COL.column_id
where S.name = @SchemaName and O.name = @ObjectName and COL.name = @ColumnName
	and IND.is_unique = 1
	)
	
declare @ReturnVal bit;
if (@Count >= 1)
BEGIN
	set @ReturnVal = 1;
END
ELSE
BEGIN
	set @ReturnVal = 0;
END

return @ReturnVal;
END
GO


---------------------------------------------

-- dbo.IsView
CREATE FUNCTION [dbo].[IsView] 
(
	@SchemaName nvarchar(128),
	@ObjectName nvarchar(max)
)
returns bit
BEGIN

declare @TOTAL int;
select @TOTAL = COUNT(*) from  sys.views V
	inner join sys.schemas S on V.schema_id = S.schema_id 
where 
	S.Name = @SchemaName and V.Name = @ObjectName

return cast(@TOTAL as bit);
END
GO


---------------------------------------------

-- dbo.JSONEscaped
CREATE FUNCTION [dbo].[JSONEscaped] ( /* this is a simple utility function that takes a SQL String with all its clobber and outputs it as a sting with all the JSON escape sequences in it.*/
 @Unescaped NVARCHAR(MAX) --a string with maybe characters that will break json
 )
RETURNS NVARCHAR(MAX)
AS
BEGIN
  SELECT @Unescaped = REPLACE(@Unescaped, FROMString, TOString)
  FROM (SELECT '' AS FromString, '\' AS ToString 
        UNION ALL SELECT '"', '"' 
        UNION ALL SELECT '/', '/'
        UNION ALL SELECT CHAR(08),'b'
        UNION ALL SELECT CHAR(12),'f'
        UNION ALL SELECT CHAR(10),'n'
        UNION ALL SELECT CHAR(13),'r'
        UNION ALL SELECT CHAR(09),'t'
 ) substitutions
RETURN @Unescaped
END
GO


---------------------------------------------

-- dbo.Last12Months
Create FUNCTION [dbo].[Last12Months]
(
    @Date DATETIME
)   RETURNS @tbl TABLE (Start DATETIME, EndDate DATETIME)
AS   
BEGIN
    WITH T AS(
    SELECT 
        DATEADD(month, DATEDIFF(month, 0, @Date), 0) AS Start,
        DATEADD(d, -DAY(DATEADD(m,1,@date)),DATEADD(m,1,@date)) AS EndDate,
        12 Cnt
    UNION ALL
    SELECT 
        DATEADD(month, -1, Start),
        DATEADD(d, -DAY(DATEADD(m,1,Start-1)),DATEADD(m,1,Start-1)),
        Cnt-1
    FROM
        T
    WHERE
        Cnt-1>0
    )
    INSERT INTO @tbl 
        (Start, EndDate)
    SELECT 
        Start, EndDate
    FROM T

    RETURN
END
GO


---------------------------------------------

-- dbo.MaxDateTime
create function dbo.MaxDateTime(@val1 datetime, @val2 datetime)
returns datetime
as
begin
  if @val1 > @val2
    return @val1
  return isnull(@val2,@val1)
end
GO


---------------------------------------------

-- dbo.ParseFullPath
CREATE FUNCTION [dbo].[ParseFullPath]
(
	@inText varchar(max),
	@delim varchar(1) = '\',
	@targetIndex int
)
RETURNS varchar(max)
AS
BEGIN

IF @inText is null BEGIN
	return ''
end

IF len(@inText) = 0 BEGIN
	return ''
end

DECLARE @remainingText varchar(max)
DECLARE @currentValue varchar(max)
DECLARE @currentIndex int

SET @remainingText = @inText
SET @currentIndex = 0

WHILE @currentIndex < @targetIndex
BEGIN

	SET @currentIndex = @currentIndex + 1

	IF charindex('\', @remainingText) = 0 BEGIN
		IF @currentIndex = @targetIndex 
			RETURN @remainingText
		ELSE
			return ''
	end
	SET @currentValue = left(@remainingText,charindex('\', @remainingText) -1)
	SET @remainingText =  right(@remainingText, len(@remainingText) - (len(@currentValue) + 1))
	
END

RETURN @currentValue
END
GO


---------------------------------------------

-- dbo.ParseFullPathGUID
CREATE FUNCTION [dbo].[ParseFullPathGUID]
(
	@inText varchar(max),
	@delim varchar(1) = '\',
	@targetIndex int
)
RETURNS uniqueidentifier
AS
BEGIN

IF @inText is null BEGIN
	return '00000000-0000-0000-0000-000000000000'
end

IF len(@inText) = 0 BEGIN
	return '00000000-0000-0000-0000-000000000000'
end

DECLARE @remainingText varchar(max)
DECLARE @currentValue uniqueidentifier
DECLARE @currentIndex int

SET @remainingText = @inText
SET @currentIndex = 0

WHILE @currentIndex < @targetIndex
BEGIN

	SET @currentIndex = @currentIndex + 1

	IF charindex('\', @remainingText) = 0 BEGIN
		IF @currentIndex = @targetIndex 
			RETURN @remainingText
		ELSE
			return '00000000-0000-0000-0000-000000000000'
	end
	SET @currentValue = left(@remainingText,charindex('\', @remainingText) -1)
	SET @remainingText =  right(@remainingText, len(@remainingText) - (len(@currentValue) + 1))
	
END

RETURN @currentValue
END
GO


---------------------------------------------

-- dbo.ParseRecord
CREATE function [dbo].[ParseRecord](
	@test nvarchar(max)
	,@findBase nvarchar(max)
) returns nvarchar(max)
as
BEGIN
	declare @ret as nvarchar(max)

	--declare @test nvarchar(max)
	--set @test = 'Quantity=126|CostPerItem=1250.00'

	--declare @findBase nvarchar(max)
	--set @findBase = 'Item'

	declare @recordStart char(1)
	set @recordStart = ','
	declare @recordEqual char(1)
	set @recordEqual = '='

	declare @find nvarchar(max)
	set @find = @recordStart + @findBase + @recordEqual

	declare @startPos int
	set @startpos = charindex(@find,@test,0) 

	if @startPos = 0 begin
		--not found, try without recordStart
		set @find = @findBase + @recordEqual
		set @startpos = charindex(@find,@test,0) 
		
		if @startPos = 0 begin
			--still not found
			return ''
		end
		
	end

	set @startPos = @startPos +  LEN(@find)

	declare @endPos int
	set @endpos = CHARINDEX(@recordStart,@test,@startPos)

	if @endPos = 0 begin
		set @endPos = LEN(@test) + 1
	end

	set @ret = SUBSTRING(@test,@startpos, @endPos - @startPos)

	return @ret
END
GO


---------------------------------------------

-- dbo.RandNumber
CREATE FUNCTION RandNumber()
RETURNS float
AS
  BEGIN
  RETURN (SELECT RandNumber FROM viewRandomNumber)
  END
GO


---------------------------------------------

-- dbo.STRAGGR
-- Unable to retrieve definition for dbo.STRAGGR.
GO


---------------------------------------------

-- dbo.SanitizeNonDelimitedIdentifier
CREATE FUNCTION dbo.SanitizeNonDelimitedIdentifier(
	@str varchar(max)
)
returns varchar(max)
BEGIN

	declare @index int;
	declare @returnVal varchar(max);
	declare @currentChar char;

	set @returnVal = '';
	set @index = 1;

	WHILE (@index <= LEN(@str)) 
	begin
		select @currentChar = SUBSTRING(@str,@index,1);
		if (@index = 1) begin
		   if (dbo.IsLetter(@currentChar) = 1 or @currentChar = '_' or @currentChar = '@' or @currentChar = '#') begin
				set @returnVal = @returnVal + @currentChar;
		   end
		   else begin
				set @returnVal = @returnVal + '_';
		   end
		end
		else
		begin 
			 if (dbo.IsLetterOrDigit(@currentChar) = 1 or @currentChar = '_' or @currentChar = '@' or @currentChar = '#' or @currentChar = '$') begin
				set @returnVal = @returnVal + @currentChar;
			 end
			 else begin
				set @returnVal = @returnVal + '_';
			 end
		end
		
		set @index = @index + 1;
	end

	return @returnVal;
	
END
GO


---------------------------------------------

-- dbo.ScoreIsDataTableInUse
CREATE FUNCTION [dbo].[ScoreIsDataTableInUse]
(
	@DataTableGUID uniqueidentifier
)
RETURNS Bit
As
BEGIN


--Is DataTable used by any composites
DECLARE @CompositeCount int;
select @CompositeCount = COUNT(*) from ScoreComposite COMP
	inner join ScoreDataTable DT on DT.DataTableGUID = COMP.DataTableGUID1 OR DT.DataTableGUID = COMP.DataTableGuid2
Where DT.DataTableGUID = @DataTableGUID;

--Any other cases? I don't think so...
declare @retval bit;
set @retval = 0;
	
if (@CompositeCount > 0)
BEGIN
	set @retval = 1;
END

RETURN @retval

END
GO


---------------------------------------------

-- dbo.ScoreIsDimensionFKsActive
CREATE FUNCTION [dbo].[ScoreIsDimensionFKsActive] (
	@DimensionGUID uniqueidentifier
)
RETURNS BIT
AS
BEGIN

--Does Given Dimension Contain an Attribute that is a foreign key to an in-use dimension?
declare @Total int;
select @Total = COUNT(*) from ScoreDataTable DT
	inner join ScoreDataTableKeyLink DTLINK on DT.DataTableGUID = DTLINK.DataTableGUID
	inner join ScoreAttribute INUSE_ATT on INUSE_ATT.AttributeGUID = DTLINK.KeyGUID
	inner join ScoreAttribute OUR_ATT on OUR_ATT.AttributeGUID = INUSE_ATT.ForeignKeyGUID
	inner join ScoreDimensionGroup OUR_DIMGROUP on OUR_DIMGROUP.DimensionGroupGUID = OUR_ATT.DimensionGroupGUID
	inner join ScoreDimension OUR_DIM on OUR_DIM.DimensionGUID = OUR_DIMGROUP.DimensionGUID
	Where OUR_DIM.DimensionGUID = @DimensionGUID

DECLARE @retval BIT;
SET @retval = 0;
IF (@Total > 0) 
BEGIN
	set @retval = 1;
END

return @retval;
END
GO


---------------------------------------------

-- dbo.ScoreIsDimensionInUse
CREATE FUNCTION [dbo].[ScoreIsDimensionInUse]
(
	@DimensionGuid uniqueidentifier
)
RETURNS Bit
As
BEGIN


--Is Dimension used by any datatables
DECLARE @DTCount int;
select @DTCount = COUNT(*) from ScoreDataTable DT
	inner join ScoreDataTableKeyLink KLINK on DT.DataTableGUID = KLINK.DataTableGUID
	inner join ScoreAttribute ATT on ATT.AttributeGUID = KLINK.KeyGUID
	inner join ScoreDimensionGroup G on ATT.DimensionGroupGUID = G.DimensionGroupGUID
	inner join ScoreDimension DIM on DIM.DimensionGUID = G.DimensionGUID
Where DIM.DimensionGUID = @DimensionGUID;

declare @retval bit;
set @retval = 0;

--Does Dimension Contain an Attribute that is a foreign key to an in use dimension?
DECLARE @IsaForeignKeyForInUse bit;
set @IsaForeignKeyForInUse = [dbo].[ScoreIsDimensionFKsActive] (@DimensionGUID);
if (@IsaForeignKeyForInUse = 1)
BEGIN
	set @retval = 1
END
	
if (@DTCount > 0)
BEGIN
	set @retval = 1;
END

RETURN @retval

END
GO


---------------------------------------------

-- dbo.ScoreIsPlaceHolderDimension
CREATE FUNCTION [dbo].[ScoreIsPlaceHolderDimension]
(
	@DimensionGuid uniqueidentifier
)
RETURNS Bit
As
BEGIN


--Is Dimension used by any datatables
DECLARE @DTCount int;
select @DTCount = COUNT(*) from ScoreComposite C
	inner join ScoreCompositeLink CL  on C.CompositeGUID = CL.CompositeGUID
	inner join ScoreAttribute ATT on ATT.AttributeGUID = CL.Key1GUID
	inner join ScoreDimensionGroup G on ATT.DimensionGroupGUID = G.DimensionGroupGUID
	inner join ScoreDimension DIM on DIM.DimensionGUID = G.DimensionGUID
Where DIM.DimensionGUID = @DimensionGUID and CL.[Type] = 1 ; --direct placeholder

declare @retval bit;
set @retval = 0;
	
if (@DTCount > 0)
BEGIN
	set @retval = 1;
END

RETURN @retval

END
GO


---------------------------------------------

-- dbo.Split
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1	2018-09-04	IP			B-20335		Component varchar(50) --> varchar(500) to support spitting of History Viewer filter
** 2   2018-09-13   SD        TK-63626		Change type from varchar(500) to varchar(max)
									TK-63621
*************************************************************/
CREATE FUNCTION [dbo].[Split](
	@Input varchar(max),
	@Delimeter char(1)
)
RETURNS  @returnTable TABLE(Component varchar(max))
AS
BEGIN
	--Parse the string and insert each component into the @returnTable table
	DECLARE @SubString varchar(max)
	DECLARE @StartPos int, @Length int
	WHILE LEN(@Input) > 0
	  BEGIN
		SET @StartPos = CHARINDEX(@Delimeter, @Input)
		IF @StartPos < 0 SET @StartPos = 0
		SET @Length = LEN(@Input) - @StartPos - 1
		IF @Length < 0 SET @Length = 0
		IF @StartPos > 0
		  BEGIN
			SET @SubString = SUBSTRING(@Input, 1, @StartPos - 1)
			SET @Input = SUBSTRING(@Input, @StartPos + 1, LEN(@Input) - @StartPos)
		  END
		ELSE
		  BEGIN
			SET @SubString = @Input
			SET @Input = ''
		  END
		INSERT @returnTable (Component) VALUES(@SubString)
	END

	--Show all Components in the @returnTable table
	RETURN
END
GO


---------------------------------------------

-- dbo.StripNewLine
CREATE function [dbo].[StripNewLine](
	@Input varchar(max)
)
returns varchar(max)
AS
BEGIN
	declare @retval varchar(max);
	set @retval = REPLACE(REPLACE(REPLACE(@Input, CHAR(13), ' '), CHAR(10), ' '), CHAR(13) + CHAR(10), ' ');
	
	return @retval;


END
GO


---------------------------------------------

-- dbo.TableColumnExists
CREATE FUNCTION [dbo].[TableColumnExists](
	@SchemaName NVARCHAR(128),
	@TableName NVARCHAR(MAX), 
	@ColumnName nvarchar(128)
)
RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists.
AS
BEGIN

IF EXISTS
	(SELECT 1 
	FROM INFORMATION_SCHEMA.COLUMNS 
	WHERE TABLE_SCHEMA = @SchemaName AND TABLE_NAME = @tablename 
	AND COLUMN_NAME = @columnname
	)
RETURN cast(1 as bit)

--Table does not contain the column.
RETURN cast(0 as bit)
END
GO


---------------------------------------------

-- dbo.TableColumnExistsByTableExpression
CREATE FUNCTION [dbo].[TableColumnExistsByTableExpression](
	@TableExpression NVARCHAR(MAX), 
	@ColumnName nvarchar(128)
)
RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists.
AS
BEGIN

IF EXISTS
	(SELECT 1 
	FROM INFORMATION_SCHEMA.COLUMNS 
	WHERE TABLE_SCHEMA + '.' + TABLE_NAME = @TableExpression
	AND COLUMN_NAME = @columnname
	)
RETURN cast(1 as bit)


IF EXISTS
	(SELECT 1 
	FROM INFORMATION_SCHEMA.COLUMNS 
	WHERE TABLE_SCHEMA + '.' + TABLE_NAME = @TableExpression
	AND '[' +  COLUMN_NAME + ']' = @columnname 
	)
RETURN cast(1 as bit)

IF EXISTS
	(SELECT 1 
	FROM INFORMATION_SCHEMA.COLUMNS 
	WHERE ('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']') = @TableExpression
	AND COLUMN_NAME = @columnname
	)
RETURN cast(1 as bit)

IF EXISTS
	(SELECT 1 
	FROM INFORMATION_SCHEMA.COLUMNS 
	WHERE ('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']') = @TableExpression
	AND '[' +  COLUMN_NAME + ']' =  @columnname 
	)
RETURN cast(1 as bit)

--Table does not contain the column.
RETURN cast(0 as bit)
END
GO


---------------------------------------------

-- dbo.TableExists
CREATE FUNCTION [dbo].[TableExists](
	@SchemaName sysname,
	@TableName sysname
)
RETURNS BIT--Returns 0 if table does not exist. Returns 1 if table exists.
AS
BEGIN

IF EXISTS
	(SELECT * FROM INFORMATION_SCHEMA.Tables  
		WHERE TABLE_SCHEMA = @SchemaName AND TABLE_NAME = @TableName and TABLE_TYPE = 'BASE TABLE')
RETURN cast(1 as bit)

--Table does not contain the column.
RETURN cast(0 as bit)
END
GO


---------------------------------------------

-- dbo.TableExistsByTableExpression
CREATE FUNCTION [dbo].[TableExistsByTableExpression](
	@TableExpression NVARCHAR(MAX)
)
RETURNS BIT--Returns 0 if table does not exist. Returns 1 if table exists.
AS
BEGIN

IF EXISTS
	(SELECT * FROM INFORMATION_SCHEMA.Tables  
		WHERE TABLE_SCHEMA + '.' + TABLE_NAME = @TableExpression)
RETURN cast(1 as bit)

IF EXISTS
	(SELECT * FROM INFORMATION_SCHEMA.Tables  
		WHERE '[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']' = @TableExpression)
RETURN cast(1 as bit)

IF EXISTS
	(SELECT * FROM INFORMATION_SCHEMA.Tables  
		WHERE TABLE_NAME = @TableExpression)
RETURN cast(1 as bit)

--Table does not contain the column.
RETURN cast(0 as bit)
END
GO


---------------------------------------------

-- dbo.TitleCase
create function dbo.TitleCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
   declare @Reset bit;
   declare @Ret varchar(8000);
   declare @i int;
   declare @c char(1);

   select @Reset = 1, @i=1, @Ret = '';

   while (@i <= len(@Text))
    select @c= substring(@Text,@i,1),
               @Ret = @Ret + case when @Reset=1 then UPPER(@c) else LOWER(@c) end,
               @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
               @i = @i +1
   return @Ret
end
GO


---------------------------------------------

-- dbo.ToValidCSV
create function dbo.ToValidCSV (@Text varchar(max))
RETURNS varchar(max)
AS
BEGIN

	declare @RetVal varchar(max);
	set @RetVal = @Text;
	
	-- if it contains " , replace with ""
	if (CHARINDEX('"', @RetVal, 1) <> 0) begin
		set @RetVal = REPLACE(@RetVal, '"', '""');
	end
	-- if it contains a comma, seperate with quotes
	if (CHARINDEX(',',@RetVal,1) <> 0) begin
		set @RetVal = '"' + @RetVal + '"';
	end
	
	return @RetVal;
END
GO


---------------------------------------------

-- dbo.TrimChar
Create FUNCTION [dbo].[TrimChar](
	@String NVARCHAR(4000),
	@c NCHAR(1)
)
RETURNS nvarchar(4000)
AS
BEGIN
 
IF @String IS NOT NULL AND @c IS NOT NULL
BEGIN  
   SET @String = REPLACE(REPLACE(LTrim(RTrim(REPLACE(REPLACE(@String,' ','~'),@c,' '))),' ',@c),'~',' ')
END

RETURN @String

END
GO


---------------------------------------------

-- dbo.ViewExists
CREATE FUNCTION [dbo].[ViewExists](@SchemaName nvarchar(128), @ViewName NVARCHAR(128))
RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists.
AS
BEGIN
--See if the Table already contains the column.


IF EXISTS
	(SELECT * FROM INFORMATION_SCHEMA.Views
		WHERE TABLE_SCHEMA = @SchemaName AND TABLE_NAME = @ViewName)
RETURN cast(1 as bit)

--Table does not contain the column.
RETURN cast(0 as bit)
END
GO


---------------------------------------------

-- dbo.YTD
CREATE FUNCTION [dbo].[YTD] 
(
	@currentMonthIndex tinyint,
	@amount01 decimal(19, 4),
	@amount02 decimal(19, 4),
	@amount03 decimal(19, 4),
	@amount04 decimal(19, 4),
	@amount05 decimal(19, 4),
	@amount06 decimal(19, 4),
	@amount07 decimal(19, 4),
	@amount08 decimal(19, 4),
	@amount09 decimal(19, 4),
	@amount10 decimal(19, 4),
	@amount11 decimal(19, 4),
	@amount12 decimal(19, 4)
)
returns decimal(19, 4) with schemabinding
BEGIN

declare @amount decimal(19, 4)

set @amount = @amount01

if @currentMonthIndex >= 2 begin set @amount = @amount + @amount02;
if @currentMonthIndex >= 3 begin set @amount = @amount + @amount03; 
if @currentMonthIndex >= 4 begin set @amount = @amount + @amount04; 
if @currentMonthIndex >= 5 begin set @amount = @amount + @amount05; 
if @currentMonthIndex >= 6 begin set @amount = @amount + @amount06; 
if @currentMonthIndex >= 7 begin set @amount = @amount + @amount07; 
if @currentMonthIndex >= 8 begin set @amount = @amount + @amount08; 
if @currentMonthIndex >= 9 begin set @amount = @amount + @amount09; 
if @currentMonthIndex >= 10 begin set @amount = @amount + @amount10; 
if @currentMonthIndex >= 11 begin set @amount = @amount + @amount11; 
if @currentMonthIndex >= 12 begin set @amount = @amount + @amount12; 
end end end end end end end end end end end  

return @amount

END
GO


---------------------------------------------

-- dbo.ZeroGUID
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION dbo.ZeroGUID ()
RETURNS uniqueidentifier
AS
BEGIN
	-- Declare the return variable here
	DECLARE @ZEROGUID uniqueidentifier
	SET @ZEROGUID = '00000000-0000-0000-0000-000000000000'
	RETURN @ZEROGUID

END
GO


---------------------------------------------

-- dbo.fnParseJSON
CREATE FUNCTION [dbo].[fnParseJSON]( @JSON NVARCHAR(MAX))
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2019-06-03	IP		D-07973		function that transforms JSON to element-list
*************************************************************/
RETURNS @hierarchy TABLE
  (
   element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
   sequenceNo [int] NULL, /* the place in the sequence for the element */
   parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
   Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
   NAME NVARCHAR(2000),/* the name of the object */
   StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
   ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
  )
AS
BEGIN
  DECLARE
    @FirstObject INT, --the index of the first open bracket found in the JSON string
    @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
    @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
    @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
    @Type NVARCHAR(10),--whether it denotes an object or an array
    @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
    @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
    @Start INT, --index of the start of the token that you are parsing
    @end INT,--index of the end of the token that you are parsing
    @param INT,--the parameter at the end of the next Object/Array token
    @EndOfName INT,--the index of the start of the parameter at end of Object/Array token
    @token NVARCHAR(200),--either a string or object
    @value NVARCHAR(MAX), -- the value as a string
    @SequenceNo int, -- the sequence number within a list
    @name NVARCHAR(200), --the name as a string
    @parent_ID INT,--the next parent ID to allocate
    @lenJSON INT,--the current length of the JSON String
    @characters NCHAR(36),--used to convert hex to decimal
    @result BIGINT,--the value of the hex symbol being parsed
    @index SMALLINT,--used for parsing the hex value
    @Escape INT --the index of the next escape character
   
 
  DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
    (
     String_ID INT IDENTITY(1, 1),
     StringValue NVARCHAR(MAX)
    )
  SELECT--initialise the characters to convert hex to ascii
    @characters='0123456789abcdefghijklmnopqrstuvwxyz',
    @SequenceNo=0, --set the sequence no. to something sensible.
  /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
    @parent_ID=0;
  WHILE 1=1 --forever until there is nothing more to do
    BEGIN
      SELECT
        @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
      IF @start=0 BREAK --no more so drop through the WHILE loop
      IF SUBSTRING(@json, @start+1, 1)='"'
        BEGIN --Delimited Name
          SET @start=@Start+1;
          SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
        END
      IF @end=0 --no end delimiter to last string
        BREAK --no more
      SELECT @token=SUBSTRING(@json, @start+1, @end-1)
      --now put in the escaped control characters
      SELECT @token=REPLACE(@token, FROMString, TOString)
      FROM
        (SELECT
          '\"' AS FromString, '"' AS ToString
         UNION ALL SELECT '\\', '\'
         UNION ALL SELECT '\/', '/'
         UNION ALL SELECT '\b', CHAR(08)
         UNION ALL SELECT '\f', CHAR(12)
         UNION ALL SELECT '\n', CHAR(10)
         UNION ALL SELECT '\r', CHAR(13)
         UNION ALL SELECT '\t', CHAR(09)
        ) substitutions
      SELECT @result=0, @escape=1
  --Begin to take out any hex escape codes
      WHILE @escape>0
        BEGIN
          SELECT @index=0,
          --find the next hex escape sequence
          @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
          IF @escape>0 --if there is one
            BEGIN
              WHILE @index<4 --there are always four digits to a \x sequence  
                BEGIN
                  SELECT --determine its value
                    @result=@result+POWER(16, @index)
                    *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
                                @characters)-1), @index=@index+1 ;
        
                END
                -- and replace the hex sequence by its unicode value
              SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
            END
        END
      --now store the string away
      INSERT INTO @Strings (StringValue) SELECT @token
      -- and replace the string with a token
      SELECT @JSON=STUFF(@json, @start, @end+1,
                    '@string'+CONVERT(NVARCHAR(5), @@identity))
    END
  -- all strings are now removed. Now we find the first leaf. 
  WHILE 1=1  --forever until there is nothing more to do
  BEGIN
 
  SELECT @parent_ID=@parent_ID+1
  --find the first object or list by looking for the open bracket
  SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
  IF @FirstObject = 0 BREAK
  IF (SUBSTRING(@json, @FirstObject, 1)='{')
    SELECT @NextCloseDelimiterChar='}', @type='object'
  ELSE
    SELECT @NextCloseDelimiterChar=']', @type='array'
  SELECT @OpenDelimiter=@firstObject
 
  WHILE 1=1 --find the innermost object or list...
    BEGIN
      SELECT
        @lenJSON=LEN(@JSON+'|')-1
  --find the matching close-delimiter proceeding after the open-delimiter
      SELECT
        @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
                                      @OpenDelimiter+1)
  --is there an intervening open-delimiter of either type
      SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
             RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
      IF @NextOpenDelimiter=0
        BREAK
      SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
      IF @NextCloseDelimiter<@NextOpenDelimiter
        BREAK
      IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
        SELECT @NextCloseDelimiterChar='}', @type='object'
      ELSE
        SELECT @NextCloseDelimiterChar=']', @type='array'
      SELECT @OpenDelimiter=@NextOpenDelimiter
    END
  ---and parse out the list or name/value pairs
  SELECT
    @contents=SUBSTRING(@json, @OpenDelimiter+1,
                        @NextCloseDelimiter-@OpenDelimiter-1)
  SELECT
    @JSON=STUFF(@json, @OpenDelimiter,
                @NextCloseDelimiter-@OpenDelimiter+1,
                '@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
  WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
    BEGIN
      IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
        BEGIN
          SELECT
            @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
          SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
          SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
            @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
            @param=RIGHT(@token, LEN(@token)-@endofname+1)
          SELECT
            @token=LEFT(@token, @endofname-1),
            @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
          SELECT  @name=stringvalue FROM @strings
            WHERE string_id=@param --fetch the name
        END
      ELSE
        SELECT @Name=null,@SequenceNo=@SequenceNo+1
      SELECT
        @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
      IF @end=0
        SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)
          +1
       SELECT
         @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e][\-]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)
		-- Edited: add more condition [\-] in order to detect negative number 08-20-2014
      --select @start,@end, LEN(@contents+'|'), @contents 
      SELECT
        @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
        @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
      IF SUBSTRING(@value, 1, 7)='@object'
        INSERT INTO @hierarchy
          (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
          SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
            SUBSTRING(@value, 8, 5), 'object'
      ELSE
        IF SUBSTRING(@value, 1, 6)='@array'
          INSERT INTO @hierarchy
            (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
            SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
              SUBSTRING(@value, 7, 5), 'array'
        ELSE
          IF SUBSTRING(@value, 1, 7)='@string'
            INSERT INTO @hierarchy
              (NAME, SequenceNo, parent_ID, StringValue, ValueType)
              SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
              FROM @strings
              WHERE string_id=SUBSTRING(@value, 8, 5)
          ELSE
            IF @value IN ('true', 'false')
              INSERT INTO @hierarchy
                (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
            ELSE
              IF @value='null'
                INSERT INTO @hierarchy
                  (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                  SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
              ELSE
                IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
                ELSE
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
      if @Contents=' ' Select @SequenceNo=0
    END
  END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
  SELECT '-',1, NULL, '', @parent_id-1, @type
--
   RETURN
END
GO


---------------------------------------------

-- dbo.fn_diagramobjects
CREATE FUNCTION dbo.fn_diagramobjects() 
	RETURNS int
	WITH EXECUTE AS N'dbo'
	AS
	BEGIN
		declare @id_upgraddiagrams		int
		declare @id_sysdiagrams			int
		declare @id_helpdiagrams		int
		declare @id_helpdiagramdefinition	int
		declare @id_creatediagram	int
		declare @id_renamediagram	int
		declare @id_alterdiagram 	int 
		declare @id_dropdiagram		int
		declare @InstalledObjects	int

		select @InstalledObjects = 0

		select 	@id_upgraddiagrams = object_id(N'dbo.sp_upgraddiagrams'),
			@id_sysdiagrams = object_id(N'dbo.sysdiagrams'),
			@id_helpdiagrams = object_id(N'dbo.sp_helpdiagrams'),
			@id_helpdiagramdefinition = object_id(N'dbo.sp_helpdiagramdefinition'),
			@id_creatediagram = object_id(N'dbo.sp_creatediagram'),
			@id_renamediagram = object_id(N'dbo.sp_renamediagram'),
			@id_alterdiagram = object_id(N'dbo.sp_alterdiagram'), 
			@id_dropdiagram = object_id(N'dbo.sp_dropdiagram')

		if @id_upgraddiagrams is not null
			select @InstalledObjects = @InstalledObjects + 1
		if @id_sysdiagrams is not null
			select @InstalledObjects = @InstalledObjects + 2
		if @id_helpdiagrams is not null
			select @InstalledObjects = @InstalledObjects + 4
		if @id_helpdiagramdefinition is not null
			select @InstalledObjects = @InstalledObjects + 8
		if @id_creatediagram is not null
			select @InstalledObjects = @InstalledObjects + 16
		if @id_renamediagram is not null
			select @InstalledObjects = @InstalledObjects + 32
		if @id_alterdiagram  is not null
			select @InstalledObjects = @InstalledObjects + 64
		if @id_dropdiagram is not null
			select @InstalledObjects = @InstalledObjects + 128
		
		return @InstalledObjects 
	END
GO


---------------------------------------------

-- dbo.funcFindTSQLPerformanceFlaws
CREATE FUNCTION [dbo].[funcFindTSQLPerformanceFlaws] (
	@SqlText NVARCHAR(MAX)
)
RETURNS @Results TABLE (
		Severity SMALLINT,
		Category NVARCHAR(MAX),
		Description NVARCHAR(MAX)
	) 
AS
BEGIN
   
	-- Rule 1  Avoid using Like ‘% %’
	IF (@SqlText LIKE '%''[%]%[%]''%')
	BEGIN
		INSERT INTO @Results (Category, Description, Severity) VALUES ('Contains Open Ended Like', 'Avoid using Like ‘% %’', 2)
	END
	
	-- Rule 2  Avoid * ,Select only the required columns
	IF (@SqlText LIKE '%SELECT%*,%FROM%' OR 
		@SqlText LIKE '%SELECT%,*%FROM%' OR	
		@SqlText LIKE '%SELECT%* ,%FROM%' OR 
		@SqlText LIKE '%SELECT%, *%FROM%' OR
		@SqlText LIKE '%SELECT * FROM%') -- I'm sure there's a better way, but for now this will do, otherwise was getting too many false positives
	BEGIN
		INSERT INTO @Results (Category, Description, Severity) VALUES ('Select Star Used', 'Avoid * ,Select only the required columns', 2)		
	END
	
	-- Rule 3  Don't use DISTINCT unless you have to
	IF (@SqlText LIKE '%DISTINCT%')
	BEGIN
		INSERT INTO @Results (Category, Description, Severity) VALUES ('Distinct Used', 'Don''t use DISTINCT unless you have to', 1)		
	END
	
	-- Rule 4  Think set based, instead of row by row (avoid cursor).
	IF (@SqlText LIKE '%CURSOR%')
	BEGIN
		INSERT INTO @Results (Category, Description, Severity) VALUES('Cursor', 'Think set based, instead of row by row (avoid cursor).', 3)	
	END
	
	-- Rule 5  Avoid using table variables, cursors or function calls that evaluate each row in where clause
	IF (@SqlText LIKE '%INNER JOIN @%')
	BEGIN
		INSERT INTO @Results (Category, Description, Severity) VALUES('Table Variables', 'Avoid using table variables, cursors or function calls that evaluate each row in where clause', 3)	
	END	
	
	RETURN;
END
GO


---------------------------------------------

-- dbo.funcFindTSQLPerformanceFlawsForMigration
CREATE FUNCTION [dbo].[funcFindTSQLPerformanceFlawsForMigration] (
	@MigrationName NVARCHAR(MAX)
)
RETURNS @Results TABLE (
		Name NVARCHAR(MAX),
		ObjectType NVARCHAR(MAX),
		Severity NVARCHAR(MAX),
		Category NVARCHAR(MAX),
		Description NVARCHAR(MAX)
	) 
AS
BEGIN
   
	DECLARE @Sql NVARCHAR(MAX) = (SELECT ForwardScript FROM [migration].[MigrationLog] WHERE Name = @MigrationName)

	INSERT INTO @Results(Name, Severity, ObjectType, Category, Description)
	SELECT @MigrationName AS Name, CASE WHEN Severity = 3 THEN 'High'
		  WHEN Severity = 2 THEN 'Medium'
		  WHEN Severity = 1 THEN 'Low' ELSE 'N/A' END AS Severity, 'Migration' AS ObjectType, Category, Description 
	FROM [dbo].[funcFindTSQLPerformanceFlaws] (@Sql)
	
	RETURN;
END
GO


---------------------------------------------

-- dbo.getScoreDimensionGuid
Create Function [dbo].[getScoreDimensionGuid]
(@DimensionName nvarchar(128))
Returns uniqueidentifier
AS
BEGIN
declare @DimGUID uniqueidentifier;
set @DimGUID = (select top 1 DimensionGUID from dbo.ScoreDimension where FriendlyName = @DimensionName)
return @DimGUID
End
GO


---------------------------------------------

-- dbo.intGetTransformationSourceField
CREATE FUNCTION [dbo].[intGetTransformationSourceField](
	@sourceColumnId uniqueidentifier
)
RETURNS varchar(1000)
BEGIN
	DECLARE @SourceField TABLE
	(
	  RowNum int identity(1,1),
	  DataSourceID uniqueidentifier, 
	  ColumnName nvarchar(1000),
	  Concatenator nvarchar(1000) default ' '
	)

	--Get all info from current Source Field
	insert into @SourceField
	select distinct DataSourceID,ColumnName,' '  from IntSourceField where SourceColumnId=@sourceColumnId

	declare @transformationID uniqueidentifier
	select @transformationID = DataSourceID  from @SourceField

	DECLARE @ResultTable TABLE (
		TransformationID uniqueidentifier NOT NULL,
		SourceDataSourceID uniqueidentifier NOT NULL,
		Depth int NOT NULL
	)

	--Get all transformations from current Source Field
	;WITH cte (TransformationID, SourceDataSourceID, Depth)  AS 
		(
			SELECT tl.TargetDataSourceID, tl.SourceDataSourceID, 1 as Depth
			FROM 
			intTransformationLink tl
			WHERE tl.TargetDataSourceID = @transformationID
		
			UNION ALL

			SELECT t.TargetDataSourceID, t.SourceDataSourceID, c.Depth + 1
			FROM intTransformationLink t
			INNER JOIN cte c ON t.TargetDataSourceID = c.SourceDataSourceID
		)

	insert into @ResultTable
	select * from cte

	DECLARE @SourceFields TABLE
	(
	  ColumnName nvarchar(1000)
	)

	insert into @SourceFields
	select distinct ColumnName from IntSourceField 
	where DataSourceID=(select top 1 SourceDataSourceID from @ResultTable WHERE Depth = (SELECT top 1 MAX(Depth) FROM @ResultTable))

	--If exists Source file field with the same name, return it
	declare @result nvarchar(1000)
	select @result = ColumnName
	from(
		select top 1 ColumnName from @SourceFields where ColumnName like (select ColumnName from @SourceField)
	) as r

	DECLARE @numrows int
	SELECT @numrows = MAX(Depth) FROM @ResultTable
	DECLARE @i int
	SET @i = 1
	declare @xml XML

	DECLARE @TransactionXml TABLE
	(
		NodeName nvarchar(1000),
		NodeValue nvarchar(1000),
		Alias nvarchar(1000)
	)

	--Go throw all transformations and look for Current Source Field
	WHILE (@i <= @numrows)
	BEGIN
		select @xml = TRY_CONVERT(XML, (select TransformXml from IntTransformation where TransformationId = (select top 1 TransformationID from @ResultTable WHERE Depth = @i)))
		If(@xml is null) 
			RETURN ''

		declare @xmlNode as varchar(1000)
		select @xmlNode = @xml.value('local-name(/*[1])','varchar(1000)')

		delete from @TransactionXml

		--Parse TransactionXml for receiving transformation type name, used column and alias
		insert into @TransactionXml
		SELECT
		NodeName = C.value('local-name(.)', 'nvarchar(1000)'), 
		NodeValue = C.value('(.)[1]', 'nvarchar(1000)'), 
		Alias = C.value('./@ALIAS','nvarchar(1000)') 
		FROM @xml.nodes('/*[local-name(.)=sql:variable("@xmlNode")]/*') AS T(C) 

		DECLARE @numrowsFields int
		SELECT @numrowsFields = count(1) FROM @SourceField
		DECLARE @iFields int
		SET @iFields = 1

		DECLARE @firstSplit TABLE
		(
			name nvarchar(1000)
		)
		DECLARE @NewNames TABLE
		(
			RowNum int identity(1,1),
			name nvarchar(1000),
			Concatenator nvarchar(1000)
		)
		DECLARE @newName nvarchar(1000)

		--Go throw all result fields (handle case when source field use calculated column with several fields)
		WHILE (@iFields <= @numrowsFields)
		BEGIN
			select @newName = NULL
			--check if column was renamed
			select @newName = NodeValue from @TransactionXml where Alias like (select ColumnName from @SourceField where RowNum = @iFields)

			IF @newName IS NOT NULL
			BEGIN  
				update @SourceField set ColumnName = @newName where RowNum = @iFields
			END
			ELSE
			BEGIN
			--Handle calculated column
				select @newName = NodeValue from @TransactionXml where NodeValue like (select ColumnName from @SourceField where RowNum = @iFields) AND NodeName like 'TARGETCOLUMN'
				IF @newName IS NOT NULL
				BEGIN
					--parse calculated formula using []
					select @newName = NodeValue from @TransactionXml where NodeName like 'CALCULATION'

					delete from @firstSplit
					insert into @firstSplit
					select * from Split(@newName, '[')

					delete from @NewNames
					insert into @NewNames
					select Left(name,CHARINDEX(']',name)-1), case when CHARINDEX(']',name) <> len(name) then replace(name,Left(name,CHARINDEX(']',name)-1),'') else ' ' end
					from @firstSplit where name like '%]%'

					DECLARE @iNewFields int
					select @iNewFields = min(RowNum) from @NewNames

					--select * from @NewNames

					WHILE (@iNewFields <= (select max(RowNum) FROM @NewNames))
					BEGIN
						declare @Concatenator varchar(1000)
						set @Concatenator=''
						select @Concatenator = Concatenator from @NewNames where RowNum = @iNewFields

						if(@Concatenator like '%||%||%')
						begin
							select @Concatenator = Component from Split(@Concatenator, '||') where (LTRIM(RTRIM(Component)) like '"%' or LTRIM(RTRIM(Component)) like '''%') 
								and (LTRIM(RTRIM(Component)) like '%"' or LTRIM(RTRIM(Component)) like '%''')
							select @Concatenator = replace(@Concatenator, '"', '')
							select @Concatenator = replace(@Concatenator, '''', '')
							update @NewNames set Concatenator = @Concatenator where RowNum = @iNewFields
						end
						else
							update @NewNames set Concatenator = ' ' where RowNum = @iNewFields
						select @iNewFields = @iNewFields + 1
					END

					--update new name for Source Field

					IF (select count(1) from @NewNames) > 0
					BEGIN
						update @SourceField set ColumnName = (select name from @NewNames where RowNum = (select min(RowNum) from @NewNames))
						where RowNum = @iFields

						update sf set sf.Concatenator = case when sf.Concatenator=' ' then nn.Concatenator else sf.Concatenator end
						from @SourceField sf
						join @NewNames nn on nn.name = sf.ColumnName
						where sf.RowNum = @iFields and nn.Concatenator<>' '
					END

					--if calculated column contains more than one field, add it
					IF (select count(1) from @NewNames) > 1
					BEGIN
						insert into @SourceField(ColumnName, Concatenator)
						select distinct name, Concatenator from @NewNames 
						where RowNum <> 1 and name not in (select ColumnName from @SourceField)
					END
				END
			END
			SET @iFields = @iFields + 1
		END
		SET @i = @i + 1
	END

	IF(select count(*) from @SourceField) = 1
	BEGIN
		update @SourceField set Concatenator=''
	END

	--join all Source File fields that were used for current Source Field
	select @result =  STUFF((
	SELECT ColumnName + Concatenator
	FROM @SourceField
	order by RowNum
	FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 0, '')

	RETURN @result
END
GO


---------------------------------------------

-- dbo.intGetTransformationSourceFileList
CREATE FUNCTION dbo.intGetTransformationSourceFileList(
	@transformationID uniqueidentifier
)
RETURNS @ResultTable TABLE (
	SourceFileID uniqueidentifier NOT NULL
)
BEGIN
	WITH cte (TransformationID, SourceDataSourceID, Depth)  AS 
	(
		SELECT TargetDataSourceID, SourceDataSourceID, 1 as Depth
		FROM intTransformationLink
		WHERE TargetDataSourceID = @transformationID
		
		UNION ALL

		SELECT t.TargetDataSourceID, t.SourceDataSourceID, c.Depth + 1
		FROM intTransformationLink t
		INNER JOIN cte c ON t.TargetDataSourceID = c.SourceDataSourceID
	)
	INSERT INTO @ResultTable
	SELECT DISTINCT SourceDataSourceID as SourceFileID from cte
	WHERE Depth = (SELECT MAX(Depth) FROM cte)

	RETURN;
END
GO


---------------------------------------------

-- dbo.parseJSON
CREATE FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX))
RETURNS @hierarchy TABLE
  (
   element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
   sequenceNo [int] NULL, /* the place in the sequence for the element */
   parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
   Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
   NAME NVARCHAR(2000),/* the name of the object */
   StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
   ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
  )
AS
BEGIN
  DECLARE
    @FirstObject INT, --the index of the first open bracket found in the JSON string
    @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
    @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
    @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
    @Type NVARCHAR(10),--whether it denotes an object or an array
    @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
    @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
    @Start INT, --index of the start of the token that you are parsing
    @end INT,--index of the end of the token that you are parsing
    @param INT,--the parameter at the end of the next Object/Array token
    @EndOfName INT,--the index of the start of the parameter at end of Object/Array token
    @token NVARCHAR(200),--either a string or object
    @value NVARCHAR(MAX), -- the value as a string
    @SequenceNo int, -- the sequence number within a list
    @name NVARCHAR(200), --the name as a string
    @parent_ID INT,--the next parent ID to allocate
    @lenJSON INT,--the current length of the JSON String
    @characters NCHAR(36),--used to convert hex to decimal
    @result BIGINT,--the value of the hex symbol being parsed
    @index SMALLINT,--used for parsing the hex value
    @Escape INT --the index of the next escape character
   
 
  DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
    (
     String_ID INT IDENTITY(1, 1),
     StringValue NVARCHAR(MAX)
    )
  SELECT--initialise the characters to convert hex to ascii
    @characters='0123456789abcdefghijklmnopqrstuvwxyz',
    @SequenceNo=0, --set the sequence no. to something sensible.
  /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
    @parent_ID=0;
  WHILE 1=1 --forever until there is nothing more to do
    BEGIN
      SELECT
        @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
      IF @start=0 BREAK --no more so drop through the WHILE loop
      IF SUBSTRING(@json, @start+1, 1)='"'
        BEGIN --Delimited Name
          SET @start=@Start+1;
          SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
        END
      IF @end=0 --no end delimiter to last string
        BREAK --no more
      SELECT @token=SUBSTRING(@json, @start+1, @end-1)
      --now put in the escaped control characters
      SELECT @token=REPLACE(@token, FROMString, TOString)
      FROM
        (SELECT
          '\"' AS FromString, '"' AS ToString
         UNION ALL SELECT '\\', '\'
         UNION ALL SELECT '\/', '/'
         UNION ALL SELECT '\b', CHAR(08)
         UNION ALL SELECT '\f', CHAR(12)
         UNION ALL SELECT '\n', CHAR(10)
         UNION ALL SELECT '\r', CHAR(13)
         UNION ALL SELECT '\t', CHAR(09)
        ) substitutions
      SELECT @result=0, @escape=1
  --Begin to take out any hex escape codes
      WHILE @escape>0
        BEGIN
          SELECT @index=0,
          --find the next hex escape sequence
          @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
          IF @escape>0 --if there is one
            BEGIN
              WHILE @index<4 --there are always four digits to a \x sequence  
                BEGIN
                  SELECT --determine its value
                    @result=@result+POWER(16, @index)
                    *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
                                @characters)-1), @index=@index+1 ;
        
                END
                -- and replace the hex sequence by its unicode value
              SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
            END
        END
      --now store the string away
      INSERT INTO @Strings (StringValue) SELECT @token
      -- and replace the string with a token
      SELECT @JSON=STUFF(@json, @start, @end+1,
                    '@string'+CONVERT(NVARCHAR(5), @@identity))
    END
  -- all strings are now removed. Now we find the first leaf. 
  WHILE 1=1  --forever until there is nothing more to do
  BEGIN
 
  SELECT @parent_ID=@parent_ID+1
  --find the first object or list by looking for the open bracket
  SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
  IF @FirstObject = 0 BREAK
  IF (SUBSTRING(@json, @FirstObject, 1)='{')
    SELECT @NextCloseDelimiterChar='}', @type='object'
  ELSE
    SELECT @NextCloseDelimiterChar=']', @type='array'
  SELECT @OpenDelimiter=@firstObject
 
  WHILE 1=1 --find the innermost object or list...
    BEGIN
      SELECT
        @lenJSON=LEN(@JSON+'|')-1
  --find the matching close-delimiter proceeding after the open-delimiter
      SELECT
        @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
                                      @OpenDelimiter+1)
  --is there an intervening open-delimiter of either type
      SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
             RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
      IF @NextOpenDelimiter=0
        BREAK
      SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
      IF @NextCloseDelimiter<@NextOpenDelimiter
        BREAK
      IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
        SELECT @NextCloseDelimiterChar='}', @type='object'
      ELSE
        SELECT @NextCloseDelimiterChar=']', @type='array'
      SELECT @OpenDelimiter=@NextOpenDelimiter
    END
  ---and parse out the list or name/value pairs
  SELECT
    @contents=SUBSTRING(@json, @OpenDelimiter+1,
                        @NextCloseDelimiter-@OpenDelimiter-1)
  SELECT
    @JSON=STUFF(@json, @OpenDelimiter,
                @NextCloseDelimiter-@OpenDelimiter+1,
                '@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
  WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
    BEGIN
      IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
        BEGIN
          SELECT
            @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
          SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
          SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
            @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
            @param=RIGHT(@token, LEN(@token)-@endofname+1)
          SELECT
            @token=LEFT(@token, @endofname-1),
            @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
          SELECT  @name=stringvalue FROM @strings
            WHERE string_id=@param --fetch the name
        END
      ELSE
        SELECT @Name=null,@SequenceNo=@SequenceNo+1
      SELECT
        @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
      IF @end=0
        SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)
          +1
       SELECT
        @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)
      --select @start,@end, LEN(@contents+'|'), @contents 
      SELECT
        @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
        @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
      IF SUBSTRING(@value, 1, 7)='@object'
        INSERT INTO @hierarchy
          (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
          SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
            SUBSTRING(@value, 8, 5), 'object'
      ELSE
        IF SUBSTRING(@value, 1, 6)='@array'
          INSERT INTO @hierarchy
            (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
            SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
              SUBSTRING(@value, 7, 5), 'array'
        ELSE
          IF SUBSTRING(@value, 1, 7)='@string'
            INSERT INTO @hierarchy
              (NAME, SequenceNo, parent_ID, StringValue, ValueType)
              SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
              FROM @strings
              WHERE string_id=SUBSTRING(@value, 8, 5)
          ELSE
            IF @value IN ('true', 'false')
              INSERT INTO @hierarchy
                (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
            ELSE
              IF @value='null'
                INSERT INTO @hierarchy
                  (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                  SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
              ELSE
                IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
                ELSE
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
      if @Contents=' ' Select @SequenceNo=0
    END
  END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
  SELECT '-',1, NULL, '', @parent_id-1, @type
--
   RETURN
END
GO


---------------------------------------------

-- dbo.ufn_GetS3ACLByUserGuid
CREATE FUNCTION dbo.ufn_GetS3ACLByUserGuid
(
    @UserGuid UNIQUEIDENTIFIER
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
		SELECT 
			acl.LootID,
			acl.LootGroupPrefix,
			case when sum(acl.ReadAllowpts) > sum(acl.ReadDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsReadable,
			case when sum(acl.WriteAllowpts) > sum(acl.WriteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsWritable,
			case when sum(acl.SecureAllowpts) > sum(acl.SecureDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsSecurable,
			case when sum(acl.DeleteAllowpts) > sum(acl.DeleteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsDeletable,
			case when sum(acl.CreateAllowpts) > sum(acl.CreateDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsCreatable
		FROM 
			(
				SELECT
					L.LootID,
					L.LootGroupPrefix,
					ReadAllowPts,
					ReadDenyPts,
					WriteAllowPts,
					WriteDenyPts,
					SecureAllowPts,
					SecureDenyPts,
					DeleteAllowPts,
					DeleteDenyPts,
					CreateAllowPts,
					CreateDenyPts
				FROM	
					 dbo.S3LootGroup LG WITH (READUNCOMMITTED)
					 INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID
					 INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID
					 INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID
					 INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) ON RA.identityguid = il.GroupingGUID
					 WHERE il.MemberGUID = @UserGuid
			 ) AS acl
			
			
		GROUP BY
			acl.LootID,
			acl.LootGroupPrefix
);
GO


---------------------------------------------

-- dbo.ufn_GetS3ACLSimpleReadable
CREATE FUNCTION dbo.ufn_GetS3ACLSimpleReadable
(
    @UserGuid UNIQUEIDENTIFIER
)
RETURNS TABLE
AS
RETURN
(
    SELECT DISTINCT P.LootID
    FROM dbo.UserProfile U WITH (READUNCOMMITTED)
        INNER JOIN dbo.S3IdentityLink IL WITH (READUNCOMMITTED)
            ON U.UserGUID = IL.MemberGUID
        INNER JOIN dbo.S3SimplePermission P WITH (READUNCOMMITTED)
            ON P.IdentityGUID = IL.GroupingGUID
    WHERE U.UserGUID = @UserGuid AND P.ReadValue = 1
);
GO


---------------------------------------------

