<?xml version="1.0" encoding="utf-8"?>
<DataHistorySql>
  <Queries>
    <Query Name="Validate_Database">
      SELECT COUNT(*) FROM master.dbo.sysdatabases WHERE [name] = @DbName
    </Query>
    <Query Name="Create_Database">
      CREATE DATABASE [{0}] COLLATE Latin1_General_CI_AI;
      ALTER DATABASE [{0}] SET RECOVERY SIMPLE;
    </Query>
    <Query Name="Validate_Fulltext_Installed">
      SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')
    </Query>
    <Query Name="Validate_Fulltext">
      IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE [Name] = DB_NAME() AND [is_fulltext_enabled] = 1 )
      BEGIN
      EXEC sp_fulltext_database 'enable'
      END
      SELECT is_fulltext_enabled FROM sys.databases WHERE [Name] = DB_NAME()
    </Query>
    <Query Name="Validate_DbCollation">
      DECLARE @DatabaseName AS SYSNAME = &apos;{0}&apos;
      IF EXISTS (SELECT * FROM sys.Databases WHERE[NAME] = @DatabaseName AND [COLLATION_NAME] &lt;&gt; &apos;Latin1_General_CI_AI&apos;)
      BEGIN
      IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @DatabaseName)
      BEGIN
      ALTER DATABASE [{0}] COLLATE Latin1_General_CI_AI
      END
      END
      SELECT COUNT(*) FROM sys.Databases WHERE[NAME] = @DatabaseName AND [COLLATION_NAME] = 'Latin1_General_CI_AI'
    </Query>
    <Query Name="Validate_MainTables">
      SELECT 1 WHERE
      (OBJECT_ID(N&apos;main-db-version&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;main-user&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;main-computer&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;main-scans&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;main-scan-history&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;main-column-validation&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;main-config&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;main-computer-quickaction&apos;, N&apos;U&apos;) IS NOT NULL) AND
      EXISTS(SELECT * FROM sys.fulltext_catalogs WHERE name=&apos;search_catalog&apos;)
    </Query>
    <Query Name="Create_MainTables">
      SET ANSI_NULLS ON
      SET QUOTED_IDENTIFIER ON

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-db-version]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-db-version]...&apos;;

      CREATE TABLE [main-db-version](
      [db_version] [int] NOT NULL,
      [db_revision] [int] NOT NULL,
      CONSTRAINT [PK_main-db-version] PRIMARY KEY CLUSTERED (
      [db_version] ASC,
      [db_revision] ASC
      ) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-user]...&apos;;

      CREATE TABLE [main-user](
      [timestamp] [timestamp] NOT NULL,
      [id] [uniqueidentifier] NOT NULL,
      [last_seen] [datetime] NOT NULL,
      [sid] [nvarchar](50) NULL,
      [sid_bin] [varbinary](68) NULL,
      [account] [nvarchar](256) NOT NULL,
      [full_name] [nvarchar](256) NOT NULL,
      [upn_internal] [nvarchar](256) NULL,
      [upn_external] [nvarchar](256) NULL,
      [mail] [nvarchar](1024) NULL,
      [phone] [nvarchar](1024) NULL,
      [phone_rev] [nvarchar](1024) NULL,
      [id_agent] [int] NULL,
      [is_active] [int] NOT NULL,
      [last_seen_by_agent] [datetime] NULL,
      CONSTRAINT [PK_main-user] PRIMARY KEY CLUSTERED
      ([id] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY];

      ALTER TABLE [main-user] ADD  CONSTRAINT [DF_main-user_id]  DEFAULT (newid()) FOR [id];
      ALTER TABLE [main-user] ADD  CONSTRAINT [DF_main-user_is_active]  DEFAULT ((0)) FOR [is_active];

      CREATE UNIQUE NONCLUSTERED INDEX [IX_main-user_sid] ON [main-user]
      ([sid_bin] ASC)WITH (IGNORE_DUP_KEY = ON, DROP_EXISTING = OFF) ON [PRIMARY];

      CREATE NONCLUSTERED INDEX [IX_main-user_full_name] ON [main-user]
      ([full_name] ASC)WITH (DROP_EXISTING = OFF) ON [PRIMARY];

      CREATE NONCLUSTERED INDEX [IX_main-user_last_seen] ON [main-user]
      ([last_seen] ASC)WITH (DROP_EXISTING = OFF) ON [PRIMARY];

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user-local]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;Start creating table [main-user-local]...&apos;;
      CREATE TABLE [main-user-local](
      [id] [uniqueidentifier] NOT NULL,
      [id_agent] [int] NOT NULL,
      [account] [nvarchar](256) NOT NULL,
      [sid] [nvarchar](50) NOT NULL,
      [sid_bin] [varbinary](68) NOT NULL,
      [last_seen_by_agent] [datetime] NULL,
      CONSTRAINT [PK_main-user-local] PRIMARY KEY CLUSTERED
      ([sid_bin] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]
      ALTER TABLE [main-user-local]  WITH CHECK ADD  CONSTRAINT [FK_main-user-local_main-user] FOREIGN KEY([id]) REFERENCES [main-user] ([id]) ON DELETE CASCADE
      ALTER TABLE [main-user-local] CHECK CONSTRAINT [FK_main-user-local_main-user]
      PRINT N&apos;... done.&apos;
      END

      IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user-tokens]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;Start creating table [main-user-tokens]...&apos;;

      CREATE TABLE [main-user-tokens](
      [timestamp] [timestamp] NOT NULL,
      [id] [uniqueidentifier] NOT NULL,
      [type] [int] NOT NULL,
      [name] [nvarchar](255) NULL,
      [name2] [nvarchar](255) NULL,
      [secret] [nvarchar](max) NULL,
      [validUntil] [datetime] NULL,
      [renewUntil] [datetime] NULL,
      CONSTRAINT [PK_main-user-tokens] PRIMARY KEY CLUSTERED
      ([id] ASC,[type] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]

      ALTER TABLE [main-user-tokens] WITH CHECK ADD CONSTRAINT [FK_main-user-tokens_main-user] FOREIGN KEY([id]) REFERENCES [main-user] ([id]) ON DELETE CASCADE

      ALTER TABLE [main-user-tokens] CHECK CONSTRAINT [FK_main-user-tokens_main-user]

      PRINT N&apos;... done.&apos;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-computer]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-computer]...&apos;;

      CREATE TABLE [main-computer](
      [timestamp] [timestamp] NOT NULL,
      [id] [uniqueidentifier] NOT NULL,
      [last_seen] [datetime] NOT NULL,
      [sid] [nvarchar](50) NULL,
      [sid_bin] [varbinary](68) NULL,
      [name] [nvarchar](256) NOT NULL,
      [upn_internal] [nvarchar](256) NOT NULL,
      [id_agent] [int] NULL,
      [is_active] [int] NULL,
      [last_seen_by_agent] [datetime] NULL,
      CONSTRAINT [PK_main-computer] PRIMARY KEY CLUSTERED
      ([id] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY];

      ALTER TABLE [main-computer] ADD CONSTRAINT [DF_main-computer_id]  DEFAULT (newid()) FOR [id];

      CREATE NONCLUSTERED INDEX [IX_main-computer_sid] ON [main-computer]
      ([sid_bin] ASC)WITH (DROP_EXISTING = OFF) ON [PRIMARY];

      CREATE UNIQUE NONCLUSTERED INDEX [IX_main-computer_upn_internal] ON [main-computer]
      ([upn_internal] ASC )WITH (IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF) ON [PRIMARY];

      CREATE NONCLUSTERED INDEX [IX_main-computer_last_seen] ON [main-computer]
      ([last_seen] ASC)WITH (DROP_EXISTING = OFF) ON [PRIMARY];

      CREATE UNIQUE NONCLUSTERED INDEX [IX_main-computer_name] ON [main-computer]
      ([name] ASC )WITH (IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF) ON [PRIMARY];

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-scans]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-scans]...&apos;;

      CREATE TABLE [main-scans](
      [Scan] [nchar](32) NOT NULL,
      [LastTime] [datetime] NOT NULL,
      CONSTRAINT [PK_main-scans] PRIMARY KEY CLUSTERED ([Scan] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY];

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM [main-scans] WHERE [Scan] = &apos;Default&apos;)
      INSERT INTO [main-scans] ([Scan], [LastTime]) VALUES (&apos;Default&apos;,&apos;1970-01-01 00:00:00&apos;);

      IF NOT EXISTS (SELECT * FROM [main-scans] WHERE [Scan] = &apos;AgentScan-all&apos;)
      INSERT INTO [main-scans] ([Scan], [LastTime]) VALUES (&apos;AgentScan-all&apos;,&apos;1971-01-01 00:00:00&apos;);

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-scan-history]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-scan-history]...&apos;;

      CREATE TABLE [main-scan-history](
      [ScanId] [uniqueidentifier] NOT NULL,
      [Scan] [nchar](32) NOT NULL,
      [TimeFrameFrom] [datetime] NOT NULL,
      [TimeFrameTo] [datetime] NOT NULL,
      [ExecutionTime] [datetime] NOT NULL,
      [State] [tinyint] NOT NULL,
      CONSTRAINT [PK_main-scans-history] PRIMARY KEY CLUSTERED (
      [ScanId] ASC
      ) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY];

      ALTER TABLE [main-scan-history] ADD  CONSTRAINT [DF_main-scans-history_ScanId]  DEFAULT (newid()) FOR [ScanId];
      ALTER TABLE [main-scan-history] ADD  CONSTRAINT [DF_main-scan-history_State]  DEFAULT ((0)) FOR [State];

      ALTER TABLE [main-scan-history]  WITH CHECK ADD  CONSTRAINT [FK_main-scan-history_main-scans] FOREIGN KEY([Scan]) REFERENCES [main-scans] ([Scan]);

      ALTER TABLE [main-scan-history] CHECK CONSTRAINT [FK_main-scan-history_main-scans];

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM [main-scan-history] WHERE [ScanId] = &apos;00000000-0000-0000-0000-000000000000&apos;)
      INSERT INTO [main-scan-history] ([ScanId], [Scan], [TimeFrameFrom], [TimeFrameTo], [ExecutionTime], [State]) VALUES (&apos;00000000-0000-0000-0000-000000000000&apos;, &apos;Default&apos;,&apos;1970-01-01 00:00:00&apos;,&apos;1970-01-01 00:00:00&apos;,&apos;1970-01-01 00:00:00&apos;,0);


      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-column-validation]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-column-validation]...&apos;;

      CREATE TABLE [main-column-validation](
      [Connector] [nvarchar](15) NOT NULL,
      [Instance] [nvarchar](50) NOT NULL,
      [SubTable] [nvarchar](50) NOT NULL,
      [Column] [nvarchar](50) NOT NULL,
      [isValid] [tinyint] NOT NULL,
      CONSTRAINT [PK_main-column-validation] PRIMARY KEY CLUSTERED ([Connector] ASC, [Instance] ASC, [SubTable] ASC, [Column] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY];

      PRINT N&apos;  ...done.&apos;;
      END

      IF  NOT EXISTS (SELECT * FROM sys.fulltext_catalogs WHERE name=&apos;search_catalog&apos;)
      BEGIN
      PRINT N&apos;start creating fulltext catalog [search_catalog]...&apos;;

      CREATE FULLTEXT CATALOG [search_catalog] WITH ACCENT_SENSITIVITY = OFF AS DEFAULT;
      CREATE FULLTEXT INDEX ON [main-user] ([account] LANGUAGE &apos;Neutral&apos;, [full_name] LANGUAGE &apos;Neutral&apos;, [upn_external] LANGUAGE &apos;Neutral&apos;, [mail] LANGUAGE &apos;Neutral&apos;, [phone] LANGUAGE &apos;Neutral&apos;, [phone_rev] LANGUAGE &apos;Neutral&apos;) KEY INDEX [PK_main-user] ON [search_catalog];
      CREATE FULLTEXT INDEX ON [main-computer] ([name] LANGUAGE &apos;Neutral&apos;) KEY INDEX [PK_main-computer] ON [search_catalog];

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM [main-db-version] WHERE [db_version] = 1 AND [db_revision] = 0)
      INSERT INTO [main-db-version] ([db_version], [db_revision]) VALUES (1,0);

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-config]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-config]...&apos;;

      CREATE TABLE [main-config](
      [Key] [nvarchar](32) NOT NULL,
      [Value] [nvarchar](1024) NULL,
      CONSTRAINT [PK_main-config] PRIMARY KEY CLUSTERED
      (
      [Key] ASC
      )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-computer-quickaction]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-computer-quickaction]...&apos;;

      CREATE TABLE [main-computer-quickaction](
      [ExecutionId] [int] IDENTITY(1,1) NOT NULL,
      [QActionId] [uniqueidentifier] NOT NULL,
      [QActionName] [nvarchar](100) NOT NULL,
      [DeviceId] [uniqueidentifier] NOT NULL,
      [UserId] [uniqueidentifier] NULL,
      [Start] [datetime] NOT NULL,
      [Finish] [datetime] NOT NULL,
      [ResultType] [nvarchar](32) NULL,
      [ExecutionType] [nvarchar](32) NULL,
      [Parameters] [nvarchar](max) NULL,
      [Result] [nvarchar](max) NULL,
      [ErrorCode] [int] NULL,
      [ErrorDescription] [nvarchar](max) NULL,
      CONSTRAINT [PK_ExecutionId] PRIMARY KEY CLUSTERED
      (
      [ExecutionId] ASC
      )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]

      PRINT N&apos;  ...done.&apos;;
      END

    </Query>
    <Query Name="Validate_AdScanTables">
      SELECT 1 WHERE (OBJECT_ID(N&apos;adscan-info&apos;, N&apos;U&apos;) IS NOT NULL) AND (OBJECT_ID(N&apos;adscan-nodes&apos;, N&apos;U&apos;) IS NOT NULL)
    </Query>
    <Query Name="Create_AdScanTables">
      SET ANSI_NULLS ON
      SET QUOTED_IDENTIFIER ON

      IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[adscan-info]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [adscan-info]...&apos;;

      CREATE TABLE [adscan-info](
      [timestamp] [timestamp] NOT NULL,
      [id] [int] IDENTITY(1,1) NOT NULL,
      [name] [nvarchar](50) NOT NULL,
      [last_run] [datetime] NOT NULL,
      CONSTRAINT [PK_adscan-info] PRIMARY KEY CLUSTERED
      ([id] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY];

      PRINT N&apos;  ...done.&apos;;
      END

      IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[adscan-nodes]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [adscan-nodes]...&apos;;

      CREATE TABLE [adscan-nodes](
      [timestamp] [timestamp] NOT NULL,
      [id_scan] [int] NOT NULL,
      [name] [nvarchar](1024) NOT NULL,
      [fingerprint] [nvarchar](1024) NOT NULL,
      [invocation_id] [nvarchar](40) NULL,
      [last_usn] [numeric](18, 0) NULL,
      CONSTRAINT [PK_adscan-nodes] PRIMARY KEY CLUSTERED
      ([id_scan] ASC, [name] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY];

      ALTER TABLE [adscan-nodes] WITH CHECK ADD CONSTRAINT [FK_adscan-nodes_adscan-info] FOREIGN KEY([id_scan])
      REFERENCES [adscan-info] ([id])
      ON UPDATE CASCADE
      ON DELETE CASCADE;

      PRINT N&apos;  ...done.&apos;;
      END
    </Query>
    <Query Name="ValidateDailyAgentEventTables">
      SELECT COUNT(*) FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[c4it_event_mapping]&apos;) AND type in (N&apos;U&apos;)
    </Query>
    <Query Name="ValidateOverallAgentEventTables">
      SELECT COUNT(*) FROM sys.objects WHERE (object_id = OBJECT_ID(N&apos;[c4it_event]&apos;) OR object_id = OBJECT_ID(N&apos;[c4it_event_data]&apos;)) AND type in (N&apos;U&apos;)
    </Query>
    <Query Name="GetDbTablesVersion">
      IF NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-db-version&apos;)
      SELECT 0, 0;
      ELSE
      SELECT MAX([db_version]), MAX([db_revision]) FROM [main-db-version] WHERE [db_version] = ( SELECT MAX([db_version]) FROM [main-db-version] );
    </Query>
    <Query Name="UpdateDbTablesV1.1">
      DECLARE @cnt INT
      SET @cnt = 0

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-db-version]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-db-version]...&apos;;

      CREATE TABLE [main-db-version](
      [db_version] [int] NOT NULL,
      [db_revision] [int] NOT NULL,
      CONSTRAINT [PK_main-db-version] PRIMARY KEY CLUSTERED (
      [db_version] ASC,
      [db_revision] ASC
      ) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY];

      SET @cnt = @cnt + 1;
      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM [main-db-version] WHERE [db_version] = 0 AND [db_revision] = 0)
      INSERT INTO [main-db-version] ([db_version], [db_revision]) VALUES (0,0);

      IF NOT EXISTS (SELECT * FROM [main-scans] WHERE [Scan] = &apos;Default&apos;)
      INSERT INTO [main-scans] ([Scan], [LastTime]) VALUES (&apos;Default&apos;,&apos;1970-01-01 00:00:00&apos;);

      IF NOT EXISTS (SELECT * FROM [main-scans] WHERE [Scan] = &apos;AgentScan-all&apos;)
      INSERT INTO [main-scans] ([Scan], [LastTime]) VALUES (&apos;AgentScan-all&apos;,&apos;1971-01-01 00:00:00&apos;);

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-scan-history]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [main-scan-history]...&apos;;

      CREATE TABLE [main-scan-history](
      [ScanId] [uniqueidentifier] NOT NULL,
      [ScanId] [uniqueidentifier] NOT NULL,
      [Scan] [nchar](32) NOT NULL,
      [TimeFrameFrom] [datetime] NOT NULL,
      [TimeFrameTo] [datetime] NOT NULL,
      [ExecutionTime] [datetime] NOT NULL,
      CONSTRAINT [PK_main-scans-history] PRIMARY KEY CLUSTERED (
      [ScanId] ASC
      ) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY];

      ALTER TABLE [main-scan-history] ADD  CONSTRAINT [DF_main-scans-history_ScanId]  DEFAULT (newid()) FOR [ScanId];

      ALTER TABLE [main-scan-history]  WITH CHECK ADD  CONSTRAINT [FK_main-scan-history_main-scans] FOREIGN KEY([Scan]) REFERENCES [main-scans] ([Scan]);

      ALTER TABLE [main-scan-history] CHECK CONSTRAINT [FK_main-scan-history_main-scans];

      SET @cnt = @cnt + 1;
      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM [main-scan-history] WHERE [ScanId] = &apos;00000000-0000-0000-0000-000000000000&apos;)
      INSERT INTO [main-scan-history] ([ScanId], [Scan], [TimeFrameFrom], [TimeFrameTo], [ExecutionTime]) VALUES (&apos;00000000-0000-0000-0000-000000000000&apos;, &apos;Default&apos;,&apos;1970-01-01 00:00:00&apos;,&apos;1970-01-01 00:00:00&apos;,&apos;1970-01-01 00:00:00&apos;);

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[ad-computer]&apos;) AND type in (N&apos;U&apos;)) AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;ad-computer&apos; AND Column_Name = &apos;ScanId&apos;)
      BEGIN
      PRINT N&apos;Start adding column [ScanId] to table [ad-computer] ...&apos;;
      ALTER Table [ad-computer] ADD [ScanId] [uniqueidentifier] NOT NULL CONSTRAINT [DF_ad-computer_ScanId]  DEFAULT (&apos;00000000-0000-0000-0000-000000000000&apos;) WITH VALUES;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[ad-computer]&apos;) AND type in (N&apos;U&apos;)) AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;ad-computer&apos; AND Column_Name = &apos;distinguishedName&apos;)
      BEGIN PRINT N&apos;Start adding column [distinguishedName] to table [ad-computer] ...&apos;;
      ALTER Table [ad-computer] ADD distinguishedName nvarchar(1024) NULL;
      UPDATE [adscan-nodes] SET [last_usn] = NULL;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[ad-user]&apos;) AND type in (N&apos;U&apos;)) AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;ad-user&apos; AND Column_Name = &apos;ScanId&apos;)
      BEGIN
      PRINT N&apos;Start adding column [ScanId] to table [ad-user] ...&apos;;
      ALTER Table [ad-user] ADD [ScanId] [uniqueidentifier] NOT NULL CONSTRAINT [DF_ad-user_ScanId]  DEFAULT (&apos;00000000-0000-0000-0000-000000000000&apos;) WITH VALUES;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      SELECT @cnt
    </Query>
    <Query Name="UpdateDbTablesV1.2">
      DECLARE @cnt INT
      SET @cnt = 0

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND type in (N&apos;U&apos;)) AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;last_seen_by_agent&apos;)
      BEGIN
      PRINT N&apos;Start adding column [last_seen_by_agent] to table [main-user] ...&apos;;
      ALTER Table [main-user] ADD [last_seen_by_agent] [datetime];
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-computer]&apos;) AND type in (N&apos;U&apos;)) AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-computer&apos; AND Column_Name = &apos;last_seen_by_agent&apos;)
      BEGIN
      PRINT N&apos;Start adding column [last_seen_by_agent] to table [main-computer] ...&apos;;
      ALTER Table [main-computer] ADD [last_seen_by_agent] [datetime];
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      SELECT @cnt
    </Query>
    <Query Name="UpdateDbTablesV1.3">
      DECLARE @cnt INT
      SET @cnt = 0

      IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[adscan-domains]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;Start creating table [adscan-domains]...&apos;;
      CREATE TABLE [adscan-domains](
      [domainDns] [nvarchar](128) NOT NULL,
      [domainNB] [nvarchar](16) NOT NULL,
      CONSTRAINT [PK_adscan-domains] PRIMARY KEY CLUSTERED
      ([domainDns] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND type in (N&apos;U&apos;)) AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;domainDns&apos;)
      BEGIN
      PRINT N&apos;Start adding column [domainDns] to table [main-user] ...&apos;;
      ALTER Table [main-user] ADD [domainDns] NVARCHAR(128) ;
      ALTER Table [main-user] ADD [domainNB] NVARCHAR(16) ;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-computer]&apos;) AND type in (N&apos;U&apos;)) AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-computer&apos; AND Column_Name = &apos;domainNB&apos;)
      BEGIN
      PRINT N&apos;Start adding column [domainNB] to table [main-computer] ...&apos;;
      ALTER Table [main-computer] ADD [domainDns] NVARCHAR(128) ;
      ALTER Table [main-computer] ADD [domainNB] NVARCHAR(16) ;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      SELECT @cnt
    </Query>
    <Query Name="UpdateDbTablesV1.4">
      DECLARE @cnt INT
      SET @cnt = 0

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND type in (N&apos;U&apos;))
      AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;id_azure&apos;)
      BEGIN
      PRINT N&apos;Start adding column [id_azure] to table [main-user] ...&apos;;
      ALTER Table [main-user] ADD [id_azure] [uniqueidentifier];
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND type in (N&apos;U&apos;))
      AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;id_agent_azure&apos;)
      BEGIN
      PRINT N&apos;Start adding column [id_agent_azure] to table [main-user] ...&apos;;
      ALTER Table [main-user] ADD [id_agent_azure] [int];
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND type in (N&apos;U&apos;))
      AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;tenant_azure&apos;)
      BEGIN
      PRINT N&apos;Start adding column [tenant_azure] to table [main-user] ...&apos;;
      ALTER Table [main-user] ADD [tenant_azure] [uniqueidentifier];
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;id_agent&apos;)
      AND NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND [name] = &apos;IX_main-user_id_agent&apos;)
      BEGIN
      PRINT N&apos;Start creating index [IX_main-user_id_agent] on table [main-user] ...&apos;;
      CREATE NONCLUSTERED INDEX [IX_main-user_id_agent] ON [main-user] ([id_agent] ASC);
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;id_agent_azure&apos;)
      AND NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND [name] = &apos;IX_main-user_id_agent_azure&apos;)
      BEGIN
      PRINT N&apos;Start creating index [IX_main-user_id_agent_azure] on table [main-user] ...&apos;;
      CREATE NONCLUSTERED INDEX [IX_main-user_id_agent_azure] ON [main-user] ([id_agent_azure] ASC);
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      SELECT @cnt
    </Query>
    <Query Name="UpdateDbTablesV1.5">
      DECLARE @cnt INT
      SET @cnt = 0

      IF EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;domainDns&apos;)
      AND NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND [name] = &apos;IX_main-user_account&apos;)
      BEGIN
      PRINT N&apos;Start creating index [IX_main-user_account] on table [main-user] ...&apos;;
      CREATE NONCLUSTERED INDEX [IX_main-user_account] ON [main-user] ([account] ASC, [domainDns] ASC)
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-computer&apos; AND Column_Name = &apos;name&apos;)
      AND NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N&apos;[main-computer]&apos;) AND [name] = &apos;IX_main-computer_name&apos;)
      BEGIN
      PRINT N&apos;Start creating index [IX_main-computer_name] on table [main-computer] ...&apos;;
      CREATE NONCLUSTERED INDEX [IX_main-computer_name] ON [main-computer] ([name] ASC)
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user-local]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;Start creating table [main-user-local]...&apos;;
      CREATE TABLE [main-user-local](
      [id] [uniqueidentifier] NOT NULL,
      [id_agent] [int] NOT NULL,
      [account] [nvarchar](256) NOT NULL,
      [sid] [nvarchar](50) NOT NULL,
      [sid_bin] [varbinary](68) NOT NULL,
      [last_seen_by_agent] [datetime] NULL,
      CONSTRAINT [PK_main-user-local] PRIMARY KEY CLUSTERED
      ([sid_bin] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]
      ALTER TABLE [main-user-local]  WITH CHECK ADD  CONSTRAINT [FK_main-user-local_main-user] FOREIGN KEY([id]) REFERENCES [main-user] ([id]) ON DELETE CASCADE
      ALTER TABLE [main-user-local] CHECK CONSTRAINT [FK_main-user-local_main-user]
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      SELECT @cnt
    </Query>
    <Query Name="UpdateDbTablesV1.6">
      DECLARE @cnt INT
      SET @cnt = 0

      IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user-tokens]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;Start creating table [main-user-tokens]...&apos;;

      CREATE TABLE [main-user-tokens](
      [timestamp] [timestamp] NOT NULL,
      [id] [uniqueidentifier] NOT NULL,
      [type] [int] NOT NULL,
      [name] [nvarchar](255) NULL,
      [name2] [nvarchar](255) NULL,
      [secret] [nvarchar](max) NULL,
      [validUntil] [datetime] NULL,
      [renewUntil] [datetime] NULL,
      CONSTRAINT [PK_main-user-tokens] PRIMARY KEY CLUSTERED
      ([id] ASC,[type] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]

      ALTER TABLE [main-user-tokens] WITH CHECK ADD CONSTRAINT [FK_main-user-tokens_main-user] FOREIGN KEY([id]) REFERENCES [main-user] ([id]) ON DELETE CASCADE

      ALTER TABLE [main-user-tokens] CHECK CONSTRAINT [FK_main-user-tokens_main-user]

      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      SELECT @cnt
    </Query>
    <Query Name="UpdateDbTablesV1.7">
      DECLARE @cnt INT
      SET @cnt = 0

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user-tokens]&apos;) AND type in (N&apos;U&apos;))
      AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user-tokens&apos; AND Column_Name = &apos;renewUntil&apos;)
      BEGIN
      PRINT N&apos;Start adding column [renewUntil] to table [main-user-tokens] ...&apos;;
      ALTER Table [main-user-tokens] ADD [renewUntil] [datetime] NULL;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      SELECT @cnt
    </Query>
    <Query Name="UpdateDbTablesV1.8">
      DECLARE @cnt INT
      SET @cnt = 0

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-computer]&apos;) AND type in (N&apos;U&apos;))
      AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-computer&apos; AND Column_Name = &apos;id_intune&apos;)
      BEGIN
      PRINT N&apos;Start adding column [id_intune] to table [main-computer] ...&apos;;
      ALTER Table [main-computer] ADD [id_intune] [uniqueidentifier] NULL;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-computer]&apos;) AND type in (N&apos;U&apos;))
      AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-computer&apos; AND Column_Name = &apos;deviceId_azure&apos;)
      BEGIN
      PRINT N&apos;Start adding column [deviceId_azure] to table [main-computer] ...&apos;;
      ALTER Table [main-computer] ADD [deviceId_azure] [uniqueidentifier] NULL;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-computer]&apos;) AND type in (N&apos;U&apos;))
      AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-computer&apos; AND Column_Name = &apos;id_azure&apos;)
      BEGIN
      PRINT N&apos;Start adding column [id_azure] to table [main-computer] ...&apos;;
      ALTER Table [main-computer] ADD [id_azure] [uniqueidentifier] NULL;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-computer]&apos;) AND type in (N&apos;U&apos;))
      AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-computer&apos; AND Column_Name = &apos;tenant_azure&apos;)
      BEGIN
      PRINT N&apos;Start adding column [tenant_azure] to table [main-computer] ...&apos;;
      ALTER Table [main-computer] ADD [tenant_azure] [uniqueidentifier] NULL;
      SET @cnt = @cnt + 1;
      PRINT N&apos;... done.&apos;
      END

      IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = &apos;IX_main-computer_deviceId_azure&apos;)
      BEGIN

      CREATE NONCLUSTERED INDEX [IX_main-computer_deviceId_azure] ON [main-computer]  ([deviceId_azure] ASC);

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      SELECT @cnt
    </Query>
	  <Query Name="UpdateDbTablesV1.9">
		  DECLARE @cnt INT
		  SET @cnt = 0

		  IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND type in (N&apos;U&apos;))
		  AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;id_citrix&apos;)
		  BEGIN
		  PRINT N&apos;Start adding column [id_citrix] to table [main-user] ...&apos;;
		  ALTER Table [main-user] ADD [id_citrix] int NULL;
		  SET @cnt = @cnt + 1;
		  PRINT N&apos;... done.&apos;
		  END

		  IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[main-user]&apos;) AND type in (N&apos;U&apos;))
		  AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;main-user&apos; AND Column_Name = &apos;tenant_citrix&apos;)
		  BEGIN
		  PRINT N&apos;Start adding column [tenant_citrix] to table [main-user] ...&apos;;
		  ALTER Table [main-user] ADD [tenant_citrix] nvarchar(100) NULL;
		  SET @cnt = @cnt + 1;
		  PRINT N&apos;... done.&apos;
		  END

		  IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[QActions]&apos;) AND type in (N&apos;U&apos;))
		  AND NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;QActions&apos; AND Column_Name = &apos;TimeStamp&apos;)
		  BEGIN
		  PRINT N&apos;Start adding column [TimeStamp] to table [QActions] ...&apos;;
		  ALTER Table [QActions] ADD [TimeStamp] Datetime NULL;
		  SET @cnt = @cnt + 1;
		  PRINT N&apos;... done.&apos;
		  END

		  IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = &apos;IX_main-user_upn_external&apos;)
		  BEGIN

		  CREATE NONCLUSTERED INDEX [IX_main-user_upn_external] ON [main-user]  ([upn_external] ASC);

		  SET @cnt = @cnt+1;
		  PRINT N&apos;... done.&apos;

		  END

		  SELECT @cnt
	  </Query>
    <Query Name="UpdateDbVersion">
      IF NOT EXISTS (SELECT 1 FROM [main-db-version] WHERE [db_version] = @version AND [db_revision] = @revision)
      INSERT INTO [main-db-version] ([db_version], [db_revision]) VALUES (@version,@revision);
    </Query>
    <Query Name="GetTableColumnValidation">
      SELECT [Column] FROM [main-column-validation] WHERE [Table] = @Table AND [Instance] = @Instance AND [isValid] = 1
    </Query>
    <Query Name="GetTableColumnValidationEx">
      SELECT [Column], [isValid] FROM [main-column-validation] WHERE [Table] = @Table AND [Instance] = @Instance
    </Query>
    <Query Name="InsertTableColumnValidation">
      INSERT INTO [main-column-validation] ([Table] [Instance], [Column], [isValid]) VALUES (@Table, @Instance, @Column, @isValid)
    </Query>
    <Query Name="UpdateTableColumnValidation">
      UPDATE [main-column-validation] SET [isValid] = @isValid WHERE [Table] = @Table AND [Instance] = @Instance AND [Column] = @Column
    </Query>
    <Query Name="DeleteTableColumnValidation">
      DELETE FROM [main-column-validation] WHERE [Table] = @Table AND [Instance] = @Instance AND [Column] = @Column
    </Query>
    <Query Name="CheckAndCreateTableColumn">
      IF NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;{0}&apos; AND Column_Name = &apos;{1}&apos;)
      BEGIN
      ALTER Table [{0}] ADD [{1}] {2} {3};
      SELECT 1
      END
    </Query>
    <Query Name="CheckScanIdTableColumn">
      SELECT COUNT(*) FROM (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;{0}&apos; AND Column_Name = &apos;ScanId&apos;) t
    </Query>
    <Query Name="PostColumnCreateActiveDirectory">
      UPDATE [adscan-nodes] SET [last_usn] = NULL
    </Query>
    <Query Name="AgentDbUpdate001" Description="Check &amp; create Agent DB index for event table (account)">
      IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[c4it_event]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      IF NOT EXISTS(SELECT * FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id WHERE t.name like &apos;c4it_event&apos; and i.name like &apos;IDX-C4IT-c4it_event-account&apos;)
      BEGIN
      PRINT N&apos;Creating index IDX-C4IT-c4it_event-account...&apos;;
      CREATE NONCLUSTERED INDEX [IDX-C4IT-c4it_event-account] ON [c4it_event] ([deviceaccountcode],[measurecode],[eventdate]) INCLUDE ([devicecode],[value],[DURATION]);
      PRINT N&apos;...done&apos;;
      END
      END
    </Query>
    <Query Name="AgentDbUpdate002" Description="Check &amp; create Agent DB index for event table (device)">
      IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[c4it_event]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      IF NOT EXISTS(SELECT * FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id WHERE t.name like &apos;c4it_event&apos; and i.name like &apos;IDX-C4IT-c4it_event-device&apos;)
      BEGIN
      PRINT N&apos;Creating index IDX-C4IT-c4it_event-device...&apos;;
      CREATE NONCLUSTERED INDEX [IDX-C4IT-c4it_event-device] ON [c4it_event] ([devicecode],[measurecode],[eventdate]) INCLUDE ([deviceaccountcode],[value],[DURATION]);
      PRINT N&apos;...done&apos;;
      END
      END
    </Query>
    <Query Name="AgentDbUpdate003" Description="Check &amp; create Agent DB index for event data table (device)">
      IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[c4it_event_data]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      IF NOT EXISTS(SELECT * FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id WHERE t.name like &apos;c4it_event_data&apos; and i.name like &apos;IDX-C4IT-c4it_event_data-device&apos;)
      BEGIN
      PRINT N&apos;Creating index IDX-C4IT-c4it_event_data-device...&apos;;
      CREATE NONCLUSTERED INDEX [IDX-C4IT-c4it_event_data-device] ON [c4it_event_data] ([devicecode],[measurecode],[eventdate]) INCLUDE ([deviceaccountcode],[value],[DURATION]);
      PRINT N&apos;...done&apos;;
      END
      END
    </Query>
    <Query Name="AgentDbUpdate004" Description="Check &amp; create Agent DB index for device attribute table (device)">
      IF NOT EXISTS(SELECT * FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id WHERE t.name like &apos;device_attribute&apos; and i.name like &apos;IDX-C4IT-device_attribute-device&apos;)
      BEGIN
      PRINT N&apos;Creating index IDX-C4IT-device_attribute-device...&apos;;
      CREATE NONCLUSTERED INDEX [IDX-C4IT-device_attribute-device] ON [device_attribute] ([devicecode])
      PRINT N&apos;...done&apos;;
      END
    </Query>
    <Query Name="GetDailyAgentEventTables">
      SELECT [from],[to], [eventtable], [eventdatatable], [eventdeviceactivitytable], [eventuseractivitytable]  FROM [c4it_event_mapping] WHERE [orgcode]=@ORGCODE ORDER BY [to]
    </Query>
    <Query Name="GetLastScanTime">
      SELECT [LastTime] FROM [main-scans] WHERE [Scan] = @Name
    </Query>
    <Query Name="SetLastScanTime">
      UPDATE [main-scans] SET [LastTime]=@LastTime WHERE [Scan]=@Name
      IF @@ROWCOUNT = 0 INSERT INTO [main-scans] ([Scan], [LastTime]) VALUES (@Name, @LastTime)
      SELECT @@ROWCOUNT
    </Query>
    <Query Name="GetAdScanInfo">
      SELECT [id], [name], [last_run] FROM [adscan-info]
    </Query>
    <Query Name="RemoveAdScanInfo">
      DELETE FROM [adscan-info] WHERE [id]=@ID
    </Query>
    <Query Name="UpdateAdScanDomains">
      UPDATE [adscan-domains] SET [domainNB] = @domainNB WHERE [domainDns] = @domainDns
      IF @@ROWCOUNT = 0
      INSERT INTO [adscan-domains] ([domainDns], [domainNB]) VALUES (@domainDns, @domainNB)
    </Query>
    <Query Name="GetAdScanDomains">
      SELECT [domainDns], [domainNB] FROM [adscan-domains]
    </Query>
    <Query Name="UpdateAdScanInfo">
      DECLARE @RetVal int;
      SET @RetVal=@ID
      UPDATE [adscan-info] SET [name]=@Name, [last_run]=@LastRun WHERE [id]=@ID
      IF @@ROWCOUNT = 0
      BEGIN
      INSERT INTO [adscan-info] ([name], [last_run]) VALUES (@Name, @LastRun)
      SET @RetVal = SCOPE_IDENTITY()
      END
      SELECT @RetVal as [RetVal]
    </Query>
    <Query Name="GetAdScanNodes">
      SELECT [id_scan], [name], [fingerprint], [invocation_id], [last_usn] FROM [adscan-nodes] WHERE [id_scan]=@ScanID
    </Query>
    <Query Name="UpdateAdScanNode">
      UPDATE [adscan-nodes] SET [fingerprint]=@Fingerprint, [invocation_id]=@InvocationId, [last_usn]=@LastUsn WHERE [id_scan]=@ScanID and [name]=@Name
      IF @@ROWCOUNT = 0 INSERT INTO [adscan-nodes] ([id_scan], [name], [fingerprint], [invocation_id], [last_usn]) VALUES (@ScanID, @Name, @Fingerprint, @InvocationId, @LastUsn)
    </Query>
    <Query Name="SearchFulltext">
      SELECT * FROM(
      SELECT TOP 11 1 AS [Type], [full_name], [id], [is_active], [upn_internal], [id_agent], [account], COALESCE([domainDns],[domainNB]) [domain] FROM [main-user] (nolock) WHERE CONTAINS(([full_name],[account],[upn_external], [mail]),@SEARCH) AND ([is_active] = 1 OR [last_seen_by_agent] >= DATEADD(DAY, -@DAYS,GETUTCDATE())) ORDER BY [full_name]
      UNION
      SELECT TOP 11 0 AS [Type], [name], [id], [is_active], [upn_internal], [id_agent], [name] [account], COALESCE([domainDns],[domainNB]) FROM [main-computer] (nolock) WHERE CONTAINS(([name]),@SEARCH) ORDER BY [name]
      ) AS D ORDER BY [Type], [full_name]
    </Query>
    <Query Name="SearchFulltextWithDelay">
      WAITFOR DELAY '00:00:06';
      SELECT * FROM(
      SELECT TOP 11 1 AS [Type], [full_name], [id], [is_active], [upn_internal], [id_agent], [account], COALESCE([domainDns],[domainNB]) [domain] FROM [main-user] (nolock) WHERE CONTAINS(([full_name],[account],[upn_external], [mail]),@SEARCH) AND ([is_active] = 1 OR [last_seen_by_agent] >= DATEADD(DAY, -@DAYS,GETUTCDATE())) ORDER BY [full_name]
      UNION
      SELECT TOP 11 0 AS [Type], [name], [id], [is_active], [upn_internal], [id_agent], [name] [account], COALESCE([domainDns],[domainNB]) FROM [main-computer] (nolock) WHERE CONTAINS(([name]),@SEARCH) ORDER BY [name]
      ) AS D ORDER BY [Type], [full_name]
    </Query>
    <Query Name="SearchFulltextRev">
      SELECT * FROM(
      SELECT TOP 11 2 AS [Type], [full_name], [id], [is_active], [upn_internal], [id_agent], [account], COALESCE([domainDns],[domainNB]) [domain], [phone] FROM [main-user] (nolock) WHERE CONTAINS(([phone_rev]),@REV) AND ([is_active] = 1 OR [last_seen_by_agent] >= DATEADD(DAY, -@DAYS,GETUTCDATE())) ORDER BY [full_name]
      UNION
      SELECT TOP 11 1 AS [Type], [full_name], [id], [is_active], [upn_internal], [id_agent], [account], COALESCE([domainDns],[domainNB]), [phone] FROM [main-user] (nolock) WHERE CONTAINS(([full_name],[account],[upn_external], [mail]),@SEARCH) AND ([is_active] = 1 OR [last_seen_by_agent] >= DATEADD(DAY, -@DAYS,GETUTCDATE())) ORDER BY [full_name]
      UNION
      SELECT TOP 11 0 AS [Type], [name], [id], [is_active], [upn_internal], [id_agent], [name] [account], COALESCE([domainDns],[domainNB]), NULL FROM [main-computer] (nolock) WHERE CONTAINS(([name]),@SEARCH) ORDER BY [name]
      ) AS D ORDER BY [Type], [full_name]
    </Query>
    <Query Name="SearchByField">
      SELECT TOP 11 1 AS [Type], [full_name], [id], [is_active], [upn_internal], [id_agent], [account], COALESCE([domainDns],[domainNB]) [domain] FROM [main-user] (nolock) WHERE CONTAINS(([{0}]),@SEARCH) AND ([is_active] = 1 OR [last_seen_by_agent] >= DATEADD(DAY, -@DAYS,GETUTCDATE()))  ORDER BY [full_name]
    </Query>
    <Query Name="SearchByFieldRev">
      SELECT TOP 11 2 AS [Type], [full_name], [id], [is_active], [upn_internal], [id_agent], [account], COALESCE([domainDns],[domainNB]) [domain], [phone] FROM [main-user] (nolock) WHERE CONTAINS(([{0}]),@REV) AND ([is_active] = 1 OR [last_seen_by_agent] >= DATEADD(DAY, -@DAYS,GETUTCDATE())) ORDER BY [full_name]
    </Query>
    <Query Name="SearchComputerByName">
      SELECT TOP 11 0 AS [Type], [name], [id], [is_active], [upn_internal], [id_agent], [name] [account], COALESCE([domainDns],[domainNB]) [domain] FROM [main-computer] (nolock) WHERE [name] like @name ORDER BY [Type], [name]
    </Query>
    <Query Name="SearchComputerByNameAndDomain">
      SELECT TOP 11 0 AS [Type], [name], [id], [is_active], [upn_internal], [id_agent], [name] [account], COALESCE([domainDns],[domainNB]) [domain] FROM [main-computer] (nolock) WHERE [name] like @name AND ([domainNB] like @domain OR [domainDns] like @domain) ORDER BY [Type], [name]
    </Query>
    <Query Name="SearchUserBySid">
      SELECT TOP 11 1 AS [Type], [full_name], [id], [is_active], [upn_internal], [id_agent], [account], COALESCE([domainDns],[domainNB]) [domain] FROM [main-user] (nolock) WHERE [sid_bin] in ({0}) ORDER BY [full_name]
    </Query>
    <Query Name="SearchUserByAzureIdDevelop">
      SELECT TOP 11 1 AS [Type], [full_name], [id], [is_active], [upn_internal], [id_agent], [account], COALESCE([domainDns],[domainNB]) [domain] FROM [main-user] (nolock) WHERE [id_azure] = @AzureId ORDER BY [full_name]
    </Query>
    <Query Name="GetActivityPeriods">
      SELECT [measurecode], [typecode], [orgcode], [valuejson] FROM [c4it_measure_attribute]
      WHERE [measurecode] in (40,41) AND [typecode] in (1,2) AND ( [orgcode] = @ORGCODE OR [orgcode] IS NULL)
      ORDER BY [measurecode], [typecode], [orgcode]
    </Query>
    <Query Name="GetAgentDevicesTotal">
      SELECT e.[devicecode], d.[name], d.[domain], d.[lastupdate], MAX(e.[eventdate]) [eventdate], a.[valuejson] tenantID FROM [c4it_event] e (nolock)
      INNER JOIN [device] d (nolock) ON d.[devicecode] = e.[devicecode]
      LEFT JOIN [device_attribute] a ON a.[devicecode] = d.[devicecode] AND a.typecode = 10001
      WHERE [measurecode] = 40 AND [eventdate] &gt;= @LASTSCAN
      GROUP BY e.[devicecode], d.[name], d.[domain], d.[lastupdate], a.[valuejson]
    </Query>
    <Query Name="GetAgentDevicesDaily">
      SELECT e.[devicecode], d.[name], d.[domain], d.[lastupdate], MAX(e.[eventdate]) [eventdate], a.[valuejson] tenantID FROM [{0}] (nolock) e
      INNER JOIN [device] (nolock) d ON d.[devicecode] = e.[devicecode]
      LEFT JOIN [device_attribute] a ON a.[devicecode] = d.[devicecode] AND a.typecode = 10001
      WHERE e.[eventdate] &gt;= @LASTSCAN
      GROUP BY e.[devicecode], d.[name], d.[domain], d.[lastupdate], a.[valuejson]
      ORDER BY MAX(e.[eventdate])
    </Query>
    <Query Name="GetAgentAccountsTotal">
      SELECT e.[deviceaccountcode],u.[uniqueid],u.[name],u.[domain], MAX(e.[eventdate]) last_seen FROM [c4it_event] (nolock) e
      INNER JOIN [device_account] (nolock) u ON u.[deviceaccountcode] = e.[deviceaccountcode]
      WHERE e.[measurecode] = 41 AND e.[eventdate] &gt;= @LASTSCAN
      GROUP BY e.[deviceaccountcode],u.[name],u.[uniqueid],u.[domain]
    </Query>
    <Query Name="GetAgentAccountsDaily">
      SELECT e.[deviceaccountcode],u.[uniqueid],u.[name],u.[domain], MAX(e.[eventdate]) last_seen FROM [{0}] (nolock) e
      INNER JOIN [device_account] (nolock) u ON u.[deviceaccountcode] = e.[deviceaccountcode]
      WHERE e.[eventdate] &gt;= @LASTSCAN
      GROUP BY e.[deviceaccountcode],u.[name],u.[uniqueid],u.[domain]
    </Query>
    <Query Name="InsertAgentDevice">
      UPDATE [main-computer] SET [id_agent]=NULL WHERE [id_agent]=@id_agent AND [upn_internal]&lt;&gt;@upn_internal
      UPDATE [main-computer] SET [id_agent]=@id_agent, [last_seen]=@last_seen, [last_seen_by_agent]=@lastAgent, [domainDns]=@domainDns, [domainNB]=@domainNB WHERE [upn_internal]=@upn_internal
      IF @@ROWCOUNT = 0 INSERT INTO [main-computer] ([id_agent], [name], [upn_internal], [last_seen], [last_seen_by_agent], [domainDns], [domainNB]) VALUES (@id_agent, @name, @upn_internal, @last_seen, @lastAgent, @domainDns, @domainNB)
    </Query>
    <Query Name="RemoveClientsWithoutID">
      DELETE FROM [main-computer] WHERE id_agent IS NULL
    </Query>
    <Query Name="UpdateMainComputerLdap">
      UPDATE [main-computer] SET [sid]=NULL, [sid_bin]=NULL WHERE [sid_bin]=@sid_bin AND [upn_internal]&lt;&gt;@upn_internal
      UPDATE [main-computer] SET [sid]=@sid, [sid_bin]=@sid_bin, [is_active]=@is_active WHERE [upn_internal]=@upn_internal
    </Query>
    <Query Name="UpdateComputerAzure">
      UPDATE [main-computer] SET [id_azure]=@id, [deviceid_azure]=@deviceid, tenant_azure = @tenant  WHERE [sid_bin]=@sid_bin
    </Query>	
    <Query Name="UpdateComputerIntune">
      UPDATE [main-computer] SET [id_intune]=@id WHERE [deviceId_azure]=@deviceId
    </Query>
	<Query Name="UpdateComputerIntune2">
	  UPDATE [main-computer] SET [id_intune]=@id, [deviceid_azure]=@deviceid, tenant_azure = @tenant  WHERE upn_internal = @upn_internal and [domainNB] is null
    </Query>
	 <Query Name="UpdateUserCitrix">
      UPDATE [main-user] SET [id_citrix]=@id WHERE [sid_bin]=@sid_bin
    </Query>
	<Query Name="UpdateUserCitrix2">
	  UPDATE [main-user] SET [id_citrix]=@id WHERE upn_internal = @upn_internal AND [id_citrix] is null
    </Query>
    <Query Name="UpdateMainUserAgent">
      UPDATE [main-user] SET [id_agent]=@id_agent WHERE [sid_bin]=@sid_bin AND ([id_agent] is null OR [id_agent] != @id_agent)
      UPDATE [main-user] SET [last_seen_by_agent]=@lastAgent WHERE [sid_bin]=@sid_bin AND ([last_seen_by_agent] is null OR [last_seen_by_agent]&lt;@lastAgent)
    </Query>
    <Query Name="UpdateMainUserAgentAzure">
      UPDATE [main-user] SET [id_agent_azure]=@id_agent WHERE [id_azure]=@id_azure AND ([id_agent_azure] is null OR [id_agent_azure] != @id_agent)
      UPDATE [main-user] SET [last_seen_by_agent]=@lastAgent WHERE [id_azure]=@id_azure AND ([last_seen_by_agent] is null OR [last_seen_by_agent]&lt;@lastAgent)
    </Query>
    <Query Name="UpdateMainUserAzureAd">
      UPDATE [main-user] SET [id_azure]=@id_azure, [tenant_azure] = @tenant WHERE [sid_bin]=@sid_bin
    </Query>
    <Query Name="GetMainUserByAccount">
      SELECT [id] FROM [main-user] WHERE [account] = @Account and [domainDns] = @Domain
    </Query>
    <Query Name="InsertLocalUser">
      UPDATE [main-user-local] SET [id]=@id, [id_agent]=@id_agent, [account]=@account, [last_seen_by_agent]=@lastseen WHERE [sid_bin]=@sid_bin
      IF @@ROWCOUNT = 0 INSERT INTO [main-user-local] ([id], [id_agent], [account], [sid], [sid_bin], [last_seen_by_agent]) VALUES (@id, @id_agent, @account, @sid, @sid_bin, @lastseen)
      SELECT @@ROWCOUNT
    </Query>
    <Query Name="UpdateMainUserLastSeen">
      UPDATE [main-user] SET [last_seen_by_agent]=@lastAgent WHERE [id]=@id AND ([last_seen_by_agent] is null OR [last_seen_by_agent]&lt;@lastAgent)
    </Query>
    <Query Name="GetLocalUserFromId">
      SELECT [id_agent], [last_seen_by_agent], [account] FROM [main-user-local] WHERE [id] = @ID
    </Query>
    <Query Name="GetUserListTest">
      SELECT TOP (3000) [full_name] + ' (' + [upn_internal] + ')', [id] FROM [main-user] WHERE [is_active] = 1 ORDER BY [full_name]
    </Query>
    <Query Name="GetUserListTestFiltered">
      SELECT TOP (3000) [full_name] + ' (' + [upn_internal] + ')', [id]  FROM [main-user] WHERE [is_active] = 1 AND [last_seen_by_agent] > DATEADD(DAY, -14,GETUTCDATE()) ORDER BY [full_name]
    </Query>
    <Query Name="GetComputerListTest">
      SELECT TOP (3000) [name], [id] FROM [main-computer] ORDER BY [name]
    </Query>
    <Query Name="GetComputerListTestFiltered">
      SELECT TOP (3000) [name], [id] FROM [main-computer] WHERE [last_seen_by_agent] > DATEADD(DAY, -14,GETUTCDATE()) ORDER BY [name]
    </Query>
    <Query Name="GetUserIdFromAccount">
      SELECT [id] FROM [main-user] WHERE [account] like @account AND ([domainNB] like @domain OR [domainDns] like @domain)
    </Query>
    <Query Name="GetConnectorIdsFromComputerId">
		SELECT [sid_bin], [id_agent], [Name], [last_seen_by_agent], NULL , [tenant_azure],[id_intune], [deviceId_azure],null,null FROM [main-computer] WHERE id = @id
	</Query>
    <Query Name="GetConnectorIdsFromUserId">
		SELECT [sid_bin], [id_agent], [account], [last_seen_by_agent], [id_agent_azure], [tenant_azure], [id_azure],null,[id_citrix],[tenant_citrix] FROM [main-user] WHERE id = @id
	</Query>
    <Query Name="GetUserInfoFromAgentId">
      SELECT [id], [full_name], [is_active], [account], COALESCE([domainDns], [domainNB] ), CASE WHEN [id_agent] &lt;&gt; @id THEN 1 ELSE 0 END   FROM [main-user] WHERE [id_agent] = @id OR [id_agent_azure] = @id
    </Query>
    <Query Name="GetComputerInfoFromAgentId">
      SELECT [id], [name], [is_active], [name], COALESCE([domainDns],[domainNB]), 0 FROM [main-computer] WHERE [id_agent] = @id
    </Query>
    <Query Name="GetLocalUserInfoFromAgentId">
      SELECT mu.[id], mu.[full_name], mu.[is_active], ul.[account] FROM [main-user-local] ul
      JOIN [main-user] mu ON mu.[id] = ul.[id]
      WHERE ul.[id_agent] = @id
    </Query>
    <Query Name="GetUserUsageCountFromAgent">
      SELECT [DEVICECODE],SUM(CONVERT(BIGINT,[DURATION])),MAX([EVENTDATE]) FROM [C4IT_EVENT] (nolock) WHERE [DEVICEACCOUNTCODE] = @ID AND [MEASURECODE] = 41 AND [EVENTDATE] &gt;= CAST(DATEADD(DAY,-@Age, GETUTCDATE()) AS DATETIME2) GROUP BY [DEVICECODE]
    </Query>
    <Query Name="GetComputerUsageCountFromAgent">
      SELECT [DEVICEACCOUNTCODE],SUM(CONVERT(BIGINT,[DURATION])),MAX([EVENTDATE]) FROM [C4IT_EVENT] (nolock) WHERE [DEVICECODE] = @ID AND [MEASURECODE] = 41 AND [EVENTDATE] &gt;= CAST(DATEADD(DAY,-@Age, GETUTCDATE()) AS DATETIME2) GROUP BY [DEVICEACCOUNTCODE]
    </Query>
    <Query Name="GetUserUsageCountFromAgentDaily">
      SELECT [devicecode], SUM(CONVERT(BIGINT,[DURATION])),MAX([EVENTDATE]) FROM [{0}] WHERE [deviceaccountcode] = @ID GROUP BY [devicecode]
    </Query>
    <Query Name="GetComputerUsageCountFromAgentDaily">
      SELECT [deviceaccountcode], SUM(CONVERT(BIGINT,[DURATION])),MAX([EVENTDATE]) FROM [{0}] WHERE [devicecode] = @ID GROUP BY [deviceaccountcode]
    </Query>
    <Query Name="GetComputerAttributesFromAgent">
      SELECT t.[NAME], d.[VALUEJSON], d.[DEVICECODE] FROM [device_attribute] (nolock) d
      JOIN [device_attribute_type] (nolock) t ON t.[TYPECODE] = d.[TYPECODE]
      WHERE [DEVICECODE] = @ID
      UNION ALL
      SELECT 'Name', [name], [DEVICECODE]  FROM [device] (nolock) WHERE [DEVICECODE] = @ID
      UNION ALL
      SELECT 'DomainDns', [domain], [DEVICECODE]  FROM [device] (nolock) WHERE [DEVICECODE] = @ID
    </Query>
    <Query Name="GetMeasureCodesFromAgent">
      SELECT m.[measurecode], m.[NAME], m.[TYPECODE], o.[statuscode] FROM [C4IT_MEASURE] (nolock) m LEFT JOIN [c4it_measure_organization] (nolock) o ON o.[measurecode] = m.[measurecode] WHERE o.[orgcode] IS NULL OR o.[orgcode] = @ORGCODE
    </Query>
    <Query Name="GetTypeJsonSettingsFromAgent">
      SELECT m.[NAME], t.[SETTINGJSON] FROM [C4IT_MEASURE] (nolock) m
      JOIN [C4IT_MEASURE_TYPE] (nolock) t ON t.[TYPECODE] = m.[TYPECODE]
      WHERE t.[SETTINGJSON] IS NOT NULL
    </Query>
    <Query Name="GetComputerHistoricEventsTotalNumericFromAgent">
      SELECT [MEASURECODE], [EVENTDATE], [VALUE], [DURATION] FROM [C4IT_EVENT] (nolock) WHERE [DEVICECODE] = @ID AND [MEASURECODE] in ({0}) AND [EVENTDATE] &gt;= CAST(DATEADD(DAY,-@Age, GETUTCDATE()) AS DATETIME2)
    </Query>
    <Query Name="GetComputerHistoricEventsTotalStringFromAgent">
      SELECT [MEASURECODE], [EVENTDATE], [VALUE], [DURATION] FROM [C4IT_EVENT_DATA] (nolock) WHERE [DEVICECODE] = @ID AND [MEASURECODE] in ({0}) AND [EVENTDATE] &gt;= CAST(DATEADD(DAY,-@Age, GETUTCDATE()) AS DATETIME2)
    </Query>
    <Query Name="GetComputerHistoricEventsDailyFromAgent">
      SELECT [MEASURECODE], [EVENTDATE], [VALUE], [DURATION] FROM [{0}] (nolock) WHERE [DEVICECODE] = @ID AND [MEASURECODE] in ({1})
    </Query>
    <Query Name="GetComputerHistoricEventsDailyUsageFromAgent">
      SELECT [MEASURECODE], [EVENTDATE], [VALUE], [DURATION] FROM [{0}] (nolock) WHERE [DEVICECODE] = @ID
    </Query>
    <Query Name="GetOrganizationCodeFromAgent">
      SELECT [ORGCODE] FROM [organization] (nolock) WHERE [NAME] = @ORGA
    </Query>
    <Query Name="GetDetailEventValuesFromAgent">
      SELECT [EVENTDATE], [VALUE], [DURATION] FROM [c4it_event_data] (nolock) WHERE [DEVICECODE]=@ID AND [MEASURECODE] = @MC  AND [EVENTDATE] &gt;= @MINDATE
    </Query>
    <Query Name="GetDetailEventValuesNumericFromAgent">
      SELECT [EVENTDATE], [VALUE], [DURATION] FROM [c4it_event] (nolock) WHERE [DEVICECODE]=@ID AND [MEASURECODE] = @MC  AND [EVENTDATE] &gt;= @MINDATE
    </Query>
    <Query Name="GetDetailEventValuesDailyFromAgent">
      SELECT [EVENTDATE], [VALUE], [DURATION] FROM [{0}] (nolock) WHERE [DEVICECODE]=@ID AND [MEASURECODE] = @MC AND [EVENTDATE] &gt;= @MINDATE
    </Query>
    <Query Name="GetDetailEventValuesDailyUsageFromAgent">
      SELECT [EVENTDATE], [VALUE], [DURATION] FROM [{0}] (nolock) WHERE [DEVICECODE]=@ID AND [EVENTDATE] &gt;= @MINDATE
    </Query>
    <Query Name="CreateScanHistoryEntry">
      INSERT INTO [main-scan-history] ([ScanId], [Scan], [TimeFrameFrom], [TimeFrameTo], [ExecutionTime], [State]) VALUES (@ID, @Name, @From, @To, @Execute, 0 )
      SELECT @@ROWCOUNT
    </Query>
    <Query Name="ConfirmScanHistoryEntry">
      UPDATE [main-scan-history] SET [State]=1 WHERE [ScanId]=@ID
      SELECT [Scan] FROM [main-scan-history] WHERE [ScanId]=@ID
    </Query>
    <Query Name="RemoveLastScanHistoryEntry">
      DELETE FROM [main-scan-history] WHERE [ScanId] = (SELECT TOP 1 [ScanId] FROM [main-scan-history] WHERE [Scan] = @Name AND [State] = 1 ORDER BY [ExecutionTime] DESC);
      SELECT TOP 1 [ExecutionTime] FROM [main-scan-history] WHERE [Scan] = @Name AND [State] = 1 ORDER BY [ExecutionTime] DESC
    </Query>
    <Query Name="LoadColumnsValidationResult">
      SELECT [Instance],[SubTable],[Column],[isValid] FROM [main-column-validation] WHERE [Connector]=@Connector
    </Query>
    <Query Name="FindNxtIdsComputer">
      SELECT TOP 1 [engine], [id_int] FROM [nxt-device] WHERE [name] = @NAME ORDER BY [last_seen] DESC
    </Query>
    <Query Name="FindNxtIdsUser">
      SELECT TOP 1 [engine], [id_int] FROM [nxt-user] WHERE [id_sid_bin] = @SID ORDER BY [last_seen] DESC
    </Query>
    <!--
    <Query Name="GetHistoricTableContent">
      SELECT TOP 1 [engine], [id_int] FROM [nxt-user] WHERE [id_sid_bin] = @SID ORDER BY [last_seen] DESC
    </Query>
    -->
    <Query Name="GetScanHistoryCleanup">
      SELECT [ScanId], [Scan], [TimeFrameFrom], [TimeFrameTo] FROM [main-scan-history] WHERE ([TimeFrameTo] &lt; DATEADD(day, -@Age1, GETUTCDATE()) OR ([TimeFrameTo] &lt; DATEADD(MINUTE, -@Age2, GETUTCDATE()) AND [State] = 0)) AND ScanId != &apos;00000000-0000-0000-0000-000000000000&apos;
    </Query>
    <Query Name="DeleteScanHistoryEntry">
      DELETE FROM [main-scan-history] WHERE [ScanId] = @ID;
    </Query>
    <!--
    <Query Name="Validate_Create_Database">
      DECLARE @HasPermission BIT = (SELECT HAS_PERMS_BY_NAME(@DbName, 'DATABASE', 'ANY'));
      SELECT @HasPermission;
    </Query>
    -->
    <Query Name="Validate_F4SDAnalyticsMainTables">
      SELECT 1 WHERE
      (OBJECT_ID(N&apos;UserSessions&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;Cases&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;CaseTime&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;QActionExecutions&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;Tickets&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;QActions&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;QActionDescriptions&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;Status&apos;, N&apos;U&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;StatusDescriptions&apos;, N&apos;U&apos;) IS NOT NULL)
    </Query>
    <Query Name="Validate_F4SDAnalyticsFunctions">
      SELECT 1 WHERE
      (OBJECT_ID(N&apos;fn_GetLocalTimeStamp&apos;, N&apos;FN&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;fn_GetDayFromTimestamp&apos;, N&apos;FN&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;fn_GetHourIntervalFromTimestamp&apos;, N&apos;FN&apos;) IS NOT NULL)
    </Query>
    <Query Name="Create_F4SDAnalyticsFunctions">
      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[fn_GetLocalTimeStamp]&apos;) AND type in (N&apos;FN&apos;))
      BEGIN
      PRINT N&apos;start creating functions [fn_GetLocalTimeStamp]...&apos;;

      EXEC(N&apos;CREATE FUNCTION [fn_GetLocalTimeStamp]
      (
      @UTCTimeStamp DATETIME
      )
      RETURNS DATETIME
      AS
      BEGIN
      DECLARE @ResultVar DATETIME
      -- Offset für Mitteleuropäische Zeit (CET)
      SET @ResultVar = SWITCHOFFSET(@UTCTimeStamp, N&apos;&apos;+01:00&apos;&apos;);
      -- Überprüfen, ob die umgewandelte Zeit innerhalb der Sommerzeit (CEST) liegt
      IF @UTCTimeStamp >= CAST(N&apos;&apos;2023-03-26&apos;&apos; AS DATETIMEOFFSET)
      AND @UTCTimeStamp &lt; CAST(N&apos;&apos;2023-10-29&apos;&apos; AS DATETIMEOFFSET)
      BEGIN
      SET @ResultVar = SWITCHOFFSET(@UTCTimeStamp, N&apos;&apos;+02:00&apos;&apos;);
      END;
      RETURN @ResultVar
      END &apos;)

      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[fn_GetDayFromTimestamp]&apos;) AND type in (N&apos;FN&apos;))
      BEGIN
      PRINT N&apos;start creating functions [fn_GetDayFromTimestamp]...&apos;;

      EXEC(N&apos;CREATE FUNCTION [fn_GetDayFromTimestamp]
      (
      @TimeStamp DATETIME,
      @Language NVARCHAR(5) = N&apos;&apos;DE&apos;&apos;
      )
      RETURNS NVARCHAR(25)
      AS
      BEGIN
      DECLARE @ResultVar NVARCHAR(25)
      SELECT  @ResultVar =
      CASE
      WHEN DATENAME(dw,(SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp))) IN (N&apos;&apos;Montag&apos;&apos;, N&apos;&apos;Monday&apos;&apos;)  THEN  IIF(@Language = N&apos;&apos;DE&apos;&apos;, N&apos;&apos;1-Montag&apos;&apos;, N&apos;&apos;1-Monday&apos;&apos;)
      WHEN DATENAME(dw,(SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp))) IN (N&apos;&apos;Dienstag&apos;&apos;, N&apos;&apos;Tuesday&apos;&apos;) THEN IIF(@Language = N&apos;&apos;DE&apos;&apos;, N&apos;&apos;2-Dienstag&apos;&apos;, N&apos;&apos;2-Tuesday&apos;&apos;)
      WHEN DATENAME(dw,(SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp))) IN (N&apos;&apos;Mittwoch&apos;&apos;, N&apos;&apos;Wednesday&apos;&apos;) THEN IIF(@Language = N&apos;&apos;DE&apos;&apos;, N&apos;&apos;3-Mittwoch&apos;&apos;, N&apos;&apos;3-Wednesday&apos;&apos;)
      WHEN DATENAME(dw,(SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp))) IN (N&apos;&apos;Donnerstag&apos;&apos;, N&apos;&apos;Thursday&apos;&apos;) THEN IIF(@Language = N&apos;&apos;DE&apos;&apos;, N&apos;&apos;4-Donnerstag&apos;&apos;, N&apos;&apos;4-Thursday&apos;&apos;)
      WHEN DATENAME(dw,(SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp))) IN (N&apos;&apos;Freitag&apos;&apos;, N&apos;&apos;Friday&apos;&apos;) THEN IIF(@Language = N&apos;&apos;DE&apos;&apos;, N&apos;&apos;5-Freitag&apos;&apos;, N&apos;&apos;5-Friday&apos;&apos;)
      WHEN DATENAME(dw,(SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp))) IN (N&apos;&apos;Samstag&apos;&apos;, N&apos;&apos;Saturday&apos;&apos;) THEN IIF(@Language = N&apos;&apos;DE&apos;&apos;, N&apos;&apos;6-Samstag&apos;&apos;, N&apos;&apos;6-Saturday&apos;&apos;)
      WHEN DATENAME(dw,(SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp))) IN (N&apos;&apos;Sonntag&apos;&apos;, N&apos;&apos;Sunday&apos;&apos;) THEN IIF(@Language = N&apos;&apos;DE&apos;&apos;, N&apos;&apos;7-Sonntag&apos;&apos;, N&apos;&apos;7-Sunday&apos;&apos;)
      END
      RETURN @ResultVar
      END &apos;)

      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[fn_GetHourIntervalFromTimestamp]&apos;) AND type in (N&apos;FN&apos;))
      BEGIN
      PRINT N&apos;start creating functions [fn_GetHourIntervalFromTimestamp]...&apos;;

      EXEC(N&apos;CREATE FUNCTION [fn_GetHourIntervalFromTimestamp]
      (
      @TimeStamp DATETIME
      )
      RETURNS NVARCHAR(25)
      AS
      BEGIN

      DECLARE @ResultVar NVARCHAR(25)

      SELECT  @ResultVar =
      CASE  WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 0 AND  DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 2 THEN  N&apos;&apos;00:00-02:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 2 AND  DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 4 THEN  N&apos;&apos;02:00-04:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 4 AND  DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 6 THEN  N&apos;&apos;04:00-06:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 6 AND  DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 8 THEN  N&apos;&apos;06:00-08:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 8 AND  DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 10 THEN N&apos;&apos;08:00-10:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 10 AND DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 12 THEN N&apos;&apos;10:00-12:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 12 AND DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 14 THEN N&apos;&apos;12:00-14:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 14 AND DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 16 THEN N&apos;&apos;14:00-16:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 16 AND DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 18 THEN N&apos;&apos;16:00-18:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 18 AND DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 20 THEN N&apos;&apos;18:00-20:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 20 AND DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 22 THEN N&apos;&apos;20:00-22:00&apos;&apos;
      WHEN DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) >= 22 AND DATEPART(HOUR, (SELECT dbo.fn_GetLocalTimeStamp( @TimeStamp ))) &lt; 24 THEN N&apos;&apos;22:00-00:00&apos;&apos;
      END
      RETURN @ResultVar
      END &apos;)
      END

      IF NOT EXISTS (SELECT * FROM [sysusers] WHERE [issqlrole] = 1 AND [name] = 'db_executor')
      BEGIN
        CREATE ROLE db_executor;
      END

      GRANT Execute ON fn_GetDayFromTimestamp TO db_executor;
      GRANT Execute ON fn_GetHourIntervalFromTimestamp TO db_executor;
      GRANT Execute ON fn_GetLocalTimeStamp TO db_executor;

    </Query>
    <Query Name="Validate_F4SDAnalyticsViews">
      SELECT 1 WHERE
      (OBJECT_ID(N&apos;vw_UserStatistics&apos;, N&apos;V&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;vw_DailyHourlyStatistic&apos;, N&apos;V&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;vw_QAExecutionsCountByUser&apos;, N&apos;V&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;vw_DailyStatistic&apos;, N&apos;V&apos;) IS NOT NULL) AND
      (OBJECT_ID(N&apos;vw_WeekdayCountsByMonth&apos;, N&apos;V&apos;) IS NOT NULL)
    </Query>
    <Query Name="Create_F4SDAnalyticsViews">
      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[vw_UserStatistics]&apos;) AND type in (N&apos;V&apos;))
      BEGIN
      PRINT N&apos;start creating view [vw_UserStatistics]...&apos;;
      EXEC(N&apos;--@Revision:2
      CREATE VIEW [dbo].[vw_UserStatistics] AS
      WITH UserSessions AS
      (
      SELECT
      UserId ,
      COUNT(SessionID) SessionCount,
      SUM(DATEDIFF(minute, UserSessions.Start, UserSessions.Finish))  [ActiveTime],
      SUM(DATEDIFF(minute, UserSessions.Start, UserSessions.Finish)) / COUNT(UserSessions.SessionId) [Ø-Time],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date],
      CAST(CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)) AS INT) AS [DateSort]
      FROM
      dbo.UserSessions
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY UserId,
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))),
      CAST(CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)) AS INT)
      ),
      UserCases AS
      (
      SELECT
      UserSessions.UserId UserId,
      COUNT(CaseId) CaseCount,
      SUM(Cases.ActiveTime) ActiveTime,
      SUM(Cases.ActiveTime) / COUNT(CaseId) [Ø-Time],
      CAST(year(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(Cases.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(5))) AS [Date]
      FROM
      dbo.UserSessions
      JOIN
      dbo.Cases
      ON
      UserSessions.SessionId = Cases.SessionId
      WHERE dbo.fn_GetLocalTimeStamp(Cases.start) >= DATEADD(MONTH, -12, GETDATE()) AND Cases.[Finish] IS NOT NULL
      GROUP BY UserSessions.UserId,
      CAST(year(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(Cases.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(5)))

      ),
      UserQActions AS
      (
      SELECT
      UserSessions.UserId UserId,
      COUNT(ExecutionId) ExecutionCount,
      CONVERT(DECIMAL ( 10,1 ),SUM(DATEDIFF(SECOND, QActionExecutions.Start, QActionExecutions.Finish))) / CONVERT(DECIMAL ( 10,1 ),COUNT(QActionId)) [Ø-Time],
      SUM(DATEDIFF(SECOND, QActionExecutions.Start, QActionExecutions.Finish))  ActiveTime,
      CAST(year(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5))) AS [Date]
      FROM
      dbo.UserSessions
      JOIN
      dbo.Cases
      ON
      UserSessions.SessionId = Cases.SessionId
      JOIN
      dbo.QActionExecutions
      ON
      QActionExecutions.CaseId = Cases.CaseId
      WHERE dbo.fn_GetLocalTimeStamp(QActionExecutions.start) >= DATEADD(MONTH, -12, GETDATE()) AND QActionExecutions.[Finish] IS NOT NULL
      GROUP BY  UserSessions.UserId,
      CAST(year(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)))

      )
      SELECT
      US.UserId UserId,
      CASE WHEN muser.full_name IS NULL THEN N&apos;&apos;User_&apos;&apos;+LEFT(US.UserId,3) ELSE muser.full_name END FullName,
      US.Date,
      US.DateSort,
      US.SessionCount,
      US.ActiveTime SessionActiveTime,
      US.[Ø-Time] [Ø-SessionTime],
      ISNULL(Uc.CaseCount,0) CaseCount,
      ISNULL(UC.ActiveTime,0) CaseActiveTime,
      ISNULL(UC.[Ø-Time],0) [Ø-CaseTime] ,
      ISNULL(UQA.ExecutionCount,0) QACount,
      ISNULL(UQA.ActiveTime,0) QAActiveTime,
      ISNULL(UQA.[Ø-Time],0) [Ø-QATime],
      IIF(Uc.CaseCount IS NOT NULL,  CONVERT(DECIMAL ( 10,1 ),Uc.CaseCount) /CONVERT(DECIMAL ( 10,1 ),US.SessionCount),0) [Ø-Cases In Session]
      FROM
      UserSessions AS US
      LEFT JOIN
      UserCases UC
      ON
      US.UserId = UC.UserId AND
      US.Date = UC.Date
      LEFT JOIN
      UserQActions UQA
      ON
      US.UserId = UQA.UserId AND
      US.Date = UQA.Date
      LEFT JOIN
      [$DatabaseHistory$].[dbo].[main-user] muser
      ON
      muser.id = US.UserId  &apos;)

      END


      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[vw_DailyHourlyStatistic]&apos;) AND type in (N&apos;V&apos;))
      BEGIN
      PRINT N&apos;start creating view [vw_DailyHourlyStatistic]...&apos;;
      EXEC(N&apos;--@Revision:2
      CREATE VIEW [dbo].[vw_DailyHourlyStatistic]
      AS
      WITH TSessions AS
      (
      SELECT
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      dbo.fn_GetHourIntervalFromTimestamp(start) AS [HourInterval],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date]

      FROM UserSessions
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;),
      dbo.fn_GetHourIntervalFromTimestamp(start),
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))

      ),
      TCases AS
      (
      SELECT
      COUNT(CaseId) [Count],
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      dbo.fn_GetHourIntervalFromTimestamp(start) AS [HourInterval],
      SUM(ActiveTime) CaseTime,
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date]
      FROM dbo.Cases
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;),
      dbo.fn_GetHourIntervalFromTimestamp(start),
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))
      ),
      TQActions AS
      (
      SELECT
      COUNT(QActionExecutions.ExecutionId) [Count],
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      dbo.fn_GetHourIntervalFromTimestamp(start) AS [HourInterval],
      SUM(DATEDIFF(second,start,Finish)) AS QATime,
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date]
      FROM QActionExecutions
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) ,
      dbo.fn_GetHourIntervalFromTimestamp(start),
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))
      )
      SELECT
      S.[Day],
      S.HourInterval,
      ISNULL(C.[Count],0) CaseCount,
      ISNULL(Q.[Count],0) QactionCount,
      C.CaseTime,
      Q.QATime,
      CASE WHEN ISNULL(Q.[Count],0) = 0 OR ISNULL(C.[Count],0) = 0 THEN 0 ELSE CONVERT(DECIMAL(10,2),ISNULL(Q.[Count],0))/CONVERT(DECIMAL(10,2),ISNULL(C.[Count],0)) END QactionCountinCases,
      S.Date
      FROM
      TSessions AS S
      LEFT JOIN
      TCases AS C
      ON
      S.[Day]  =  C.[Day] AND
      S.HourInterval = C.HourInterval AND
      S.Date = C.Date
      LEFT JOIN
      TQActions Q
      ON
      S.[Day]  =  Q.[Day] AND
      S.HourInterval = Q.HourInterval	AND
      S.Date = Q.Date &apos;)
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[vw_DailyStatistic]&apos;) AND type in (N&apos;V&apos;))
      BEGIN
      PRINT N&apos;start creating view [vw_DailyStatistic]...&apos;;
      EXEC(N&apos;--@Revision:2
      CREATE VIEW [dbo].[vw_DailyStatistic]
      AS
      WITH TSessions AS
      (
      SELECT
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)) AS [SessionDate],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date]
      FROM UserSessions with(nolock)
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE())
      ),
      TCases AS
      (
      SELECT
      COUNT(CaseId) [Count],
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date],
      SUM(Cases.ActiveTime) CaseTime
      FROM dbo.Cases with(nolock)
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;),
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))
      ),
      TQActions AS
      (
      SELECT
      COUNT(QActionExecutions.ExecutionId) [Count],
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date],
      SUM(DATEDIFF(SECOND,start,Finish)) QactionTime
      FROM QActionExecutions with(nolock)
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) ,
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))
      ),
      TMinMax as
      (
      SELECT MIN(dbo.fn_GetLocalTimeStamp(start)) minDate, max(dbo.fn_GetLocalTimeStamp(start)) maxDate
      FROM [dbo].[UserSessions] with(nolock)
      ),DateList AS (
      SELECT
      DATEADD(DAY, number, (SELECT minDate from TMinMax)) AS CurrentDate
      FROM
      master.dbo.spt_values
      WHERE
      type = &apos;&apos;P&apos;&apos;
      AND number BETWEEN 0 AND DATEDIFF(DAY, (SELECT minDate from TMinMax), (SELECT maxDate from TMinMax))

      ), Result AS
      (
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 2 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;1-Monday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 3 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;2-Tuesday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 4 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;3-Wednesday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 5 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;4-Thursday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 6 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;5-Friday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 7 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;6-Saturday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 1 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;7-Sunday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      )
      SELECT DISTINCT
      S.[Day],
      CASE WHEN ISNULL(C.[Count],0) = 0 OR ISNULL(cw.daycount,0) = 0 THEN 0 ELSE CONVERT(DECIMAL(10,2),C.[Count])/CONVERT(DECIMAL(10,2),cw.daycount) END AS [Ø-CaseCount],
      CASE WHEN ISNULL(Q.[Count],0) = 0 OR ISNULL(cw.daycount,0) = 0 THEN 0 ELSE CONVERT(DECIMAL(10,2),Q.[Count])/CONVERT(DECIMAL(10,2),cw.daycount) END AS [Ø-QactionCount],
      ISNULL(C.[Count],0) CaseCount,
      ISNULL(Q.[Count],0) QactionCount,
      CASE WHEN ISNULL(Q.[Count],0) = 0 OR ISNULL(C.[Count],0) = 0 THEN 0 ELSE CONVERT(DECIMAL(10,2),ISNULL(Q.[Count],0))/CONVERT(DECIMAL(10,2),ISNULL(C.[Count],0)) END QactionCountinCases,
      CASE WHEN ISNULL(C.[Count],0) = 0 OR ISNULL(cw.daycount,0) = 0 THEN 0 ELSE C.CaseTime/CONVERT(DECIMAL(10,2),cw.daycount) END AS [Ø-CaseTime],
      CASE WHEN ISNULL(C.[Count],0) = 0 OR ISNULL(cw.daycount,0) = 0 THEN 0 ELSE Q.QactionTime/CONVERT(DECIMAL(10,2),cw.daycount) END AS [Ø-QactionTime],
      S.Date
      FROM
      TSessions AS S
      JOIN
      Result cw
      ON
      cw.Date = S.SessionDate and
      cw.Tagname = S.[Day]
      LEFT JOIN
      TCases AS C
      ON
      S.[Day]  =  C.[Day] AND
      S.Date = C.Date
      LEFT JOIN
      TQActions Q
      ON
      S.[Day]  =  Q.[Day] AND
      S.Date = Q.Date  &apos;)

      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[vw_QAExecutionsCountByUser]&apos;) AND type in (N&apos;V&apos;))
      BEGIN
      PRINT N&apos;start creating view [vw_QAExecutionsCountByUser]...&apos;;
      EXEC(N&apos;--@Revision:2
      CREATE VIEW [dbo].[vw_QAExecutionsCountByUser]
      AS
      SELECT
      COUNT(QActionId) ExecutionCount,
      QActions.Id  QActionId,
      ISNULL(QActions.[Name], N&apos;&apos;N/A&apos;&apos;) [Name],
      CAST(year(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5))) AS [Date],
      UserSessions.UserId ,
      CASE WHEN muser.full_name IS NULL THEN N&apos;&apos;User_&apos;&apos;+LEFT(UserSessions.UserId,3) ELSE muser.full_name END FullName
      FROM
      dbo.QActionExecutions
      LEFT JOIN
      dbo.QActions
      ON
      QActions.Id = QActionExecutions.QActionId
      JOIN
      dbo.Cases
      ON
      Cases.CaseId = QActionExecutions.CaseId
      JOIN
      dbo.UserSessions
      ON
      UserSessions.SessionId = Cases.SessionId
      LEFT JOIN
      [$DatabaseHistory$].[dbo].[main-user] muser
      ON
      muser.id = UserSessions.UserId
      WHERE
      dbo.fn_GetLocalTimeStamp(QActionExecutions.start) >= DATEADD(MONTH, -12, GETDATE()) AND
      QActionExecutions.[Finish] IS NOT NULL
      GROUP BY
      QActions.Id,
      QActions.[Name] ,
      CAST(year(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5))),
      UserSessions.UserId, CASE WHEN muser.full_name IS NULL THEN N&apos;&apos;User_&apos;&apos;+LEFT(UserSessions.UserId,3) ELSE muser.full_name END &apos;)

      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[vw_WeekdayCountsByMonth]&apos;) AND type in (N&apos;V&apos;))
      BEGIN
      PRINT N&apos;start creating view [vw_WeekdayCountsByMonth]...&apos;;
      EXEC(N&apos;--@Revision:2
      CREATE VIEW [dbo].[vw_WeekdayCountsByMonth]
      AS
      SELECT
      COUNT(*) AS DayCount,
      CAST(year(MinDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(MinDate)&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(MinDate) AS NVARCHAR(5)),CAST(month(MinDate) AS NVARCHAR(5))) AS [Date],
      CAST(CAST(year(MinDate) AS NVARCHAR(10))+CAST(month(MinDate) AS NVARCHAR(5)) AS INT) AS [DateSort]
      FROM (
      SELECT
      DATEADD(DAY, number, (SELECT MIN(dbo.fn_GetLocalTimeStamp(start)) FROM [dbo].[UserSessions] WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL)) AS MinDate
      FROM master.dbo.spt_values
      WHERE type = N&apos;&apos;P&apos;&apos; AND number BETWEEN 1 AND DATEDIFF(DAY, (SELECT MIN(dbo.fn_GetLocalTimeStamp(start)) minDate FROM [dbo].[UserSessions] WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL),
      (SELECT max(dbo.fn_GetLocalTimeStamp(start)) maxDate FROM [dbo].[UserSessions]))
      ) AS date_series
      GROUP BY
      YEAR(MinDate) ,
      MONTH(MinDate) &apos;)

      END

    </Query>
    <Query Name="Create_F4SDAnalyticsMainTables">
      SET ANSI_NULLS ON
      SET QUOTED_IDENTIFIER ON

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[UserSessions]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [UserSessions]...&apos;;

      CREATE TABLE [UserSessions](
      [SessionId] [uniqueidentifier] NOT NULL,
      [UserId] [uniqueidentifier] NOT NULL,
      [Start] [datetime] NULL,
      [Finish] [datetime] NULL)

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[Cases]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [Cases]...&apos;;

      CREATE TABLE [Cases](
      [CaseId] [uniqueidentifier] NOT NULL,
      [Start] [datetime] NULL,
      [Finish] [datetime] NULL,
      [ActiveTime] [int] NULL,
      [UserId] [uniqueidentifier] NOT NULL,
      [SessionId] [uniqueidentifier] NOT NULL )

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[CaseTime]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [CaseTime]...&apos;;

      CREATE TABLE [CaseTime](
      [CaseId] [uniqueidentifier] NOT NULL,
      [StatusId] [int] NOT NULL,
      [TimeStamp] [datetime] NOT NULL,
      CONSTRAINT [PK_CaseTime] PRIMARY KEY CLUSTERED
      (
      [StatusId] ASC,
      [TimeStamp] ASC
      )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY]

      PRINT N&apos;  ...done.&apos;;
      END
	  
	  IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[Tickets]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [Tickets]...&apos;;

		CREATE TABLE [Tickets](
		[TicketId] [uniqueidentifier] NOT NULL,
		[Status] [nvarchar](16) NOT NULL,
		[Start] [datetime] NULL,
		[Finish] [datetime] NULL,
		[ActiveTime] [int] NULL,
		[UserId] [uniqueidentifier] NOT NULL,
		[CaseId] [uniqueidentifier] NOT NULL
		)

		PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[QActions]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [QActions]...&apos;;

      CREATE TABLE [QActions](
      [Id] [uniqueidentifier] default newid() NOT NULL,
      [Name] [nvarchar](200) NOT NULL,
      [Type] [nvarchar](50) NULL,
      [TimeStamp] DateTime,
      CONSTRAINT [PK_QActions] PRIMARY KEY CLUSTERED
      ( [Id] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY]

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[QActionDescriptions]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [QActionDescriptions]...&apos;;

      CREATE TABLE [QActionDescriptions](
      [QActionId] [uniqueidentifier] NOT NULL,
      [Description] [nvarchar](250) NULL,
      [LanguageCode] [nvarchar](10) NOT NULL,
      CONSTRAINT [PK_QActionDescriptions] PRIMARY KEY CLUSTERED
      (
      [QActionId] ASC,
      [LanguageCode] ASC
      )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY]

      ALTER TABLE [QActionDescriptions]  WITH CHECK ADD  CONSTRAINT [FK_QActionDescriptions_QActionId] FOREIGN KEY([QActionId])
      REFERENCES [QActions] ([Id])

      ALTER TABLE [QActionDescriptions] CHECK CONSTRAINT [FK_QActionDescriptions_QActionId]

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[QActionExecutions]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [QActionExecutions]...&apos;;

      CREATE TABLE [QActionExecutions](
      [ExecutionId] [int] IDENTITY(1,1) NOT NULL,
      [CaseId] [uniqueidentifier] NOT NULL,
      [QActionId] [uniqueidentifier] NOT NULL,
      [DeviceId] [uniqueidentifier],
      [Start] [datetime] NOT NULL,
      [Finish] [datetime] NOT NULL,
      [Parameters] [nvarchar](max) NULL,
      [Result] [nvarchar](max) NULL,
      [ErrorCode] [int] NULL,
      [ErrorDescription] [nvarchar](max) NULL,
      [ResultType] [nvarchar](100),
      [ExecutionType] [nvarchar](100),
      CONSTRAINT [PK_ExecutionId] PRIMARY KEY CLUSTERED
      (
      [ExecutionId] ASC
      )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY]

      ALTER TABLE [QActionExecutions]  WITH CHECK ADD  CONSTRAINT [FK_QActionExecutions_QActionId] FOREIGN KEY([QActionId])
      REFERENCES [QActions] ([Id])

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[Status]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [Status]...&apos;;

      CREATE TABLE [Status](
      [Id] [int] NOT NULL,
      [Name] [nvarchar](100) NOT NULL,
      CONSTRAINT [PK_Status] PRIMARY KEY CLUSTERED
      (
      [Id] ASC
      )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY]

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N&apos;[StatusDescriptions]&apos;) AND type in (N&apos;U&apos;))
      BEGIN
      PRINT N&apos;start creating table [StatusDescriptions]...&apos;;

      CREATE TABLE [StatusDescriptions](
      [StatusId] [int] NOT NULL,
      [Description] [nvarchar](50) NULL,
      [LanguageCode] [nvarchar](10) NOT NULL,
      CONSTRAINT [PK_StatusDescriptions] PRIMARY KEY CLUSTERED
      (
      [StatusId] ASC,
      [LanguageCode] ASC
      )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY]

      ALTER TABLE [StatusDescriptions]  WITH CHECK ADD  CONSTRAINT [FK_StatusDescriptions_StatusId] FOREIGN KEY([StatusId])
      REFERENCES [Status] ([Id])

      ALTER TABLE [StatusDescriptions] CHECK CONSTRAINT [FK_StatusDescriptions_StatusId]

      PRINT N&apos;  ...done.&apos;;
      END

      IF NOT EXISTS (SELECT TOP 1 * FROM [status])
      BEGIN
      PRINT N&apos;start fill tables [Status] and [StatusDescriptions]...&apos;;
      INSERT INTO [Status] ([Id],[Name])
      VALUES
      (1, 'Start'),
      (2, 'Hold'),
      (3, 'Continue'),
      (4, 'Cancel'),
      (5, 'Finish')

      INSERT INTO [StatusDescriptions]
      ([StatusId]
      ,[Description]
      ,[LanguageCode])
      VALUES
      (1, 'Starten','DE'),
      (1, 'Start', N&apos;EN&apos;),
      (2, 'Pause','DE'),
      (2, 'Hold', N&apos;EN&apos;),
      (3, 'Continue','DE'),
      (3, 'Fortsetzen', N&apos;EN&apos;),
      (4, 'Cancel','DE'),
      (4, 'Abbrechen', N&apos;EN&apos;),
      (5, 'Finish','DE'),
      (5, 'Beenden', N&apos;EN&apos;)

      PRINT N&apos;  ...done.&apos;;

      CREATE NONCLUSTERED INDEX [IX_UserSession_SessionId] ON [UserSessions]
      ([SessionId] ASC) INCLUDE([UserId]) WITH (DROP_EXISTING = OFF) ON [PRIMARY];
      
      CREATE NONCLUSTERED INDEX [IX_Cases_CaseId] ON [Cases]
      ([CaseId] ASC) INCLUDE(SessionId) WITH (DROP_EXISTING = OFF) ON [PRIMARY];
      
      
      CREATE NONCLUSTERED INDEX [IX_CaseTime_CaseId] ON [CaseTime]
      ([CaseId] ASC) INCLUDE(StatusId) WITH (DROP_EXISTING = OFF) ON [PRIMARY];
      
      CREATE NONCLUSTERED INDEX [IX_QActionExecutions_ExecutionId_CaseId] ON [QActionExecutions]
      ([ExecutionId],[CaseId] ASC) WITH (DROP_EXISTING = OFF) ON [PRIMARY];
      
      CREATE NONCLUSTERED INDEX [IX_Tickets_TicketId_CaseId] ON [dbo].[Cases]
      ([TicketId] ASC, [CaseId] ASC) WITH (DROP_EXISTING = OFF) ON [PRIMARY];
      
      END
    </Query>
    <Query Name="Update_F4SDAnalyticsMainTables">
      DECLARE @cnt INT
      SET @cnt = 0

      IF NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;QActionExecutions&apos; AND Column_Name = &apos;DeviceId&apos;)
      BEGIN
      ALTER TABLE QActionExecutions
      ADD [DeviceId] [uniqueidentifier]

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;
      END
      IF NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;QActionExecutions&apos; AND Column_Name = &apos;ResultType&apos;)
      BEGIN
      ALTER TABLE QActionExecutions
      ADD [ResultType] [nvarchar](100)

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END
      IF NOT EXISTS (SELECT * FROM Information_Schema.Columns WHERE Table_Name = &apos;QActionExecutions&apos; AND Column_Name = &apos;ExecutionType&apos;)
      BEGIN
      ALTER TABLE QActionExecutions
      ADD [ExecutionType] [nvarchar](100)

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END


      IF EXISTS (SELECT 1 FROM sys.objects WHERE name = &apos;FK_CasesTime_CaseId&apos; AND type=&apos;F&apos;)
      BEGIN
      ALTER TABLE CaseTime DROP CONSTRAINT  FK_CasesTime_CaseId

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

	  END	  
	  
      IF EXISTS (SELECT 1 FROM sys.objects WHERE name = &apos;FK_Cases_SessionId&apos; AND type=&apos;F&apos;)
      BEGIN
      ALTER TABLE Cases DROP CONSTRAINT  FK_Cases_SessionId

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF EXISTS (SELECT 1 FROM sys.objects WHERE name = &apos;FK_QActionsExecutions_CaseId&apos; AND type=&apos;F&apos;)
      BEGIN
      ALTER TABLE QActionExecutions DROP CONSTRAINT  FK_QActionsExecutions_CaseId

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF EXISTS (SELECT 1 FROM sys.objects WHERE name = &apos;PK_SessionId&apos; AND type=&apos;PK&apos;)
      BEGIN
      ALTER TABLE UserSessions DROP CONSTRAINT  PK_SessionId

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF EXISTS (SELECT 1 FROM sys.objects WHERE name = &apos;PK_CaseId&apos; AND type=&apos;PK&apos;)
      BEGIN
      ALTER TABLE Cases DROP CONSTRAINT PK_CaseId

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = &apos;IX_UserSession_SessionId&apos;)
      BEGIN

      CREATE NONCLUSTERED INDEX [IX_UserSession_SessionId] ON [UserSessions]
      ([SessionId] ASC) INCLUDE([UserId]) WITH (DROP_EXISTING = OFF) ON [PRIMARY];

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = &apos;IX_Cases_CaseId&apos;)
      BEGIN

      CREATE NONCLUSTERED INDEX [IX_Cases_CaseId] ON [Cases]
      ([CaseId] ASC) INCLUDE(SessionId) WITH (DROP_EXISTING = OFF) ON [PRIMARY];

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = &apos;IX_CaseTime_CaseId&apos;)
      BEGIN

      CREATE NONCLUSTERED INDEX [IX_CaseTime_CaseId] ON [CaseTime]
      ([CaseId] ASC) INCLUDE(StatusId) WITH (DROP_EXISTING = OFF) ON [PRIMARY];

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = &apos;IX_CaseTime_CaseId&apos;)
      BEGIN

      CREATE NONCLUSTERED INDEX [IX_QActionExecutions_ExecutionId_CaseId] ON [QActionExecutions]
      ([ExecutionId],[CaseId] ASC) WITH (DROP_EXISTING = OFF) ON [PRIMARY];

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END
      SELECT @cnt
    </Query>

    <Query Name="Update_F4SDAnalyticsViews">

      DECLARE @cnt INT
      SET @cnt = 0

      IF ( IIF((SELECT CHARINDEX(&apos;@Revision&apos;,(SELECT definition
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_UserStatistics&apos;)
      AND o.type      = &apos;V&apos;)) ) = 0  , 0 , CAST(LTRIM(RTRIM((select REPLACE(REPLACE(REPLACE(REPLACE(LEFT(REPLACE(definition,&apos;--@Revision:&apos;,&apos;&apos;),3),&apos; &apos;,&apos;&apos;),CHAR(9), &apos;&apos;), CHAR(10), &apos;&apos;), CHAR(13), &apos;&apos;)
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_UserStatistics&apos;)
      AND o.type      = &apos;V&apos;))) AS INT))  &lt; 3)
      BEGIN
      EXEC(N&apos;--@Revision:2
      ALTER VIEW [dbo].[vw_UserStatistics] AS
      WITH UserSessions AS
      (
      SELECT
      UserId ,
      COUNT(SessionID) SessionCount,
      SUM(DATEDIFF(minute, UserSessions.Start, UserSessions.Finish))  [ActiveTime],
      SUM(DATEDIFF(minute, UserSessions.Start, UserSessions.Finish)) / COUNT(UserSessions.SessionId) [Ø-Time],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date],
      CAST(CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)) AS INT) AS [DateSort]
      FROM
      dbo.UserSessions
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY UserId,
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))),
      CAST(CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)) AS INT)
      ),
      UserCases AS
      (
      SELECT
      UserSessions.UserId UserId,
      COUNT(CaseId) CaseCount,
      SUM(Cases.ActiveTime) ActiveTime,
      SUM(Cases.ActiveTime) / COUNT(CaseId) [Ø-Time],
      CAST(year(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(Cases.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(5))) AS [Date]
      FROM
      dbo.UserSessions
      JOIN
      dbo.Cases
      ON
      UserSessions.SessionId = Cases.SessionId
      WHERE dbo.fn_GetLocalTimeStamp(Cases.start) >= DATEADD(MONTH, -12, GETDATE()) AND Cases.[Finish] IS NOT NULL
      GROUP BY UserSessions.UserId,
      CAST(year(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(Cases.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(Cases.start)) AS NVARCHAR(5)))

      ),
      UserQActions AS
      (
      SELECT
      UserSessions.UserId UserId,
      COUNT(ExecutionId) ExecutionCount,
      CONVERT(DECIMAL ( 10,1 ),SUM(DATEDIFF(SECOND, QActionExecutions.Start, QActionExecutions.Finish))) / CONVERT(DECIMAL ( 10,1 ),COUNT(QActionId)) [Ø-Time],
      SUM(DATEDIFF(SECOND, QActionExecutions.Start, QActionExecutions.Finish))  ActiveTime,
      CAST(year(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5))) AS [Date]
      FROM
      dbo.UserSessions
      JOIN
      dbo.Cases
      ON
      UserSessions.SessionId = Cases.SessionId
      JOIN
      dbo.QActionExecutions
      ON
      QActionExecutions.CaseId = Cases.CaseId
      WHERE dbo.fn_GetLocalTimeStamp(QActionExecutions.start) >= DATEADD(MONTH, -12, GETDATE()) AND QActionExecutions.[Finish] IS NOT NULL
      GROUP BY  UserSessions.UserId,
      CAST(year(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)))

      )
      SELECT
      US.UserId UserId,
      CASE WHEN muser.full_name IS NULL THEN N&apos;&apos;User_&apos;&apos;+LEFT(US.UserId,3) ELSE muser.full_name END FullName,
      US.Date,
      US.DateSort,
      US.SessionCount,
      US.ActiveTime SessionActiveTime,
      US.[Ø-Time] [Ø-SessionTime],
      ISNULL(Uc.CaseCount,0) CaseCount,
      ISNULL(UC.ActiveTime,0) CaseActiveTime,
      ISNULL(UC.[Ø-Time],0) [Ø-CaseTime] ,
      ISNULL(UQA.ExecutionCount,0) QACount,
      ISNULL(UQA.ActiveTime,0) QAActiveTime,
      ISNULL(UQA.[Ø-Time],0) [Ø-QATime],
      IIF(Uc.CaseCount IS NOT NULL,  CONVERT(DECIMAL ( 10,1 ),Uc.CaseCount) /CONVERT(DECIMAL ( 10,1 ),US.SessionCount),0) [Ø-Cases In Session]
      FROM
      UserSessions AS US
      LEFT JOIN
      UserCases UC
      ON
      US.UserId = UC.UserId AND
      US.Date = UC.Date
      LEFT JOIN
      UserQActions UQA
      ON
      US.UserId = UQA.UserId AND
      US.Date = UQA.Date
      LEFT JOIN
      [$DatabaseHistory$].[dbo].[main-user] muser
      ON
      muser.id = US.UserId  &apos;)

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF ( IIF((SELECT CHARINDEX(&apos;@Revision&apos;,(SELECT definition
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_DailyHourlyStatistic&apos;)
      AND o.type      = &apos;V&apos;)) ) = 0  , 0 , CAST(LTRIM(RTRIM((select REPLACE(REPLACE(REPLACE(REPLACE(LEFT(REPLACE(definition,&apos;--@Revision:&apos;,&apos;&apos;),3),&apos; &apos;,&apos;&apos;),CHAR(9), &apos;&apos;), CHAR(10), &apos;&apos;), CHAR(13), &apos;&apos;)
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_DailyHourlyStatistic&apos;)
      AND o.type      = &apos;V&apos;))) AS INT)) &lt; 3)
      BEGIN
      EXEC(N&apos;--@Revision:2
      ALTER VIEW [dbo].[vw_DailyHourlyStatistic]
      AS
      WITH TSessions AS
      (
      SELECT
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      dbo.fn_GetHourIntervalFromTimestamp(start) AS [HourInterval],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date]

      FROM UserSessions
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;),
      dbo.fn_GetHourIntervalFromTimestamp(start),
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))

      ),
      TCases AS
      (
      SELECT
      COUNT(CaseId) [Count],
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      dbo.fn_GetHourIntervalFromTimestamp(start) AS [HourInterval],
      SUM(ActiveTime) CaseTime,
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date]
      FROM dbo.Cases
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;),
      dbo.fn_GetHourIntervalFromTimestamp(start),
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))
      ),
      TQActions AS
      (
      SELECT
      COUNT(QActionExecutions.ExecutionId) [Count],
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      dbo.fn_GetHourIntervalFromTimestamp(start) AS [HourInterval],
      SUM(DATEDIFF(second,start,Finish)) AS QATime,
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date]
      FROM QActionExecutions
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) ,
      dbo.fn_GetHourIntervalFromTimestamp(start),
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))
      )
      SELECT
      S.[Day],
      S.HourInterval,
      ISNULL(C.[Count],0) CaseCount,
      ISNULL(Q.[Count],0) QactionCount,
      C.CaseTime,
      Q.QATime,
      CASE WHEN ISNULL(Q.[Count],0) = 0 OR ISNULL(C.[Count],0) = 0 THEN 0 ELSE CONVERT(DECIMAL(10,2),ISNULL(Q.[Count],0))/CONVERT(DECIMAL(10,2),ISNULL(C.[Count],0)) END QactionCountinCases,
      S.Date
      FROM
      TSessions AS S
      LEFT JOIN
      TCases AS C
      ON
      S.[Day]  =  C.[Day] AND
      S.HourInterval = C.HourInterval AND
      S.Date = C.Date
      LEFT JOIN
      TQActions Q
      ON
      S.[Day]  =  Q.[Day] AND
      S.HourInterval = Q.HourInterval	AND
      S.Date = Q.Date &apos;)

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF ( IIF((SELECT CHARINDEX(&apos;@Revision&apos;,(SELECT definition
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_DailyStatistic&apos;)
      AND o.type      = &apos;V&apos;)) ) = 0  , 0 , CAST(LTRIM(RTRIM((select REPLACE(REPLACE(REPLACE(REPLACE(LEFT(REPLACE(definition,&apos;--@Revision:&apos;,&apos;&apos;),3),&apos; &apos;,&apos;&apos;),CHAR(9), &apos;&apos;), CHAR(10), &apos;&apos;), CHAR(13), &apos;&apos;)
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_DailyStatistic&apos;)
      AND o.type      = &apos;V&apos;))) AS INT))  &lt; 3)
      BEGIN
      EXEC(N&apos;--@Revision:2
      ALTER VIEW [dbo].[vw_DailyStatistic]
      AS
      WITH TSessions AS
      (
      SELECT
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)) AS [SessionDate],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date]
      FROM UserSessions with(nolock)
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE())
      ),
      TCases AS
      (
      SELECT
      COUNT(CaseId) [Count],
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date],
      SUM(Cases.ActiveTime) CaseTime
      FROM dbo.Cases with(nolock)
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;),
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))
      ),
      TQActions AS
      (
      SELECT
      COUNT(QActionExecutions.ExecutionId) [Count],
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) AS [Day],
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5))) AS [Date],
      SUM(DATEDIFF(SECOND,start,Finish)) QactionTime
      FROM QActionExecutions with(nolock)
      WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL
      GROUP BY
      dbo.fn_GetDayFromTimestamp(start,N&apos;&apos;EN&apos;&apos;) ,
      CAST(year(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(start)) AS NVARCHAR(5)))
      ),
      TMinMax as
      (
      SELECT MIN(dbo.fn_GetLocalTimeStamp(start)) minDate, max(dbo.fn_GetLocalTimeStamp(start)) maxDate
      FROM [dbo].[UserSessions] with(nolock)
      ),DateList AS (
      SELECT
      DATEADD(DAY, number, (SELECT minDate from TMinMax)) AS CurrentDate
      FROM
      master.dbo.spt_values
      WHERE
      type = &apos;&apos;P&apos;&apos;
      AND number BETWEEN 0 AND DATEDIFF(DAY, (SELECT minDate from TMinMax), (SELECT maxDate from TMinMax))

      ), Result AS
      (
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 2 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;1-Monday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 3 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;2-Tuesday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 4 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;3-Wednesday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 5 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;4-Thursday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 6 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;5-Friday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 7 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;6-Saturday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      UNION ALL
      SELECT
      CAST(year(CurrentDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ CAST(month(CurrentDate) AS NVARCHAR(5)) AS [Date],
      SUM(CASE WHEN DATEPART(WEEKDAY, CurrentDate) = 1 THEN 1 ELSE 0 END) AS DayCount,
      N&apos;&apos;7-Sunday&apos;&apos; AS Tagname
      FROM DateList
      WHERE CurrentDate >= DATEADD(MONTH, -12, GETDATE())
      GROUP BY DATEPART(MONTH, CurrentDate), DATEPART(YEAR, CurrentDate)
      )
      SELECT DISTINCT
      S.[Day],
      CASE WHEN ISNULL(C.[Count],0) = 0 OR ISNULL(cw.daycount,0) = 0 THEN 0 ELSE CONVERT(DECIMAL(10,2),C.[Count])/CONVERT(DECIMAL(10,2),cw.daycount) END AS [Ø-CaseCount],
      CASE WHEN ISNULL(Q.[Count],0) = 0 OR ISNULL(cw.daycount,0) = 0 THEN 0 ELSE CONVERT(DECIMAL(10,2),Q.[Count])/CONVERT(DECIMAL(10,2),cw.daycount) END AS [Ø-QactionCount],
      ISNULL(C.[Count],0) CaseCount,
      ISNULL(Q.[Count],0) QactionCount,
      CASE WHEN ISNULL(Q.[Count],0) = 0 OR ISNULL(C.[Count],0) = 0 THEN 0 ELSE CONVERT(DECIMAL(10,2),ISNULL(Q.[Count],0))/CONVERT(DECIMAL(10,2),ISNULL(C.[Count],0)) END QactionCountinCases,
      CASE WHEN ISNULL(C.[Count],0) = 0 OR ISNULL(cw.daycount,0) = 0 THEN 0 ELSE C.CaseTime/CONVERT(DECIMAL(10,2),cw.daycount) END AS [Ø-CaseTime],
      CASE WHEN ISNULL(C.[Count],0) = 0 OR ISNULL(cw.daycount,0) = 0 THEN 0 ELSE Q.QactionTime/CONVERT(DECIMAL(10,2),cw.daycount) END AS [Ø-QactionTime],
      S.Date
      FROM
      TSessions AS S
      JOIN
      Result cw
      ON
      cw.Date = S.SessionDate and
      cw.Tagname = S.[Day]
      LEFT JOIN
      TCases AS C
      ON
      S.[Day]  =  C.[Day] AND
      S.Date = C.Date
      LEFT JOIN
      TQActions Q
      ON
      S.[Day]  =  Q.[Day] AND
      S.Date = Q.Date  &apos;)

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF ( IIF((SELECT CHARINDEX(&apos;@Revision&apos;,(SELECT definition
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_QAExecutionsCountByUser&apos;)
      AND o.type      = &apos;V&apos;)) ) = 0  , 0 , CAST(LTRIM(RTRIM((select REPLACE(REPLACE(REPLACE(REPLACE(LEFT(REPLACE(definition,&apos;--@Revision:&apos;,&apos;&apos;),3),&apos; &apos;,&apos;&apos;),CHAR(9), &apos;&apos;), CHAR(10), &apos;&apos;), CHAR(13), &apos;&apos;)
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_QAExecutionsCountByUser&apos;)
      AND o.type      = &apos;V&apos;))) AS INT))  &lt; 3)
      BEGIN
      EXEC(N&apos;--@Revision:2
      ALTER VIEW [dbo].[vw_QAExecutionsCountByUser]
      AS
      SELECT
      COUNT(QActionId) ExecutionCount,
      QActions.Id  QActionId,
      ISNULL(QActions.[Name], N&apos;&apos;N/A&apos;&apos;) [Name],
      CAST(year(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5))) AS [Date],
      UserSessions.UserId ,
      CASE WHEN muser.full_name IS NULL THEN N&apos;&apos;User_&apos;&apos;+LEFT(UserSessions.UserId,3) ELSE muser.full_name END FullName
      FROM
      dbo.QActionExecutions
      LEFT JOIN
      dbo.QActions
      ON
      QActions.Id = QActionExecutions.QActionId
      JOIN
      dbo.Cases
      ON
      Cases.CaseId = QActionExecutions.CaseId
      JOIN
      dbo.UserSessions
      ON
      UserSessions.SessionId = Cases.SessionId
      LEFT JOIN
      [$DatabaseHistory$].[dbo].[main-user] muser
      ON
      muser.id = UserSessions.UserId
      WHERE
      dbo.fn_GetLocalTimeStamp(QActionExecutions.start) >= DATEADD(MONTH, -12, GETDATE()) AND
      QActionExecutions.[Finish] IS NOT NULL
      GROUP BY
      QActions.Id,
      QActions.[Name] ,
      CAST(year(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start))&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5)),CAST(month(dbo.fn_GetLocalTimeStamp(QActionExecutions.start)) AS NVARCHAR(5))),
      UserSessions.UserId, CASE WHEN muser.full_name IS NULL THEN N&apos;&apos;User_&apos;&apos;+LEFT(UserSessions.UserId,3) ELSE muser.full_name END &apos;)

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      IF ( IIF((SELECT CHARINDEX(&apos;@Revision&apos;,(SELECT definition
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_WeekdayCountsByMonth&apos;)
      AND o.type      = &apos;V&apos;)) ) = 0  , 0 , CAST(LTRIM(RTRIM((select REPLACE(REPLACE(REPLACE(REPLACE(LEFT(REPLACE(definition,&apos;--@Revision:&apos;,&apos;&apos;),3),&apos; &apos;,&apos;&apos;),CHAR(9), &apos;&apos;), CHAR(10), &apos;&apos;), CHAR(13), &apos;&apos;)
      FROM sys.objects     o
      JOIN sys.sql_modules m on m.object_id = o.object_id
      WHERE o.object_id = object_id( &apos;vw_WeekdayCountsByMonth&apos;)
      AND o.type      = &apos;V&apos;))) AS INT))  &lt; 3)
      BEGIN
      EXEC(N&apos;--@Revision:2
      ALTER VIEW [dbo].[vw_WeekdayCountsByMonth]
      AS
      SELECT
      COUNT(*) AS DayCount,
      CAST(year(MinDate) AS NVARCHAR(10))+N&apos;&apos;-&apos;&apos;+ IIF(month(MinDate)&lt;10,&apos;&apos;0&apos;&apos;+CAST(month(MinDate) AS NVARCHAR(5)),CAST(month(MinDate) AS NVARCHAR(5))) AS [Date],
      CAST(CAST(year(MinDate) AS NVARCHAR(10))+CAST(month(MinDate) AS NVARCHAR(5)) AS INT) AS [DateSort]
      FROM (
      SELECT
      DATEADD(DAY, number, (SELECT MIN(dbo.fn_GetLocalTimeStamp(start)) FROM [dbo].[UserSessions] WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL)) AS MinDate
      FROM master.dbo.spt_values
      WHERE type = N&apos;&apos;P&apos;&apos; AND number BETWEEN 1 AND DATEDIFF(DAY, (SELECT MIN(dbo.fn_GetLocalTimeStamp(start)) minDate FROM [dbo].[UserSessions] WHERE dbo.fn_GetLocalTimeStamp(start) >= DATEADD(MONTH, -12, GETDATE()) AND [Finish] IS NOT NULL),
      (SELECT max(dbo.fn_GetLocalTimeStamp(start)) maxDate FROM [dbo].[UserSessions]))
      ) AS date_series
      GROUP BY
      YEAR(MinDate) ,
      MONTH(MinDate) &apos;)

      SET @cnt = @cnt+1;
      PRINT N&apos;... done.&apos;

      END

      SELECT @cnt
    </Query>

    <Query Name="CreateCase">

      DECLARE @CurrentTimeStamp DATETIME = GETUTCDATE();

      INSERT INTO [Cases]
      ( CaseId, UserId, SessionId, [Start] )
      SELECT  @CaseId, @UserId, @SessionId, @CurrentTimeStamp;
      IF @@RowCount = 1
      BEGIN
      INSERT INTO [CaseTime]
      ( CaseId, StatusId, [TimeStamp] )
      SELECT @CaseId, 1, @CurrentTimeStamp;
      END


    </Query>
    <Query Name="UpdateCaseState">

      DECLARE @CurrentTimeStamp DATETIME = GETUTCDATE();
      DECLARE @Status XML = @StatusXML;

      INSERT INTO [CaseTime]
      ( CaseId, StatusId, [TimeStamp] )
      SELECT  @CaseId, @StatusId, @CurrentTimeStamp;

      INSERT INTO [CaseTime] (CaseId, StatusId,[TimeStamp])
      SELECT
      @CaseId,
      Item.value('(StatusId/text())[1]', 'int') AS StatusId,
      Item.value('(TimeStamp/text())[1]', 'DateTime') AS [TimeStamp]
      FROM
      @Status.nodes('/Root/Item') AS A(Item);

      IF @StatusID IN (4,5)
      BEGIN
      UPDATE [Cases]
      SET [Finish] = @CurrentTimeStamp,
      ActiveTime = @ActiveTime
      WHERE CaseId = @CaseId;
      END

    </Query>
    <Query Name="CreateUserSession">

      INSERT INTO [UserSessions]
      ( UserId, SessionId, [Start])
      SELECT @UserId, @SessionId, @SessionDate ;

    </Query>
    <Query Name="CloseUserSession">

		IF EXISTS (SELECT TOP 1 * FROM UserSessions WHERE SessionId = @SessionId)
		BEGIN
		    UPDATE [UserSessions]
		    SET [Finish] = @SessionDate
		    WHERE SessionId = @SessionId;
        END
		
		IF NOT EXISTS (SELECT TOP 1 * FROM UserSessions WHERE SessionId = @SessionId) AND EXISTS (SELECT TOP 1 * FROM dbo.Cases WHERE SessionId = @SessionId)
		BEGIN
		    DECLARE @CurrentTimeStamp DATETIME = GETUTCDATE();
		    INSERT INTO UserSessions
		    ( UserId, SessionId, [Start], [Finish] )
		    SELECT TOP 1 UserId,SessionId,[Start],@CurrentTimeStamp FROM Cases
		    WHERE SessionId = @SessionId ORDER BY [Start] ASC;
		END

		IF EXISTS (SELECT TOP 1 * FROM dbo.Cases WHERE SessionId = @SessionId)
		BEGIN
		    INSERT INTO [CaseTime]
		    ( CaseId, StatusId, [TimeStamp] )
		    SELECT  CaseId, 4, @SessionDate
		    FROM dbo.Cases
		    WHERE SessionId = @SessionId AND Finish IS NULL;

		    UPDATE [Cases]
		    SET [Finish] = @SessionDate
		    WHERE SessionId = @SessionId AND Finish IS NULL;
		END

	</Query>
    <Query Name="UpdateCases">

      DECLARE @CurrentTimeStamp DATETIME = GETUTCDATE();

      IF EXISTS (SELECT TOP 1 * FROM dbo.Cases JOIN dbo.CaseTime ON Cases.CaseId = CaseTime.CaseId  WHERE Cases.CaseId = @CaseId AND CaseTime.StatusId = 4 )
      BEGIN
          UPDATE [CaseTime]
          SET Statusid = 2
          FROM dbo.Cases
          JOIN dbo.CaseTime ON Cases.CaseId = CaseTime.CaseId
          WHERE Cases.CaseId = @CaseId AND
          CaseTime.StatusId = 4

          INSERT INTO [CaseTime]
          ( CaseId, StatusId, [TimeStamp] )
          SELECT  @CaseId, 3, @CurrentTimeStamp;

          UPDATE [Cases]
          SET [Finish] = NULL
          WHERE CaseId = @CaseId;
      END
	</Query>
    <Query Name="InsertTicket">
		IF NOT EXISTS (SELECT [TicketId], [UserId],[CaseId],[Status],[Start], [Finish],ActiveTime FROM [Tickets]
		WHERE [TicketId] = @TicketId AND [UserId] = @UserId AND [CaseId] = @CaseId AND [Status] = @Status AND [Start] = @Start AND [Finish] = @Finish AND ActiveTime = @ActiveTime )
		BEGIN
		    INSERT INTO [Tickets]
		    ([TicketId], [UserId],[CaseId],[Status],[Start], [Finish],ActiveTime)
		    SELECT  @TicketId,@UserId,@CaseId,@Status,@Start,@Finish,@ActiveTime;
		END
	</Query>

    <Query Name="AnalyticsReportQuickActionExecution">
      INSERT INTO [QActionExecutions]
      ([CaseId],[QActionId],[DeviceId],[Start],[Finish],[Parameters],[Result],[ErrorCode],[ErrorDescription],[ExecutionType],[ResultType])
      SELECT @CaseId,@QActionId,@DeviceId,@Start,@Finish,@Parameters,@Result,@ErrorCode,@ErrorDescription, ISNULL(@ExecutionType, 'Undefined'), ISNULL(@ResultType, 'Undefined')
    </Query>
    <Query Name="ReportQuickActionExecution">
      INSERT INTO [main-computer-quickaction]
      ([UserId],[QActionId],[QActionName],[DeviceId],[Start],[Finish],[Parameters],[Result],[ErrorCode],[ErrorDescription],[ExecutionType],[ResultType])
      SELECT @UserId,@QActionId,@QActionName,@DeviceId,@Start,@Finish,@Parameters,@Result,@ErrorCode,@ErrorDescription, ISNULL(@ExecutionType, 'Undefined'), ISNULL(@ResultType, 'Undefined')
    </Query>
    <!--<Query Name="UpdateQActionInfo">
      UPDATE [QActions] SET [Name]=@Name, [Type]=@Type WHERE [Id]=@Id
      IF @@ROWCOUNT = 0 INSERT INTO [QActions] ([Id], [Name], [Type], [TimeStamp]) VALUES (@Id, @Name, @Type,GETUTCDATE())
      SELECT @@ROWCOUNT
    </Query>-->
    <Query Name="UpdateQActionInfo">
      UPDATE [QActions] SET [Name]=@Name, [Type]=@Type WHERE [Id]=@Id
      IF @@ROWCOUNT = 0 INSERT INTO [QActions] ([Id], [Name], [Type]) VALUES (@Id, @Name, @Type)
      SELECT @@ROWCOUNT
    </Query>
    <Query Name="UpdateQActionInfoLang">
      UPDATE [QActionDescriptions] SET [Description]=@Name WHERE [QActionId]=@Id  AND [LanguageCode]=@Lang
      IF @@ROWCOUNT = 0 INSERT INTO [QActionDescriptions] ([QActionId], [Description], [LanguageCode]) VALUES (@Id, @Name, @Lang)
      SELECT @@ROWCOUNT
    </Query>
    <Query Name="UpdateConfigValue">
      UPDATE [main-config] SET [Value]=@Value WHERE [Key]=@Key
      IF @@ROWCOUNT = 0 INSERT INTO [main-config] ([Key], [Value]) VALUES (@Key, @Value)
      SELECT @@ROWCOUNT
    </Query>
    <Query Name="GetConfigValues">
      SELECT [Key],[Value] FROM [main-config]
    </Query>
    <Query Name="GetAllExternalTokens">
      SELECT [id],[type],[name],[name2],[secret],[validUntil],[renewUntil] FROM [main-user-tokens]
    </Query>
    <Query Name="RemoveExpieredExternalTokens">
      DELETE FROM [main-user-tokens] WHERE [validUntil] &lt; @ValidUntil
    </Query>
    <Query Name="InsertOrUpdateExternalToken">
      UPDATE [main-user-tokens] SET [name]=@Name, [name2]=@Name2, [secret]=@Secret, [validUntil]=@ValidUntil, [renewUntil]=@RenewUntil WHERE [id]=@Id AND [type]=@Type
      IF @@ROWCOUNT = 0 INSERT INTO [main-user-tokens] ([id], [type], [name], [name2], [secret], [validUntil], [renewUntil]) VALUES (@Id, @Type, @Name, @Name2, @Secret, @ValidUntil, @RenewUntil)
      SELECT @@ROWCOUNT
    </Query>
    <Query Name="GetComputerVitalSignInfoForIntune">
      SELECT [id],[last_seen_by_agent] FROM [main-computer] WHERE [deviceId_azure]=@AZURE_ID
    </Query>
    <Query Name="UpdateVitalSignMonitoringAll">
      UPDATE [main-vitalSignMonitoring-All] SET [TimeStamp]=@TimeStamp, [DiffToAgent]=@DiffToAgent, [UserName]=@UserName WHERE [DeviceId]=@Id AND [EventId]=1
      IF @@ROWCOUNT = 0 INSERT INTO [main-vitalSignMonitoring-All] ([DeviceId], [EventId], [TimeStamp], [DiffToAgent], [UserName]) VALUES (@Id, 1, @TimeStamp, @DiffToAgent,@UserName)
      SELECT @@ROWCOUNT
    </Query>
    <Query Name="UpdateVitalSignMonitoringIntune">
      UPDATE [main-vitalSignMonitoring-Intune] SET [name]=@name, [AzureID]=@AzureID, [UserName]=@UserName, [TimeStamp]=@TimeStamp WHERE [TenantID]=@TenantId AND [IntuneID]=@IntuneId AND [EventId]=1
      IF @@ROWCOUNT = 0 INSERT INTO [main-vitalSignMonitoring-Intune] ([TenantID], [IntuneID], [EventId], [name], [AzureID], [UserName], [TimeStamp]) VALUES (@TenantId, @IntuneId, 1, @name, @AzureID, @UserName, @TimeStamp)
      SELECT @@ROWCOUNT
    </Query>
  </Queries>
</DataHistorySql>