/*-------------------------------------------------------------------------*/
/*  Invensys Systems, Inc - InSQL 9.0                                      */
/*  Runtime database build script for Wonderware IndustrialSQL Server 9.0  */
/*  Wed Jul 13 12:15:37 2005                                               */
/*-------------------------------------------------------------------------*/
/* DO NOT RUN THIS SCRIPT AGAINST AN ALREADY CONFIGURED InSQL DATABASE!    */
/*-------------------------------------------------------------------------*/


use master
go

set QUOTED_IDENTIFIER OFF
set NOCOUNT ON
go

/* set ANSI options for dblib OLE DB clients */
sp_dboption Runtime, 'ANSI nulls', TRUE
go
sp_dboption Runtime, 'ANSI warnings', TRUE
go
sp_configure 'user option', 40
RECONFIGURE WITH OVERRIDE
go


/* Configuration of roles and logins */

/* Create the database roles for the various databases */
use master
go

if (not exists (select name from sysusers where name = 'aaAdministrators'))
begin
  exec sp_addrole aaAdministrators
end
go

use Runtime
go

if (not exists (select name from sysusers where name = 'aaUsers'))
begin
  exec sp_addrole aaUsers
end
go

if (not exists (select name from sysusers where name = 'aaPowerUsers'))
begin
  exec sp_addrole aaPowerUsers
end
go

if (not exists (select name from sysusers where name = 'aaAdministrators'))
begin
  exec sp_addrole aaAdministrators
end
go

/* Grant permissions for the database roles in the Runtime database */
grant create table, create view, create procedure, create rule, create default to aaPowerUsers
go

grant create table, create view, create procedure, create rule, create default to aaAdministrators
go
grant dump database, dump transaction to aaAdministrators
go


/* Windows Authentication */
/* Add the local Windows aa* groups to the relevant database roles. */
/* The Windows aa* groups must already exist when this script is run. */
/* This is done only for a non-clustered system; if clustered, the system admin */
/* must perform the following steps manually. */

if serverproperty('IsClustered') = 0
begin

  /* Get the local server name */
  declare @servername sysname
  declare @pos int
  set @servername = convert(sysname, serverproperty('machinename'))
  set @pos = charindex(N'\', @servername, 0)

  if @pos > 0
    set @servername = left(@servername, @pos-1)

  use master

  declare @loginame sysname
  set @loginame = @servername + '\aaUsers'
  if (not exists (select name from syslogins where name = @loginame))
  begin
    exec sp_grantlogin @loginame
  end
  exec sp_defaultdb @loginame, Runtime

  set @loginame = @servername + '\aaPowerUsers'
  if (not exists (select name from syslogins where name = @loginame))
  begin
    exec sp_grantlogin @loginame
  end
  exec sp_defaultdb @loginame, Runtime

  set @loginame = @servername + '\aaAdministrators'
  if (not exists (select name from syslogins where name = @loginame))
  begin
    exec sp_grantlogin @loginame
  end
  -- exec sp_defaultdb @loginame, Runtime
  -- Set default db to 'master' for aaAdministrators, in case Runtime does not exist.
  exec sp_defaultdb @loginame, master


  /* Add the logins to the relevant database roles */
  use master
  set @loginame = @servername + '\aaAdministrators'
  if (not exists (select name from sysusers where name = @loginame))
  begin
    exec sp_grantdbaccess @loginame
  end
  exec sp_addrolemember 'aaAdministrators', @loginame

  use Runtime
  if (not exists (select name from sysusers where name = @loginame))
  begin
    exec sp_grantdbaccess @loginame
  end
  exec sp_addrolemember 'aaAdministrators', @loginame

  set @loginame = @servername + '\aaPowerUsers'
  if (not exists (select name from sysusers where name = @loginame))
  begin
    exec sp_grantdbaccess @loginame
  end
  exec sp_addrolemember 'aaPowerUsers', @loginame

  set @loginame = @servername + '\aaUsers'
  if (not exists (select name from sysusers where name = @loginame))
  begin
    exec sp_grantdbaccess @loginame
  end
  exec sp_addrolemember 'aaUsers', @loginame

end  -- if serverproperty('IsClustered') = 0
go

/* SQL Server Authentication */
/* Check that the SQL Server logins exist within the SQL server, add if needed */

use master
go

declare @version varchar(128)
select @version = convert(varchar(128), serverproperty('ProductVersion'))

if (not exists (select name from syslogins where name = 'aadbo'))
begin
  if convert(int, substring(@version, 1, 1)) > 8
  begin
    -- SQL Server 2005: use new syntax
    exec sp_executesql N'create login aadbo with password = ''pwddbo'', DEFAULT_DATABASE = master, CHECK_POLICY = OFF'
  end
  else
  begin
    exec sp_addlogin aadbo, pwddbo, master
  end
end

if (not exists (select name from syslogins where name = 'aaUser'))
begin
  if convert(int, substring(@version, 1, 1)) > 8
  begin
    exec sp_executesql N'create login aaUser with password = ''pwUser'', DEFAULT_DATABASE = Runtime, CHECK_POLICY = OFF'
  end
  else
  begin
    exec sp_addlogin aaUser, pwUser, Runtime
  end
end
else
begin
  exec sp_defaultdb aaUser, Runtime
end

if (not exists (select name from syslogins where name = 'aaPower'))
begin
  if convert(int, substring(@version, 1, 1)) > 8
  begin
    exec sp_executesql N'create login aaPower with password = ''pwPower'', DEFAULT_DATABASE = Runtime, CHECK_POLICY = OFF'
  end
  else
  begin
    exec sp_addlogin aaPower, pwPower, Runtime
  end
end
else
begin
  exec sp_defaultdb aaPower, Runtime
end

if (not exists (select name from syslogins where name = 'aaAdmin'))
begin
  if convert(int, substring(@version, 1, 1)) > 8
  begin
    exec sp_executesql N'create login aaAdmin with password = ''pwAdmin'', DEFAULT_DATABASE = Runtime, CHECK_POLICY = OFF'
  end
  else
  begin
    exec sp_addlogin aaAdmin, pwAdmin, Runtime
  end
end
else
begin
  exec sp_defaultdb aaAdmin, Runtime
end
go

/* Grant access to the SQL Server logins */
/* User aaAdmin is granted access to both master and Runtime databases.
   aaAdmin is also added to the aaAdministrators roles for both databases. */

use master
go

if (not exists (select name from sysusers where name = 'aaAdmin'))
begin
  exec sp_adduser aaAdmin, aaAdmin, aaAdministrators
end
go

use Runtime
go

if (not exists (select name from sysusers where name = 'aaUser'))
begin
  exec sp_adduser aaUser, aaUser, aaUsers
end
go

if (not exists (select name from sysusers where name = 'aaPower'))
begin
  exec sp_adduser aaPower, aaPower, aaPowerUsers
end
go

if (not exists (select name from sysusers where name = 'aaAdmin'))
begin
  exec sp_adduser aaAdmin, aaAdmin, aaAdministrators
end
go

/* transfer ownership of database to aadbo with all permissions */
exec sp_changedbowner aadbo, true
go
exec sp_defaultdb aadbo,Runtime
go

 
 
 
 exec sp_addtype CalcTypes, "char(3)", "NULL"
go
 
 exec sp_addtype Platforms, "nchar(20)", "NULL"
go
 
 CREATE TABLE aaAreaData (
        AreaKey              int NOT NULL,
        Category             int NOT NULL,
        AreaName             nvarchar(255) NOT NULL,
        ContainedName        nvarchar(255) NULL,
        ParentKey            int NOT NULL,
        PRIMARY KEY (AreaKey)
 )
go
 
 grant SELECT on aaAreaData to aaUsers
go
grant SELECT on  aaAreaData to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  aaAreaData to aaAdministrators
go
 
 
 CREATE TABLE aaAreaXML (
        Version              bigint NULL DEFAULT 0,
        AreaXML              ntext NULL
 )
go
 
 grant SELECT on aaAreaXML to aaUsers
go
grant SELECT on  aaAreaXML to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  aaAreaXML to aaAdministrators
go
 
 
 CREATE TABLE aaAttributeData (
        AttributeName        nvarchar(256) NOT NULL,
        ObjectKey            int NOT NULL,
        wwDomainTagKey       int NOT NULL DEFAULT -1
 )
go
 
 CREATE INDEX XIF1aaAttributeData ON aaAttributeData
 (
        ObjectKey
 )
go
 
 CREATE INDEX XIE1aaAttributeData ON aaAttributeData
 (
        wwDomainTagKey
 )
go
 
 grant SELECT on aaAttributeData to aaUsers
go
grant SELECT on  aaAttributeData to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  aaAttributeData to aaAdministrators
go
 
 
 CREATE TABLE aaAttributeDataPending (
        AttributeName        nvarchar(256) NOT NULL,
        ObjectKey            int NOT NULL
 )
go
 
 CREATE INDEX XIF1aaAttributeDataPending ON aaAttributeDataPending
 (
        ObjectKey
 )
go
 
 grant SELECT on aaAttributeDataPending to aaUsers
go
grant SELECT on  aaAttributeDataPending to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  aaAttributeDataPending to aaAdministrators
go
 
 
 CREATE TABLE aaObjectData (
        ObjectKey            int IDENTITY,
        Type                 int NOT NULL,
        aaTagName            nvarchar(256) NULL,
        ContainedName        nvarchar(256) NULL,
        ParentKey            int NOT NULL,
        Status               tinyint NOT NULL DEFAULT 0,
        PRIMARY KEY (ObjectKey)
 )
go
 
 grant SELECT on aaObjectData to aaUsers
go
grant SELECT on  aaObjectData to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  aaObjectData to aaAdministrators
go
 
 
 CREATE TABLE aaObjectDataPending (
        ObjectKey            int NOT NULL,
        Type                 int NOT NULL,
        aaTagName            nvarchar(256) NULL,
        ContainedName        nvarchar(256) NULL,
        ParentKey            int NOT NULL,
        PRIMARY KEY (ObjectKey)
 )
go
 
 grant SELECT on aaObjectDataPending to aaUsers
go
grant SELECT on  aaObjectDataPending to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  aaObjectDataPending to aaAdministrators
go
 
 
 CREATE TABLE ActionType (
        ActionTypeKey        int IDENTITY,
        Name                 nvarchar(33) NOT NULL,
        Description          nvarchar(50) NULL,
        EditorClassName      nvarchar(80) NULL,
        ActionClassName      nvarchar(80) NULL,
        PRIMARY KEY (ActionTypeKey)
 )
go
 
 CREATE UNIQUE INDEX XAK1ActionType ON ActionType
 (
        Name
 )
go
 
 grant SELECT on ActionType to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ActionType to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ActionType to aaAdministrators
go
 
 
 CREATE TABLE AnalogHistory_OLEDB (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                float(25) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        OPCQuality           int NULL,
        wwTagKey             int NOT NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwEdgeDetection      nvarchar(20) NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwValueDeadband      float(25) NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwInterpolationType  nvarchar(20) NULL,
        wwQualityRule        nvarchar(20) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 grant SELECT on AnalogHistory_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE AnalogLive_OLEDB (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                float(25) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        OPCQuality           int NULL,
        wwTagKey             int NOT NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwValueDeadband      float(25) NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 grant SELECT on AnalogLive_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE AnalogSnapshot (
        SnapshotTagKey       int NOT NULL,
        EventLogKey          int NOT NULL,
        Value                float(25) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        PRIMARY KEY (SnapshotTagKey, EventLogKey)
 )
go
 
 CREATE INDEX XIF44AnalogSnapshot ON AnalogSnapshot
 (
        EventLogKey
 )
go
 
 CREATE INDEX XIF7AnalogSnapshot ON AnalogSnapshot
 (
        SnapshotTagKey
 )
go
 
 grant SELECT on AnalogSnapshot to aaUsers
go
grant SELECT on  AnalogSnapshot to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  AnalogSnapshot to aaAdministrators
go
 
 
 CREATE TABLE AnalogTag (
        TagName              nvarchar(256) NOT NULL,
        EUKey                int NOT NULL,
        MinEU                float(25) NOT NULL DEFAULT 0,
        MaxEU                float(25) NOT NULL DEFAULT 100,
        MinRaw               float(25) NULL DEFAULT 0,
        MaxRaw               float(25) NULL DEFAULT 100,
        Scaling              int NOT NULL DEFAULT 0,
        RawType              int NOT NULL DEFAULT 3
                                    CHECK (RawType BETWEEN 1 AND 8),
        ValueDeadband        float(25) NOT NULL DEFAULT 0
                                    CHECK (ValueDeadband BETWEEN 0 AND 100),
        InitialValue         float(25) NOT NULL DEFAULT 0,
        IntegerSize          tinyint NOT NULL DEFAULT 16,
        SignedInteger        bit NOT NULL DEFAULT 0,
        RateDeadband         float(25) NOT NULL DEFAULT 0
                                    CHECK (RateDeadband >= 0),
        InterpolationType    tinyint NOT NULL DEFAULT 254
                                    CHECK (InterpolationType IN (0, 1, 254)),
        RolloverValue        int NOT NULL DEFAULT 0
                                    CHECK (RolloverValue >= 0),
        PRIMARY KEY (TagName)
 )
go
 
 CREATE INDEX XIF1AnalogTag ON AnalogTag
 (
        EUKey
 )
go
 
 grant SELECT on AnalogTag to aaUsers
go
grant SELECT on  AnalogTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  AnalogTag to aaAdministrators
go
 
 
 CREATE TABLE AnalogWideHistory_OLEDB (
        DateTime             datetime NOT NULL,
        TagA1                float(25) NULL,
        TagA2                float(25) NULL,
        ManyOtherTags        float(25) NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwEdgeDetection      nvarchar(20) NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwValueDeadband      float(25) NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwInterpolationType  nvarchar(20) NULL,
        wwQualityRule        nvarchar(20) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime)
 )
go
 
 grant SELECT on AnalogWideHistory_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE Annotation (
        AnnotationKey        int IDENTITY,
        UserKey              int NOT NULL,
        TagName              nvarchar(256) NULL,
        DateCreated          datetime NULL,
        Content              nvarchar(1000) NOT NULL,
        DateTime             datetime NOT NULL,
        Value                float(25) NULL DEFAULT 0,
        PRIMARY KEY (AnnotationKey)
 )
go
 
 CREATE INDEX XIF31Annotation ON Annotation
 (
        TagName
 )
go
 
 CREATE INDEX XIF32Annotation ON Annotation
 (
        UserKey
 )
go
 
 grant SELECT on Annotation to aaUsers
go
grant SELECT on  Annotation to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Annotation to aaAdministrators
go
 
 
 CREATE TABLE BlobTag (
        TagName              nvarchar(256) NOT NULL,
        MaxLength            int NULL,
        PRIMARY KEY (TagName)
 )
go
 
 grant SELECT on BlobTag to aaUsers
go
grant SELECT on  BlobTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  BlobTag to aaAdministrators
go
 
 
 CREATE TABLE CalcType (
        CalcType             CalcTypes NOT NULL
                                    CHECK (CalcType IN ('AVG', 'SUM', 'MIN', 'MAX')),
        Description          nvarchar(50) NULL,
        PRIMARY KEY (CalcType)
 )
go
 
 grant SELECT on CalcType to aaUsers
go
grant SELECT on  CalcType to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  CalcType to aaAdministrators
go
 
 
 CREATE TABLE ComplexHistory (
        TagName              nvarchar(256) NOT NULL,
        DateTime             datetime NOT NULL,
        Content              image NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        PRIMARY KEY (TagName, DateTime)
 )
go
 
 CREATE INDEX XIF29ComplexHistory ON ComplexHistory
 (
        TagName
 )
go
 
 grant SELECT on ComplexHistory to aaUsers
go
grant SELECT on  ComplexHistory to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ComplexHistory to aaAdministrators
go
 
 
 CREATE TABLE ComplexTag (
        TagName              nvarchar(256) NOT NULL,
        InitialValue         image NULL,
        Provider             nvarchar(128) NULL,
        Retriever            nvarchar(128) NULL,
        Type                 int NOT NULL DEFAULT 0,
        PRIMARY KEY (TagName)
 )
go
 
 grant SELECT on ComplexTag to aaUsers
go
grant SELECT on  ComplexTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ComplexTag to aaAdministrators
go
 
 
 CREATE TABLE ConfigStatusPending (
        ID                   int IDENTITY,
        Type                 tinyint NOT NULL,
        ObjectKey            int NOT NULL,
        Status               tinyint NULL,
        PRIMARY KEY (ID)
 )
go
 
 CREATE INDEX XIE1ConfigStatusPending ON ConfigStatusPending
 (
        Type,
        ObjectKey
 )
go
 
 grant SELECT on ConfigStatusPending to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ConfigStatusPending to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ConfigStatusPending to aaAdministrators
go
 
 
 CREATE TABLE ConfigStatusSnapshot (
        ID                   int NOT NULL,
        Type                 tinyint NOT NULL,
        ObjectKey            int NOT NULL,
        Status               tinyint NULL,
        PRIMARY KEY (ID)
 )
go
 
 grant SELECT on ConfigStatusSnapshot to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ConfigStatusSnapshot to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ConfigStatusSnapshot to aaAdministrators
go
 
 
 CREATE TABLE Context (
        ContextKey           int IDENTITY,
        Description          nvarchar(50) NOT NULL,
        PRIMARY KEY (ContextKey)
 )
go
 
 CREATE UNIQUE INDEX XAK1Context ON Context
 (
        Description
 )
go
 
 grant SELECT on Context to aaUsers
go
grant SELECT on  Context to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Context to aaAdministrators
go
 
 
 CREATE TABLE DetectorType (
        DetectorTypeKey      int IDENTITY,
        Name                 nvarchar(33) NOT NULL,
        Description          nvarchar(50) NULL,
        EditorClassName      nvarchar(80) NULL,
        DetectorClassName    nvarchar(80) NULL,
        ExecutionMode        tinyint NOT NULL DEFAULT 0,
        PRIMARY KEY (DetectorTypeKey)
 )
go
 
 CREATE UNIQUE INDEX XAK1DetectorType ON DetectorType
 (
        Name
 )
go
 
 grant SELECT on DetectorType to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  DetectorType to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  DetectorType to aaAdministrators
go
 
 
 CREATE TABLE Deviation (
        TagName              nvarchar(256) NOT NULL,
        ContextKey           int NOT NULL,
        MinorDeviation       real NULL DEFAULT 0,
        MinorChecked         bit NOT NULL DEFAULT 0,
        MinorPriority        int NULL DEFAULT 0,
        MajorDeviation       real NULL DEFAULT 0,
        MajorChecked         bit NOT NULL DEFAULT 0,
        MajorPriority        int NULL DEFAULT 0,
        Target               float(25) NULL,
        Deadband             real NULL DEFAULT 0,
        PRIMARY KEY (TagName, ContextKey)
 )
go
 
 CREATE INDEX XIF52Deviation ON Deviation
 (
        TagName
 )
go
 
 CREATE INDEX XIF53Deviation ON Deviation
 (
        ContextKey
 )
go
 
 grant SELECT on Deviation to aaUsers
go
grant SELECT on  Deviation to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Deviation to aaAdministrators
go
 
 
 CREATE TABLE DiscreteHistory_OLEDB (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                float(25) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        OPCQuality           int NULL,
        wwTagKey             int NOT NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwEdgeDetection      nvarchar(20) NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 grant SELECT on DiscreteHistory_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE DiscreteLive_OLEDB (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                float(25) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        OPCQuality           int NULL,
        wwTagKey             int NOT NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 grant SELECT on DiscreteLive_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE DiscreteSnapshot (
        SnapshotTagKey       int NOT NULL,
        EventLogKey          int NOT NULL,
        Value                tinyint NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        PRIMARY KEY (SnapshotTagKey, EventLogKey)
 )
go
 
 CREATE INDEX XIF16DiscreteSnapshot ON DiscreteSnapshot
 (
        SnapshotTagKey
 )
go
 
 CREATE INDEX XIF45DiscreteSnapshot ON DiscreteSnapshot
 (
        EventLogKey
 )
go
 
 grant SELECT on DiscreteSnapshot to aaUsers
go
grant SELECT on  DiscreteSnapshot to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  DiscreteSnapshot to aaAdministrators
go
 
 
 CREATE TABLE DiscreteTag (
        TagName              nvarchar(256) NOT NULL,
        MessageKey           int NOT NULL,
        InitialValue         tinyint NOT NULL DEFAULT 0,
        PRIMARY KEY (TagName)
 )
go
 
 CREATE INDEX XIF5DiscreteTag ON DiscreteTag
 (
        MessageKey
 )
go
 
 grant SELECT on DiscreteTag to aaUsers
go
grant SELECT on  DiscreteTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  DiscreteTag to aaAdministrators
go
 
 
 CREATE TABLE DiscreteWideHistory_OLEDB (
        DateTime             datetime NOT NULL,
        TagD1                tinyint NULL,
        TagD2                tinyint NULL,
        ManyOtherTags        tinyint NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwEdgeDetection      nvarchar(20) NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime)
 )
go
 
 grant SELECT on DiscreteWideHistory_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE EngineeringUnit (
        EUKey                int IDENTITY,
        Unit                 nvarchar(32) NULL DEFAULT '',
        DefaultTagRate       int NULL DEFAULT 10000
                                    CHECK (DefaultTagRate IN (0, 1000, 2000, 3000, 5000, 6000, 10000, 15000, 30000, 60000, 120000, 180000, 300000, 360000, 600000, 900000, 1200000, 1800000, 3600000)),
        IntegralDivisor      float(25) NOT NULL DEFAULT 1
                                    CHECK (IntegralDivisor > 0),
        Status               tinyint NULL DEFAULT 0,
        PRIMARY KEY (EUKey)
 )
go
 
 grant SELECT on EngineeringUnit to aaUsers
go
grant SELECT on  EngineeringUnit to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  EngineeringUnit to aaAdministrators
go
 
 
 CREATE TABLE EnumeratedTag (
        TagName              nvarchar(256) NOT NULL,
        EnumerationTypeKey   int NOT NULL,
        InitialValue         int NOT NULL DEFAULT 0,
        PRIMARY KEY (TagName)
 )
go
 
 CREATE INDEX XIF5EnumeratedTag ON EnumeratedTag
 (
        EnumerationTypeKey
 )
go
 
 grant SELECT on EnumeratedTag to aaUsers
go
grant SELECT on  EnumeratedTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  EnumeratedTag to aaAdministrators
go
 
 
 CREATE TABLE EnumerationType (
        EnumerationTypeKey   int IDENTITY,
        EnumerationID        bigint NOT NULL,
        EnumerationName      nvarchar(256) NULL,
        PRIMARY KEY (EnumerationTypeKey)
 )
go
 
 grant SELECT on EnumerationType to aaUsers
go
grant SELECT on  EnumerationType to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  EnumerationType to aaAdministrators
go
 
 
 CREATE TABLE ErrorLog (
        DateTime             datetime NOT NULL,
        Type                 nvarchar(10) NULL DEFAULT '',
        ErrorCode            int NULL DEFAULT 0,
        Parameter            nvarchar(256) NULL DEFAULT '',
        TotalCount           int NULL DEFAULT 0,
        ModuleID             int NULL DEFAULT 0,
        Host                 nvarchar(32) NULL DEFAULT '',
        FileName             nvarchar(64) NULL DEFAULT '',
        Line                 int NULL DEFAULT 0
 )
go
 
 CREATE INDEX XIE1ErrorLog ON ErrorLog
 (
        DateTime
 )
go
 
 grant SELECT on ErrorLog to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ErrorLog to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ErrorLog to aaAdministrators
go
 
 
 CREATE TABLE EventHistory (
        EventLogKey          int IDENTITY,
        TagName              nvarchar(256) NULL,
        DateTime             datetime NOT NULL,
        DetectDateTime       datetime NOT NULL,
        Edge                 tinyint NULL DEFAULT 1
                                    CHECK (Edge BETWEEN 0 AND 5),
        PRIMARY KEY (EventLogKey)
 )
go
 
 CREATE INDEX XIF38EventHistory ON EventHistory
 (
        TagName
 )
go
 
 grant SELECT on EventHistory to aaUsers
go
grant SELECT on  EventHistory to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  EventHistory to aaAdministrators
go
 
 
 CREATE TABLE EventTag (
        TagName              nvarchar(256) NOT NULL,
        DetectorTypeKey      int NULL,
        ActionTypeKey        int NULL,
        ScanRate             int NULL DEFAULT 60000
                                    CHECK (ScanRate >= 500
                                                OR ScanRate = 0),
        TimeDeadband         int NOT NULL DEFAULT 0,
        Logged               bit NOT NULL DEFAULT 1,
        Status               tinyint NOT NULL DEFAULT 0,
        PostDetectorDelay    int NOT NULL DEFAULT 0,
        UseThreadPool        bit NOT NULL DEFAULT 1,
        DetectorString       nvarchar(1500) NULL DEFAULT '',
        ActionString         nvarchar(1500) NULL DEFAULT '',
        Priority             tinyint NOT NULL DEFAULT 0
                                    CHECK (Priority IN (0, 1)),
        Edge                 tinyint NOT NULL DEFAULT 1
                                    CHECK (Edge BETWEEN 0 AND 5),
        PRIMARY KEY (TagName)
 )
go
 
 CREATE INDEX XIF50EventTag ON EventTag
 (
        ActionTypeKey
 )
go
 
 CREATE INDEX XIF51EventTag ON EventTag
 (
        DetectorTypeKey
 )
go
 
 grant SELECT on EventTag to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  EventTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  EventTag to aaAdministrators
go
 
 
 CREATE TABLE EventTagPendingDelete (
        TagName              nvarchar(256) NOT NULL,
        DetectorTypeKey      int NULL,
        ActionTypeKey        int NULL,
        ScanRate             int NULL,
        TimeDeadband         int NOT NULL DEFAULT 0,
        Logged               bit NOT NULL DEFAULT 1,
        Status               tinyint NOT NULL DEFAULT 0,
        PostDetectorDelay    int NOT NULL DEFAULT 0,
        UseThreadPool        bit NOT NULL DEFAULT 1,
        DetectorString       nvarchar(1500) NULL,
        ActionString         nvarchar(1500) NULL,
        Priority             tinyint NOT NULL DEFAULT 0
                                    CHECK (Priority IN (0, 1)),
        Edge                 tinyint NULL DEFAULT 1
                                    CHECK (Edge BETWEEN 0 AND 5),
        PRIMARY KEY (TagName)
 )
go
 
 grant SELECT on EventTagPendingDelete to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  EventTagPendingDelete to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  EventTagPendingDelete to aaAdministrators
go
 
 
 CREATE TABLE Frequency (
        FrequencyID          int IDENTITY,
        Frequency            nvarchar(12) NOT NULL,
        PRIMARY KEY (FrequencyID)
 )
go
 
 grant SELECT on Frequency to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Frequency to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Frequency to aaAdministrators
go
 
 
 CREATE TABLE GroupTagList (
        GroupID              int NOT NULL,
        wwDomainTagKey       int NOT NULL,
        Triggerval           float(25) NULL,
        PRIMARY KEY (GroupID, wwDomainTagKey)
 )
go
 
 CREATE INDEX XIF40GroupTagList ON GroupTagList
 (
        GroupID
 )
go
 
 CREATE INDEX XIF41GroupTagList ON GroupTagList
 (
        wwDomainTagKey
 )
go
 
 grant SELECT on GroupTagList to aaUsers
go
grant SELECT on  GroupTagList to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  GroupTagList to aaAdministrators
go
 
 grant SELECT, UPDATE, INSERT, DELETE on GroupTagList to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  GroupTagList to aaPowerUsers, aaAdministrators
go
 
 
 CREATE TABLE HistorianSysObjects (
        id                   int NOT NULL,
        Type                 char(2) NULL,
        Name                 varchar(50) NULL,
        PRIMARY KEY (id)
 )
go
 
 grant SELECT on HistorianSysObjects to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  HistorianSysObjects to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  HistorianSysObjects to aaAdministrators
go
 
 
 CREATE TABLE History_OLEDB (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                float(25) NULL,
        vValue               sql_variant NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        OPCQuality           int NULL,
        wwTagKey             int NOT NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwEdgeDetection      nvarchar(20) NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwValueDeadband      float(25) NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwInterpolationType  nvarchar(20) NULL,
        wwQualityRule        nvarchar(20) NULL,
        wwStateCalc          nvarchar(20) NULL,
        StateTime            float(25) NULL,
        PercentGood          float(25) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 grant SELECT on History_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE HistoryBlock_OLEDB (
        FromDate             datetime NOT NULL,
        ToDate               datetime NOT NULL,
        StorageNodeKey       int NOT NULL,
        Description          nvarchar(50) NULL,
        OnLine               bit NOT NULL,
        HistoryArchived      int NOT NULL,
        SummaryArchived      int NOT NULL,
        EventArchived        int NOT NULL,
        StorageAreaType      int NOT NULL,
        ArchiveDate          datetime NULL,
        ArchiveLocation      nvarchar(50) NULL,
        Version              int NULL,
        Compression          int NULL,
        Sequence             int NOT NULL DEFAULT 0,
        TimeZoneOffset       int NULL,
        wwTimeZone           nvarchar(50) NULL,
        PRIMARY KEY (FromDate, ToDate, StorageNodeKey)
 )
go
 
 grant SELECT on HistoryBlock_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE InTouchNode (
        NodeKey              int NOT NULL,
        MachineName          nvarchar(255) NOT NULL,
        ApplicationName      nvarchar(32) NULL,
        Path                 nvarchar(250) NULL,
        Description          nvarchar(50) NULL,
        DuplicateChar        nvarchar(12) NOT NULL DEFAULT '',
        PrefixOrSuffix       bit NOT NULL DEFAULT 0,
        AlwaysModifyName     bit NOT NULL DEFAULT 0,
        ImportPlantTags      tinyint NOT NULL DEFAULT 0,
        ImportSystemTags     tinyint NOT NULL DEFAULT 0,
        ImportMemoryTags     tinyint NOT NULL DEFAULT 0,
        ImportAllTags        int NOT NULL DEFAULT 0,
        FixedStorageRate     tinyint NOT NULL DEFAULT 0,
        ImportRoute          tinyint NOT NULL DEFAULT 0,
        PRIMARY KEY (NodeKey)
 )
go
 
 CREATE UNIQUE INDEX XAKInTouchNode ON InTouchNode
 (
        MachineName,
        DuplicateChar
 )
go
 
 grant SELECT on InTouchNode to aaUsers
go
grant SELECT on  InTouchNode to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  InTouchNode to aaAdministrators
go
 
 
 CREATE TABLE InTouchSpecific (
        NodeKey              int NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        OriginalName         nvarchar(32) NOT NULL DEFAULT '',
        TypeInfo             int NOT NULL,
        InInSQL              bit NOT NULL DEFAULT 0,
        Comment              nvarchar(50) NULL,
        PRIMARY KEY (NodeKey, TagName)
 )
go
 
 CREATE INDEX XIF24InTouchSpecific ON InTouchSpecific
 (
        TagName
 )
go
 
 CREATE INDEX XIF33InTouchSpecific ON InTouchSpecific
 (
        NodeKey
 )
go
 
 CREATE INDEX XIE27InTouchSpecific ON InTouchSpecific
 (
        TypeInfo
 )
go
 
 grant SELECT on InTouchSpecific to aaUsers
go
grant SELECT on  InTouchSpecific to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  InTouchSpecific to aaAdministrators
go
 
 
 CREATE TABLE IODriver (
        IODriverKey          int IDENTITY,
        StorageNodeKey       int NOT NULL,
        ComputerName         nvarchar(255) NOT NULL DEFAULT '',
        AltComputerName      nvarchar(255) NULL DEFAULT '',
        StoreForwardMode     tinyint NOT NULL DEFAULT 0,
        StoreForwardPath     nvarchar(255) NULL DEFAULT '',
        MinMBThreshold       int NOT NULL DEFAULT 16
                                    CHECK (MinMBThreshold >= 0),
        Status               tinyint NULL DEFAULT 1,
        Enabled              bit NOT NULL DEFAULT 1,
        StoreForwardDuration int NOT NULL DEFAULT 180
                                    CHECK (StoreForwardDuration BETWEEN 0 AND 3600 OR StoreForwardDuration = -1),
        AutonomousStartupTimeout int NOT NULL DEFAULT 60
                                    CHECK (AutonomousStartupTimeout >= 1),
        BufferCount          int NOT NULL DEFAULT 128
                                    CHECK (BufferCount >= 1),
        FileChunkSize        int NOT NULL DEFAULT 65536
                                    CHECK (FileChunkSize >= 256),
        ForwardingDelay      int NOT NULL DEFAULT 0
                                    CHECK (ForwardingDelay >= 0),
        ConnectionTimeout    int NOT NULL DEFAULT 60
                                    CHECK (ConnectionTimeout >= 1),
        PRIMARY KEY (IODriverKey, StorageNodeKey)
 )
go
 
 CREATE INDEX XIF63IODriver ON IODriver
 (
        StorageNodeKey
 )
go
 
 grant SELECT on IODriver to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  IODriver to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  IODriver to aaAdministrators
go
 
 
 CREATE TABLE IOServer (
        IOServerKey          int IDENTITY,
        StorageNodeKey       int NOT NULL,
        IODriverKey          int NULL,
        ApplicationName      nvarchar(32) NULL,
        Path                 nvarchar(255) NULL,
        ComputerName         nvarchar(255) NULL DEFAULT '',
        AltComputerName      nvarchar(255) NULL DEFAULT '',
        AutoStart            bit NOT NULL DEFAULT 0,
        ExeType              int NOT NULL DEFAULT 0,
        InitializationStatus tinyint NOT NULL DEFAULT 0,
        ProtocolType         tinyint NOT NULL DEFAULT 2,
        Description          nvarchar(50) NULL DEFAULT '',
        Status               tinyint NULL DEFAULT 1,
        PRIMARY KEY (IOServerKey, StorageNodeKey)
 )
go
 
 CREATE INDEX XIF26IOServer ON IOServer
 (
        ApplicationName
 )
go
 
 CREATE INDEX XIF62IOServer ON IOServer
 (
        StorageNodeKey,
        IODriverKey
 )
go
 
 grant SELECT on IOServer to aaUsers
go
grant SELECT on  IOServer to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  IOServer to aaAdministrators
go
 
 
 CREATE TABLE IOServerType (
        ApplicationName      nvarchar(32) NOT NULL,
        Description          nvarchar(50) NULL,
        ExeName              nvarchar(255) NULL,
        Revision             nchar(20) NULL,
        Platform             Platforms,
        PRIMARY KEY (ApplicationName)
 )
go
 
 grant SELECT on IOServerType to aaUsers
go
grant SELECT on  IOServerType to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  IOServerType to aaAdministrators
go
 
 
 CREATE TABLE Limit (
        TagName              nvarchar(256) NOT NULL,
        ContextKey           int NOT NULL,
        LimitType            tinyint NOT NULL,
        Value                float(25) NOT NULL,
        LimitNameKey         int NOT NULL,
        Priority             int NOT NULL DEFAULT 0,
        Checked              bit NOT NULL,
        Description          nvarchar(50) NULL,
        PRIMARY KEY (TagName, ContextKey, LimitType, Value, 
               LimitNameKey)
 )
go
 
 CREATE INDEX XIF18Limit ON Limit
 (
        TagName
 )
go
 
 CREATE INDEX XIF22Limit ON Limit
 (
        ContextKey
 )
go
 
 CREATE INDEX XIF27Limit ON Limit
 (
        LimitNameKey
 )
go
 
 grant SELECT on Limit to aaUsers
go
grant SELECT on  Limit to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Limit to aaAdministrators
go
 
 
 CREATE TABLE LimitName (
        LimitNameKey         int IDENTITY,
        Name                 nvarchar(20) NULL,
        PRIMARY KEY (LimitNameKey)
 )
go
 
 CREATE UNIQUE INDEX XAK2LimitName ON LimitName
 (
        Name
 )
go
 
 grant SELECT on LimitName to aaUsers
go
grant SELECT on  LimitName to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  LimitName to aaAdministrators
go
 
 
 CREATE TABLE Live_OLEDB (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                float(25) NULL,
        vValue               sql_variant NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        OPCQuality           int NULL,
        wwTagKey             int NOT NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwValueDeadband      float(25) NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 grant SELECT on Live_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE LocalizedText (
        TextKey              int NOT NULL,
        LanguageID           int NOT NULL,
        LocalizedText        nvarchar(256) NULL,
        PRIMARY KEY (TextKey, LanguageID)
 )
go
 
 grant SELECT on LocalizedText to aaUsers
go
grant SELECT on  LocalizedText to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  LocalizedText to aaAdministrators
go
 
 
 CREATE TABLE ManualAnalogHistory (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                float(25) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        wwTagKey             int NOT NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 CREATE INDEX XIF54ManualAnalogHistory ON ManualAnalogHistory
 (
        TagName
 )
go
 
 grant SELECT on ManualAnalogHistory to aaUsers
go
grant SELECT on  ManualAnalogHistory to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ManualAnalogHistory to aaAdministrators
go
 
 
 CREATE TABLE ManualDiscreteHistory (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                tinyint NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        wwTagKey             int NOT NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 CREATE INDEX XIF55ManualDiscreteHistory ON ManualDiscreteHistory
 (
        TagName
 )
go
 
 grant SELECT on ManualDiscreteHistory to aaUsers
go
grant SELECT on  ManualDiscreteHistory to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ManualDiscreteHistory to aaAdministrators
go
 
 
 CREATE TABLE ManualStringHistory (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                nvarchar(512) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        wwTagKey             int NOT NULL,
        PRIMARY KEY NONCLUSTERED (DateTime, TagName)
 )
go
 
 CREATE INDEX XIF66ManualStringHistory ON ManualStringHistory
 (
        TagName
 )
go
 
 grant SELECT on ManualStringHistory to aaUsers
go
grant SELECT on  ManualStringHistory to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ManualStringHistory to aaAdministrators
go
 
 
 CREATE TABLE Message (
        MessageKey           int IDENTITY,
        Message0             nvarchar(64) NULL DEFAULT '',
        Message1             nvarchar(64) NULL DEFAULT '',
        PRIMARY KEY (MessageKey)
 )
go
 
 grant SELECT on Message to aaUsers
go
grant SELECT on  Message to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Message to aaAdministrators
go
 
 
 CREATE TABLE ModLogColumn (
        ModTableKey          int NOT NULL,
        ColumnName           varchar(30) NOT NULL,
        OldValue             sql_variant NULL DEFAULT 'N/A',
        NewValue             sql_variant NULL DEFAULT 'N/A',
        PRIMARY KEY (ModTableKey, ColumnName)
 )
go
 
 CREATE INDEX XIF74ModLogColumn ON ModLogColumn
 (
        ModTableKey
 )
go
 
 grant SELECT on ModLogColumn to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ModLogColumn to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ModLogColumn to aaAdministrators
go
 
 
 CREATE TABLE ModLogTable (
        ModTableKey          int IDENTITY,
        id                   int NOT NULL,
        ModType              char(1) NOT NULL,
        RowKey               sql_variant NOT NULL,
        UserKey              int NOT NULL,
        DateTime             datetime NOT NULL,
        UserName             nvarchar(256) NOT NULL,
        PRIMARY KEY (ModTableKey)
 )
go
 
 CREATE INDEX XIF73ModLogTable ON ModLogTable
 (
        id
 )
go
 
 grant SELECT on ModLogTable to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ModLogTable to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ModLogTable to aaAdministrators
go
 
 
 CREATE TABLE NameSpaceIcons (
        Type                 int NOT NULL,
        Icon                 image NULL,
        Name                 nvarchar(30) NOT NULL,
        Description          nvarchar(50) NULL,
        PRIMARY KEY (Type)
 )
go
 
 grant SELECT on NameSpaceIcons to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  NameSpaceIcons to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  NameSpaceIcons to aaAdministrators
go
 
 
 CREATE TABLE OPCQualityMap (
        OPCQuality           tinyint NOT NULL,
        Description          nvarchar(100) NULL,
        PRIMARY KEY (OPCQuality)
 )
go
 
 grant SELECT on OPCQualityMap to aaUsers
go
grant SELECT on  OPCQualityMap to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  OPCQualityMap to aaAdministrators
go
 
 
 CREATE TABLE PrivateGroupTag (
        NameKey              int NOT NULL,
        UserKey              int NOT NULL,
        wwDomainTagKey       int NOT NULL,
        PRIMARY KEY (NameKey, UserKey, wwDomainTagKey)
 )
go
 
 CREATE INDEX XIF19PrivateGroupTag ON PrivateGroupTag
 (
        NameKey,
        UserKey
 )
go
 
 CREATE INDEX XIF21PrivateGroupTag ON PrivateGroupTag
 (
        wwDomainTagKey
 )
go
 
 grant SELECT on PrivateGroupTag to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  PrivateGroupTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  PrivateGroupTag to aaAdministrators
go
 
 
 CREATE TABLE PrivateNameSpace (
        UserKey              int NOT NULL,
        NameKey              int IDENTITY,
        Type                 int NULL,
        Name                 nvarchar(255) NULL,
        ConfigStor           ntext NULL,
        ParentKey            int NOT NULL,
        PRIMARY KEY (UserKey, NameKey)
 )
go
 
 CREATE INDEX XIF14PrivateNameSpace ON PrivateNameSpace
 (
        UserKey,
        ParentKey
 )
go
 
 CREATE INDEX XIF39PrivateNameSpace ON PrivateNameSpace
 (
        UserKey
 )
go
 
 grant SELECT on PrivateNameSpace to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  PrivateNameSpace to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  PrivateNameSpace to aaAdministrators
go
 
 
 CREATE TABLE PublicGroupTag (
        NameKey              int NOT NULL,
        wwDomainTagKey       int NOT NULL,
        PRIMARY KEY (NameKey, wwDomainTagKey)
 )
go
 
 CREATE INDEX XIF34PublicGroupTag ON PublicGroupTag
 (
        wwDomainTagKey
 )
go
 
 CREATE INDEX XIF35PublicGroupTag ON PublicGroupTag
 (
        NameKey
 )
go
 
 grant SELECT on PublicGroupTag to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  PublicGroupTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  PublicGroupTag to aaAdministrators
go
 
 
 CREATE TABLE PublicNameSpace (
        NameKey              int IDENTITY,
        Type                 int NULL,
        Name                 nvarchar(255) NULL,
        ConfigStor           ntext NULL,
        ParentKey            int NOT NULL,
        PRIMARY KEY (NameKey)
 )
go
 
 CREATE INDEX XIF36PublicNameSpace ON PublicNameSpace
 (
        ParentKey
 )
go
 
 grant SELECT on PublicNameSpace to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  PublicNameSpace to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  PublicNameSpace to aaAdministrators
go
 
 
 CREATE TABLE QualityMap (
        QualityDetail        int NOT NULL,
        QualityString        nvarchar(200) NULL,
        PRIMARY KEY (QualityDetail)
 )
go
 
 grant SELECT on QualityMap to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  QualityMap to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  QualityMap to aaAdministrators
go
 
 
 CREATE TABLE RateOfChange (
        TagName              nvarchar(256) NOT NULL,
        ContextKey           int NOT NULL,
        Value                float(25) NOT NULL,
        TimeBase             int NOT NULL,
        Priority             int NOT NULL DEFAULT 0,
        Checked              bit NOT NULL DEFAULT 0,
        PRIMARY KEY (TagName, ContextKey)
 )
go
 
 CREATE INDEX XIF47RateOfChange ON RateOfChange
 (
        TagName
 )
go
 
 CREATE INDEX XIF48RateOfChange ON RateOfChange
 (
        ContextKey
 )
go
 
 grant SELECT on RateOfChange to aaUsers
go
grant SELECT on  RateOfChange to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  RateOfChange to aaAdministrators
go
 
 
 CREATE TABLE ServerList (
        ServerKey            int IDENTITY,
        ComputerName         nvarchar(50) NOT NULL DEFAULT 'UnNamed',
        Description          nvarchar(50) NULL,
        PRIMARY KEY (ServerKey)
 )
go
 
 grant SELECT on ServerList to aaUsers
go
grant SELECT on  ServerList to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  ServerList to aaAdministrators
go
 
 
 CREATE TABLE SnapshotDetail (
        StorageSize          int NOT NULL,
        SnapshotSize         int NOT NULL DEFAULT 2097152
                                    CHECK (SnapshotSize >= 0),
        ImageTime            int NOT NULL DEFAULT 30
                                    CHECK (ImageTime >= 0),
        ThresholdTime        int NOT NULL DEFAULT 3600
                                    CHECK (ThresholdTime >= 0),
        Status               tinyint NULL DEFAULT 0,
        PRIMARY KEY (StorageSize)
 )
go
 
 grant SELECT on SnapshotDetail to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SnapshotDetail to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SnapshotDetail to aaAdministrators
go
 
 
 CREATE TABLE SnapshotTag (
        SnapshotTagKey       int IDENTITY,
        TagName              nvarchar(256) NOT NULL,
        EventTagName         nvarchar(256) NOT NULL,
        TagType              int NOT NULL DEFAULT 1
                                    CHECK (TagType IN (1,2,3,4,5,7,9)),
        PRIMARY KEY (SnapshotTagKey)
 )
go
 
 CREATE INDEX XIF43SnapshotTag ON SnapshotTag
 (
        EventTagName
 )
go
 
 CREATE INDEX XIF6SnapshotTag ON SnapshotTag
 (
        TagName
 )
go
 
 grant SELECT on SnapshotTag to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SnapshotTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SnapshotTag to aaAdministrators
go
 
 
 CREATE TABLE SQLTemplate (
        TemplateKey          int IDENTITY,
        Description          nvarchar(50) NULL,
        Type                 int NULL,
        Script               ntext NULL,
        PRIMARY KEY (TemplateKey)
 )
go
 
 grant SELECT on SQLTemplate to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SQLTemplate to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SQLTemplate to aaAdministrators
go
 
 
 CREATE TABLE StateWideHistory_OLEDB (
        DateTime             datetime NOT NULL,
        vValue               sql_variant NULL,
        Tag1                 float(25) NULL,
        Tag2                 float(25) NULL,
        ManyOtherTags        float(25) NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwValueDeadband      float(25) NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwQualityRule        nvarchar(20) NULL,
        wwStateCalc          nvarchar(20) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime)
 )
go
 
 grant SELECT on StateWideHistory_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE StorageLocation (
        StorageType          int NOT NULL DEFAULT 0
                                    CHECK NOT FOR REPLICATION (StorageType BETWEEN 1 AND 4),
        SortOrder            int NOT NULL,
        StorageNodeKey       int NOT NULL,
        Path                 nvarchar(255) NOT NULL,
        MaxMBSize            int NOT NULL DEFAULT 0
                                    CHECK (MaxMBSize >= 0),
        MinMBThreshold       int NOT NULL
                                    CHECK (MinMBThreshold >= 0),
        Status               tinyint NULL DEFAULT 0,
        MaxAgeThreshold      int NOT NULL DEFAULT 0
                                    CHECK (MaxAgeThreshold >= 2
                                                OR MaxAgeThreshold = 0),
        PRIMARY KEY (StorageType, SortOrder, StorageNodeKey)
 )
go
 
 CREATE INDEX XIF17StorageLocation ON StorageLocation
 (
        StorageNodeKey
 )
go
 
 grant SELECT on StorageLocation to aaUsers
go
grant SELECT on  StorageLocation to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  StorageLocation to aaAdministrators
go
 
 
 CREATE TABLE StorageNode (
        StorageNodeKey       int IDENTITY,
        ComputerName         nvarchar(255) NOT NULL DEFAULT 'UnNamed',
        Description          nvarchar(50) NULL,
        DbStatus             int NOT NULL DEFAULT 0,
        DbModAcquisition     int NOT NULL DEFAULT 0,
        DbError              varchar(255) NULL,
        DbModStorage         int NOT NULL DEFAULT 0,
        DbModServer          int NOT NULL DEFAULT 0,
        DbModAll             int NOT NULL DEFAULT 0,
        DbRevision           int NOT NULL DEFAULT 0,
        PRIMARY KEY (StorageNodeKey)
 )
go
 
 grant SELECT on StorageNode to aaUsers
go
grant SELECT on  StorageNode to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  StorageNode to aaAdministrators
go
 
 
 CREATE TABLE StringHistory_OLEDB (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                nvarchar(512) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        OPCQuality           int NULL,
        wwTagKey             int NOT NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwEdgeDetection      nvarchar(20) NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 grant SELECT on StringHistory_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE StringLive_OLEDB (
        DateTime             datetime NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Value                nvarchar(512) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        OPCQuality           int NULL,
        wwTagKey             int NOT NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime, TagName)
 )
go
 
 grant SELECT on StringLive_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE StringSnapshot (
        SnapshotTagKey       int NOT NULL,
        EventLogKey          int NOT NULL,
        Value                nvarchar(512) NULL,
        Quality              tinyint NOT NULL,
        QualityDetail        int NULL,
        PRIMARY KEY (SnapshotTagKey, EventLogKey)
 )
go
 
 CREATE INDEX XIF56StringSnapshot ON StringSnapshot
 (
        SnapshotTagKey
 )
go
 
 CREATE INDEX XIF57StringSnapshot ON StringSnapshot
 (
        EventLogKey
 )
go
 
 grant SELECT on StringSnapshot to aaUsers
go
grant SELECT on  StringSnapshot to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  StringSnapshot to aaAdministrators
go
 
 
 CREATE TABLE StringTag (
        TagName              nvarchar(256) NOT NULL,
        MaxLength            smallint NOT NULL DEFAULT 131
                                    CHECK (MaxLength IN (8, 16, 24, 32, 48, 64, 128, 131, 256, 512)),
        InitialValue         nvarchar(512) NOT NULL DEFAULT '',
        DoubleByte           tinyint NOT NULL DEFAULT 0
                                    CHECK (DoubleByte IN (0, 1)),
        PRIMARY KEY (TagName)
 )
go
 
 grant SELECT on StringTag to aaUsers
go
grant SELECT on  StringTag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  StringTag to aaAdministrators
go
 
 
 CREATE TABLE StringWideHistory_OLEDB (
        DateTime             datetime NOT NULL,
        TagS1                nvarchar(512) NULL,
        TagS2                nvarchar(512) NULL,
        ManyOtherTags        nvarchar(512) NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwEdgeDetection      nvarchar(20) NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime)
 )
go
 
 grant SELECT on StringWideHistory_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE SummaryData (
        LogKey               int NOT NULL,
        SumVarKey            int NOT NULL,
        Value                float(25) NULL,
        Quality              tinyint NOT NULL,
        Modified             int NOT NULL DEFAULT 0,
        PRIMARY KEY (LogKey, SumVarKey)
 )
go
 
 CREATE INDEX XIF10SummaryData ON SummaryData
 (
        LogKey
 )
go
 
 CREATE INDEX XIF12SummaryData ON SummaryData
 (
        SumVarKey
 )
go
 
 grant SELECT on SummaryData to aaUsers
go
grant SELECT on  SummaryData to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SummaryData to aaAdministrators
go
 
 
 CREATE TABLE SummaryHistory (
        LogKey               int IDENTITY,
        OperationKey         int NOT NULL,
        SummaryDate          datetime NOT NULL,
        SumDateTimeStamp     tinyint NULL,
        SumDateCalcType      varchar(3) NULL,
        SumDateDuration      real NULL,
        SumDateResolution    int NULL,
        Status               tinyint NOT NULL,
        OperationStart       datetime NULL,
        OperationEnd         datetime NULL,
        PRIMARY KEY (LogKey)
 )
go
 
 CREATE UNIQUE INDEX XAKSummaryHistory ON SummaryHistory
 (
        LogKey
 )
go
 
 CREATE INDEX XIF11SummaryHistory ON SummaryHistory
 (
        OperationKey
 )
go
 
 grant SELECT on SummaryHistory to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SummaryHistory to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SummaryHistory to aaAdministrators
go
 
 
 CREATE TABLE SummaryOperation (
        OperationKey         int IDENTITY,
        TagName              nvarchar(256) NOT NULL,
        CalcType             CalcTypes NOT NULL
                                    CHECK (CalcType IN ('AVG', 'SUM', 'MIN', 'MAX')),
        Description          nvarchar(50) NULL,
        Duration             real NOT NULL DEFAULT 3600,
        Resolution           int NOT NULL DEFAULT 1000,
        TimeStamp            tinyint NOT NULL DEFAULT 1
                                    CHECK (TimeStamp IN (0, 1)),
        Frequency            nvarchar(12) NULL DEFAULT NULL,
        SourceType           varchar(3) NULL DEFAULT 'DYN',
        PRIMARY KEY (OperationKey)
 )
go
 
 CREATE UNIQUE INDEX XAKSummaryOperation ON SummaryOperation
 (
        TagName,
        CalcType,
        Duration,
        Resolution,
        TimeStamp
 )
go
 
 CREATE INDEX XIF60SummaryOperation ON SummaryOperation
 (
        TagName
 )
go
 
 CREATE INDEX XIF8SummaryOperation ON SummaryOperation
 (
        CalcType
 )
go
 
 grant SELECT on SummaryOperation to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SummaryOperation to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SummaryOperation to aaAdministrators
go
 
 
 CREATE TABLE SummaryTagList (
        SumVarKey            int IDENTITY,
        TagName              nvarchar(256) NOT NULL,
        OperationKey         int NOT NULL,
        LowerLimit           float(25) NULL DEFAULT -9999999,
        UpperLimit           float(25) NULL DEFAULT 9999999,
        Description          nvarchar(50) NULL,
        PRIMARY KEY (SumVarKey)
 )
go
 
 CREATE UNIQUE INDEX XAK1SummaryTagList ON SummaryTagList
 (
        TagName,
        OperationKey
 )
go
 
 CREATE INDEX XIF13SummaryTagList ON SummaryTagList
 (
        TagName
 )
go
 
 CREATE INDEX XIF9SummaryTagList ON SummaryTagList
 (
        OperationKey
 )
go
 
 grant SELECT on SummaryTagList to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SummaryTagList to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SummaryTagList to aaAdministrators
go
 
 
 CREATE TABLE SystemParameter (
        Name                 nvarchar(50) NOT NULL,
        Value                sql_variant NULL,
        Editable             bit NOT NULL DEFAULT 0,
        Description          nvarchar(255) NULL,
        Status               tinyint NULL DEFAULT 0,
        PRIMARY KEY (Name)
 )
go
 
 grant SELECT on SystemParameter to aaUsers
go
grant SELECT on  SystemParameter to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  SystemParameter to aaAdministrators
go
 
 
 CREATE TABLE Tag (
        TagName              nvarchar(256) NOT NULL,
        IOServerKey          int NULL,
        StorageNodeKey       int NOT NULL,
        wwTagKey             int IDENTITY,
        TopicKey             int NULL,
        Description          nvarchar(512) NULL DEFAULT '',
        AcquisitionType      tinyint NOT NULL DEFAULT 1
                                    CHECK (AcquisitionType BETWEEN 0 AND 3),
        StorageType          smallint NOT NULL DEFAULT 2
                                    CHECK (StorageType IN (0, 1, 2, 3, 17, 18, 19)),
        AcquisitionRate      int NULL DEFAULT 0,
        StorageRate          int NOT NULL DEFAULT 10000
                                    CHECK (StorageRate IN (0, 1000, 2000, 3000, 5000, 6000, 10000, 15000, 30000, 60000, 120000, 180000, 300000, 360000, 600000, 900000, 1200000, 1800000, 3600000)),
        ItemName             nvarchar(256) NULL DEFAULT '',
        TagType              int NOT NULL
                                    CHECK (TagType IN (1,2,3,4,5,7,9)),
        TimeDeadband         int NULL DEFAULT 0
                                    CHECK (TimeDeadband >= 0),
        DateCreated          datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
        CreatedBy            nvarchar(256) NOT NULL DEFAULT SYSTEM_USER,
        CurrentEditor        int NULL DEFAULT 0,
        SamplesInActiveImage int NULL DEFAULT 0
                                    CHECK (SamplesInActiveImage >= 0),
        AIRetrievalMode      tinyint NULL DEFAULT 0
                                    CHECK (AIRetrievalMode IN (0, 1)),
        Status               tinyint NULL DEFAULT 1,
        CalculatedAISamples  int NULL DEFAULT 0
                                    CHECK (CalculatedAISamples >= 0),
        ServerTimeStamp      bit NOT NULL DEFAULT 0
                                    CHECK (ServerTimeStamp IN (0, 1)),
        DeadbandType         smallint NOT NULL DEFAULT 1
                                    CHECK (DeadbandType IN (1, 2)),
        CEVersion            tinyint NOT NULL DEFAULT 0,
        PRIMARY KEY (TagName)
 )
go
 
 CREATE UNIQUE INDEX Key_wwTagKey ON Tag
 (
        wwTagKey
 )
go
 
 CREATE UNIQUE INDEX XAK2Tag ON Tag
 (
        TagName,
        wwTagKey
 )
go
 
 CREATE INDEX XIF30Tag ON Tag
 (
        IOServerKey,
        StorageNodeKey,
        TopicKey
 )
go
 
 grant SELECT on Tag to aaUsers
go
grant SELECT on  Tag to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Tag to aaAdministrators
go
 
 
 CREATE TABLE TagGroup (
        GroupID              int NOT NULL,
        Description          nvarchar(50) NULL,
        CreatedDate          datetime NULL,
        CreatedBy            nchar(18) NULL,
        Type                 int NULL,
        PRIMARY KEY (GroupID)
 )
go
 
 grant SELECT on TagGroup to aaUsers
go
grant SELECT on  TagGroup to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TagGroup to aaAdministrators
go
 
 grant SELECT, UPDATE, INSERT, DELETE on TagGroup to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TagGroup to aaPowerUsers, aaAdministrators
go
 
 
 CREATE TABLE TagRef (
        wwDomainTagKey       int IDENTITY,
        wwTagKey             int NOT NULL,
        ServerKey            int NOT NULL,
        TagName              nvarchar(256) NULL,
        TagType              int NOT NULL,
        PRIMARY KEY (wwDomainTagKey)
 )
go
 
 CREATE UNIQUE INDEX XAK1TagRef ON TagRef
 (
        wwTagKey,
        wwDomainTagKey
 )
go
 
 CREATE INDEX XIF20TagRef ON TagRef
 (
        TagName
 )
go
 
 CREATE INDEX XIF42TagRef ON TagRef
 (
        ServerKey
 )
go
 
 grant SELECT on TagRef to aaUsers
go
grant SELECT on  TagRef to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TagRef to aaAdministrators
go
 
 
 CREATE TABLE TimeDetectorDetail (
        TimeDetectorDetailKey int IDENTITY,
        FrequencyID          int NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        Periodicity          int NULL DEFAULT 60
                                    CHECK (Periodicity >= 1),
        StartDateTime        datetime NULL DEFAULT CURRENT_TIMESTAMP,
        RunTimeDay           tinyint NULL DEFAULT 1
                                    CHECK (RunTimeDay BETWEEN 0 AND 31),
        RunTimeHour          tinyint NULL DEFAULT 0
                                    CHECK (RunTimeHour BETWEEN 0 AND 23),
        RunTimeMin           tinyint NULL DEFAULT 0
                                    CHECK (RunTimeMin BETWEEN 0 AND 59),
        PRIMARY KEY (TimeDetectorDetailKey)
 )
go
 
 CREATE INDEX XIF58TimeDetectorDetail ON TimeDetectorDetail
 (
        TagName
 )
go
 
 CREATE INDEX XIF59TimeDetectorDetail ON TimeDetectorDetail
 (
        FrequencyID
 )
go
 
 grant SELECT on TimeDetectorDetail to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TimeDetectorDetail to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TimeDetectorDetail to aaAdministrators
go
 
 
 CREATE TABLE TimeDetectorDetailPendingDelete (
        TagName              nvarchar(256) NOT NULL,
        FrequencyID          int NULL,
        Periodicity          int NULL,
        StartDateTime        datetime NULL,
        RunTimeDay           tinyint NULL,
        RunTimeHour          tinyint NULL,
        RunTimeMin           tinyint NULL,
        PRIMARY KEY (TagName)
 )
go
 
 grant SELECT on TimeDetectorDetailPendingDelete to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TimeDetectorDetailPendingDelete to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TimeDetectorDetailPendingDelete to aaAdministrators
go
 
 
 CREATE TABLE TimeZone (
        TimeZoneID           smallint NOT NULL,
        TimeZone             nvarchar(100) NULL DEFAULT '',
        Description          nvarchar(100) NULL DEFAULT '',
        Offset               smallint NOT NULL DEFAULT 0,
        RegistryName         nvarchar(100) NULL,
        PRIMARY KEY (TimeZoneID)
 )
go
 
 grant SELECT on TimeZone to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TimeZone to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TimeZone to aaAdministrators
go
 
 
 CREATE TABLE Topic (
        TopicKey             int IDENTITY,
        IOServerKey          int NOT NULL,
        StorageNodeKey       int NOT NULL,
        Name                 nvarchar(180) NOT NULL,
        TimeOut              int NOT NULL DEFAULT 60000
                                    CHECK (TimeOut >= 500
                                                OR TimeOut = 0),
        Status               tinyint NULL DEFAULT 1,
        LateData             bit NOT NULL DEFAULT 0
                                    CHECK (LateData IN (0, 1)),
        IdleDuration         int NOT NULL DEFAULT 60
                                    CHECK (IdleDuration >= 60),
        ProcessingInterval   int NOT NULL DEFAULT 120
                                    CHECK (ProcessingInterval >= 60),
        PRIMARY KEY (TopicKey, IOServerKey, StorageNodeKey)
 )
go
 
 CREATE INDEX XIF25Topic ON Topic
 (
        IOServerKey,
        StorageNodeKey
 )
go
 
 grant SELECT on Topic to aaUsers
go
grant SELECT on  Topic to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  Topic to aaAdministrators
go
 
 
 CREATE TABLE TopicImportInfo (
        NodeKey              int NOT NULL,
        DdeSourceKey         int NOT NULL,
        SourceName           nchar(50) NOT NULL DEFAULT '',
        ApplicationName      nchar(50) NULL,
        TopicName            nchar(50) NOT NULL DEFAULT '',
        RequestInitialData   bit NOT NULL DEFAULT 0,
        AlwaysAdvise         bit NOT NULL DEFAULT 0,
        DefaultStorageRate   int NOT NULL DEFAULT 0,
        DefaultStorageType   int NOT NULL DEFAULT 1,
        TimeDeadband         int NOT NULL DEFAULT 0,
        ValueDeadband        float(25) NOT NULL DEFAULT 0,
        DeadbandType         tinyint NULL,
        Import               bit NOT NULL DEFAULT 1,
        ProtocolType         tinyint NOT NULL DEFAULT 2,
        IODriverKey          int NULL,
        RateDeadband         float(25) NOT NULL DEFAULT 0,
        PRIMARY KEY (NodeKey, DdeSourceKey)
 )
go
 
 CREATE INDEX XIF49TopicImportInfo ON TopicImportInfo
 (
        NodeKey
 )
go
 
 grant SELECT on TopicImportInfo to aaUsers
go
grant SELECT on  TopicImportInfo to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  TopicImportInfo to aaAdministrators
go
 
 
 CREATE TABLE UserDetail (
        UserKey              int NOT NULL,
        UserName             nvarchar(128) NOT NULL,
        AccessLevel          int NOT NULL DEFAULT 1,
        uid                  int NOT NULL,
        gid                  int NOT NULL,
        PRIMARY KEY (UserKey)
 )
go
 
 grant SELECT on UserDetail to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  UserDetail to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  UserDetail to aaAdministrators
go
 
 
 CREATE TABLE WideHistory_OLEDB (
        DateTime             datetime NOT NULL,
        Tag1                 sql_variant NULL,
        Tag2                 sql_variant NULL,
        ManyOtherTags        sql_variant NULL,
        wwRowCount           int NULL,
        wwResolution         int NULL,
        wwEdgeDetection      nvarchar(20) NULL,
        wwRetrievalMode      nvarchar(20) NULL,
        wwTimeDeadband       int NULL,
        wwValueDeadband      float(25) NULL,
        wwTimeZone           nvarchar(50) NULL,
        wwVersion            nvarchar(30) NULL,
        wwCycleCount         int NULL,
        wwTimeStampRule      nvarchar(20) NULL,
        wwInterpolationType  nvarchar(20) NULL,
        wwQualityRule        nvarchar(20) NULL,
        wwParameters         nvarchar(128) NULL,
        PRIMARY KEY (DateTime)
 )
go
 
 grant SELECT on WideHistory_OLEDB to aaUsers, aaPowerUsers, aaAdministrators
 
 
 CREATE TABLE WideTableDictionary (
        UserKey              int NOT NULL,
        TagName              nvarchar(256) NOT NULL,
        PRIMARY KEY (UserKey, TagName)
 )
go
 
 CREATE INDEX XIF23WideTableDictionary ON WideTableDictionary
 (
        UserKey
 )
go
 
 CREATE INDEX XIF37WideTableDictionary ON WideTableDictionary
 (
        TagName
 )
go
 
 grant SELECT on WideTableDictionary to aaUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  WideTableDictionary to aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  WideTableDictionary to aaAdministrators
go
 
 
 /**********  aaActionStringSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaActionStringSelect'))
  DROP PROCEDURE dbo.aaActionStringSelect
GO

CREATE PROCEDURE aaActionStringSelect
  @TagName nvarchar(256)

AS
BEGIN
  select ActionString from EventTag where TagName = @TagName
END
GO

GRANT EXEC ON aaActionStringSelect TO aaAdministrators
go
 
 /**********  aaAddTag  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAddTag'))
  DROP PROCEDURE dbo.aaAddTag
GO

CREATE procedure aaAddTag 
   @wTagName         nvarchar(256),
   @wTopicKey        int        ,
   @wIOServerKey     int        ,
   @wStorageNodeKey  int        ,
   @wDescription     nvarchar(512),
   @wAcquisitionType tinyint        ,
   @wStorageType     smallint        ,
   @wAcquisitionRate int        ,
   @wStorageRate     int        ,
   @wItemName        nvarchar(256),
   @wTagType         int        ,
   @wTimeDeadband    int,
   @wCurrentEditor   int           

AS
   INSERT Tag (TagName, TopicKey, IOServerKey, StorageNodeKey, Description,
               AcquisitionType, StorageType, AcquisitionRate, StorageRate,
               ItemName, TagType, TimeDeadband, CurrentEditor)
      VALUES (@wTagName, @wTopicKey, @wIOServerKey, @wStorageNodeKey, @wDescription,
              @wAcquisitionType, @wStorageType, @wAcquisitionRate, @wStorageRate,
              @wItemName, @wTagType,  @wTimeDeadband, @wCurrentEditor)
     RETURN  SCOPE_IDENTITY()
GO

GRANT exec on aaAddTag to  aaAdministrators
go
GRANT exec on aaAddTag to  aaPowerUsers
go
 
 /**********  aaAnalogDetail  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnalogDetail'))
  DROP PROCEDURE dbo.aaAnalogDetail
GO

CREATE procedure aaAnalogDetail 
@TagList nvarchar(4000)
AS
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SELECT @TagList = @TagList + ','
  SET QUOTED_IDENTIFIER OFF
  SELECT @TempChar = ""
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SELECT @TempChar = @TempChar + (SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1)) + "','" 
    SELECT @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END;
  SELECT @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SELECT @SelectStatement = 
           'SELECT Tag.TagName, Tag.Description, Tag.AcquisitionRate, eu.Unit, at.MinEU, at.MaxEU, Tag.StorageRate '  + 
           'FROM Tag, EngineeringUnit eu, AnalogTag at ' +
           'WHERE Tag.TagName = at.TagName ' +
           'AND at.EUKey = eu.EUKey ' + 
           'AND Tag.TagName IN (''' + @TempChar + ''')' 
  EXECUTE( @SelectStatement )
GO

GRANT Exec on aaAnalogDetail to Public
go
 
 /**********  aaAnalogTagDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnalogTagDelete'))
  DROP PROCEDURE dbo.aaAnalogTagDelete
GO

CREATE procedure aaAnalogTagDelete 
  @wwTagKey int
AS
  DELETE FROM Tag
  WHERE  wwTagKey = @wwTagKey
GO

GRANT  EXEC  ON aaAnalogTagDelete  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaAnalogTagDelete  TO aaPowerUsers
go
 
 /**********  aaAnalogTagInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnalogTagInsert'))
  DROP PROCEDURE dbo.aaAnalogTagInsert
GO

CREATE procedure aaAnalogTagInsert 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @AcquisitionType tinyint      = 1,
  @StorageType     smallint     = 2,
  @StorageRate     int          = 10000,
  @ItemName        nvarchar(256) = '',
  @TimeDeadband    int          = 0,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime     = NULL,
  @CurrentEditor   int          = 0,
  @EUKey           int          = 1,
  @MinEU           float(25)    = 0,
  @MaxEU           float(25)    = 100,
  @MinRaw          float(25)    = 0,
  @MaxRaw          float(25)    = 4095,
  @Scaling         int          = 1,
  @RawType         int          = 3,
  @ValueDeadband   float(25)    = 0,
  @InitialValue    float(25)    = 0,
  @IntegerSize     tinyint      = 16,
  @SignedInteger   bit          = 0,
  @TopicKey        int          = NULL,
  @IOServerKey     int          = NULL,
  @StorageNodeKey  int          = 1,
  @AIRetrievalMode tinyint      = 0,
  @SamplesInActiveImage int     = 0,
  @RateDeadband    float(25)    = 0,
  @InterpolationType tinyint    = 254,
  @RolloverValue   int          = 0,
  @ServerTimeStamp bit          = 0,
  @DeadbandType    smallint     = 1
AS
BEGIN
  BEGIN TRAN

  DECLARE @result int

  SELECT @result = 0

  INSERT Tag
    (
    TagName, TopicKey, IOServerKey, StorageNodeKey, Description,
    AcquisitionType, StorageType, AcquisitionRate, StorageRate,
    ItemName, TagType, TimeDeadband, CurrentEditor, AIRetrievalMode,
    SamplesInActiveImage, ServerTimeStamp, DeadbandType
    )
  VALUES
    (
    RTRIM(@TagName), @TopicKey, @IOServerKey, 1, RTRIM(@Description),
    @AcquisitionType, @StorageType, 0, @StorageRate,
    RTRIM(@ItemName), 1, @TimeDeadband, @CurrentEditor, 
    @AIRetrievalMode, @SamplesInActiveImage, @ServerTimeStamp, @DeadbandType
    )

  IF @@Error = 0
  BEGIN
    INSERT AnalogTag
      (
      TagName, EUKey, MinEU, MaxEU, MinRaw, MaxRaw,
      Scaling, RawType, ValueDeadband, InitialValue,
      IntegerSize, SignedInteger, RateDeadband, InterpolationType,
      RolloverValue
      )
    VALUES
      (
      RTRIM(@TagName), @EUKey, @MinEU, @MaxEU, @MinRaw, @MaxRaw,
      @Scaling, @RawType, @ValueDeadband, @InitialValue, @IntegerSize,
      @SignedInteger, @RateDeadband, @InterpolationType, @RolloverValue
      )
  END

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
    SELECT @result = (SELECT wwTagKey from Tag where TagName = RTRIM(@TagName))
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @result = -1
  END

  RETURN @result
END
GO

GRANT exec on aaAnalogTagInsert to aaAdministrators
GO
GRANT exec on aaAnalogTagInsert to aaPowerUsers
go
 
 /**********  aaAnalogTagSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnalogTagSelect'))
  DROP PROCEDURE dbo.aaAnalogTagSelect
GO

CREATE procedure aaAnalogTagSelect 
  @wwTagKey int = NULL
AS
IF @wwTagKey IS NULL 
BEGIN 
  SELECT 
    Tag.wwTagKey wwTagKey,
    Tag.TagName TagName,
    Tag.Description Description,
    AcquisitionType,
    StorageType = 
    CASE StorageType
       WHEN 17 THEN 0
       WHEN 18 THEN 0
       WHEN 19 THEN 0
       ELSE StorageType
    END,
    StorageRate,
    ItemName,
    TimeDeadband,
    CreatedBy,
    DateCreated,
    CurrentEditor,
    EUKey,
    MinEU,
    MaxEU,
    MinRaw,
    MaxRaw,
    Scaling,
    RawType,
    ValueDeadband,
    InitialValue,
    IntegerSize,
    SignedInteger,
    TopicKey,
    IOServerKey,
    StorageNodeKey,
    AIRetrievalMode,
    SamplesInActiveImage,
    CalculatedAISamples,
    RateDeadband,
    InterpolationType=
       CASE InterpolationType
       WHEN 254 THEN 2
       ELSE InterpolationType
    END,
    RolloverValue,
    ServerTimeStamp,
    DeadbandType
  FROM
    Tag, AnalogTag
    WHERE
      Tag.TagName = AnalogTag.TagName
END
ELSE
BEGIN 
  SELECT 
    Tag.wwTagKey wwTagKey,
    Tag.TagName TagName,
    Tag.Description Description,
    AcquisitionType,
    StorageType = 
    CASE StorageType
       WHEN 17 THEN 0
       WHEN 18 THEN 0
       WHEN 19 THEN 0
       ELSE StorageType
    END,
    StorageRate,
    ItemName,
    TimeDeadband,
    CreatedBy,
    DateCreated,
    CurrentEditor,
    EUKey,
    MinEU,
    MaxEU,
    MinRaw,
    MaxRaw,
    Scaling,
    RawType,
    ValueDeadband,
    InitialValue,
    IntegerSize,
    SignedInteger,
    TopicKey,
    IOServerKey,
    StorageNodeKey,
    AIRetrievalMode,
    SamplesInActiveImage,
    CalculatedAISamples,
    RateDeadband,
    InterpolationType,
    RolloverValue,
    ServerTimeStamp,
    DeadbandType
  FROM
    Tag, AnalogTag 
    WHERE
      Tag.wwTagKey = @wwTagKey
      AND Tag.TagName = AnalogTag.TagName
END
GO

GRANT exec on aaAnalogTagSelect to Public
go
 
 /**********  aaAnalogTagUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnalogTagUpdate'))
  DROP PROCEDURE dbo.aaAnalogTagUpdate
GO

CREATE procedure aaAnalogTagUpdate 
  @wwTagKey        int, 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @AcquisitionType tinyint = 1,
  @StorageType     smallint,
  @StorageRate     int,
  @ItemName        nvarchar(256) = '',
  @TimeDeadband    int,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @CurrentEditor   int = NULL,
  @EUKey           int,
  @MinEU           float(25),
  @MaxEU           float(25),
  @MinRaw          float(25),
  @MaxRaw          float(25),
  @Scaling         int,
  @RawType         int,
  @ValueDeadband   float(25),
  @InitialValue    float(25),
  @IntegerSize     tinyint,
  @SignedInteger   bit,
  @TopicKey        int,
  @IOServerKey     int,
  @StorageNodeKey  int,
  @AIRetrievalMode tinyint,
  @SamplesInActiveImage int  = 0,
  @RateDeadband    float(25) = 0,
  @InterpolationType tinyint = 254,
  @RolloverValue   int       = 0,
  @ServerTimeStamp bit       = 0,
  @DeadbandType    smallint  = 1
 
AS
BEGIN
  /* This proc updates an analog tag based upon the tag key */
  /*   it is used by the configuration editor */
  
  BEGIN TRAN

  DECLARE @nTagName nvarchar(256)
  SELECT @nTagName = (SELECT TagName FROM Tag WHERE wwTagKey = @wwTagKey)
    
  UPDATE Tag 
  SET
    Description     = RTRIM(@Description),
    AcquisitionType = @AcquisitionType,
    StorageType     = @StorageType,
    StorageRate     = @StorageRate,
    ItemName        = RTRIM(@ItemName),
    TimeDeadband    = @TimeDeadband,
    TopicKey        = @TopicKey,
    IOServerKey     = @IOServerKey,
    CurrentEditor   = @CurrentEditor,
    AIRetrievalMode = @AIRetrievalMode,
    SamplesInActiveImage = @SamplesInActiveImage,
    ServerTimeStamp = @ServerTimeStamp,
    DeadbandType    = @DeadbandType 
  WHERE wwTagKey = @wwTagKey

  UPDATE AnalogTag
  SET
    EUKey         = @EUKey,
    MinEU         = @MinEU,
    MaxEU         = @MaxEU,
    MinRaw        = @MinRaw,
    MaxRaw        = @MaxRaw,
    Scaling       = @Scaling,
    RawType       = @RawType,                                                   
    ValueDeadband = @ValueDeadband,
    InitialValue  = @InitialValue,
    IntegerSize   = @IntegerSize,
    SignedInteger = @SignedInteger,
    RateDeadband  = @RateDeadband,
    InterpolationType = @InterpolationType,
    RolloverValue = @RolloverValue
  WHERE TagName = @nTagName

  COMMIT TRAN
END
GO

GRANT exec on aaAnalogTagUpdate to aaAdministrators
GO
GRANT exec on aaAnalogTagUpdate to aaPowerUsers
go
 
 /**********  aaInternalAnalogTagExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAnalogTagExport'))
  DROP PROCEDURE dbo.aaInternalAnalogTagExport
GO

CREATE procedure aaInternalAnalogTagExport 
  @Format int=0,
  @Filter nvarchar(256)='%',
  @AcquisitionType int=0,
  @StorageType int=0,
  @StorageRate int=0
AS
--****************************
-- Export AnalogTag
--****************************
declare @acq_type_lo int, @acq_type_hi int
declare @store_type_lo int, @store_type_hi int
declare @store_rate_lo int, @store_rate_hi int
declare @insql_name nvarchar(32)

select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList

set @acq_type_lo=CASE @AcquisitionType
 WHEN 0 THEN 0
 ELSE @AcquisitionType
 END
set @acq_type_hi=CASE @AcquisitionType
 WHEN 0 THEN 2
 ELSE @AcquisitionType
 END
set @store_type_lo=CASE @StorageType
 WHEN  0 THEN 0
 ELSE @StorageType
 END
set @store_type_hi=CASE @StorageType
 WHEN 0 THEN 18
 ELSE @StorageType
 END
set @store_rate_lo=CASE @StorageRate
 WHEN 0 THEN 0
 ELSE CASE @StorageType
  WHEN 1 THEN @StorageRate
  ELSE 0
  END
 END
set @store_rate_hi=CASE @StorageRate
 WHEN 0 THEN 3600000
 ELSE CASE @StorageType
  WHEN 1 THEN @StorageRate
  ELSE 3600000
  END
 END

SELECT [:(AnalogTag)TagName]=Tag.TagName, 
 [Description]=Tag.Description,
 [IOServerComputerName]=CASE LOWER(IOServer.ComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(IOServer.ComputerName)
 END,
 [IOServerAppName]=IOServer.ApplicationName,
 [TopicName]=Topic.Name,
 [ItemName]=ItemName,
 [AcquisitionType]=CASE AcquisitionType
  WHEN 0 THEN 'Not Acquired'
  WHEN 1 THEN 'IOServer'
  WHEN 2 THEN 'Manual'
  WHEN 3 THEN 'System'
  ELSE 'Unknown'
  END,
 [StorageType]=CASE StorageType
  WHEN 1 THEN 'Cyclic'
  WHEN 2 THEN 'Delta'
  WHEN 3 THEN 'Forced'
  ELSE 'Not Stored'
  END,
 [AcquisitionRate]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),AcquisitionRate))
  ELSE AcquisitionRate
  END,
 [StorageRate]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),StorageRate))
  ELSE StorageRate
  END,
 [TimeDeadband]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),TimeDeadband))
  ELSE TimeDeadband
  END,
 [SamplesInAI]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),SamplesInActiveImage))
  ELSE SamplesInActiveImage
  END,
 [AIMode]=CASE AIRetrievalMode
  WHEN 0 THEN 'All'
  ELSE 'Disk'
  END,
 [EngUnits]=EngineeringUnit.Unit,
 [MinEU]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(64),MinEU,2))
  ELSE MinEU
  END,
 [MaxEU]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(64),MaxEU,2))
  ELSE MaxEU
  END,
 [MinRaw]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(64),MinRaw,2))
  ELSE MinRaw
  END,
 [MaxRaw]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(64),MaxRaw,2))
  ELSE MaxRaw
  END,
 [Scaling]=CASE Scaling
  WHEN 0 THEN 'None'
  WHEN 1 THEN 'Linear'
  ELSE 'Nonlinear'
  END,
 [RawType]=CASE RawType
  WHEN 0 THEN 'Byte'
  WHEN 1 THEN 'EuroFloat'
  WHEN 2 THEN 'MSFloat'
  WHEN 3 THEN 'Integer'
  WHEN 4 THEN 'Double'
  WHEN 5 THEN 'Complex'
  WHEN 7 THEN 'FILETIME'
  WHEN 8 THEN 'ElapsedTime'
  ELSE 'Unknown'
  END,
 [IntegerSize]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),IntegerSize))
  ELSE IntegerSize
  END,
 [Sign]=CASE SignedInteger
  WHEN 0 THEN CASE RawType
   WHEN 0 THEN 'Unsigned'
   WHEN 3 THEN 'Unsigned'
   ELSE ''
   END 
  ELSE 'Signed'
  END,
 [ValueDeadband]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),ValueDeadband))
  ELSE ValueDeadband
  END,
 [InitialValue]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(64),InitialValue,2))
  ELSE InitialValue
  END,
 [CurrentEditor]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),CurrentEditor))
  ELSE CurrentEditor
  END,
 [RateDeadband]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),RateDeadband))
  ELSE RateDeadband
  END,
 [InterpolationType]=CASE InterpolationType
  WHEN 0 THEN 'Stair'
  WHEN 1 THEN 'Linear'
  WHEN 254 THEN 'System Default'
  ELSE 'None'
  END,
 [RolloverValue]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),RolloverValue))
  ELSE RolloverValue
  END,
 [ServerTimeStamp]=CASE ServerTimeStamp
  WHEN 1 THEN 'Yes'
  ELSE 'No'
  END,
 [DeadbandType]=CASE DeadbandType
  WHEN 2 THEN 'Rate'
  ELSE 'TimeValue'
  END
FROM Tag, AnalogTag, IOServer, Topic, EngineeringUnit
WHERE AnalogTag.TagName=Tag.TagName
AND EngineeringUnit.EUKey=AnalogTag.EUKey
AND IOServer.IOServerKey=Tag.IOServerKey
AND Topic.IOServerKey=IOServer.IOServerKey
AND Topic.TopicKey=Tag.TopicKey
AND TagType=1
AND Tag.TagName like @Filter
AND AcquisitionType between @acq_type_lo AND @acq_type_hi
AND StorageType between @store_type_lo AND @store_type_hi
AND StorageRate between @store_rate_lo AND @store_rate_hi
AND CurrentEditor != 2

if @@ERROR <> 0
begin
   goto error
end

return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50003
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='AnalogTag export failed'
end
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalAnalogTagExport to aaAdministrators
go
 
 /**********  aaInternalAnalogTagImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAnalogTagImport'))
  DROP PROCEDURE dbo.aaInternalAnalogTagImport
GO

CREATE procedure aaInternalAnalogTagImport 
  @Mode nvarchar(32)='update',
  @TagName nvarchar(256),
  @Description nvarchar(512),
  @ComputerName nvarchar(256),
  @ApplicationName nvarchar(64),
  @TopicName nvarchar(80),
  @ItemName nvarchar(256),
  @AcquisitionType nvarchar(16),
  @StorageType nvarchar(16),
  @AcquisitionRate nvarchar(32),
  @StorageRate nvarchar(32),
  @TimeDeadband nvarchar(16),
  @SamplesInAI nvarchar(16),
  @AIMode nvarchar(16),
  @Unit nvarchar(32),
  @MinEU nvarchar(64),
  @MaxEU nvarchar(64),
  @MinRaw nvarchar(64),
  @MaxRaw nvarchar(64),
  @Scaling nvarchar(16),
  @RawType nvarchar(16),
  @IntegerSize nvarchar(16),
  @Sign nvarchar(16),
  @ValueDeadband nvarchar(64),
  @InitialValue nvarchar(64),
  @CurrentEditor nvarchar(16)='0',
  @RateDeadband nvarchar(16)='0',
  @InterpolationType nvarchar(16)='System Default',
  @RolloverValue nvarchar(16)='0',
  @ServerTimeStamp nvarchar(8)='No',
  @DeadbandType nvarchar(16)='TimeValue'
AS
--*****************************
-- Import AnalogTag
--*****************************
declare @key int, @storagenode_key int, @ios_key int, @topic_key int, @eu_key int
declare @acq_type tinyint, @store_type smallint, @raw_type int, @cur_edit int
declare @store_rate int, @timedb int, @created_by nvarchar(30), @date_created datetime
declare @ai_samples int, @ai_mode tinyint, @int_size tinyint
declare @min_eu float, @max_eu float, @min_raw float, @max_raw float
declare @valuedb float, @init_value float, @scaling_type int, @signed bit
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)
declare @insql_name nvarchar(32)
declare @ratedb float, @interp_type tinyint, @rollover_value int
declare @server_timestamp bit
declare @deadband_type smallint

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

if len(@TagName) = 0
 BEGIN
 set @errno=50304
 set @errmsg_default='AnalogTag import failed (an empty TagName is not allowed)'
 goto error
 END

select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList
set @ComputerName=LTRIM(RTRIM(LOWER(@ComputerName)))
if @ComputerName='$local'
BEGIN
 set @ComputerName=@insql_name
END

-- Convert parameters into expected types and resolve text
-- representations of numerical fields

set @store_rate=CONVERT(int, @StorageRate)
set @timedb=CONVERT(int, @TimeDeadband)
set @created_by=null
set @date_created=getdate()
set @ai_samples=CONVERT(int, @SamplesInAI)
set @valuedb=CONVERT(float, @ValueDeadband)
set @min_eu=CONVERT(float, @MinEU)
set @max_eu=CONVERT(float, @MaxEU)
set @min_raw=CONVERT(float, @MinRaw)
set @max_raw=CONVERT(float, @MaxRaw)
set @init_value=CONVERT(float, @InitialValue)
set @int_size=CONVERT(float, @IntegerSize)
set @ratedb=CONVERT(float, @RateDeadband)
set @rollover_value=CONVERT(int, @RolloverValue)

set @ai_mode=CASE LTRIM(RTRIM(LOWER(@AIMode)))
 WHEN 'all' THEN 0
 ELSE 1
 END
set @acq_type=CASE LTRIM(RTRIM(LOWER(@AcquisitionType)))
 WHEN 'ioserver' THEN 1
 WHEN 'manual' THEN 2
 ELSE 0
 END
set @store_type=CASE LTRIM(RTRIM(LOWER(@StorageType)))
 WHEN 'cyclic' THEN 1
 WHEN 'delta' THEN 2
 WHEN 'forced' THEN 3
 ELSE 0
 END
set @scaling_type=CASE LTRIM(RTRIM(LOWER(@Scaling)))
 WHEN 'none' THEN 0
 WHEN 'linear' THEN 1
 WHEN 'nonlinear' THEN 2
 ELSE 0
 END
set @raw_type=CASE LTRIM(RTRIM(LOWER(@RawType)))
 WHEN 'byte' THEN 0
 WHEN 'eurofloat' THEN 1
 WHEN 'msfloat' THEN 2
 WHEN 'integer' THEN 3
 WHEN 'double' THEN 4
 WHEN 'complex' THEN 5
 WHEN 'filetime' THEN 7
 WHEN 'elapsedtime' THEN 8
 ELSE 3
 END
set @signed=CASE LTRIM(RTRIM(LOWER(@Sign)))
 WHEN 'signed' THEN 1
 ELSE 0
 END
set @interp_type=CASE LTRIM(RTRIM(LOWER(@InterpolationType)))
 WHEN 'stair' THEN 0
 WHEN 'linear' THEN 1
 WHEN 'system default' THEN 254
 ELSE 0
 END
set @server_timestamp=CASE LTRIM(RTRIM(LOWER(@ServerTimeStamp)))
 WHEN 'yes' THEN 1
 ELSE 0
 END
set @deadband_type=CASE LTRIM(RTRIM(LOWER(@DeadbandType)))
 WHEN 'rate' THEN 2
 ELSE 1
 END

-- Check if the tag exists by getting its tagkey

select @key=wwTagKey from Tag where TagName=@TagName and TagType=1

SET @cur_edit = CONVERT(int, @CurrentEditor)

-- If this is a delete, do it if the tag exists, otherwise
-- return an error to the caller.

if @Mode='delete'
BEGIN
if @key is null
 BEGIN
 return
 END
else
 BEGIN
 exec aaAnalogTagDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50121
  set @errmsg_default='AnalogTag import failed (delete failed)'
  goto error
  END
 return
 END
END

-- If this is insert only (no update), and the tag already 
-- exists, we don't need to do anything more.

if (@Mode='insert') AND (@key is not null)
return

-- We need to check the relational integrity to proceed
-- beyond this point. All objects that this tag depends
-- on must already exist, otherwise we return an error.

select TOP 1 @eu_key=EUKey 
From EngineeringUnit
where Unit=@Unit

if @eu_key is null
BEGIN
set @errno=50122
set @errmsg_default='AnalogTag import failed (engineering unit does not exist)'
goto error
END

select @ios_key=IOServerKey 
from IOServer 
where LTRIM(RTRIM(LOWER(ComputerName)))=LTRIM(RTRIM(LOWER(@ComputerName)))
AND LTRIM(RTRIM(LOWER(ApplicationName)))=LTRIM(RTRIM(LOWER(@ApplicationName)))

if @ios_key is null
BEGIN
set @errno=50123
set @errmsg_default='AnalogTag import failed (IOServer does not exist)'
goto error
END

select @topic_key=TopicKey 
From Topic
where IOServerKey=@ios_key
and Name=@TopicName

if @topic_key is null
BEGIN
set @errno=50124
set @errmsg_default='AnalogTag import failed (topic does not exist)'
goto error
END

-- Parent objects are all OK, update or insert the tag.

if @key is null
BEGIN
exec aaAnalogTagInsert
 @TagName,
 @Description,
 @acq_type,
 @store_type,
 @store_rate,
 @ItemName,
 @timedb,
 @created_by,
 @date_created,
 @cur_edit,
 @eu_key,
 @min_eu,
 @max_eu,
 @min_raw,
 @max_raw,
 @scaling_type,
 @raw_type,
 @valuedb,
 @init_value,
 @int_size,
 @signed,
 @topic_key,
 @ios_key,
 1,
 @ai_mode,
 @ai_samples,
 @ratedb,
 @interp_type,
 @rollover_value,
 @server_timestamp,
 @deadband_type
 if @@ERROR <> 0
 BEGIN
  set @errno=50125
  set @errmsg_default='AnalogTag import failed (insert failed)'
  goto error
 END
END
else
BEGIN
exec aaAnalogTagUpdate
 @key,
 @TagName,
 @Description,
 @acq_type,
 @store_type,
 @store_rate,
 @ItemName,
 @timedb,
 @created_by,
 @date_created,
 @cur_edit,
 @eu_key,
 @min_eu,
 @max_eu,
 @min_raw,
 @max_raw,
 @scaling_type,
 @raw_type,
 @valuedb,
 @init_value,
 @int_size,
 @signed,
 @topic_key,
 @ios_key,
 1,
 @ai_mode,
 @ai_samples,
 @ratedb,
 @interp_type,
 @rollover_value,
 @server_timestamp,
 @deadband_type
 if @@ERROR <> 0
 BEGIN
  set @errno=50126
  set @errmsg_default='AnalogTag import failed (update failed)'
  goto error
 END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalAnalogTagImport to aaAdministrators
go
 
 /**********  aaAnnotationDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnnotationDelete'))
  DROP PROCEDURE dbo.aaAnnotationDelete
GO

CREATE PROCEDURE aaAnnotationDelete 
  @AnnotationKey int
AS
  DELETE FROM Annotation
    WHERE  AnnotationKey = @AnnotationKey
GO

GRANT  EXECUTE  ON aaAnnotationDelete  TO aaUsers
GO
GRANT  EXECUTE  ON aaAnnotationDelete  TO aaPowerUsers
GO
GRANT  EXECUTE  ON aaAnnotationDelete  TO aaAdministrators
go
 
 /**********  aaAnnotationInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnnotationInsert'))
  DROP PROCEDURE dbo.aaAnnotationInsert
GO

CREATE PROCEDURE aaAnnotationInsert 
  @TagName       nvarchar(256),
  @UserKey       int = NULL,
  @DateTime      datetime = NULL,
  @DateCreated   datetime = NULL,
  @Content       nvarchar(1000) = N'Annotation:',
  @Value         real = 0.0
AS
  IF @DateCreated IS NULL
    SET @DateCreated = GetDate()

  IF @DateTime IS NULL
    SET @DateTime = GetDate()

  IF @UserKey = 0    -- userkey of zero has special meaning and indicates 'public'
  BEGIN
    INSERT INTO Annotation
     ( TagName, UserKey, [DateTime], DateCreated, Content, Value )
     VALUES
     ( @TagName, 0, @DateTime, @DateCreated, @Content, @Value )
  END
  ELSE
  BEGIN
    INSERT INTO Annotation
     ( TagName, UserKey, [DateTime], DateCreated, Content, Value )
     VALUES
     ( @TagName, dbo.faaUser_ID(), @DateTime, @DateCreated, @Content, @Value )
  END

  RETURN  SCOPE_IDENTITY()
GO

GRANT  EXECUTE  ON aaAnnotationInsert  TO aaUsers
GO
GRANT  EXECUTE  ON aaAnnotationInsert  TO aaPowerUsers
GO
GRANT  EXECUTE  ON aaAnnotationInsert  TO aaAdministrators
go
 
 /**********  aaAnnotationRetrieve  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnnotationRetrieve'))
  DROP PROCEDURE dbo.aaAnnotationRetrieve
GO

CREATE procedure aaAnnotationRetrieve
  @TagList nvarchar(4000),
  @StartTime nvarchar(50),
  @EndTime nvarchar(50)
AS
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ''
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ','
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SET @TempChar = @TempChar + SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1) + ''','''
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END;
  SET @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SET @SelectStatement = 
        'SELECT Annotation.DateTime, Annotation.Content, UserDetail.UserName, Annotation.TagName, Annotation.Value, Annotation.DateCreated ' +
            'FROM UserDetail, Annotation ' + 
        'WHERE  Annotation.UserKey = UserDetail.UserKey AND ' +
        '       Annotation.TagName in (''' + @TempChar + ''') AND ' +
        '       Annotation.DateTime >= ''' + @StartTime + '''  AND ' +
        '       Annotation.DateTime <= ''' + @EndTime + ''''

  Execute (@SelectStatement)
GO

GRANT  EXECUTE  ON aaAnnotationRetrieve  TO public
go
 
 /**********  aaAnnotationSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnnotationSelect'))
  DROP PROCEDURE dbo.aaAnnotationSelect
GO

CREATE PROCEDURE aaAnnotationSelect 
  @AnnotationKey int = NULL
AS
  IF @AnnotationKey IS NULL 
  BEGIN 
    SELECT AnnotationKey, TagName, UserKey, DateTime, DateCreated, Content, Value
      FROM Annotation
  END
  ELSE
  BEGIN
    SELECT AnnotationKey, TagName, UserKey, DateTime, DateCreated, Content, Value
      FROM Annotation
      WHERE AnnotationKey = @AnnotationKey
  END
GO

GRANT  EXECUTE  ON aaAnnotationSelect  TO public
go
 
 /**********  aaAnnotationUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaAnnotationUpdate'))
  DROP PROCEDURE dbo.aaAnnotationUpdate
GO

CREATE PROCEDURE aaAnnotationUpdate 
  @AnnotationKey int,
  @TagName       nvarchar(256),
  @UserKey       int = NULL,
  @DateTime      datetime = NULL,
  @Content       nvarchar(1000) = N'Annotation:',
  @Value         real = 0.0
AS
  IF @DateTime IS NULL
    SELECT @DateTime = GetDate()

  IF @UserKey IS NULL
  BEGIN
    UPDATE Annotation
    SET
      TagName = @TagName,
      UserKey = dbo.faaUser_ID(),
      [DateTime] = @DateTime,
      Content = @Content,
      Value = @Value
    WHERE  AnnotationKey = @AnnotationKey
  END
  ELSE
  BEGIN
    UPDATE Annotation
    SET
      TagName = @TagName,
      UserKey = @UserKey,
      [DateTime] = @DateTime,
      Content = @Content,
      Value = @Value
    WHERE  AnnotationKey = @AnnotationKey
  END

GO

GRANT  EXECUTE  ON aaAnnotationUpdate  TO aaUsers
GO
GRANT  EXECUTE  ON aaAnnotationUpdate  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaAnnotationUpdate  TO aaPowerUsers
go
 
 /**********  aaCleanupAfterCommit  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaCleanupAfterCommit'))
  DROP PROCEDURE dbo.aaCleanupAfterCommit
GO

CREATE procedure aaCleanupAfterCommit 
as

declare @errno int,  @errmsg nvarchar(255)

BEGIN TRAN
   /* Reset DbStatus */
   Update StorageNode set DbStatus = 0

   /* Cleanup snapshot table */
   delete ConfigStatusSnapshot

   if @@ERROR <> 0
   begin
      goto error
   end
COMMIT TRAN

return

error:
   set @errno = 17004
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  Cleanup after commit failed.'
   end

   raiserror @errno @errmsg

GO
GRANT exec on aaCleanupAfterCommit to aaAdministrators
go
 
 /**********  aaCleanupSystemNotRunning  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaCleanupSystemNotRunning'))
  DROP PROCEDURE dbo.aaCleanupSystemNotRunning
GO

CREATE procedure aaCleanupSystemNotRunning 
as

declare @errno int,  @errmsg nvarchar(255)

BEGIN TRAN
   /* Reset DbStatus */
   Update StorageNode set DbStatus = 0

   /* Cleanup snapshot table */
   delete ConfigStatusSnapshot
      where Type <> 6

   if @@ERROR <> 0
   begin
      goto error
   end
COMMIT TRAN

return

error:
   set @errno = 17004
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  Cleanup after commit failed.'
   end

   raiserror @errno @errmsg

GO
GRANT exec on aaCleanupSystemNotRunning to aaAdministrators
go
 
 /**********  aaCommitChanges  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaCommitChanges'))
  DROP PROCEDURE dbo.aaCommitChanges
GO

CREATE procedure aaCommitChanges 
as

declare @errno int,  @errmsg nvarchar(255)
declare @allowcommit int

/*  There is a check to see whether a Commit is allowed or not 
xp_AllowCommit int param OUTPUT

The xp takes a single output parameter that returns one of the following values:
0        =  OK to commit
1        =  System not running or not started, ignore commit request and clean up ConfigStatusPending
2        =  Cannot commit, history block in progress
4        =  Cannot commit, dynamic config in progress
8        =  Cannot commit, one or more IDAS offline
128    =  Cannot commit for unknown reason (this should never happen)
*/

exec  master..xp_AllowCommit @allowcommit OUTPUT

if @allowcommit = 0  -- commit Allowed
begin
   goto resume
end
else
if @allowcommit = 1 -- Historian not running allow commit and perform a cleanup
begin
   goto resume --  Commit allowed. In addition, cleanup after normal process has been completed (conditional task after commit logic)
end
else
if @allowcommit = 2 -- HistoryBlock in progress - no commit
begin
   set @errno = 17032
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  A history block change over is in progress - Cannot commit changes'
   end
   goto error
end
else
if @allowcommit = 4 -- previous commit in progress - no commit
begin
   set @errno = 17001
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  Previous commit not completed.'
   end
   goto error
end
else
if @allowcommit = 8 -- IDAS off line - no commit
begin
   set @errno = 17033
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  An IDAS is offline - Cannot commit.'
   end
   goto error
end
if @allowcommit = 128 -- Unknown error - no commit
begin
   set @errno = 17034
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  An unknown error occurred - Cannot commit.'
   end
   goto error
end

resume:

if exists (select Status from ConfigStatusPending where Status = 99)
begin
   set @errno = 17031
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  A pending modification requires a complete shutdown and restart. Cannot perform a dynamic reconfiguration'
   end
   goto error
end

if (select count(ID) from ConfigStatusSnapshot) > 0
begin
   set @errno = 17001
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  Previous commit not completed.'
   end
   goto error
end

if (select count(*) from ConfigStatusPending) = 0
begin
   set @errno = 17002
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  No change pending.'
   end
   goto error
end

BEGIN TRAN
   /* get error msg ready */
   set @errno = 17003
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  Commit preparation failed.'
   end

   /* start Commit process */
   /* Process any pending enumeration value-message inserts */
   /* (for future use) */
--   if (select count(*) from EnumerationPending) > 0
--   begin
--     exec aaCommitEnumerations
--   end

   /* Copy pending mods to snapshot table */
   insert into ConfigStatusSnapshot (ID, Type, ObjectKey, Status)
      select ID, Type, ObjectKey, Status from ConfigStatusPending with (UPDLOCK)
   if @@ERROR <> 0
   begin
      ROLLBACK TRAN
      goto error    
   end

   /* Reset Status flags */
   /* join on the rows in the snapshot table as new mods could be in already */
   update IODriver set Status = 0 
         from IODriver t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 0
            and css.ObjectKey = t.IODriverKey
            and css.Status <> 3        -- no need to worry about deleted rows

   update IOServer set Status = 0 
         from IOServer t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 1
            and css.ObjectKey = t.IOServerKey
            and css.Status <> 3        -- no need to worry about deleted rows

   update Topic set Status = 0 
         from Topic t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 2
            and css.ObjectKey = t.TopicKey
            and css.Status <> 3        -- no need to worry about deleted rows

   update Tag set Status = 0 
         from Tag t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 3
            and css.ObjectKey = t.wwTagKey
            and css.Status <> 3        -- no need to worry about deleted rows

   update StorageLocation set Status = 0 
         from StorageLocation t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 4
            and css.ObjectKey = t.StorageType
            and css.Status <> 3        -- no need to worry about deleted rows

   update SnapshotDetail set Status = 0 
         from SnapshotDetail t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 5
            and css.ObjectKey = t.StorageSize
            and css.Status <> 3        -- no need to worry about deleted rows

   /* no key for SystemParam */
   update SystemParameter set Status = 0 where Status <> 0

   update EngineeringUnit set Status = 0 
         from EngineeringUnit t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 7
            and css.ObjectKey = t.EUKey
            and css.Status <> 3        -- no need to worry about deleted rows

   if @@ERROR <> 0
   begin
      ROLLBACK TRAN
      goto error    
   end

   /* Clean pending table */ 
   delete ConfigStatusPending
      where ID in (select ID from ConfigStatusSnapshot)       
   if @@ERROR <> 0
   begin
      ROLLBACK TRAN
      goto error    
   end

   /* set generic commit flag */
   update StorageNode set DbStatus = 2
   if @@ERROR <> 0
   begin
      ROLLBACK TRAN
      goto error    
   end

   /* If system is not running, cleanup all except system parameters */
   if @allowcommit = 1
   begin
      exec aaCleanupSystemNotRunning
   end

COMMIT TRAN

return

error:
    raiserror @errno @errmsg

GO
GRANT exec on aaCommitChanges to aaAdministrators
go
 
 /**********  aaCommitChangesAtStartup  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaCommitChangesAtStartup'))
  DROP PROCEDURE dbo.aaCommitChangesAtStartup
GO

CREATE procedure aaCommitChangesAtStartup 
as

declare @errno int,  @errmsg nvarchar(255)

if (select count(ID) from ConfigStatusSnapshot) > 0
begin
   set @errno = 17001
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  Previous commit not completed.'
   end
   goto error
end

if (select count(*) from ConfigStatusPending) = 0
begin
   set @errno = 17002
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  No change pending.'
   end
   goto error
end

BEGIN TRAN
   /* get error msg ready */
   set @errno = 17003
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg is NULL
   begin
      set @errmsg = 'Error msg not found  -  Commit preparation failed.'
   end

   /* start Commit process */
   /* Copy pending mods to snapshot table */
   insert into ConfigStatusSnapshot (ID, Type, ObjectKey, Status)
      select ID, Type, ObjectKey, Status from ConfigStatusPending with (UPDLOCK)
   if @@ERROR <> 0
   begin
      ROLLBACK TRAN
      goto error    
   end

   /* Reset Status flags */
   /* join on the rows in the snapshot table as new mods could be in already */
   update IODriver set Status = 0 
         from IODriver t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 0
            and css.ObjectKey = t.IODriverKey
            and css.Status <> 3        -- no need to worry about deleted rows

   update IOServer set Status = 0 
         from IOServer t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 1
            and css.ObjectKey = t.IOServerKey
            and css.Status <> 3        -- no need to worry about deleted rows

   update Topic set Status = 0 
         from Topic t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 2
            and css.ObjectKey = t.TopicKey
            and css.Status <> 3        -- no need to worry about deleted rows

   update Tag set Status = 0 
         from Tag t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 3
            and css.ObjectKey = t.wwTagKey
            and css.Status <> 3        -- no need to worry about deleted rows

   update StorageLocation set Status = 0 
         from StorageLocation t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 4
            and css.ObjectKey = t.StorageType
            and css.Status <> 3        -- no need to worry about deleted rows

   update SnapshotDetail set Status = 0 
         from SnapshotDetail t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 5
            and css.ObjectKey = t.StorageSize
            and css.Status <> 3        -- no need to worry about deleted rows

   /* no key for SystemParam */
   update SystemParameter set Status = 0 where Status <> 0

   update EngineeringUnit set Status = 0 
         from EngineeringUnit t, ConfigStatusSnapshot css
            where t.Status <> 0
            and css.Type = 7
            and css.ObjectKey = t.EUKey
            and css.Status <> 3        -- no need to worry about deleted rows

   if @@ERROR <> 0
   begin
      ROLLBACK TRAN
      goto error    
   end

   /* Clean pending table */ 
   delete ConfigStatusPending
      where ID in (select ID from ConfigStatusSnapshot)       
   if @@ERROR <> 0
   begin
      ROLLBACK TRAN
      goto error    
   end

   /* set generic commit flag */
   update StorageNode set DbStatus = 2
   if @@ERROR <> 0
   begin
      ROLLBACK TRAN
      goto error    
   end
COMMIT TRAN

return

error:
    raiserror @errno @errmsg

GO
GRANT exec on aaCommitChangesAtStartup to aaAdministrators
go
 
 /**********  aaContextDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaContextDelete'))
  DROP PROCEDURE dbo.aaContextDelete
GO

CREATE procedure aaContextDelete
   @ContextKey     int 
AS
  IF exists (select ContextKey from Context  where ContextKey = @ContextKey)
   BEGIN 
      delete Context where ContextKey = @ContextKey
   END   

GO

GRANT exec on aaContextDelete to aaAdministrators
GO
GRANT exec on aaContextDelete to aaPowerUsers
go
 
 /**********  aaContextInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaContextInsert'))
  DROP PROCEDURE dbo.aaContextInsert
GO

CREATE procedure aaContextInsert
   @Description     nvarchar(50) = NULL 
AS
  IF not exists (select Description from Context  where Description = @Description)
   BEGIN 
      insert Context (Description)
                  values (@Description)
      RETURN  SCOPE_IDENTITY()
   END   
   ELSE
   BEGIN
      return 0
   END

GO

GRANT exec on aaContextInsert to aaAdministrators
GO
GRANT exec on aaContextInsert to aaPowerUsers
go
 
 /**********  aaContextSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaContextSelect'))
  DROP PROCEDURE dbo.aaContextSelect
GO

CREATE procedure aaContextSelect
   @ContextKey    int = NULL 
AS
  if @ContextKey is null
   BEGIN 
      Select ContextKey, Description from Context
   END   
 else
   BEGIN
      Select ContextKey, Description from Context
        where ContextKey = @ContextKey
   END
GO

GRANT exec on aaContextSelect to public
go
 
 /**********  aaContextUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaContextUpdate'))
  DROP PROCEDURE dbo.aaContextUpdate
GO

CREATE procedure aaContextUpdate
   @ContextKey    int,
   @Description nvarchar(50)
AS
  IF exists (select ContextKey from Context  where ContextKey = @ContextKey)
   BEGIN 
      update Context set Description = @Description
          where ContextKey = @ContextKey
   END   

GO

GRANT exec on aaContextUpdate to aaAdministrators
GO
GRANT exec on aaContextUpdate to aaPowerUsers
go
 
 /**********  aaDBChangesPending  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDBChangesPending'))
  DROP PROCEDURE dbo.aaDBChangesPending
GO

CREATE procedure aaDBChangesPending 
as
select [Object Type] = '0 - IDAS',
       [Status] =
         case CSP.Status
            when 1 then 'Inserted  '
            when 2 then 'Modified  '
            when 3 then 'Deleted   '
         end,
       [Object Key] = CSP.ObjectKey,
       [Item] = OBJ.ComputerName
   from ConfigStatusPending CSP LEFT OUTER JOIN IODriver OBJ
      ON CSP.ObjectKey = OBJ.IODriverKey
      where CSP.Type = 0
UNION
select [Object Type] = '1 - IOServer',
       [Status] =
         case CSP.Status
            when 1 then 'Inserted  '
            when 2 then 'Modified  '
            when 3 then 'Deleted   '
         end,
       [Object Key] = CSP.ObjectKey,
       [Item] = OBJ.ComputerName + '\' + OBJ.ApplicationName
   from ConfigStatusPending CSP LEFT OUTER JOIN IOServer OBJ
      ON CSP.ObjectKey = OBJ.IOServerKey
      where CSP.Type = 1
UNION
select [Object Type] = '2 - Topic',
       [Status] =
         case CSP.Status
            when 1 then 'Inserted  '
            when 2 then 'Modified  '
            when 3 then 'Deleted   '
         end,
       [Object Key] = CSP.ObjectKey,
       [Item] = OBJ.Name
   from ConfigStatusPending CSP LEFT OUTER JOIN Topic OBJ
      ON CSP.ObjectKey = OBJ.TopicKey
      where CSP.Type = 2
UNION
select [Object Type] = '3 - Tag',
       [Status] =
         case CSP.Status
            when 1 then 'Inserted  '
            when 2 then 'Modified  '
            when 3 then 'Deleted   '
            when 6 then 'Acq Modif.'
         end,
       [Object Key] = CSP.ObjectKey,
       [Item] = OBJ.TagName
   from ConfigStatusPending CSP LEFT OUTER JOIN Tag OBJ
      ON CSP.ObjectKey = OBJ.wwTagKey
      where CSP.Type = 3
UNION
select [Object Type] = '4 - StorageLocation',
       [Status] =
         case CSP.Status
            when 1 then 'Inserted  '
            when 2 then 'Modified  '
            when 3 then 'Deleted   '
            when 99 then 'Full Restart Required'
         end,
       [Object Key] = CSP.ObjectKey,
       [Item] = 
         case StorageType
            when 1 then 'Circular    - ' + OBJ.Path
            when 2 then 'Alternative - ' + OBJ.Path
            when 3 then 'Buffer      - ' + OBJ.Path
            when 4 then 'Permanent   - ' + OBJ.Path
         end      
   from ConfigStatusPending CSP LEFT OUTER JOIN StorageLocation OBJ
      ON CSP.ObjectKey = OBJ.StorageType
      where CSP.Type = 4
UNION
select [Object Type] = '5 - SnapshotDetail',
       [Status] =
         case CSP.Status
            when 1 then 'Inserted  '
            when 2 then 'Modified  '
            when 3 then 'Deleted   '
         end,
       [Object Key] = CSP.ObjectKey,
       [Item] = 'SnapshotSize: ' + str(SnapshotSize) 
   from ConfigStatusPending CSP LEFT OUTER JOIN SnapshotDetail OBJ
      ON CSP.ObjectKey = OBJ.StorageSize
      where CSP.Type = 5
UNION
select [Object Type] = '6 - System Parameter',
       [Status] =
         case OBJ.Status
            when 1 then 'Inserted  '
            when 2 then 'Modified  '
            when 3 then 'Deleted   '
         end,
       [Object Key] = NULL,
       [Item] = OBJ.Name
   from SystemParameter OBJ
      where OBJ.Status = 2
UNION
select [Object Type] = '7 - EngineeringUnit',
       [Status] =
         case CSP.Status
            when 1 then 'Inserted  '
            when 2 then 'Modified  '
            when 3 then 'Deleted   '
         end,
       [Object Key] = CSP.ObjectKey,
       [Item] = OBJ.Unit
   from ConfigStatusPending CSP LEFT OUTER JOIN EngineeringUnit OBJ
      ON CSP.ObjectKey = OBJ.EUKey
      where CSP.Type = 7
go
GRANT exec on aaDBChangesPending to Public
go
 
 /**********  aaDBConfig  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDBConfig'))
  DROP PROCEDURE dbo.aaDBConfig
GO

create procedure aaDBConfig
AS
set nocount ON

Print 'System Parameters'
Print '================='
select Name as [Parameter],
     convert(nchar(100), Value) as [Value]
from SystemParameter
order by Name

Print 'Tag Count'
Print '========='
select Count(TagName) as [Total Tag Count]
from Tag
Print''
select Count(TagName) as [Licensed Tag Count]
from Tag
where TagType in (1,2,3,7,9) and IOServerKey <> 1


Print 'Tag Types'
Print '========='
select [Tag Type] =
   CASE TagType
      WHEN 1 THEN 'Analog'
      WHEN 2 THEN 'Discrete'
      WHEN 3 THEN 'String'
      WHEN 5 THEN 'Event'
      WHEN 7 THEN 'Blob'
      WHEN 9 THEN 'Enumerated'
   END,
   Count(TagName) as [Tag Count]
from Tag
group by TagType
order by TagType

Print 'Analog Tag Storage Details'
Print '=========================='
select [Storage Type] =
   CASE StorageType
      WHEN 1 THEN 'Cyclic'
      WHEN 2 THEN 'Delta'
      WHEN 3 THEN 'Forced'
      WHEN 0 THEN 'Not Stored'
   END,
   Count(TagName) as [Tag Count]
from Tag
where TagType = 1
group by StorageType
order by StorageType

Print 'Cyclic Storage Details'
Print '======================'
select StorageRate/1000 as [Storage Rate (sec)],
   Count(TagName) as [Tag Count]
from Tag
where TagType = 1
and StorageType = 1
group by StorageRate
order by StorageRate

Print 'IDAS, IOServers and Topic Details'
Print '================================='
select  convert(char(30), iod.ComputerName) as [IDAS Location],  
        convert(char(30), ios.ComputerName) as [IOServer Location],
        convert(char(20), ios.ApplicationName) as [Application Name],
       [Protocol  ] = CASE ios.ProtocolType
           WHEN 1 THEN 'DDE'
           WHEN 2 THEN 'SuiteLink'
           ELSE 'Unknown'
        END,
       [Topic Name] = convert(char(20), tp.Name)
from IODriver iod JOIN IOServer ios on iod.IODriverKey = ios.IODriverKey
 JOIN Topic tp on ios.IOServerKey = tp.IOServerKey
order by [IDAS Location], [IOServer Location], ApplicationName, Name


Print 'Event Tag Details'
Print '================='  
select evt.TagName, det.Name, act.Name, evt.PostDetectorDelay
from EventTag evt, DetectorType det, ActionType act
where evt.DetectorTypeKey = det.DetectorTypeKey 
and   evt.ActionTypeKey = act.ActionTypeKey 


Print '"Schedule" Event Tag Details'
Print '============================'  
select evt.TagName, f.Frequency, [Day ] = 
   CASE tdd.FrequencyID
    WHEN 3 THEN 
       CASE RunTimeDay
          WHEN 0 THEN 'Sun'
          WHEN 1 THEN 'Mon'
          WHEN 2 THEN 'Tue'
          WHEN 3 THEN 'Wed'
          WHEN 4 THEN 'Thu'
          WHEN 5 THEN 'Fri'
          WHEN 6 THEN 'Sat'
       END
    WHEN 4 THEN convert(char(4), RunTimeDay) 
    ELSE '-'
    END,
   [Hour] = 
   CASE tdd.FrequencyID 
      WHEN 2 THEN convert(char(4), RunTimeHour)
      WHEN 3 THEN convert(char(4), RunTimeHour)
      WHEN 4 THEN convert(char(4), RunTimeHour)
      ELSE '-'
   END,
   [Min ] = 
   CASE tdd.FrequencyID 
      WHEN 5 THEN '-'
      ELSE convert(char(4), RunTimeMin)
   END,
   [Period] = 
   CASE tdd.FrequencyID 
      WHEN 5 THEN convert(char(6), Periodicity)
      ELSE '-'
   END,
   [Start Datetime] = StartDateTime
from EventTag evt, TimeDetectorDetail tdd, Frequency f
where evt.TagName = tdd.TagName 
and   tdd.FrequencyID = f.FrequencyID


print 'Summary Operations'
print '=================='
select [Summary Event] = so.TagName, Type = CalcType,
   Duration, Resolution, [Time Stamp] = 
     CASE TimeStamp
       WHEN 1 THEN 'End'
       WHEN 2 THEN 'Start'
     END
from SummaryOperation so
order by so.TagName, CalcType, Duration

print 'Summary Tag List, by Summary Type'
print '================================='
select [Summary Event] = so.TagName, so.CalcType,
       [Calculation On]= st.TagName
from SummaryOperation so, SummaryTagList st
where so.OperationKey = st.OperationKey
order by so.TagName, so.CalcType, st.TagName

print 'Summary Tag List, by Calculated Tag'
print '==================================='
select [Calculation On]= st.TagName, so.CalcType,
       [Summary Event] = so.TagName
from SummaryOperation so, SummaryTagList st
where so.OperationKey = st.OperationKey
order by st.TagName, so.CalcType, so.TagName

set nocount OFF
GO
GRANT EXEC on aaDBConfig to public
go
 
 /**********  aaDeleteOlderEvents  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDeleteOlderEvents'))
  DROP PROCEDURE dbo.aaDeleteOlderEvents
GO

CREATE PROCEDURE aaDeleteOlderEvents
AS 
   set DEADLOCK_PRIORITY low
 
   Declare @duration int
   
   Select @duration = ISNULL((Select -1 * Convert(integer,(Value))
                         From SystemParameter
                           Where Name = "EventStorageDuration"),-24)

   Delete EventHistory
      WHERE DateTime < DateAdd(hour, @duration, getdate())

GO

GRANT exec on aaDeleteOlderEvents to aaAdministrators
go
 
 /**********  aaDeleteOlderSummaries  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDeleteOlderSummaries'))
  DROP PROCEDURE dbo.aaDeleteOlderSummaries
GO

CREATE PROCEDURE aaDeleteOlderSummaries
AS
   set DEADLOCK_PRIORITY low

   Declare @duration int
   
   Select @duration = ISNULL((Select -1 * Convert(integer,(Value))
                         From SystemParameter
                           Where Name = "SummaryStorageDuration"),-24)

   Delete SummaryHistory
      WHERE OperationStart < DateAdd(hour, @duration, getdate())

GO

GRANT exec on aaDeleteOlderSummaries to aaAdministrators
go
 
 /**********  aaDeleteTag  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDeleteTag'))
  DROP PROCEDURE dbo.aaDeleteTag
GO

CREATE procedure aaDeleteTag 
   @TagName         nvarchar(256) 
AS
  DELETE Tag where TagName = @TagName
GO

GRANT exec on aaDeleteTag to aaAdministrators
GO
GRANT exec on aaDeleteTag to aaPowerUsers
go
 
 /**********  aaDetectorStringSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDetectorStringSelect'))
  DROP PROCEDURE dbo.aaDetectorStringSelect
GO

CREATE PROCEDURE aaDetectorStringSelect
  @TagName nvarchar(256)
AS
BEGIN
  select DetectorString from EventTag where TagName = @TagName
END
GO

GRANT EXEC ON aaDetectorStringSelect TO aaAdministrators
go
 
 /**********  aaDiscreteDetail  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDiscreteDetail'))
  DROP PROCEDURE dbo.aaDiscreteDetail
GO

CREATE procedure aaDiscreteDetail
  @TagList nvarchar(4000)
AS
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ','
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SET @TempChar = @TempChar + SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1) + "','"
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END;
  SET @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SET @SelectStatement = 
    "SELECT Tag.TagName, Tag.Description, mc.Message0, mc.Message1 " +
    "FROM Tag , Message mc, DiscreteTag dt " +  
    "WHERE Tag.TagName IN ('" +  @TempChar + "') " +
    "and Tag.TagName = dt.TagName " +
    "and dt.MessageKey = mc.MessageKey"

  Execute( @SelectStatement )
GO

GRANT exec on aaDiscreteDetail to Public
go
 
 /**********  aaDiscreteTagDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDiscreteTagDelete'))
  DROP PROCEDURE dbo.aaDiscreteTagDelete
GO

CREATE procedure aaDiscreteTagDelete 
 @wwTagKey int
AS
  DELETE FROM Tag
  WHERE  wwTagKey = @wwTagKey
GO

GRANT exec on aaDiscreteTagDelete to aaAdministrators
go
GRANT exec on aaDiscreteTagDelete to aaPowerUsers
go
 
 /**********  aaDiscreteTagInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDiscreteTagInsert'))
  DROP PROCEDURE dbo.aaDiscreteTagInsert
GO

CREATE PROCEDURE aaDiscreteTagInsert 
   @TagName         nvarchar(256),
   @Description     nvarchar(512) = '',
   @AcquisitionType tinyint      = 1,
   @StorageType     smallint     = 2,
   @StorageRate     int          = 0,
   @ItemName        nvarchar(256) = '',
   @TimeDeadband    int          = 0,
   @CreatedBy       nvarchar(256) = '',
   @DateCreated     datetime     = NULL,
   @CurrentEditor   int          = 0,
   @MessageKey      int          = 1,
   @InitialValue    tinyint      = 0,
   @TopicKey        int          = NULL,
   @IOServerKey     int          = NULL,
   @AIRetrievalMode  tinyint     = 0,
   @SamplesInActiveImage  int    = 0,
   @ServerTimeStamp bit          = 0,
   @DeadbandType    smallint     = 1

AS
BEGIN
  BEGIN TRAN

  DECLARE @result int

  SELECT @result = 0

  INSERT Tag
    (
    TagName, TopicKey, IOServerKey, StorageNodeKey, Description,
    AcquisitionType, StorageType, AcquisitionRate, StorageRate,
    ItemName, TagType, TimeDeadband, CurrentEditor,
    AIRetrievalMode, SamplesInActiveImage, ServerTimeStamp, DeadbandType
    )
  VALUES
    (
    RTRIM(@TagName), @TopicKey, @IOServerKey, 1, RTRIM(@Description),
    @AcquisitionType, @StorageType, 0, @StorageRate, RTRIM(@ItemName), 
    2, @TimeDeadband, @CurrentEditor,
    @AIRetrievalMode, @SamplesInActiveImage, @ServerTimeStamp, @DeadbandType
    )

  IF @@Error = 0
  BEGIN
    INSERT DiscreteTag
      (
      TagName,
      MessageKey,
      InitialValue
      )
    VALUES
      (
      RTRIM(@TagName),
      @MessageKey,
      @InitialValue
      )
  END

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
    SELECT @result = (SELECT wwTagKey from Tag where TagName = RTRIM(@TagName))
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @result = -1
  END

  RETURN @result
END
GO

GRANT EXEC ON aaDiscreteTagInsert TO aaAdministrators
GO
GRANT EXEC ON aaDiscreteTagInsert TO aaPowerUsers
go
 
 /**********  aaDiscreteTagSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDiscreteTagSelect'))
  DROP PROCEDURE dbo.aaDiscreteTagSelect
GO

CREATE procedure aaDiscreteTagSelect 
  @wwTagKey int = NULL
AS
IF @wwTagKey IS NULL 
BEGIN 
  SELECT 
    Tag.wwTagKey wwTagKey,
    Tag.TagName TagName,
    Tag.Description Description,
    AcquisitionType,
    StorageType = 
    CASE StorageType
       WHEN 17 THEN 0
       WHEN 18 THEN 0
       WHEN 19 THEN 0
       ELSE StorageType
    END,
    StorageRate,
    ItemName,
    TimeDeadband,
    CreatedBy,
    DateCreated,
    CurrentEditor,
    MessageKey,
    InitialValue,
    TopicKey,
    IOServerKey,
    AIRetrievalMode,
    SamplesInActiveImage,
    CalculatedAISamples,
    ServerTimeStamp,
    DeadbandType
FROM
    Tag, DiscreteTag
WHERE
    Tag.TagName = DiscreteTag.TagName
END ELSE
BEGIN 
  SELECT 
    Tag.wwTagKey wwTagKey,
    Tag.TagName TagName,
    Tag.Description Description,
    AcquisitionType,
    StorageType = 
    CASE StorageType
       WHEN 17 THEN 0
       WHEN 18 THEN 0
       WHEN 19 THEN 0
       ELSE StorageType
    END,
    StorageRate,
    ItemName,
    TimeDeadband,
    CreatedBy,
    DateCreated,
    CurrentEditor,
    MessageKey,
    InitialValue,
    TopicKey,
    IOServerKey,
    AIRetrievalMode,
    SamplesInActiveImage,
    CalculatedAISamples,
    ServerTimeStamp,
    DeadbandType 
FROM
    Tag, DiscreteTag
WHERE
    Tag.wwTagKey = @wwTagKey
    AND Tag.TagName = DiscreteTag.TagName
END
GO

GRANT exec on aaDiscreteTagSelect to Public
go
 
 /**********  aaDiscreteTagUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaDiscreteTagUpdate'))
  DROP PROCEDURE dbo.aaDiscreteTagUpdate
GO

CREATE procedure aaDiscreteTagUpdate 
  @wwTagKey        int, 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @AcquisitionType tinyint = 1,
  @StorageType     smallint,
  @StorageRate     int,
  @ItemName        nvarchar(256) = '',
  @TimeDeadband    int,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @CurrentEditor   int,
  @MessageKey      int,
  @InitialValue    tinyint,
  @TopicKey        int,
  @IOServerKey     int,
  @AIRetrievalMode tinyint,
  @SamplesInActiveImage int = 0,
  @ServerTimeStamp bit      = 0,
  @DeadbandType    smallint = 1
 
AS
BEGIN
  /* This proc updates a discrete tag based upon the tag key */
  /*   it is used by the configuration editor */
  BEGIN TRAN

  DECLARE @nTagName nvarchar(256)

  SELECT @nTagName = (SELECT TagName FROM Tag WHERE wwTagKey = @wwTagKey)

  UPDATE Tag 
  SET
    Description     = RTRIM(@Description),
    AcquisitionType = @AcquisitionType, 
    StorageType     = @StorageType,
    StorageRate     = @StorageRate,
    ItemName        = RTRIM(@ItemName),
    TimeDeadband    = @TimeDeadband,
    TopicKey        = @TopicKey,
    IOServerKey     = @IOServerKey,
    CurrentEditor   = @CurrentEditor,
    AIRetrievalMode = @AIRetrievalMode,
    SamplesInActiveImage = @SamplesInActiveImage,
    ServerTimeStamp = @ServerTimeStamp,
    DeadbandType    = @DeadbandType
  WHERE wwTagKey    = @wwTagKey

  UPDATE DiscreteTag
  SET
    MessageKey   = @MessageKey,
    InitialValue = @InitialValue
  WHERE TagName  = @nTagName

  COMMIT TRAN
END
GO

GRANT exec on aaDiscreteTagUpdate to aaAdministrators
go
GRANT exec on aaDiscreteTagUpdate to aaPowerUsers
go
 
 /**********  aaInternalDiscreteTagExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalDiscreteTagExport'))
  DROP PROCEDURE dbo.aaInternalDiscreteTagExport
GO

CREATE procedure aaInternalDiscreteTagExport 
  @Format int=0,
  @Filter nvarchar(256)='%',
  @AcquisitionType int=0
AS
--****************************
-- Export DiscreteTag
--****************************
declare @acq_type_lo int, @acq_type_hi int
declare @insql_name nvarchar(32)

select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList

set @acq_type_lo=CASE @AcquisitionType
 WHEN 0 THEN 0
 ELSE @AcquisitionType
 END
set @acq_type_hi=CASE @AcquisitionType
 WHEN 0 THEN 2
 ELSE @AcquisitionType
 END

SELECT [:(DiscreteTag)TagName]=Tag.TagName, 
 [Description]=Tag.Description,
 [IOServerComputerName]=CASE LOWER(IOServer.ComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(IOServer.ComputerName)
 END,
 [IOServerAppName]=IOServer.ApplicationName,
 [TopicName]=Topic.Name,
 [ItemName]=ItemName,
 [AcquisitionType]=CASE AcquisitionType
  WHEN 0 THEN 'Not Acquired'
  WHEN 1 THEN 'IOServer'
  WHEN 2 THEN 'Manual'
  WHEN 3 THEN 'System'
  ELSE 'Unknown'
  END,
 [StorageType]=CASE StorageType
  WHEN 2 THEN 'Delta'
  WHEN 3 THEN 'Forced'
  ELSE 'Not Stored'
  END,
 [AcquisitionRate]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),AcquisitionRate))
  ELSE AcquisitionRate
  END,
 [TimeDeadband]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),TimeDeadband))
  ELSE TimeDeadband
  END,
 [SamplesInAI]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),SamplesInActiveImage))
  ELSE SamplesInActiveImage
  END,
 [AIMode]=CASE AIRetrievalMode
  WHEN 0 THEN 'All'
  ELSE 'Disk'
  END,
 [Message0]=Message.Message0,
 [Message1]=Message.Message1,
 [InitialValue]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),InitialValue))
  ELSE InitialValue
  END,
 [CurrentEditor]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),CurrentEditor))
  ELSE CurrentEditor
  END,
 [ServerTimeStamp]=CASE ServerTimeStamp
  WHEN 1 THEN 'Yes'
  ELSE 'No'
  END
FROM Tag, DiscreteTag, IOServer, Topic, Message
WHERE DiscreteTag.TagName=Tag.TagName
AND Message.MessageKey=DiscreteTag.MessageKey
AND IOServer.IOServerKey=Tag.IOServerKey
AND Topic.IOServerKey=IOServer.IOServerKey
AND Topic.TopicKey=Tag.TopicKey
AND TagType=2
AND Tag.TagName like @Filter
AND AcquisitionType between @acq_type_lo AND @acq_type_hi
AND CurrentEditor != 2

if @@ERROR <> 0
begin
   goto error
end

return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50004
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='DiscreteTag export failed'
end
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalDiscreteTagExport to aaAdministrators
go
 
 /**********  aaInternalDiscreteTagImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalDiscreteTagImport'))
  DROP PROCEDURE dbo.aaInternalDiscreteTagImport
GO

CREATE procedure aaInternalDiscreteTagImport 
  @Mode nvarchar(32)='update',
  @TagName nvarchar(256),
  @Description nvarchar(512),
  @ComputerName nvarchar(256),
  @ApplicationName nvarchar(64),
  @TopicName nvarchar(80),
  @ItemName nvarchar(256),
  @AcquisitionType nvarchar(16),
  @StorageType nvarchar(16),
  @AcquisitionRate nvarchar(32),
  @TimeDeadband nvarchar(16),
  @SamplesInAI nvarchar(16),
  @AIMode nvarchar(16),
  @Message0 nvarchar(64),
  @Message1 nvarchar(64),
  @InitialValue nvarchar(64),
  @CurrentEditor nvarchar(16)='0',
  @ServerTimeStamp nvarchar(8)='No'
AS
--*****************************
-- Import DiscreteTag
--*****************************
declare @key int, @storagenode_key int, @ios_key int, @topic_key int, @mess_key int
declare @acq_type tinyint, @store_type smallint, @cur_edit int
declare @timedb int, @created_by nvarchar(30), @date_created datetime
declare @ai_samples int, @ai_mode tinyint
declare @init_value tinyint
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)
declare @insql_name nvarchar(32)
declare @server_timestamp bit

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

if len(@TagName) = 0
 BEGIN
 set @errno=50305
 set @errmsg_default='DiscreteTag import failed (an empty TagName is not allowed)'
 goto error
 END
select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList
set @ComputerName=LTRIM(RTRIM(LOWER(@ComputerName)))
if @ComputerName='$local'
BEGIN
 set @ComputerName=@insql_name
END

-- Convert parameters into expected types and resolve text
-- representations of numerical fields

set @timedb=CONVERT(int, @TimeDeadband)
set @created_by=null
set @date_created=getdate()
set @ai_samples=CONVERT(int, @SamplesInAI)
set @init_value=CONVERT(tinyint, @InitialValue)

set @ai_mode=CASE LTRIM(RTRIM(LOWER(@AIMode)))
 WHEN 'all' THEN 0
 ELSE 1
 END
set @acq_type=CASE LTRIM(RTRIM(LOWER(@AcquisitionType)))
 WHEN 'ioserver' THEN 1
 WHEN 'manual' THEN 2
 ELSE 0
 END
set @store_type=CASE LTRIM(RTRIM(LOWER(@StorageType)))
 WHEN 'delta' THEN 2
 WHEN 'forced' THEN 3
 ELSE 0
 END
set @server_timestamp=CASE LTRIM(RTRIM(LOWER(@ServerTimeStamp)))
 WHEN 'yes' THEN 1
 ELSE 0
 END

-- Check if the tag exists by getting its tagkey

select @key=wwTagKey from Tag where TagName=@TagName and TagType=2

SET @cur_edit = CONVERT(int, @CurrentEditor)

-- If this is a delete, do it if the tag exists.

if @Mode='delete'
BEGIN
if @key is null
 BEGIN
 return
 END
else
 BEGIN
 exec aaDiscreteTagDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50151
  set @errmsg_default='DiscreteTag import failed (delete failed)'
  goto error
  END
 return
 END
END

-- If this is insert only (no update), and the tag already 
-- exists, we don't need to do anything more.

if (@Mode='insert') AND (@key is not null)
return

-- We need to check the relational integrity to proceed
-- beyond this point. All objects that this tag depends
-- on must already exist, otherwise we return an error.

select TOP 1 @mess_key=MessageKey 
From Message
where Message0=@Message0 and Message1=@Message1

if @mess_key is null
BEGIN
set @errno=50152
set @errmsg_default='DiscreteTag import failed (message does not exist)'
goto error
END

select @ios_key=IOServerKey 
from IOServer 
where LTRIM(RTRIM(LOWER(ComputerName)))=LTRIM(RTRIM(LOWER(@ComputerName)))
AND LTRIM(RTRIM(LOWER(ApplicationName)))=LTRIM(RTRIM(LOWER(@ApplicationName)))

if @ios_key is null
BEGIN
set @errno=50153
set @errmsg_default='DiscreteTag import failed (IOServer does not exist)'
goto error
END

select @topic_key=TopicKey 
From Topic
where IOServerKey=@ios_key
and Name=@TopicName

if @topic_key is null
BEGIN
set @errno=50154
set @errmsg_default='DiscreteTag import failed (topic does not exist)'
goto error
END

-- Parent objects are all OK, update or insert the tag.

if @key is null
BEGIN
exec aaDiscreteTagInsert
 @TagName,
 @Description,
 @acq_type,
 @store_type,
 0,
 @ItemName,
 @timedb,
 @created_by,
 @date_created,
 @cur_edit,
 @mess_key,
 @init_value,
 @topic_key,
 @ios_key,
 @ai_mode,
 @ai_samples,
 @server_timestamp
 if @@ERROR <> 0
 BEGIN
  set @errno=50155
  set @errmsg_default='DiscreteTag import failed (insert failed)'
  goto error
 END
END
else
BEGIN
exec aaDiscreteTagUpdate
 @key,
 @TagName,
 @Description,
 @acq_type,
 @store_type,
 0,
 @ItemName,
 @timedb,
 @created_by,
 @date_created,
 @cur_edit,
 @mess_key,
 @init_value,
 @topic_key,
 @ios_key,
 @ai_mode,
 @ai_samples,
 @server_timestamp
 if @@ERROR <> 0
 BEGIN
  set @errno=50156
  set @errmsg_default='DiscreteTag import failed (update failed)'
  goto error
 END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalDiscreteTagImport to aaAdministrators
go
 
 /**********  aaEngineeringUnitDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEngineeringUnitDelete'))
  DROP PROCEDURE dbo.aaEngineeringUnitDelete
GO

CREATE PROCEDURE aaEngineeringUnitDelete 
  @EUKey int
AS
  DELETE FROM EngineeringUnit 
  WHERE EUKey = @EUKey
GO

GRANT  EXECUTE  ON aaEngineeringUnitDelete  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaEngineeringUnitDelete  TO aaPowerUsers
go
 
 /**********  aaEngineeringUnitInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEngineeringUnitInsert'))
  DROP PROCEDURE dbo.aaEngineeringUnitInsert
GO

CREATE PROCEDURE aaEngineeringUnitInsert 
  @Unit nvarchar(32),
  @DefaultTagRate int = 10000,
  @IntegralDivisor float(25) = 1
AS 
   IF not exists (select Unit from EngineeringUnit where Unit = @Unit)
   BEGIN 
      INSERT INTO EngineeringUnit
        (Unit, DefaultTagRate, IntegralDivisor)
      VALUES
        (@Unit, @DefaultTagRate, @IntegralDivisor)
      RETURN  SCOPE_IDENTITY()
   END   
   ELSE
   BEGIN
      RETURN 0
   END
GO

GRANT  EXECUTE  ON aaEngineeringUnitInsert  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaEngineeringUnitInsert  TO aaPowerUsers
go
 
 /**********  aaEngineeringUnitSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEngineeringUnitSelect'))
  DROP PROCEDURE dbo.aaEngineeringUnitSelect
GO

CREATE procedure aaEngineeringUnitSelect 
  @EUKey int = NULL
AS 
   IF @EUKey is NULL
   BEGIN
      SELECT EUKey, Unit, DefaultTagRate, IntegralDivisor FROM EngineeringUnit
        ORDER BY Unit
   END
   ELSE
   BEGIN
      SELECT EUKey, Unit, DefaultTagRate, IntegralDivisor FROM EngineeringUnit
        WHERE EUKey = @EUKey
   END
GO

GRANT  EXECUTE  ON aaEngineeringUnitSelect  TO public
go
 
 /**********  aaEngineeringUnitUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEngineeringUnitUpdate'))
  DROP PROCEDURE dbo.aaEngineeringUnitUpdate
GO

CREATE PROCEDURE aaEngineeringUnitUpdate 
  @EUKey int,
  @Unit nvarchar(32),
  @DefaultTagRate int,
  @IntegralDivisor float(25) = 1
AS
BEGIN 
  UPDATE EngineeringUnit
  SET    Unit = @Unit,
         DefaultTagRate = @DefaultTagRate,
         IntegralDivisor = @IntegralDivisor
  WHERE  EUKey = @EUKey
END
GO

GRANT  EXECUTE  ON aaEngineeringUnitUpdate  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaEngineeringUnitUpdate  TO aaPowerUsers
go
 
 /**********  aaInternalEngineeringUnitExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalEngineeringUnitExport'))
  DROP PROCEDURE dbo.aaInternalEngineeringUnitExport
GO

CREATE procedure aaInternalEngineeringUnitExport 
  @Format int=0
AS
--****************************
-- Export EngineeringUnit
--****************************
SELECT [:(EngineeringUnit)Unit]=Unit, 
 DefaultTagRate,
 IntegralDivisor
from EngineeringUnit

if @@ERROR <> 0
begin
   goto error
end
return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50006
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='Engineering unit export failed'
end
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalEngineeringUnitExport to aaAdministrators
go
 
 /**********  aaInternalEngineeringUnitImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalEngineeringUnitImport'))
  DROP PROCEDURE dbo.aaInternalEngineeringUnitImport
GO

CREATE procedure aaInternalEngineeringUnitImport 
  @Mode nvarchar(32)='update',
  @Unit nvarchar(32),
  @DefaultTagRate nvarchar(16),
  @IntegralDivisor nvarchar(64)='1'
AS
--*****************************
-- Import EngineeringUnit
--*****************************
declare @key int, @tagrate int, @exist_rate int
declare @integral_divisor float
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)

set @tagrate=CONVERT(int, @DefaultTagRate)
set @integral_divisor=CONVERT(float, @IntegralDivisor)
set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

-- Check if this EngineeringUnit already exists
-- If so, update or delete it as specified by the mode parameter

select TOP 1 @key=EUKey, @exist_rate=DefaultTagRate from EngineeringUnit 
where Unit=@Unit

if @key is not null
BEGIN
 if @Mode='delete'
 BEGIN
 exec aaEngineeringUnitDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50112
  set @errmsg_default='Engineering unit import failed (delete failed)'
  goto error
  END
 END
 if (@Mode='update') AND (@tagrate <> @exist_rate)
 BEGIN
 exec aaEngineeringUnitUpdate 
  @key,
  @Unit,
  @tagrate,
  @integral_divisor
 if @@ERROR <> 0
  BEGIN
  set @errno=50113
  set @errmsg_default='Engineering unit import failed (update failed)'
  goto error
  END
 END
END
else

-- The EngineeringUnit does not exist, insert it if this is what 
-- the user specified, otherwise return an error

BEGIN
if @Mode='delete'
BEGIN
return
END
else
BEGIN
exec aaEngineeringUnitInsert 
 @Unit,
 @tagrate,
 @integral_divisor
if @@ERROR <> 0
 BEGIN
 set @errno=50113
 set @errmsg_default='Engineering unit import failed (insert failed)'
 goto error
 END
END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalEngineeringUnitImport to aaAdministrators
go
 
 /**********  aaEventDetection  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventDetection'))
  DROP PROCEDURE dbo.aaEventDetection
GO

CREATE procedure aaEventDetection 
  @TagName nvarchar(256),
  @Operator char(2),
  @DetectValue float(25),
  @Edge char(8),
  @Resolution int,
  @StartTime varchar(30),
  @EndTime varchar(30)
AS
begin
   -- Need to trap quote in the TagName and we could have more than 1
   if (select CHARINDEX('''', @TagName)) > 0
   begin
      declare @pos int, @prevpos int   -- where is the quote, where did we start from
      set @pos = 0
      set @prevpos = 0
      tryagain:
      select @pos = CHARINDEX('''', SUBSTRING(@TagName, @prevpos + 1, LEN(@TagName)))
      set @TagName = SUBSTRING(@TagName, 1, @prevpos + @pos) + '''' + 
                        SUBSTRING(@TagName, @prevpos + @pos + 1, (LEN(@TagName) - (@prevpos + @pos)))
      set @prevpos = @prevpos + @pos + 1
      if (select CHARINDEX('''', SUBSTRING(@TagName, @prevpos + 1, LEN(@TagName)))) > 0
        goto tryagain 
   end

   set quoted_identifier off
   declare @Statement nvarchar(1000)

   if @Edge = 'None'  -- None, cyclic retrieval
   begin
      set @Statement = "select DateTime from History " + 
          "where TagName = '" + RTRIM(@TagName) + 
          "' and Value " + RTRIM(@Operator) + " " +
          RTRIM(convert(varchar(100), @DetectValue)) + " and Value IS NOT NULL and  Quality <> 1 " +
          " and DateTime > '" + RTRIM(@StartTime) + 
          "' and DateTime <= '" + RTRIM(@EndTime) + 
          "' and wwEdgeDetection = 'None' and wwRetrievalMode = 'Cyclic'" +
          " and wwResolution = " + RTRIM(convert(varchar(100), @Resolution)) 
   end
   else -- Trailing / Leading / Both, delta retrieval
   begin
      set @Statement = "select DateTime from History " + 
          "where TagName = '" + RTRIM(@TagName) + 
          "' and Value " + RTRIM(@Operator) + " " + 
          RTRIM(convert(varchar(100), @DetectValue)) + " and Value IS NOT NULL and Quality <> 1 " +
          " and DateTime > '" + RTRIM(@StartTime) + 
          "' and DateTime <= '" + RTRIM(@EndTime) + 
          "' and wwEdgeDetection = '" + RTRIM(@Edge) + "' and wwRetrievalMode = 'Delta'"
   end

   exec (@Statement) 

end

GO

GRANT  EXECUTE  ON aaEventDetection TO aaAdministrators
go
 
 /**********  aaEventHistoryInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventHistoryInsert'))
  DROP PROCEDURE dbo.aaEventHistoryInsert
GO

CREATE procedure aaEventHistoryInsert 
   @TagName          nvarchar(256),
   @DateTime         datetime,
   @DetectDateTime   datetime,
   @Edge int
AS
   set NOCOUNT ON

   INSERT EventHistory
     (TagName, DateTime, DetectDateTime, Edge)
   VALUES
     (@TagName, @DateTime, @DetectDateTime, @Edge)

     -- RETURN  SCOPE_IDENTITY()
     select SCOPE_IDENTITY()

GO

GRANT  EXECUTE  ON aaEventHistoryInsert  TO aaAdministrators
go
 
 /**********  aaEventHistorySelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventHistorySelect'))
  DROP PROCEDURE dbo.aaEventHistorySelect
GO

CREATE procedure aaEventHistorySelect 
  @TagList nvarchar(4000),
  @StartTime nvarchar(50),
  @EndTime nvarchar(50)
AS
BEGIN
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ','
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SET @TempChar = @TempChar + SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1) + "','"
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END;
  SET @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SET @SelectStatement = 
        "SELECT e.EventLogKey, e.TagName, e.DateTime, e.DetectDateTime, e.Edge " +
        "FROM EventHistory e " + 
        "WHERE e.TagName in ('" + @TempChar + "') AND " +
        "       e.DateTime >= '" + @StartTime + "'  AND " +        
        "       e.DateTime <= '" + @EndTime + "'"

  Execute (@SelectStatement)
END
GO

GRANT  EXECUTE  ON aaEventHistorySelect  TO Public
go
 
 /**********  aaEventSnapshotInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventSnapshotInsert'))
  DROP PROCEDURE dbo.aaEventSnapshotInsert
GO

CREATE procedure aaEventSnapshotInsert 
  @EventLogKey int,
  @EventTime datetime,
  @EventTagName nvarchar(256)
AS
begin
  /* This stored Procedure is used by the Event System Snapshot Action */
   insert into AnalogSnapshot (SnapshotTagKey, EventLogKey, Value, Quality, QualityDetail)
      select SnapshotTagKey, @EventLogKey, Value, Quality, QualityDetail
         from SnapshotTag inner remote join History
            on SnapshotTag.TagName = History.TagName
         where History.DateTime = @EventTime
         and SnapshotTag.EventTagName = @EventTagName
         and SnapshotTag.TagType = 1
         and wwRetrievalMode = 'Cyclic'

   insert into DiscreteSnapshot (SnapshotTagKey, EventLogKey, Value, Quality, QualityDetail)
      select SnapshotTagKey, @EventLogKey, Value, Quality, QualityDetail
         from SnapshotTag inner remote join History
            on SnapshotTag.TagName = History.TagName
         where History.DateTime = @EventTime
         and SnapshotTag.EventTagName = @EventTagName
         and SnapshotTag.TagType = 2
         and wwRetrievalMode = 'Cyclic'

   insert into StringSnapshot (SnapshotTagKey, EventLogKey, Value, Quality, QualityDetail)
      select SnapshotTagKey, @EventLogKey, RTRIM(convert(nvarchar(512), vValue)), Quality, QualityDetail
         from SnapshotTag inner remote join History
            on SnapshotTag.TagName = History.TagName
         where History.DateTime = @EventTime
         and SnapshotTag.EventTagName = @EventTagName
         and SnapshotTag.TagType = 3
         and wwRetrievalMode = 'Cyclic'
end

GO

GRANT  EXECUTE  ON aaEventSnapshotInsert  TO aaAdministrators
go
 
 /**********  aaEventSnapshotSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventSnapshotSelect'))
  DROP PROCEDURE dbo.aaEventSnapshotSelect
GO

CREATE PROCEDURE aaEventSnapshotSelect 
  @TagList nvarchar(4000),
  @StartTime nvarchar(50),
  @EndTime nvarchar(50),
  @OrderBy nvarchar(2000)='Event'
AS
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ','
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SET @TempChar = @TempChar + SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1) + "','"
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END;
  SET @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SET @SelectStatement = 
        "SELECT v.Event, v.EventTime, v.DetectionTime, v.Edge, v.TagName, v.Value, v.Quality, v.QualityDetail " +
        "FROM  v_EventSnapshot v " + 
        "WHERE v.Event in ('" + @TempChar + "') AND " +
        "  v.EventTime >= '" + @StartTime + "'  AND " +        
        "  v.EventTime <= '" + @EndTime + "' " +
        "Order By " + @OrderBy

  Execute (@SelectStatement)
GO

GRANT  EXECUTE  ON aaEventSnapshotSelect  TO public
go
 
 /**********  aaEventTagDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagDelete'))
  DROP PROCEDURE dbo.aaEventTagDelete
GO

CREATE procedure aaEventTagDelete 
  @wwTagKey int
AS
  DELETE FROM Tag
    WHERE wwTagKey = @wwTagKey
GO

GRANT  EXECUTE  ON aaEventTagDelete  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaEventTagDelete  TO aaPowerUsers
go
 
 /**********  aaEventTagDetail  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagDetail'))
  DROP PROCEDURE dbo.aaEventTagDetail
GO

CREATE procedure aaEventTagDetail 
  @TagList nvarchar(4000)  = '%'

AS
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ','
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SET @TempChar = @TempChar + SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1) + "','"
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END;
  SET @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SET @SelectStatement = 
   "SELECT TagName = Tag.TagName, " + 
   "                  Description = Tag.Description, " + 
   "                  DetectorName = DetectorType.Name, " + 
   "                  ActionName = ActionType.Name, " + 
   "                  ScanRate = EventTag.ScanRate, " + 
   "                  TimeDeadband = EventTag.TimeDeadband, " + 
   "                  Edge = CASE EventTag.Edge " + 
   "                                     WHEN 0 THEN 'Trailing' " + 
   "                                     WHEN 1 THEN 'Leading' " + 
   "                                     WHEN 2 THEN 'Both' " + 
   "                                     WHEN 3 THEN 'None' " + 
   "                                  END, " + 
   "                   Logged = CASE EventTag.Logged " + 
   "                                          WHEN 0 THEN 'False' " + 
   "                                          WHEN 1 THEN 'True' " + 
   "                                       END, " + 
   "                   Priority = CASE EventTag.Priority " + 
   "                                          WHEN 0 THEN 'Normal' " + 
   "                                          WHEN 1 THEN 'Critical' " + 
   "                                      END, " + 
   "                   PostDetectorDelay = EventTag.PostDetectorDelay, " + 
   "                   Periodicity = CASE EventTag.DetectorTypeKey " + 
   "                                                WHEN 6 THEN TimeDetectorDetail.Periodicity " + 
   "                                                ELSE NULL " + 
   "                                            END, " +     
   "                   RunTimeDay = CASE EventTag.DetectorTypeKey " + 
   "                                                WHEN 6 THEN TimeDetectorDetail.RunTimeDay " + 
   "                                                 ELSE NULL " + 
   "                                            END,     " + 
   "                   RunTimeHour = CASE EventTag.DetectorTypeKey " + 
   "                                                WHEN 6 THEN TimeDetectorDetail.RunTimeHour " + 
   "                                                 ELSE NULL " + 
   "                                            END,     " + 
   "                   RunTimeMin = CASE EventTag.DetectorTypeKey " + 
   "                                                WHEN 6 THEN TimeDetectorDetail.RunTimeMin " + 
   "                                                 ELSE NULL " + 
   "                                            END " + 
   "FROM Tag INNER JOIN EventTag on Tag.TagName = EventTag.TagName " + 
   "           LEFT OUTER JOIN TimeDetectorDetail ON EventTag.TagName = TimeDetectorDetail.TagName , DetectorType, ActionType  " + 
   "   WHERE      EventTag.ActionTypeKey = ActionType.ActionTypeKey " + 
   "   AND        EventTag.DetectorTypeKey = DetectorType.DetectorTypeKey " + 
   "   AND        Tag.TagName IN ('" + @TempChar + "') "

  Execute (@SelectStatement)
GO

GRANT exec on aaEventTagDetail to Public
go
 
 /**********  aaEventTagInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagInsert'))
  DROP PROCEDURE dbo.aaEventTagInsert
GO

CREATE procedure aaEventTagInsert 
  @TagName            nvarchar(256),
  @Description        nvarchar(512) = '',
  @CreatedBy          nvarchar(256) = '',
  @DateCreated        datetime = NULL,
  @CurrentEditor      int = 0,
  @ScanRate           int = 0,
  @TimeDeadband       int = 0,
  @Logged             bit = 0,
  @Status             tinyint = 0,
  @PostDetectorDelay  int = 0,
  @UseThreadPool      bit = 1,
  @DetectorTypeKey    int = 0,
  @DetectorString     nvarchar(1500) = NULL,
  @ActionTypeKey      int = 0,
  @ActionString       nvarchar(1500) = NULL,
  @Priority tinyint = 0,
  @Edge tinyint = 1

AS
BEGIN
  BEGIN TRAN

  DECLARE @result int

  SELECT @result = 0

  INSERT Tag
    (
    TagName, TopicKey, IOServerKey, StorageNodeKey, Description,
    AcquisitionType, StorageType, AcquisitionRate, StorageRate,
    ItemName, TagType, TimeDeadband, CurrentEditor
    )
  VALUES
    (
    RTRIM(@TagName), NULL, NULL, 1, RTRIM(@Description),
    0, 0, 0, 0,
    '', 5, @TimeDeadband, @CurrentEditor
    )

  IF @@Error = 0
  BEGIN
    INSERT EventTag
      (
      TagName, TimeDeadband, Logged, Status, PostDetectorDelay, UseThreadPool, 
      ScanRate, DetectorTypeKey, DetectorString, ActionTypeKey, ActionString, Priority, Edge
      )
    VALUES
      (
      RTRIM(@TagName), @TimeDeadband,  @Logged, @Status, @PostDetectorDelay, @UseThreadPool, 
      @ScanRate, @DetectorTypeKey, RTRIM(@DetectorString), @ActionTypeKey, RTRIM(@ActionString),
      @Priority, @Edge
      )
  END

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
    SELECT @result = (SELECT wwTagKey from Tag where TagName = RTRIM(@TagName))
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @result = -1
  END

  RETURN @result
END
GO

GRANT  EXECUTE  ON aaEventTagInsert  TO aaAdministrators
GO

GRANT  EXECUTE  ON aaEventTagInsert  TO aaPowerUsers
go
 
 /**********  aaEventTagSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagSelect'))
  DROP PROCEDURE dbo.aaEventTagSelect
GO

CREATE procedure aaEventTagSelect 
@wwTagKey int = NULL
AS
IF @wwTagKey IS NULL 
BEGIN 
  SELECT 
    Tag.wwTagKey wwTagKey,
    Tag.TagName TagName,
    Tag.Description Description,
    Tag.CreatedBy CreatedBy,
    Tag.DateCreated DateCreated,
    Tag.CurrentEditor CurrentEditor,
    ScanRate,
    EventTag.TimeDeadband TimeDeadband,
    Logged,
    EventTag.Status,
    PostDetectorDelay,
    UseThreadPool,
    DetectorTypeKey,
    DetectorString,
    ActionTypeKey,
    ActionString,
    Priority,
    Edge
  FROM  Tag, EventTag
  WHERE Tag.TagName = EventTag.TagName END
ELSE
BEGIN
  SELECT 
    Tag.wwTagKey wwTagKey,
    Tag.TagName TagName,
    Tag.Description Description,
    Tag.CreatedBy CreatedBy,
    Tag.DateCreated DateCreated,
    Tag.CurrentEditor CurrentEditor,
    ScanRate,
    EventTag.TimeDeadband TimeDeadband,
    Logged,
    EventTag.Status,
    PostDetectorDelay,
    UseThreadPool,
    DetectorTypeKey,
    DetectorString,
    ActionTypeKey,
    ActionString,
    Priority,
    Edge
  FROM  Tag, EventTag   WHERE Tag.wwTagKey = @wwTagKey
    AND Tag.TagName = EventTag.TagName 
END
GO

GRANT  EXECUTE  ON aaEventTagSelect  TO public
go
 
 /**********  aaEventTagUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagUpdate'))
  DROP PROCEDURE dbo.aaEventTagUpdate
GO

CREATE procedure aaEventTagUpdate 
  @wwTagKey           int,
  @TagName            nvarchar(256),
  @Description        nvarchar(512),
  @CreatedBy          nvarchar(256) = '',
  @DateCreated        datetime,
  @CurrentEditor      int = 0,
  @ScanRate           int = 0,
  @TimeDeadband       int = 0,
  @Logged             bit = 0,
  @Status             tinyint = 0,
  @PostDetectorDelay  int = 0,
  @UseThreadPool      bit = 0,
  @DetectorTypeKey    int = 0,
  @DetectorString     nvarchar(1500),
  @ActionTypeKey      int = 0,
  @ActionString       nvarchar(1500),
  @Priority tinyint = 0,
  @Edge tinyint = 1

AS
BEGIN
  BEGIN TRAN 

  DECLARE @nTagName nvarchar(256)

  SELECT @nTagName = (SELECT TagName FROM Tag WHERE wwTagKey = @wwTagKey)
    
  UPDATE Tag 
  SET
    Description     = RTRIM(@Description),
    AcquisitionType = 0,
    StorageType     = 0,
    StorageRate     = 0,
    ItemName        = '',
    TimeDeadband    = @TimeDeadband,
    TopicKey        = NULL,
    IOServerKey     = NULL,
    CurrentEditor   = @CurrentEditor
  WHERE wwTagKey    = @wwTagKey

  UPDATE EventTag
  SET
    ScanRate = @ScanRate,
    TimeDeadband = @TimeDeadband,
    Logged = @Logged,
    Status = @Status,
    PostDetectorDelay = @PostDetectorDelay,
    UseThreadPool = @UseThreadPool,
    DetectorTypeKey = @DetectorTypeKey,
    DetectorString = RTRIM(@DetectorString),
    ActionTypeKey = @ActionTypeKey,
    ActionString = RTRIM(@ActionString),
    Priority = @Priority,
    Edge = @Edge
  WHERE TagName  = @nTagName

 COMMIT TRAN
END
GO

GRANT  EXECUTE  ON aaEventTagUpdate  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaEventTagUpdate  TO aaPowerUsers
go
 
 /**********  aaInternalEventTagExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalEventTagExport'))
  DROP PROCEDURE dbo.aaInternalEventTagExport
GO

CREATE procedure aaInternalEventTagExport 
  @Format int=0,
  @Filter nvarchar(256)='%'
AS
--****************************
-- Export EventTag
--****************************
SELECT [:(EventTag)TagName]=EventTag.TagName, 
 [Description]=Tag.Description,
 [DetectorType]=DetectorType.Name,
 [ActionType]=ActionType.Name,
 [ScanRate]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),ScanRate)
  ELSE ScanRate
  END,
 [TimeDeadband]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),EventTag.TimeDeadband)
  ELSE EventTag.TimeDeadband
  END,
 [Logged]=CASE Logged
  WHEN 1 THEN 'Yes'
  ELSE 'No'
  END,
 [PostDetectorDelay]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),PostDetectorDelay)
  ELSE PostDetectorDelay
  END,
 [EdgeDetection]=CASE Edge
  WHEN 1 THEN 'Leading'
  WHEN 0 THEN 'Trailing'
  WHEN 2 THEN 'Both'
  WHEN 3 THEN 'None'
  WHEN 4 THEN 'Time'
  WHEN 5 THEN 'External'
  END,
 [Priority]=CASE Priority
  WHEN 1 THEN 'Critical'
  ELSE 'Normal'
  END,
 [DetectorString]=REPLACE(REPLACE(DetectorString, nchar(10), ' '), nchar(13), ' '), 
 [ActionString]=REPLACE(REPLACE(ActionString, nchar(10), ' '), nchar(13), ' '), 
 [Frequency]=CASE DetectorType.DetectorTypeKey
  WHEN 6 THEN CASE FrequencyID
   WHEN 1 THEN 'Hourly'
   WHEN 2 THEN 'Daily'
   WHEN 3 THEN 'Weekly'
   WHEN 4 THEN 'Monthly'
   WHEN 5 THEN 'Periodic'
   END
  ELSE ''
  END,
  [Periodicity]=CASE DetectorType.DetectorTypeKey
  WHEN 6 THEN CASE FrequencyID 
  WHEN 5 THEN CONVERT(nvarchar(16),Periodicity)
  ELSE '1'
  END
  ELSE ''
  END,
 [StartDateTime]=CASE DetectorType.DetectorTypeKey
  WHEN 6 THEN CONVERT(nvarchar(32),StartDateTime,109)
  ELSE ''
  END,
 [RunTimeDay]=CASE DetectorType.DetectorTypeKey
  WHEN 6 THEN CONVERT(nvarchar(16),RunTimeDay)  
  ELSE ''
  END,
 [RunTimeHour]=CASE DetectorType.DetectorTypeKey
  WHEN 6 THEN CONVERT(nvarchar(16),RunTimeHour)
  ELSE ''
  END,
 [RunTimeMin]=CASE DetectorType.DetectorTypeKey
  WHEN 6 THEN CONVERT(nvarchar(16),RunTimeMin)
  ELSE ''
  END,
 [Status]=CASE EventTag.Status
  WHEN 0 THEN 'Yes'
  ELSE 'No'
  END
FROM EventTag INNER JOIN Tag
ON EventTag.TagName=Tag.TagName
INNER JOIN ActionType
ON ActionType.ActionTypeKey=EventTag.ActionTypeKey
INNER JOIN DetectorType
ON DetectorType.DetectorTypeKey=EventTag.DetectorTypeKey
LEFT OUTER JOIN TimeDetectorDetail
ON TimeDetectorDetail.TagName=EventTag.TagName
WHERE EventTag.TagName like @Filter

if @@ERROR <> 0
begin
   goto error
end
return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50008
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='EventTag export failed'
end
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalEventTagExport to aaAdministrators
go
 
 /**********  aaInternalEventTagImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalEventTagImport'))
  DROP PROCEDURE dbo.aaInternalEventTagImport
GO

CREATE procedure aaInternalEventTagImport 
  @Mode nvarchar(32)='update',
  @TagName nvarchar(256),
  @Description nvarchar(512),
  @DetectorType nvarchar(64),
  @ActionType nvarchar(64),
  @ScanRate nvarchar(16),
  @TimeDeadband nvarchar(16),
  @Logged nvarchar(8),
  @PostDetectorDelay nvarchar(16),
  @EdgeDetection nvarchar(32),
  @Priority nvarchar(8),
  @DetectorString nvarchar(1500),
  @ActionString nvarchar(1500),
  @Frequency nvarchar(32)=null,
  @Periodicity nvarchar(32)=null,
  @StartDateTime nvarchar(64)=null,
  @RunTimeDay nvarchar(16)=null,
  @RunTimeHour nvarchar(16)=null,
  @RunTimeMin nvarchar(16)=null,
  @Status nvarchar(8)='YES'
AS
--*****************************
-- Import EventTag
--*****************************
declare @key int, @cur_edit int, @det_type int, @act_type int, @scan_rate int
declare @time_db int, @log bit, @postdet_delay int, @timedet_exists int
declare @edge tinyint, @prior tinyint, @period int, @freq int
declare @start_date datetime, @run_day tinyint, @run_hour tinyint, @run_minute tinyint
declare @det_string nvarchar(1500), @act_string nvarchar(1500), @created_by nvarchar(30), @date_created datetime
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)
declare @len int, @value_det_tagname nvarchar(255), @temp_detstring nvarchar(1500)
declare @find int
declare @Stat tinyint

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

-- Convert parameters into expected types and resolve text
-- representations of numerical fields

set @created_by=null
set @date_created=getdate()
set @scan_rate=CONVERT(int, @ScanRate)
set @time_db=CONVERT(int, @TimeDeadband)
set @log=CASE LTRIM(RTRIM(LOWER(@Logged)))
  WHEN 'yes' THEN 1
  ELSE 0
  END
set @postdet_delay=CONVERT(int, @PostDetectorDelay)
set @edge=CASE LTRIM(RTRIM(LOWER(@EdgeDetection)))
  WHEN 'leading' THEN 1
  WHEN 'trailing' THEN 0
  WHEN 'both' THEN 2
  WHEN 'none' THEN 3
  WHEN 'time' THEN 4
  WHEN 'external' THEN 5
  ELSE 3
  END
set @prior=CASE LTRIM(RTRIM(LOWER(@Priority)))
  WHEN 'critical' THEN 1
  ELSE 0
  END
set @freq=CASE LTRIM(RTRIM(LOWER(@Frequency)))
  WHEN 'hourly' THEN 1
  WHEN 'daily' THEN 2
  WHEN 'weekly' THEN 3
  WHEN 'monthly' THEN 4
  WHEN 'periodic' THEN 5
  ELSE 0
  END
set @period=CONVERT(int, @Periodicity)
set @start_date=CONVERT(datetime, @StartDateTime)
set @run_day=CONVERT(tinyint, @RunTimeDay)  
set @run_hour=CONVERT(tinyint, @RunTimeHour)  
set @run_minute=CONVERT(tinyint, @RunTimeMin)  
set @Stat=CASE LTRIM(RTRIM(LOWER(@Status)))
  WHEN 'yes' THEN 0
  ELSE 99
  END

-- Check if the tag exists by getting its tagkey

if len(@TagName) = 0
 BEGIN
 set @errno=50307
 set @errmsg_default='EventTag import failed (an empty TagName is not allowed)'
 goto error
 END

select @det_type=DetectorTypeKey from DetectorType
  where LTRIM(RTRIM(LOWER(Name)))=LTRIM(RTRIM(LOWER(@DetectorType)))
select @act_type=ActionTypeKey from ActionType
  where LTRIM(RTRIM(LOWER(Name)))=LTRIM(RTRIM(LOWER(@ActionType)))

select @key=wwTagKey, @cur_edit=CurrentEditor from Tag where TagName=@TagName and TagType=5

-- If this is a delete, do it if the tag exists, otherwise
-- return an error to the caller.

if @Mode='delete'
BEGIN
if @key is null
 BEGIN
 return
 END
else
 BEGIN
 exec aaEventTagDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50251
  set @errmsg_default='EventTag import failed (delete failed)'
  goto error
  END
 return
 END
END

-- If this is insert only (no update), and the tag already 
-- exists, we don't need to do anything more.

if (@Mode='insert') AND (@key is not null)
return

-- We need to check the relational integrity to proceed
-- beyond this point. 
-- Check for valid detector and action types

if @det_type is null
 BEGIN
 set @errno=50252
 set @errmsg_default='EventTag import failed (invalid detector type)'
 goto error
 END
if @act_type is null
 BEGIN
 set @errno=50253
 set @errmsg_default='EventTag import failed (invalid action type)'
 goto error
 END

-- If this is ASV or DSV detection, check that the detector tag exists

if @det_type=4
BEGIN
 set @temp_detstring=@DetectorString
 set @temp_detstring=REPLACE(@temp_detstring, '"', '|')
 set @temp_detstring=REPLACE(@temp_detstring, '''', '|')
 set @temp_detstring=LTRIM(RTRIM(@temp_detstring))
 set @find=CHARINDEX('|', @temp_detstring)
 set @temp_detstring=RIGHT(@temp_detstring, LEN(@temp_detstring)-@find)
 set @temp_detstring=LTRIM(RTRIM(@temp_detstring))
 set @temp_detstring=LEFT(@temp_detstring, CHARINDEX('|',@temp_detstring)-1)
 if not exists(select TagName from AnalogTag where TagName=@temp_detstring)
  BEGIN
  set @errno=50259
  set @errmsg_default='EventTag import failed (detector tag does not exist or invalid tagtype)'
  goto error
  END
END

if @det_type=5
BEGIN
 set @temp_detstring=@DetectorString
 set @temp_detstring=REPLACE(@temp_detstring, '"', '|')
 set @temp_detstring=REPLACE(@temp_detstring, '''', '|')
 set @temp_detstring=LTRIM(RTRIM(@temp_detstring))
 set @find=CHARINDEX('|', @temp_detstring)
 set @temp_detstring=RIGHT(@temp_detstring, LEN(@temp_detstring)-@find)
 set @temp_detstring=LTRIM(RTRIM(@temp_detstring))
 set @temp_detstring=LEFT(@temp_detstring, CHARINDEX('|',@temp_detstring)-1)
 if not exists(select TagName from DiscreteTag where TagName=@temp_detstring)
  BEGIN
  set @errno=50259
  set @errmsg_default='EventTag import failed (detector tag does not exist or invalid tagtype)'
  goto error
  END
END


-- If this is for scheduled detection, check for time detector validity

if @det_type=6
BEGIN
if @freq=0
 BEGIN
 set @errno=50254
 set @errmsg_default='EventTag import failed (invalid time detector frequency type)'
 goto error
 END
END

-- Construct the detector string and action string

set @det_string=CASE @det_type
 WHEN 1 THEN ''
 WHEN 2 THEN ''
 WHEN 6 THEN ''
 WHEN 3 THEN @DetectorString
 WHEN 4 THEN @DetectorString
 WHEN 5 THEN @DetectorString
 END

if @act_type=1 
BEGIN
set @act_string=''
END
else 
BEGIN
set @act_string=@ActionString
END

-- Fix @det_string/@act_string if needed
if CHARINDEX('"', @det_string, 0) = 1
   set @det_string = RTRIM(SUBSTRING(@det_string, 2, 1500))
if CHARINDEX('"', @det_string, 0) = LEN(@det_string)
BEGIN
   set @len = LEN(@det_string) - 1
   if @len >= 0  set @det_string = RTRIM(LEFT(@det_string, @len))
END

if CHARINDEX('"', @act_string, 0) = 1
   set @act_string = RTRIM(SUBSTRING(@act_string, 2, 1500))
if CHARINDEX('"', @act_string, 0) = LEN(@act_string)
 BEGIN
   set @len = LEN(@act_string) - 1
   if @len >= 0  set @act_string = RTRIM(LEFT(@act_string, @len))
END

-- Insert or update the event tag

if @key is null
BEGIN
exec aaEventTagInsert
 @TagName,
 @Description,
 @created_by,
 @date_created,
 @cur_edit,
 @scan_rate,
 @time_db,
 @log,
 @Stat,
 @postdet_delay,
 1,
 @det_type,
 @det_string,
 @act_type,
 @act_string,
 @prior,
 @edge
 if @@ERROR <> 0
 BEGIN
  set @errno=50255
  set @errmsg_default='EventTag import failed (invalid time detector frequency type)'
  goto error
 END
if @det_type=6
BEGIN
exec aaTimeDetectorDetailInsert
 @freq,
 @TagName,
 @period,
 @start_date,
 @run_day,
 @run_hour,
 @run_minute
 if @@ERROR <> 0
 BEGIN
  set @errno=50256
  set @errmsg_default='EventTag import failed (time detector detail insert failed)'
  goto error
 END
END
END
else
BEGIN
exec aaEventTagUpdate
 @key,
 @TagName,
 @Description,
 @created_by,
 @date_created,
 @cur_edit,
 @scan_rate,
 @time_db,
 @log,
 @Stat,
 @postdet_delay,
 1,
 @det_type,
 @det_string,
 @act_type,
 @act_string,
 @prior,
 @edge
 if @@ERROR <> 0
 BEGIN
  set @errno=50257
  set @errmsg_default='EventTag import failed (update failed)'
  goto error
 END
if @det_type=6
BEGIN
exec aaTimeDetectorDetailUpdate
 @freq,
 @TagName,
 @period,
 @start_date,
 @run_day,
 @run_hour,
 @run_minute
 if @@ERROR <> 0
 BEGIN
  set @errno=50258
  set @errmsg_default='EventTag import failed (time detector detail update failed)'
  goto error
 END
END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalEventTagImport to aaAdministrators
go
 
 /**********  aaEventTagSelectAll  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagSelectAll'))
  DROP PROCEDURE dbo.aaEventTagSelectAll
GO

CREATE PROCEDURE aaEventTagSelectAll
AS

set NOCOUNT ON

delete from EventTagPendingDelete 

BEGIN Tran 
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTag e WITH (HOLDLOCK) LEFT OUTER JOIN TimeDetectorDetail t WITH (HOLDLOCK) on e.TagName = t.TagName 
        where e.ScanRate != 0
                or e.DetectorTypeKey = 6

        update EventTag set Status = 0
                     where Status != 99 
                     and Status != 98 
                     and Status != 0 
COMMIT Tran
GO

GRANT  EXECUTE  ON aaEventTagSelectAll  TO Public
go
 
 /**********  aaEventTagSelectDeleted  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagSelectDeleted'))
  DROP PROCEDURE dbo.aaEventTagSelectDeleted
GO

CREATE PROCEDURE aaEventTagSelectDeleted
AS

set NOCOUNT ON

IF (0 = (select count(*) from EventTagPendingDelete))
BEGIN /* still need to return a null row for correct binding */
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTagPendingDelete e WITH (HOLDLOCK)
             LEFT OUTER JOIN TimeDetectorDetailPendingDelete t WITH (HOLDLOCK) on e.TagName = t.TagName 

END
ELSE BEGIN
   BEGIN Tran 
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTagPendingDelete e WITH (HOLDLOCK)
             LEFT OUTER JOIN TimeDetectorDetailPendingDelete t WITH (HOLDLOCK) on e.TagName = t.TagName  
        delete from EventTagPendingDelete 
   COMMIT Tran
END
GO

GRANT  EXECUTE  ON aaEventTagSelectDeleted  TO Public
go
 
 /**********  aaEventTagSelectDisabled  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagSelectDisabled'))
  DROP PROCEDURE dbo.aaEventTagSelectDisabled
GO

CREATE PROCEDURE aaEventTagSelectDisabled
AS

set NOCOUNT ON

IF (0 = (select count(*) from EventTag where Status = 99))
BEGIN /* still need to return null row for correct data binding */
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTag e WITH (HOLDLOCK) LEFT OUTER JOIN TimeDetectorDetail t WITH (HOLDLOCK) on e.TagName = t.TagName 
        where Status = 99
        and (ScanRate != 0 or DetectorTypeKey = 6) 
END
ELSE
BEGIN
   BEGIN Tran 
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTag e WITH (HOLDLOCK) LEFT OUTER JOIN TimeDetectorDetail t WITH (HOLDLOCK) on e.TagName = t.TagName 
        where Status = 99
        and (ScanRate != 0 or DetectorTypeKey = 6) 
        update EventTag set Status = 98 where Status = 99
   COMMIT Tran
END
GO

GRANT  EXECUTE  ON aaEventTagSelectDisabled  TO Public
go
 
 /**********  aaEventTagSelectInserted  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagSelectInserted'))
  DROP PROCEDURE dbo.aaEventTagSelectInserted
GO

CREATE PROCEDURE aaEventTagSelectInserted
AS

set NOCOUNT ON

IF (0 = (select count(*) from EventTag where Status = 1))
BEGIN /* still need to return a null row for correct binding */
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTag e WITH (HOLDLOCK) LEFT OUTER JOIN TimeDetectorDetail t WITH (HOLDLOCK) on e.TagName = t.TagName 
        where e.Status = 1 
        and (e.ScanRate != 0 or e.DetectorTypeKey = 6) 
END
ELSE
BEGIN
   BEGIN Tran 
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTag e WITH (HOLDLOCK) LEFT OUTER JOIN TimeDetectorDetail t WITH (HOLDLOCK) on e.TagName = t.TagName 
        where e.Status = 1 
        and (e.ScanRate != 0 or e.DetectorTypeKey = 6) 
 
        update EventTag set Status = 0 where Status = 1 
   COMMIT Tran
END
GO

GRANT  EXECUTE  ON aaEventTagSelectInserted  TO Public
go
 
 /**********  aaEventTagSelectUpdated  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaEventTagSelectUpdated'))
  DROP PROCEDURE dbo.aaEventTagSelectUpdated
GO

CREATE PROCEDURE aaEventTagSelectUpdated
AS

set NOCOUNT ON

IF (0 = (select count(*) from EventTag where Status = 2))
BEGIN /* still need to return null row for correct data binding */
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTag e WITH (HOLDLOCK) LEFT OUTER JOIN TimeDetectorDetail t WITH (HOLDLOCK) on e.TagName = t.TagName 
        where e.Status = 2
        and  (e.ScanRate != 0 or e.DetectorTypeKey = 6) 
END
ELSE
BEGIN
   BEGIN Tran 
        select e.TagName, e.ScanRate, e.UseThreadPool, e.Status, e.Logged, e.Priority, e.Edge,
               e.DetectorTypeKey, t.FrequencyID, t.Periodicity, t.RunTimeDay, t.RunTimeHour, t.RunTimeMin, t.StartDateTime   
        from EventTag e WITH (HOLDLOCK) LEFT OUTER JOIN TimeDetectorDetail t WITH (HOLDLOCK) on e.TagName = t.TagName 
        where e.Status = 2
        and  (e.ScanRate != 0 or e.DetectorTypeKey = 6) 
 
        update EventTag set Status = 0 where Status = 2
   COMMIT Tran
END

GO

GRANT  EXECUTE  ON aaEventTagSelectUpdated TO Public
go
 
 /**********  aaGetDbRevision  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaGetDbRevision'))
  DROP PROCEDURE dbo.aaGetDbRevision
GO

CREATE procedure aaGetDbRevision 
AS
    SELECT DbRevision 
        FROM StorageNode 
GO

GRANT exec on aaGetDbRevision to Public
go
 
 /**********  aaGetLastTagKey  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaGetLastTagKey'))
  DROP PROCEDURE dbo.aaGetLastTagKey
GO

CREATE procedure aaGetLastTagKey 
@TagType int
AS
    DECLARE @Index int
  
    SELECT @Index = Max(wwTagKey) 
        FROM Tag 
        WHERE TagType = @TagType

    RETURN ISNULL(@Index,0)
GO

GRANT exec on aaGetLastTagKey to Public
go
 
 /**********  aaHistorianConfigNSExpand  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaHistorianConfigNSExpand'))
  DROP PROCEDURE dbo.aaHistorianConfigNSExpand
GO

CREATE PROCEDURE aaHistorianConfigNSExpand 
  @PKey int
AS
BEGIN
  IF @PKey = 1
  BEGIN
    -- Need System namespace
    SELECT TypeKey = 1000002,
           Name = 'System Configuration',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
  END

  IF @PKey = 2
  BEGIN
    -- Need Public namespace
    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 3
  BEGIN
    -- Need System and Public namespace
    SELECT TypeKey = 1000002,
           Name = 'System Configuration',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
 
    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 4
  BEGIN
    -- Need Private namespace
    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PrivateNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 5
  BEGIN
    -- Need System and Private namespaces
    SELECT TypeKey = 1000002,
           Name = 'System Configuration',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
 
    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PrivateNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 6
  BEGIN
    -- Need Private and Public namespaces
    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = 0
 
    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PrivateNameSpace
    WHERE  ParentKey = 0

  END

  IF @PKey = 7
  BEGIN
    -- Need System, Public and Private namespaces
    SELECT TypeKey = 1000002,
           Name = 'System Configuration',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
 
    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = 0

    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PrivateNameSpace
    WHERE  ParentKey = 0
  END
END
GO

GRANT  EXECUTE  ON aaHistorianConfigNSExpand  TO Public
go
 
 /**********  aaHistorianNSExpand  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaHistorianNSExpand'))
  DROP PROCEDURE dbo.aaHistorianNSExpand
GO

CREATE PROCEDURE aaHistorianNSExpand 
  @PKey int
AS
BEGIN
  IF @PKey = 1
  BEGIN
    -- Need System namespace
    SELECT TypeKey = 1000002,
           Name = 'System Objects',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
  END

  IF @PKey = 2
  BEGIN
    -- Need Public namespace
    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 3
  BEGIN
    -- Need System and Public namespace
    SELECT TypeKey = 1000002,
           Name = 'System Objects',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
 
    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 4
  BEGIN
    -- Need Private namespace
    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PrivateNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 5
  BEGIN
    -- Need System and Private namespaces
    SELECT TypeKey = 1000002,
           Name = 'System Objects',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
 
    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PrivateNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 6
  BEGIN
    -- Need System and Public namespaces
    SELECT TypeKey = 1000002,
           Name = 'System Objects',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
 
    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = 0
  END

  IF @PKey = 7
  BEGIN
    -- Need System, Public and Private namespaces
    SELECT TypeKey = 1000002,
           Name = 'System Objects',
           ServerKey = 1,
           PKey = 2,
           HasChildren = 1
 
    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = 0

    UNION ALL

    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PrivateNameSpace
    WHERE  ParentKey = 0
  END
END
GO

GRANT  EXECUTE  ON aaHistorianNSExpand  TO Public
go
 
 /**********  aaHistorianStatusSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaHistorianStatusSelect'))
  DROP PROCEDURE dbo.aaHistorianStatusSelect
GO

CREATE procedure aaHistorianStatusSelect 
AS
BEGIN
   SELECT  DbStatus
    FROM  StorageNode
    WHERE StorageNodeKey = 1
END
GO

GRANT EXEC ON aaHistorianStatusSelect TO Public
go
 
 /**********  aaHistorianStatusSet  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaHistorianStatusSet'))
  DROP PROCEDURE dbo.aaHistorianStatusSet
GO

/* This procedure is used to indicate to the back end control service that a 
    reinitialisation is needed.  Only the first argument is required, the others are
    used to indicate that a specific sub system needs to be initialised */
CREATE procedure aaHistorianStatusSet 
  @DbStatus  int,
  @Acquisition int = 0,
  @Storage int = 0,
  @DBServer int = 0
AS
BEGIN
  UPDATE StorageNode 
  SET DbStatus  = @DbStatus
  WHERE  StorageNodeKey = 1
END
GO

GRANT EXEC ON aaHistorianStatusSet TO aaAdministrators
GO
GRANT EXEC ON aaHistorianStatusSet TO aaPowerUsers
go
 
 /**********  aaHistoryBlockSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaHistoryBlockSelect'))
  DROP PROCEDURE dbo.aaHistoryBlockSelect
GO

CREATE procedure aaHistoryBlockSelect 
  @fromdate datetime = NULL,
  @todate  datetime = NULL
AS
  if @fromdate IS NULL
    set @fromdate = '19000101'
  if @todate IS NULL
    set @todate = (select getdate())

  select FromDate as 'From Date', ToDate as 'To Date', Description from HistoryBlock
    where FromDate >= @fromdate
    and   ToDate   <= @todate
GO

GRANT exec on aaHistoryBlockSelect to Public
go
 
 /**********  aaIODriverDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIODriverDelete'))
  DROP PROCEDURE dbo.aaIODriverDelete
GO

CREATE procedure aaIODriverDelete 
  @IODriverKey int
AS
  DECLARE @Result int

  DELETE FROM IODriver
  WHERE  IODriverKey = @IODriverKey

if @@ERROR <> 0
begin
   goto error
end

return

error:
  declare @errno int, @errmsg varchar (255)
  set @errno = 17007
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid IODriver delete'
  end

  raiserror @errno @errmsg 
GO

GRANT exec on aaIODriverDelete to aaAdministrators
GO
GRANT exec on aaIODriverDelete to aaPowerUsers
go
 
 /**********  aaIODriverInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIODriverInsert'))
  DROP PROCEDURE dbo.aaIODriverInsert
GO

CREATE PROCEDURE aaIODriverInsert 
  @StorageNodeKey                 int = 1,
  @ComputerName                   nvarchar(255) = @@SERVERNAME,
  @StoreForwardMode               tinyint = 0,
  @StoreForwardPath               nvarchar(255) = '', 
  @MinMBThreshold                 int = 16,
  @AltComputerName                nvarchar(255) = '',
  @Enabled                        bit = 1,
  @StoreForwardDuration           int = 180,
  @AutonomousStartupTimeout       int = 60,
  @BufferCount                    int = 128,
  @FileChunkSize                  int = 65536,
  @ForwardingDelay                int = 0,
  @ConnectionTimeout              int = 30
AS
BEGIN
  DECLARE @result int

  INSERT INTO IODriver
   (
   StorageNodeKey,
   ComputerName,
   StoreForwardMode,
   StoreForwardPath,
   MinMBThreshold,
   AltComputerName,
   Enabled,
   StoreForwardDuration,
   AutonomousStartupTimeout,
   BufferCount,
   FileChunkSize,
   ForwardingDelay,
   ConnectionTimeout
   )
  VALUES
   (
   1,
   @ComputerName,
   @StoreForwardMode,
   @StoreForwardPath, 
   @MinMBThreshold,
   @AltComputerName,
   @Enabled,
   @StoreForwardDuration,
   @AutonomousStartupTimeout,
   @BufferCount,
   @FileChunkSize,
   @ForwardingDelay,
   @ConnectionTimeout
   )

   if @@ERROR <> 0
   begin
      goto error
   end

   /* Need to return the IODriverKey */
   /* @@IDENTITY cannot be used because of Insert trigger actions */
   set @result = (select IODriverKey from IODriver where ComputerName = @ComputerName)

   return @result

   error:
     declare @errno int, @errmsg nvarchar (255)
     set @errno = 17006
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
     if @errmsg  is NULL
     begin
        set @errmsg = 'Error msg not found - Invalid IODriver insert'
     end

     raiserror @errno @errmsg 
END

GO

GRANT EXEC ON aaIODriverInsert TO aaAdministrators
GO
GRANT EXEC ON aaIODriverInsert TO aaPowerUsers
go
 
 /**********  aaIODriverSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIODriverSelect'))
  DROP PROCEDURE dbo.aaIODriverSelect
GO

CREATE procedure aaIODriverSelect 
  @IODriverKey int = NULL
AS
IF @IODriverKey IS NULL 
BEGIN 
   SELECT IODriverKey,
          StorageNodeKey,
          ComputerName,
          StoreForwardMode,
          StoreForwardPath,
          MinMBThreshold,
          AltComputerName,
          Enabled,
          StoreForwardDuration,
          AutonomousStartupTimeout,
          BufferCount,
          FileChunkSize,
          ForwardingDelay,
          ConnectionTimeout
   FROM   IODriver
   ORDER BY IODriverKey
END
ELSE
BEGIN
   SELECT IODriverKey,
          StorageNodeKey,
          ComputerName,
          StoreForwardMode,
          StoreForwardPath,
          MinMBThreshold,
          AltComputerName,
          Enabled,
          StoreForwardDuration,
          AutonomousStartupTimeout,
          BufferCount,
          FileChunkSize,
          ForwardingDelay,
          ConnectionTimeout
   FROM   IODriver
   WHERE  IODriverKey = @IODriverKey
END

if @@ERROR <> 0
begin
   goto error
end

return

error:
  declare @errno int, @errmsg nvarchar (255)
  set @errno = 17008
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid IODriver select'
  end

  raiserror @errno @errmsg 

GO

GRANT EXEC ON aaIODriverSelect TO Public
go
 
 /**********  aaIODriverUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIODriverUpdate'))
  DROP PROCEDURE dbo.aaIODriverUpdate
GO

CREATE procedure aaIODriverUpdate 
  @IODriverKey           int,
  @StorageNodeKey        int = 1,
  @ComputerName          nvarchar(255),
  @StoreForwardMode      tinyint,
  @StoreForwardPath      nvarchar(255),
  @MinMBThreshold        int = 16,
  @AltComputerName       nvarchar(255),
  @Enabled               bit = 1,
  @StoreForwardDuration  int = 180,
  @AutonomousStartupTimeout  int = 60,
  @BufferCount          int = 128,
  @FileChunkSize        int = 65536,
  @ForwardingDelay      int = 0,
  @ConnectionTimeout    int = 30
AS
UPDATE IODriver
SET
 ComputerName  = @ComputerName,
 StoreForwardMode  = @StoreForwardMode,
 StoreForwardPath = @StoreForwardPath,
 MinMBThreshold = @MinMBThreshold,
 AltComputerName = @AltComputerName,
 Enabled = @Enabled,
 StoreForwardDuration = @StoreForwardDuration,
 AutonomousStartupTimeout = @AutonomousStartupTimeout,
 BufferCount = @BufferCount,
 FileChunkSize = @FileChunkSize,
 ForwardingDelay = @ForwardingDelay,
 ConnectionTimeout = @ConnectionTimeout
WHERE  IODriverKey = @IODriverKey

if @@ERROR <> 0
begin
   goto error
end

return

error:
  declare @errno int, @errmsg nvarchar (255)
  set @errno = 17009
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid IODriver update'
  end

  raiserror @errno @errmsg 

GO
GRANT EXEC ON aaIODriverUpdate TO aaAdministrators
GO
GRANT exec on aaIODriverUpdate to aaPowerUsers
go
 
 /**********  aaInternalIODriverExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalIODriverExport'))
  DROP PROCEDURE dbo.aaInternalIODriverExport
GO

CREATE procedure aaInternalIODriverExport 
  @Format int=0
AS
--**************************
-- Export IODriver
--**************************
declare @insql_name nvarchar(32)

select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList

SELECT [:(IODriver)ComputerName]=CASE LOWER(ComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(ComputerName)
 END, 
 [AltComputerName]=CASE LOWER(AltComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(AltComputerName)
 END, 
 [StoreForwardMode]=CASE StoreForwardMode
 WHEN 2 THEN 'Autonomous'
 WHEN 1 THEN 'Standard'
 ELSE 'Off'
 END,
 StoreForwardPath,
 [MinMBThreshold]=CASE @Format
 WHEN 0 THEN RTRIM(CONVERT(nvarchar(16), MinMBThreshold))
 ELSE MinMBThreshold
 END,
 [Enabled]=CASE Enabled
 WHEN 1 THEN 'Yes'
 ELSE 'No'
 END,
 [StoreForwardDuration]=CASE @Format
 WHEN 0 THEN RTRIM(CONVERT(nvarchar(16), StoreForwardDuration))
 ELSE StoreForwardDuration
 END,
 [AutonomousStartupTimeout]=CASE @Format
 WHEN 0 THEN RTRIM(CONVERT(nvarchar(16), AutonomousStartupTimeout))
 ELSE AutonomousStartupTimeout
 END,
 [BufferCount]=CASE @Format
 WHEN 0 THEN RTRIM(CONVERT(nvarchar(16), BufferCount))
 ELSE BufferCount
 END,
 [FileChunkSize]=CASE @Format
 WHEN 0 THEN RTRIM(CONVERT(nvarchar(16), FileChunkSize))
 ELSE FileChunkSize
 END,
 [ForwardingDelay]=CASE @Format
 WHEN 0 THEN RTRIM(CONVERT(nvarchar(16), ForwardingDelay))
 ELSE ForwardingDelay
 END,
 [ConnectionTimeout]=CASE @Format
 WHEN 0 THEN RTRIM(CONVERT(nvarchar(16), ConnectionTimeout))
 ELSE ConnectionTimeout
 END
FROM IODriver
WHERE IODriverKey > 1

if @@ERROR <> 0
begin
   goto error
end

return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50000
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='IODriver export failed'
end
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalIODriverExport to aaAdministrators
go
 
 /**********  aaInternalIODriverImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalIODriverImport'))
  DROP PROCEDURE dbo.aaInternalIODriverImport
GO

CREATE procedure aaInternalIODriverImport 
  @Mode nvarchar(32)='update',
  @ComputerName nvarchar(256),
  @AltComputerName nvarchar(256),
  @StoreForwardMode nvarchar(10),
  @StoreForwardPath nvarchar(256),
  @MinMBThreshold nvarchar(16),
  @Enabled nvarchar(10)='enabled',
  @StoreForwardDuration nvarchar(16)='180',
  @AutonomousStartupTimeout nvarchar(16)='60',
  @BufferCount nvarchar(16)='128',
  @FileChunkSize nvarchar(16)='65536',
  @ForwardingDelay nvarchar(16)='0',
  @ConnectionTimeout nvarchar(16)='30'
AS
--**************************
-- Import IODriver
--**************************
declare @key int, @storagenode_key int
declare @sfmode int, @min_mb int
declare @enabled_flag bit, @sfduration int, @autostartup_timeout int
declare @bufcount int, @filechunk_size int, @forwarding_delay int,  @connection_timeout int
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)
declare @insql_name nvarchar(32)

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything
IF @Mode='ignore'
return

select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList
set @ComputerName=LTRIM(RTRIM(LOWER(@ComputerName)))

if len(@ComputerName) = 0
 BEGIN
 set @errno=50300
 set @errmsg_default='IODriver import failed (an empty ComputerName is not allowed)'
 goto error
 END

if @ComputerName='$local'
BEGIN
 set @ComputerName=@insql_name
END
set @AltComputerName=LTRIM(RTRIM(LOWER(@AltComputerName)))
if @AltComputerName='$local'
BEGIN
 set @AltComputerName=@insql_name
END

set @sfmode=CASE LTRIM(RTRIM(LOWER(@StoreForwardMode)))
  WHEN 'off' THEN 0
  WHEN 'on' THEN 1    -- legacy
  WHEN 'standard' THEN 1
  WHEN 'autonomous' THEN 2
  ELSE 1
  END
set @min_mb=CONVERT(int, @MinMBThreshold)
set @enabled_flag=CASE LTRIM(RTRIM(LOWER(@Enabled)))
  WHEN 'no' THEN 0
  ELSE 1
  END
set @sfduration=CONVERT(int, @StoreForwardDuration)
set @autostartup_timeout=CONVERT(int, @AutonomousStartupTimeout)
set @bufcount=CONVERT(int, @BufferCount)
set @filechunk_size=CONVERT(int, @FileChunkSize)
set @forwarding_delay=CONVERT(int, @ForwardingDelay)
set @connection_timeout=CONVERT(int, @ConnectionTimeout)

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- First, check if an IDAS with this computer name already exists
-- If so, update or delete it as specified by the mode parameter

select @key=IODriverKey, @storagenode_key=StorageNodeKey from IODriver 
where LTRIM(RTRIM(LOWER(ComputerName)))=LTRIM(RTRIM(LOWER(@ComputerName)))
IF @key is not null
BEGIN
 if @Mode='update'
 BEGIN
 exec aaIODriverUpdate 
  @key,
  @storagenode_key,
  @ComputerName,
  @sfmode,
  @StoreForwardPath,
  @min_mb,
  @AltComputerName,
  @enabled_flag,
  @sfduration,
  @autostartup_timeout,
  @bufcount,
  @filechunk_size,
  @forwarding_delay,
  @connection_timeout
 if @@ERROR <> 0
  BEGIN
  set @errno=50100
  set @errmsg_default='IODriver import failed (update failed)'
  goto error
  END
 END
 else if @Mode='delete'
 BEGIN
 exec aaIODriverDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50102
  set @errmsg_default='IODriver import failed (delete failed)'
  goto error
  END
 END
END
ELSE
-- The IDAS does not exist, insert it if this is what 
-- the user specified, otherwise return an error
BEGIN
if @Mode='delete'
BEGIN
return
END
else
BEGIN
exec aaIODriverInsert 
 1,
 @ComputerName,
 @sfmode,
 @StoreForwardPath,
 @min_mb,
 @AltComputerName,
 @enabled_flag,
 @sfduration,
 @autostartup_timeout,
 @bufcount,
 @filechunk_size,
 @forwarding_delay,
 @connection_timeout
if @@ERROR <> 0
 BEGIN
 set @errno=50101
 set @errmsg_default='IODriver import failed (insert failed)'
 goto error
 END
END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalIODriverImport to aaAdministrators
go
 
 /**********  aaIOServerDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIOServerDelete'))
  DROP PROCEDURE dbo.aaIOServerDelete
GO

CREATE procedure aaIOServerDelete 
  @IOServerKey int
AS
  DELETE FROM IOServer
  WHERE  IOServerKey = @IOServerKey
GO

GRANT exec on aaIOServerDelete to aaAdministrators
GO
GRANT exec on aaIOServerDelete to aaPowerUsers
go
 
 /**********  aaIOServerInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIOServerInsert'))
  DROP PROCEDURE dbo.aaIOServerInsert
GO

CREATE PROCEDURE aaIOServerInsert 
  @StorageNodeKey        int = 1,
  @ApplicationName       nvarchar(32),
  @Description           nvarchar(50) = NULL,
  @Path                  nvarchar(255) = NULL, 
  @ComputerName          nvarchar(255),
  @AutoStart             bit = 0,
  @ExeType               int = 0,
  @InitializationStatus  tinyint,
  @ProtocolType          int = 1,
  @AltComputerName      nvarchar(255) = NULL,
  @IODriverKey           int = 2

AS
BEGIN
  DECLARE @result int

  INSERT INTO IOServer
   (
   StorageNodeKey,
   IODriverKey,
   ApplicationName,
   Description,
   Path,
   ComputerName,
   AutoStart,
   ExeType,
   InitializationStatus,
   ProtocolType,
   AltComputerName
   )
  VALUES
   (
   @StorageNodeKey,
   @IODriverKey,
   @ApplicationName,
   @Description,
   @Path,
   @ComputerName,
   @AutoStart,
   @ExeType,
   @InitializationStatus,
   @ProtocolType,
   @AltComputerName
   )

   if @@ERROR <> 0
   begin
      goto error
   end

   /* Need to return the IOServerKey */
   /* @@IDENTITY cannot be used because of Insert trigger actions */
   set @result = (select IOServerKey from IOServer
                        where ComputerName = @ComputerName
                        and   ApplicationName = @ApplicationName)

   return @result

   error:
     declare @errno int, @errmsg nvarchar (255)
     set @errno = 17015
     set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
     if @errmsg  is NULL
     begin
        set @errmsg = 'Error msg not found - Invalid IOServer insert'
     end

     raiserror @errno @errmsg 
END

GO

GRANT EXEC ON aaIOServerInsert TO aaAdministrators
GO
GRANT EXEC ON aaIOServerInsert TO aaPowerUsers
go
 
 /**********  aaIOServerSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIOServerSelect'))
  DROP PROCEDURE dbo.aaIOServerSelect
GO

CREATE procedure aaIOServerSelect 
  @IOServerKey int = NULL
AS
IF @IOServerKey IS NULL 
BEGIN 
   SELECT IOServerKey,
          StorageNodeKey,
          IODriverKey,
          ApplicationName,
          Description,
          Path,
          ComputerName,
          AltComputerName,
          AutoStart,
          ExeType,
          InitializationStatus,
          ProtocolType

   FROM   IOServer
END
ELSE
BEGIN
   SELECT IOServerKey,
          StorageNodeKey,
          IODriverKey,
          ApplicationName,
          Description,
          Path,
          ComputerName,
          AltComputerName,
          AutoStart,
          ExeType,
          InitializationStatus,
          ProtocolType
   FROM   IOServer
   WHERE  IOServerKey = @IOServerKey
END
GO

GRANT EXEC ON aaIOServerSelect TO Public
go
 
 /**********  aaIOServerUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIOServerUpdate'))
  DROP PROCEDURE dbo.aaIOServerUpdate
GO

CREATE procedure aaIOServerUpdate 
 @IOServerKey           int,
 @StorageNodeKey        int,
 @IODriverKey           int,
 @ApplicationName       nvarchar(32),
 @Description           nvarchar(50),
 @Path                  nvarchar(255),
 @ComputerName          nvarchar(255),
 @AutoStart             bit,
 @ExeType               int,
 @InitializationStatus  tinyint,
 @ProtocolType          int,
 @AltComputerName      nvarchar(255) = NULL
AS
UPDATE IOServer
SET
 ApplicationName      = @ApplicationName,
 Description          = @Description,
 Path                 = @Path,
 ComputerName         = @ComputerName,
 AutoStart            = @AutoStart,
 ExeType              = @ExeType,
 InitializationStatus = @InitializationStatus,
 ProtocolType         = @ProtocolType,
 AltComputerName      = @AltComputerName,
 IODriverKey          = @IODriverKey
WHERE  IOServerKey = @IOServerKey

if @@ERROR <> 0
begin
   goto error
end

return

error:
  declare @errno int, @errmsg nvarchar (255)
  set @errno = 17013
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid IOServer update'
  end

  raiserror @errno @errmsg 

GO

GRANT EXEC ON aaIOServerUpdate TO aaAdministrators
GO
GRANT exec on aaIOServerUpdate to aaPowerUsers
go
 
 /**********  aaIOServerTypeDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIOServerTypeDelete'))
  DROP PROCEDURE dbo.aaIOServerTypeDelete
GO

CREATE procedure aaIOServerTypeDelete 
  @ApplicationName   nvarchar(32)
AS
BEGIN
  DELETE FROM IOServerType
  WHERE  ApplicationName = @ApplicationName

   if @@ERROR <> 0
   begin
      goto error
   end

   return 

   error:
     declare @errno int, @errmsg nvarchar (255)
     set @errno = 17026
     set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
     if @errmsg  is NULL
     begin
        set @errmsg = 'Error msg not found - Invalid IOServerType delete'
     end
     raiserror @errno @errmsg 

END

GO

GRANT exec on aaIOServerTypeDelete to aaAdministrators
GO
GRANT exec on aaIOServerTypeDelete to aaPowerUsers
go
 
 /**********  aaIOServerTypeInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIOServerTypeInsert'))
  DROP PROCEDURE dbo.aaIOServerTypeInsert
GO

CREATE PROCEDURE aaIOServerTypeInsert 
  @ApplicationName       nvarchar(32),
  @Description           nvarchar(50) = NULL,
  @ExeName                  nvarchar(255) = NULL, 
  @Revision          nchar(20) = NULL,
  @Platform             nchar(20) = NULL
AS
BEGIN
  DECLARE @result int

  INSERT INTO IOServerType
   (
   ApplicationName,
   Description,
   ExeName,
   Revision,
   Platform
   )
  VALUES
   (
   @ApplicationName,
   @Description,
   @ExeName,
   @Revision,
   @Platform
   )

   if @@ERROR <> 0
   begin
      goto error
   end

   return

   error:
     declare @errno int, @errmsg nvarchar (255)
     set @errno = 17025
     set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
     if @errmsg  is NULL
     begin
        set @errmsg = 'Error msg not found - Invalid IOServerType insert'
     end

     raiserror @errno @errmsg 
END

GO

GRANT EXEC ON aaIOServerTypeInsert TO aaAdministrators
GO
GRANT EXEC ON aaIOServerTypeInsert TO aaPowerUsers
go
 
 /**********  aaIOServerTypeSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIOServerTypeSelect'))
  DROP PROCEDURE dbo.aaIOServerTypeSelect
GO

CREATE procedure aaIOServerTypeSelect 
  @ApplicationName nvarchar(32) = NULL
AS
BEGIN 
   IF @ApplicationName IS NULL 
   BEGIN 
      SELECT ApplicationName, Description, ExeName, Revision, Platform
         FROM   IOServerType
            ORDER BY ApplicationName
   END
   ELSE
   BEGIN
      SELECT ApplicationName, Description, ExeName, Revision, Platform
         FROM   IOServerType
            WHERE ApplicationName = @ApplicationName
   END
END

if @@ERROR <> 0
begin
   goto error
end

return

error:
  declare @errno int, @errmsg nvarchar (255)
  set @errno = 17028
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid IOServerType select'
  end

  raiserror @errno @errmsg 

GO

GRANT EXEC ON aaIOServerTypeSelect TO Public
go
 
 /**********  aaIOServerTypeUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaIOServerTypeUpdate'))
  DROP PROCEDURE dbo.aaIOServerTypeUpdate
GO

CREATE procedure aaIOServerTypeUpdate 
  @ApplicationName       nvarchar(32),
  @Description           nvarchar(50),
  @ExeName             nvarchar(255),
  @Revision          nchar(20),
  @Platform           nchar(20)
AS
UPDATE IOServerType
SET
 Description          = @Description,
 ExeName                 = @ExeName,
 Revision         = @Revision,
 Platform            = @Platform
WHERE  ApplicationName = @ApplicationName

if @@ERROR <> 0
begin
   goto error
end

return

error:
  declare @errno int, @errmsg nvarchar (255)
  set @errno = 17027
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid IOServerType update'
  end

  raiserror @errno @errmsg 

GO

GRANT EXEC ON aaIOServerTypeUpdate TO aaAdministrators
GO
GRANT exec on aaIOServerTypeUpdate to aaPowerUsers
go
 
 /**********  aaInternalIOServerExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalIOServerExport'))
  DROP PROCEDURE dbo.aaInternalIOServerExport
GO

CREATE procedure aaInternalIOServerExport 
  @Format int=0
AS
--**************************
-- Export IOServer
--**************************
declare @insql_name nvarchar(32)

select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList

SELECT [:(IOServer)ComputerName]=CASE LOWER(IOServer.ComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(IOServer.ComputerName)
 END, 
 ApplicationName, 
 [AltComputerName]=CASE LOWER(IOServer.AltComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(IOServer.AltComputerName)
 END,
 [IDASComputerName]=CASE LOWER(IODriver.ComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(IODriver.ComputerName)
 END, 
 [ProtocolType]=CASE ProtocolType
 WHEN 1 THEN 'DDE'
 ELSE 'SuiteLink'
 END
FROM IOServer, IODriver
WHERE IOServerKey > 2 and IODriver.IODriverKey=IOServer.IODriverKey

if @@ERROR <> 0
begin
   goto error
end

return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50001
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='IOServer export failed'
end
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalIOServerExport to aaAdministrators
go
 
 /**********  aaInternalIOServerImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalIOServerImport'))
  DROP PROCEDURE dbo.aaInternalIOServerImport
GO

CREATE procedure aaInternalIOServerImport 
  @Mode nvarchar(32)='update',
  @ComputerName nvarchar(256),
  @ApplicationName nvarchar(64),
  @AltComputerName nvarchar(256),
  @IDASComputerName nvarchar(256),
  @ProtocolType nvarchar(32)
AS
--**************************
-- Import IOServer
--**************************
declare @key int, @storagenode_key int, @idas_key int, @protocol int
declare @description nvarchar(50), @path nvarchar(255)
declare @autostart bit, @exetype int, @init_status tinyint
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)
declare @insql_name nvarchar(32)

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

set @ApplicationName=LTRIM(RTRIM(@ApplicationName))
if len(@ApplicationName) = 0
 BEGIN
 set @errno=50302
 set @errmsg_default='IOServer import failed (an empty ApplicationName is not allowed)'
 goto error
 END
select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList
set @ComputerName=LTRIM(RTRIM(LOWER(@ComputerName)))
if len(@ComputerName) = 0
 BEGIN
 set @errno=50301
 set @errmsg_default='IOServer import failed (an empty ComputerName is not allowed)'
 goto error
 END
if @ComputerName='$local'
BEGIN
 set @ComputerName=@insql_name
END
set @AltComputerName=LTRIM(RTRIM(LOWER(@AltComputerName)))
if @AltComputerName='$local'
BEGIN
 set @AltComputerName=@insql_name
END
set @IDASComputerName=LTRIM(RTRIM(LOWER(@IDASComputerName)))
if @IDASComputerName='$local'
BEGIN
 set @IDASComputerName=@insql_name
END

set @protocol=CASE LTRIM(RTRIM(LOWER(@ProtocolType)))
  WHEN 'dde' THEN 1
  ELSE 2
  END

-- Check if we have a corresponding IOServer type, if not
-- create it.

if not exists(select ApplicationName from IOServerType
  where LOWER(LTRIM(RTRIM(ApplicationName)))=LOWER(LTRIM(RTRIM(@ApplicationName))))
BEGIN
 exec aaIOServerTypeInsert @ApplicationName, @ApplicationName,  @ApplicationName, NULL,NULL
END
ELSE
BEGIN
 -- Get the exact case from the IOServerType table
 select @ApplicationName=ApplicationName from IOServerType
  where LOWER(LTRIM(RTRIM(ApplicationName)))=LOWER(LTRIM(RTRIM(@ApplicationName)))
END

-- Get the key of the IDAS to which this IOServer is supposed to belong.
-- If the IDAS does not exist, and the user is not deleting this IOServer, 
-- return an error.

select @idas_key=IODriverKey from IODriver 
where LTRIM(RTRIM(LOWER(ComputerName)))=LTRIM(RTRIM(LOWER(@IDASComputerName)))
if (@idas_key is null) AND (@Mode <> 'delete')
BEGIN
 set @errno=50103
 set @errmsg_default='IOServer import failed (IDAS does not exist)'
 goto error
END

-- Check if an IOServer with this computer name/app name already exists
-- If so, update or delete it as specified by the mode parameter

select 
@key=IOServerKey, @storagenode_key=StorageNodeKey,
@description=Description, @path=Path, @autostart=AutoStart, 
@exetype=ExeType, @init_status=InitializationStatus
from IOServer 
where LTRIM(RTRIM(LOWER(ComputerName)))=LTRIM(RTRIM(LOWER(@ComputerName)))
and LTRIM(RTRIM(LOWER(ApplicationName)))=LTRIM(RTRIM(LOWER(@ApplicationName)))

if @key is not null
BEGIN
 if @Mode='update'
 BEGIN
 exec aaIOServerUpdate 
  @key,
  @storagenode_key,
  @idas_key,
  @ApplicationName,
  @description,
  @path,
  @ComputerName,
  @autostart,
  @exetype,
  @init_status,
  @protocol,
  @AltComputerName
 if @@ERROR <> 0
  BEGIN
  set @errno=50104
  set @errmsg_default='IOServer import failed (update failed)'
  goto error
  END
 END
 else if @Mode='delete'
 BEGIN
 exec aaIOServerDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50105
  set @errmsg_default='IOServer import failed (delete failed)'
  goto error
  END
 END
END
else

-- The IOServer does not exist, insert it if this is what 
-- the user specified, otherwise return an error

BEGIN
if @Mode='delete'
BEGIN
return
END
else
BEGIN
exec aaIOServerInsert 
 1,
 @ApplicationName,
 '',
 '',
 @ComputerName,
 0,
 0,
 0,
 @protocol,
 @AltComputerName,
 @idas_key
if @@ERROR <> 0
 BEGIN
 set @errno=50106
 set @errmsg_default='IOServer import failed (insert failed)'
 goto error
 END
END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalIOServerImport to aaAdministrators
go
 
 /**********  aaInTouchNodeTagList  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInTouchNodeTagList'))
  DROP PROCEDURE dbo.aaInTouchNodeTagList
GO

CREATE procedure aaInTouchNodeTagList 
  @nodekey int = NULL,
  @FilterStr nvarchar(100) = N'%'
AS
if @nodekey IS NULL
begin
   select its.TagName, OriginalName, [InTouch Tag Type] =
      CASE TypeInfo
        WHEN 1 THEN 'I/O Integer'
        WHEN 2 THEN 'I/O Real'
        WHEN 3 THEN 'Memory Integer'
        WHEN 4 THEN 'Memory Real'
        WHEN 5 THEN 'I/O Discrete'
        WHEN 6 THEN 'Memory Discrete'
        WHEN 7 THEN 'I/O Message'
        WHEN 8 THEN 'Memory Message'
        ELSE ''    
      END, t.TagType 
    from InTouchSpecific its, Tag t
       where its.TagName = t.TagName
       and its.TagName LIKE @FilterStr
       and its.InInSQL = 1
    order by its.TagName
end
else
begin
   select its.TagName, OriginalName, [InTouch Tag Type] =
      CASE TypeInfo
        WHEN 1 THEN 'I/O Integer'
        WHEN 2 THEN 'I/O Real'
        WHEN 3 THEN 'Memory Integer'
        WHEN 4 THEN 'Memory Real'
        WHEN 5 THEN 'I/O Discrete'
        WHEN 6 THEN 'Memory Discrete'
        WHEN 7 THEN 'I/O Message'
        WHEN 8 THEN 'Memory Message'
        ELSE ''    
      END, t.TagType 
    from InTouchSpecific its, Tag t
      where its.NodeKey = @nodekey
      and its.TagName = t.TagName
       and its.TagName LIKE @FilterStr
       and its.InInSQL = 1
    order by its.TagName
end

GO

GRANT EXEC ON aaInTouchNodeTagList TO Public
go
 
 /**********  aaLimitDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaLimitDelete'))
  DROP PROCEDURE dbo.aaLimitDelete
GO

CREATE procedure aaLimitDelete
  @TagName   nvarchar(256),
  @ContextKey   int,
  @LimitNameKey   int 
AS
   delete Limit where TagName = @TagName and ContextKey = @ContextKey
      and LimitNameKey = @LimitNameKey
GO

GRANT exec on aaLimitDelete to aaAdministrators
GO
GRANT exec on aaLimitDelete to aaPowerUsers
go
 
 /**********  aaLimitInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaLimitInsert'))
  DROP PROCEDURE dbo.aaLimitInsert
GO

CREATE procedure aaLimitInsert
   @TagName         nvarchar(256),
   @ContextKey      int = 1,
   @LimitType       int = 1,
   @Value           real,
   @LimitNameKey    int,
   @Priority        int      = 1,
   @Checked         bit      = 1,
   @Description     nvarchar(50) = NULL 

AS
  IF not exists (SELECT TagName FROM Limit  WHERE TagName = @TagName
                        AND ContextKey = @ContextKey AND LimitType = @LimitType
                        AND LimitNameKey = @LimitNameKey AND Value = @Value)
   BEGIN 
      INSERT Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                              Priority, Checked, Description)
                   VALUES (@TagName, @ContextKey, @LimitType, @Value, @LimitNameKey,
                           @Priority, @Checked, @Description)
   END   

GO

GRANT exec on aaLimitInsert to aaAdministrators
GO
GRANT exec on aaLimitInsert to aaPowerUsers
go
 
 /**********  aaLimitSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaLimitSelect'))
  DROP PROCEDURE dbo.aaLimitSelect
GO

CREATE procedure aaLimitSelect
  @TagName   nvarchar(256) = NULL 
AS
if @TagName is NULL
begin
      Select TagName, ContextKey, LimitNameKey, Value, Priority, LimitType, Checked, Description
         from Limit 
            order by TagName, ContextKey, LimitNameKey
end
else
begin
      Select TagName, ContextKey, LimitNameKey, Value, Priority, LimitType, Checked, Description
         from Limit where TagName = @TagName
            order by ContextKey, LimitNameKey
end

GO

GRANT exec on aaLimitSelect to public
go
 
 /**********  aaLimitUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaLimitUpdate'))
  DROP PROCEDURE dbo.aaLimitUpdate
GO

CREATE procedure aaLimitUpdate
  @TagName         nvarchar(256),
  @ContextKey      int,
  @LimitType       int,
  @Value           real,
  @LimitNameKey    int,
  @Priority        int,
  @Checked         bit,
  @Description     nvarchar(50) = NULL 
AS
      update Limit set LimitType = @LimitType, Value = @Value, Priority = @Priority, 
                               Checked = @Checked, Description = @Description
         where TagName = @TagName and  ContextKey = @ContextKey
                   and LimitNameKey =  @LimitNameKey
  
GO

GRANT exec on aaLimitUpdate to aaAdministrators
GO
GRANT exec on aaLimitUpdate to aaPowerUsers
go
 
 /**********  aaLimitNameDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaLimitNameDelete'))
  DROP PROCEDURE dbo.aaLimitNameDelete
GO

CREATE procedure aaLimitNameDelete
  @LimitNameKey     int 
AS
  IF exists (select LimitNameKey from LimitName  where LimitNameKey = @LimitNameKey)
   BEGIN 
      delete LimitName where LimitNameKey = @LimitNameKey
   END   

GO

GRANT exec on aaLimitNameDelete to aaAdministrators
GO
GRANT exec on aaLimitNameDelete to aaPowerUsers
go
 
 /**********  aaLimitNameInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaLimitNameInsert'))
  DROP PROCEDURE dbo.aaLimitNameInsert
GO

CREATE procedure aaLimitNameInsert
  @Name    nvarchar(20) = ''
AS
  IF not exists (select Name from LimitName  where Name = @Name)
   BEGIN 
      insert LimitName (Name)
                   values (@Name)
      RETURN  SCOPE_IDENTITY()
   END   
   ELSE
   BEGIN
      return 0
   END 

GO

GRANT exec on aaLimitNameInsert to aaAdministrators
GO
GRANT exec on aaLimitNameInsert to aaPowerUsers
go
 
 /**********  aaLimitNameSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaLimitNameSelect'))
  DROP PROCEDURE dbo.aaLimitNameSelect
GO

CREATE procedure aaLimitNameSelect
  @LimitNameKey    int = NULL 
AS
  if @LimitNameKey is null
   BEGIN 
      Select LimitNameKey, Name from LimitName
   END   
 else
   BEGIN
      Select LimitNameKey, Name from LimitName
         where LimitNameKey = @LimitNameKey
   END
GO

GRANT exec on aaLimitNameSelect to public
go
 
 /**********  aaLimitNameUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaLimitNameUpdate'))
  DROP PROCEDURE dbo.aaLimitNameUpdate
GO

CREATE procedure aaLimitNameUpdate
  @LimitNameKey    int,
  @Name nvarchar(20)
AS
  IF exists (select LimitNameKey from LimitName where LimitNameKey = @LimitNameKey)
   BEGIN 
      update LimitName set Name = @Name
          where LimitNameKey = @LimitNameKey
   END   

GO

GRANT exec on aaLimitNameUpdate to aaAdministrators
GO
GRANT exec on aaLimitNameUpdate to aaPowerUsers
go
 
 /**********  aaInternalMDASAnalogTagInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalMDASAnalogTagInsert'))
  DROP PROCEDURE dbo.aaInternalMDASAnalogTagInsert
GO

CREATE procedure aaInternalMDASAnalogTagInsert 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @StorageType     smallint      = 2,
  @StorageRate     int           = 10000,
  @TimeDeadband    int           = 0,
  @CreatedBy       nvarchar(256)  = '',
  @DateCreated     datetime      = NULL,
  @CurrentEditor   int           = 2,
  @Unit            nvarchar(32)  = 'None',
  @MinEU           float(25)     = 0,
  @MaxEU           float(25)     = 100,
  @MinRaw          float(25)     = 0,
  @MaxRaw          float(25)     = 100,
  @Scaling         int           = 0,
  @RawType         int           = 3,
  @ValueDeadband   float(25)     = 0,
  @InitialValue    float(25)     = 0,
  @IntegerSize     tinyint       = 32,
  @SignedInteger   bit           = 1,
  @StorageNodeKey  int           = 1,
  @AIRetrievalMode tinyint       = 0,
  @SamplesInActiveImage int      = 0,
  @RateDeadband    float(25)     = 0,
  @InterpolationType tinyint     = 254,
  @RolloverValue   int           = 0,
  @ServerTimeStamp bit           = 0,
  @DeadbandType    smallint      = 1,
  @DefaultTagRate  int           = 10000,
  @IntegralDivisor float(25)     = 1

AS
begin
   declare @result int, @EUKey int, @wwTagKey int
   set @result = 0

  /* Check if tag is already there */
   select @wwTagKey = wwTagKey from Tag where TagName = @TagName 
   if @wwTagKey > 0
   begin
      /* Validate the TagType */
      if (select TagType from Tag where TagName = @TagName) = 1
      begin
      /* Tag already exists and is of correct type, update it */
         exec @result = aaInternalMDASAnalogTagUpdate 
    @wwTagKey,
    @Description,
    @StorageType,
    @StorageRate,
    @TimeDeadband,
    @CreatedBy,
    @DateCreated,
    @CurrentEditor,
    @Unit,
    @MinEU,
    @MaxEU,
    @MinRaw,
    @MaxRaw,
    @Scaling,
    @RawType,
    @ValueDeadband,
    @InitialValue,
    @IntegerSize,
    @SignedInteger,
    @StorageNodeKey,
    @AIRetrievalMode,
    @SamplesInActiveImage,
    @RateDeadband,
    @InterpolationType,
    @RolloverValue,
    @ServerTimeStamp,
    @DeadbandType,
    @DefaultTagRate,
    @IntegralDivisor
         RETURN @result
      end
      else
      /* Tag exists but it is of the wrong Type */
      begin
         delete Tag where TagName = @TagName
      end
   end

   /* Tag does not exist, create it */
   begin tran
   if @Unit is NULL
   begin
     select @Unit = 'None'
   end

   select @EUKey=EUKey from EngineeringUnit where Unit=@Unit
   if @EUKey is null 
   begin
     exec @EUKey=aaEngineeringUnitInsert @Unit, @DefaultTagRate, @IntegralDivisor
   end

   exec @result = aaAnalogTagInsert  
     @TagName         = @TagName,
     @Description     = @Description,
     @AcquisitionType = 2,
     @StorageType     = @StorageType,
     @StorageRate     = @StorageRate,
     @ItemName        = '',
     @TimeDeadband    = @TimeDeadband,
     @CreatedBy       = @CreatedBy,
     @DateCreated     = @DateCreated,
     @CurrentEditor   = @CurrentEditor,
     @EUKey           = @EUKey,
     @MinEU           = @MinEU,
     @MaxEU           = @MaxEU,
     @MinRaw          = @MinRaw,
     @MaxRaw          = @MaxRaw,
     @Scaling         = @Scaling,
     @RawType         = @RawType,
     @ValueDeadband   = @ValueDeadband,
     @InitialValue    = @InitialValue,
     @IntegerSize     = @IntegerSize,
     @SignedInteger   = @SignedInteger,
     @TopicKey        = 2,
     @IOServerKey     = 2,
     @StorageNodeKey  = @StorageNodeKey,
     @AIRetrievalMode = @AIRetrievalMode,
     @SamplesInActiveImage = @SamplesInActiveImage,
     @RateDeadband    = @RateDeadband,
     @InterpolationType = @InterpolationType,
     @RolloverValue   = @RolloverValue,
     @ServerTimeStamp = @ServerTimeStamp,
     @DeadbandType    = @DeadbandType

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @result = -1
  END

  RETURN @result
END
GO

GRANT exec on aaInternalMDASAnalogTagInsert to aaAdministrators
GO
GRANT exec on aaInternalMDASAnalogTagInsert to aaPowerUsers
go
 
 /**********  aaInternalMDASAnalogTagUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalMDASAnalogTagUpdate'))
  DROP PROCEDURE dbo.aaInternalMDASAnalogTagUpdate
GO

CREATE procedure aaInternalMDASAnalogTagUpdate 
  @wwTagKey        int, 
  @Description     nvarchar(512) = '',
  @StorageType     smallint = 2,
  @StorageRate     int = 10000,
  @TimeDeadband    int = 0,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @CurrentEditor   int = 2,
  @Unit            nvarchar(32),
  @MinEU           float(25),
  @MaxEU           float(25),
  @MinRaw          float(25),
  @MaxRaw          float(25),
  @Scaling         int,
  @RawType         int,
  @ValueDeadband   float(25),
  @InitialValue    float(25),
  @IntegerSize     tinyint,
  @SignedInteger   bit,
  @StorageNodeKey  int = 1,
  @AIRetrievalMode tinyint,
  @SamplesInActiveImage int = 0,
  @RateDeadband    float(25)    = 0,
  @InterpolationType tinyint    = 254,
  @RolloverValue   int          = 0,
  @ServerTimeStamp bit          = 0,
  @DeadbandType    smallint     = 1,
  @DefaultTagRate  int          = 10000,
  @IntegralDivisor float(25)    = 1

AS
BEGIN
  declare @TagName nvarchar(256)
  declare @EUKey int
  if @Unit IS NULL
  begin
    select @Unit = 'None'
  end

  /* Check if the tag exists with another tagtype */
  if exists (select wwTagKey from Tag where wwTagKey = @wwTagKey and TagType <> 1)
  begin
     /* Tag already exists in other TagType */
     /*  Delete it and call the Insert SP */
     select @TagName = TagName from Tag where wwTagKey = @wwTagKey
     delete Tag where wwTagKey = @wwTagKey
     goto CallTagInsert
  end

  /* This proc updates an analog tag based upon the tag key */
  BEGIN TRAN

  select @EUKey = EUKey from EngineeringUnit where Unit = @Unit
  if @EUKey is null 
  begin
    exec @EUKey = aaEngineeringUnitInsert @Unit, @DefaultTagRate, @IntegralDivisor
  end

  exec aaAnalogTagUpdate    
     @wwTagKey        = @wwTagKey, 
     @TagName         = '',
     @Description     = @Description,
     @AcquisitionType = 2,
     @StorageType     = @StorageType,
     @StorageRate     = @StorageRate,
     @ItemName        = '',
     @TimeDeadband    = @TimeDeadband,
     @CreatedBy       = @CreatedBy,
     @DateCreated     = @DateCreated,
     @CurrentEditor   = @CurrentEditor,
     @EUKey           = @EUKey,
     @MinEU           = @MinEU,
     @MaxEU           = @MaxEU,
     @MinRaw          = @MinRaw,
     @MaxRaw          = @MaxRaw,
     @Scaling         = @Scaling,
     @RawType         = @RawType,
     @ValueDeadband   = @ValueDeadband,
     @InitialValue    = @InitialValue,
     @IntegerSize     = @IntegerSize,
     @SignedInteger   = @SignedInteger,
     @TopicKey        = 2,
     @IOServerKey     = 2,
     @StorageNodeKey  = @StorageNodeKey,
     @AIRetrievalMode = @AIRetrievalMode,
     @SamplesInActiveImage = @SamplesInActiveImage,
     @RateDeadband    = @RateDeadband,
     @InterpolationType = @InterpolationType,
     @RolloverValue   = @RolloverValue,
     @ServerTimeStamp = @ServerTimeStamp,
     @DeadbandType    = @DeadbandType

  COMMIT TRAN

  RETURN

  CallTagInsert:
     exec aaInternalMDASAnalogTagInsert
        @TagName           = @TagName,
        @Description       = @Description,
        @StorageType       = 2,
        @TimeDeadband      = @TimeDeadband,
        @CreatedBy         = @CreatedBy,
        @DateCreated       = @DateCreated,
        @CurrentEditor     = 2,
        @Unit              = @EUKey,
        @MinEU             = @MinEU,
        @MaxEU             = @MaxEU,
        @MinRaw            = @MinRaw,
        @MaxRaw            = @MaxRaw,
        @Scaling           = @Scaling,
        @RawType           = @RawType,
        @ValueDeadband     = @ValueDeadband,
        @InitialValue      = @InitialValue,
        @IntegerSize       = @IntegerSize,
        @SignedInteger     = @SignedInteger,
        @StorageNodeKey    = @StorageNodeKey,
        @AIRetrievalMode      = @AIRetrievalMode,
        @SamplesInActiveImage = @SamplesInActiveImage,
        @RateDeadband      = @RateDeadband,
        @InterpolationType = @InterpolationType,
        @RolloverValue     = @RolloverValue,
        @ServerTimeStamp   = @ServerTimeStamp,
        @DeadbandType      = @DeadbandType,
        @DefaultTagRate    = @DefaultTagRate,
        @IntegralDivisor   = @IntegralDivisor

END
GO

GRANT exec on aaInternalMDASAnalogTagUpdate to aaAdministrators
GO
GRANT exec on aaInternalMDASAnalogTagUpdate to aaPowerUsers
go
 
 /**********  aaInternalMDASDiscreteTagInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalMDASDiscreteTagInsert'))
  DROP PROCEDURE dbo.aaInternalMDASDiscreteTagInsert
GO

CREATE procedure aaInternalMDASDiscreteTagInsert 
   @TagName         nvarchar(256),
   @Description     nvarchar(512) = '',
   @TimeDeadband    int           = 0,
   @CreatedBy       nvarchar(256)  = '',
   @DateCreated     datetime      = NULL,
   @CurrentEditor   int           = 2,
   @Message0        nvarchar(64)  = 'OFF',
   @Message1        nvarchar(64)  = 'ON',
   @InitialValue    tinyint       = 0,
   @AIRetrievalMode tinyint       = 0,
   @SamplesInActiveImage int      = 0,
   @ServerTimeStamp bit           = 0,
   @DeadbandType    smallint      = 1,
   @StorageType     smallint      = 2

AS
BEGIN
   declare @result int, @MessageKey int, @wwTagKey int
   set @result = 0

   /* Check if tag is already there */
   select @wwTagKey = wwTagKey from Tag where TagName = @TagName
   if @wwTagKey > 0
   begin
      /* Validate the TagType */
      if (select TagType from Tag where TagName = @TagName) = 2
      begin
         exec @result = aaInternalMDASDiscreteTagUpdate
    @wwTagKey,
    @Description,
    @TimeDeadband,
    @CreatedBy,
    @DateCreated,
    @CurrentEditor,
    @Message0,
    @Message1,
    @InitialValue,
    @AIRetrievalMode,
    @SamplesInActiveImage,
    @ServerTimeStamp,
    @DeadbandType,
    @StorageType
         RETURN @result
      end
      else
      /* Tag exists but it is of the wrong Type */
      begin
         delete Tag where TagName = @TagName
      end
   end

   /* Tag does not exist, create it */
  BEGIN TRAN

  IF @Message0 IS NULL
  BEGIN
    SELECT @Message0 = 'OFF'
  END
  IF @Message1 IS NULL
  BEGIN
    SELECT @Message1 = 'ON'
  END

  select @MessageKey = MessageKey
       from Message where Message0 = @Message0 and Message1 = @Message1
  if @MessageKey is null 
  begin
    exec @MessageKey = aaMessageInsert @Message0, @Message1
  end

  exec aaDiscreteTagInsert 
   @TagName         = @TagName,
   @Description     = @Description,
   @AcquisitionType = 2,
   @StorageType     = @StorageType,
   @StorageRate     = 0,
   @ItemName        = '',
   @TimeDeadband    = @TimeDeadband,
   @CreatedBy       = @CreatedBy,
   @DateCreated     = @DateCreated,
   @CurrentEditor   = @CurrentEditor,
   @MessageKey      = @MessageKey,
   @InitialValue    = @InitialValue,
   @TopicKey        = 2,
   @IOServerKey     = 2,
   @AIRetrievalMode = @AIRetrievalMode,
   @SamplesInActiveImage = @SamplesInActiveImage,
   @ServerTimeStamp = @ServerTimeStamp,
   @DeadbandType    = @DeadbandType

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
    SELECT @result = (SELECT wwTagKey from Tag where TagName = @TagName)
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @result = -1
  END

  RETURN @result
END
GO

GRANT exec on aaInternalMDASDiscreteTagInsert to aaAdministrators
GO
GRANT exec on aaInternalMDASDiscreteTagInsert to aaPowerUsers
go
 
 /**********  aaInternalMDASDiscreteTagUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalMDASDiscreteTagUpdate'))
  DROP PROCEDURE dbo.aaInternalMDASDiscreteTagUpdate
GO

CREATE procedure aaInternalMDASDiscreteTagUpdate 
  @wwTagKey        int, 
  @Description     nvarchar(512) = '',
  @TimeDeadband    int = 0,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @CurrentEditor   int,
  @Message0        nvarchar(64) = 'OFF',
  @Message1        nvarchar(64) = 'ON',
  @InitialValue    tinyint = 0,
  @AIRetrievalMode tinyint = 0,
  @SamplesInActiveImage int  = 0,
  @ServerTimeStamp bit       = 0,
  @DeadbandType    smallint  = 1,
  @StorageType     smallint  = 2
 
AS
BEGIN
  declare @TagName nvarchar(256)
  declare @MessageKey int

  if @Message0 IS NULL
  begin
    select @Message0 = 'OFF'
  end
  if @Message1 IS NULL
  begin
    select @Message1 = 'ON'
  end

  /* Check if the tag exists with another tagtype */
  if exists (select wwTagKey from Tag where wwTagKey = @wwTagKey and TagType <> 2)
  begin
     /* Tag already exists in other TagType */
     /*  Delete it and call the Insert SP */
     select @TagName = TagName from Tag where wwTagKey = @wwTagKey
     delete Tag where wwTagKey = @wwTagKey
     goto CallTagInsert
  end

  /* This proc updates a discrete tag based upon the tag key */
  BEGIN TRAN
  select @MessageKey=MessageKey from Message where Message0=@Message0 and Message1=@Message1
  if @MessageKey is null 
  begin
    exec @MessageKey=aaMessageInsert @Message0, @Message1
  end

  exec aaDiscreteTagUpdate
     @wwTagKey        = @wwTagKey, 
     @TagName         = '',
     @Description     = @Description,
     @AcquisitionType = 2,
     @StorageType     = @StorageType,
     @StorageRate     = 0,
     @ItemName        = '',
     @TimeDeadband    = @TimeDeadband,
     @CreatedBy       = @CreatedBy,
     @DateCreated     = @DateCreated,
     @CurrentEditor   = @CurrentEditor,
     @MessageKey      = @MessageKey,
     @InitialValue    = @InitialValue,
     @TopicKey        = 2,
     @IOServerKey     = 2,
     @AIRetrievalMode = @AIRetrievalMode,
     @SamplesInActiveImage = @SamplesInActiveImage,
     @ServerTimeStamp = @ServerTimeStamp,
     @DeadbandType    = @DeadbandType

  COMMIT TRAN
  RETURN

  CallTagInsert:
     exec aaInternalMDASDiscreteTagInsert
         @TagName         = @TagName,
         @Description     = @Description,
         @TimeDeadband    = @TimeDeadband,
         @CreatedBy       = @CreatedBy,
         @DateCreated     = @DateCreated,
         @CurrentEditor   = 2,
         @Message0        = @Message0,
         @Message1        = @Message1,
         @InitialValue    = @InitialValue,
         @AIRetrievalMode = @AIRetrievalMode,
         @SamplesInActiveImage = @SamplesInActiveImage,
         @ServerTimeStamp = @ServerTimeStamp,
         @DeadbandType    = @DeadbandType,
         @StorageType     = @StorageType

END
GO

GRANT exec on aaInternalMDASDiscreteTagUpdate to aaAdministrators
GO
GRANT exec on aaInternalMDASDiscreteTagUpdate to aaPowerUsers
go
 
 /**********  aaInternalMDASStringTagInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalMDASStringTagInsert'))
  DROP PROCEDURE dbo.aaInternalMDASStringTagInsert
GO

CREATE procedure aaInternalMDASStringTagInsert 
   @TagName         nvarchar(256),
   @Description     nvarchar(512) = '',
   @TimeDeadband    int           = 0,
   @CreatedBy       nvarchar(256)  = '',
   @DateCreated     datetime      = NULL,
   @MaxLength       smallint  = 131,
   @InitialValue    nvarchar(512)  = '',
   @CurrentEditor   int  = 2,
   @DoubleByte      tinyint = 0,
   @SamplesInActiveImage int = 0,
   @ServerTimeStamp bit      = 0,
   @DeadbandType    smallint = 1,
   @StorageType     smallint = 2

AS
BEGIN
  DECLARE @result int, @wwTagKey int
  SELECT @result = 0

   /* Check if tag is already there */
   select @wwTagKey = wwTagKey from Tag where TagName = @TagName
   if @wwTagKey > 0
   begin
      /* Validate the TagType */
      if (select TagType from Tag where TagName = @TagName) = 3
      begin
         exec @result = aaInternalMDASStringTagUpdate
    @wwTagKey,
    @Description,
    @TimeDeadband,
    @CreatedBy,
    @DateCreated,
    @MaxLength,
    @InitialValue,
    @CurrentEditor,
    @DoubleByte,
    @SamplesInActiveImage,
    @ServerTimeStamp,
    @DeadbandType,
    @StorageType
         RETURN @result
      end
      else
      /* Tag exists but it is of the wrong Type */
      begin
         delete Tag where TagName = @TagName
      end
   end

   /* Tag does not exist, create it */
   BEGIN TRAN
   exec aaStringTagInsert 
   @TagName         = @TagName,
   @Description     = @Description,
   @AcquisitionType = 2,
   @StorageType     = @StorageType,
   @StorageRate     = 0,
   @ItemName        = '',
   @TimeDeadband    = @TimeDeadband,
   @CreatedBy       = @CreatedBy,
   @DateCreated     = @DateCreated,
   @CurrentEditor   = @CurrentEditor,
   @MaxLength       = @MaxLength,
   @InitialValue    = @InitialValue,
   @TopicKey        = 2,
   @IOServerKey     = 2,
   @DoubleByte      = @DoubleByte,
   @SamplesInActiveImage = @SamplesInActiveImage,
   @ServerTimeStamp = @ServerTimeStamp,
   @DeadbandType    = @DeadbandType

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
    SELECT @result = (SELECT wwTagKey from Tag where TagName = @TagName)
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @result = -1
  END

  RETURN @result
END
GO

GRANT exec on aaInternalMDASStringTagInsert to aaAdministrators
GO
GRANT exec on aaInternalMDASStringTagInsert to aaPowerUsers
go
 
 /**********  aaInternalMDASStringTagUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalMDASStringTagUpdate'))
  DROP PROCEDURE dbo.aaInternalMDASStringTagUpdate
GO

CREATE procedure aaInternalMDASStringTagUpdate 
  @wwTagKey        int, 
  @Description     nvarchar(512) = '',
  @TimeDeadband    int = 0,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @MaxLength       smallint = 131,
  @InitialValue    nvarchar(512) = '',
  @CurrentEditor   int,
  @DoubleByte      tinyint = 0,
  @SamplesInActiveImage int = 0,
  @ServerTimeStamp bit      = 0,
  @DeadbandType    smallint = 1,
  @StorageType     smallint = 2
 
AS
BEGIN
  declare @TagName nvarchar(256)

  /* Check if the tag exists with another tagtype */
  if exists (select wwTagKey from Tag where wwTagKey = @wwTagKey and TagType <> 3)
  begin
     /* Tag already exists in other TagType */
     /*  Delete it and call the Insert SP */
     select @TagName = TagName from Tag where wwTagKey = @wwTagKey
     delete Tag where wwTagKey = @wwTagKey
     goto CallTagInsert
     RETURN
  end

  /* This proc updates a discrete tag based upon the tag key */
  BEGIN TRAN

  exec aaStringTagUpdate
     @wwTagKey        = @wwTagKey, 
     @TagName         = '',
     @Description     = @Description,
     @AcquisitionType = 2,
     @StorageType     = @StorageType,
     @StorageRate     = 0,
     @ItemName        = '',
     @TimeDeadband    = @TimeDeadband,
     @CreatedBy       = @CreatedBy,
     @DateCreated     = @DateCreated,
     @CurrentEditor   = @CurrentEditor,
     @MaxLength       = @MaxLength,
     @InitialValue    = @InitialValue,
     @TopicKey        = 2,
     @IOServerKey     = 2,
     @DoubleByte      = @DoubleByte,
     @SamplesInActiveImage = @SamplesInActiveImage,
     @ServerTimeStamp = @ServerTimeStamp,
     @DeadbandType    = @DeadbandType

  COMMIT TRAN
  RETURN

  CallTagInsert:
      exec aaInternalMDASStringTagInsert 
         @TagName         = @TagName,
         @Description     = @Description,
         @TimeDeadband    = @TimeDeadband,
         @CreatedBy       = @CreatedBy,
         @DateCreated     = @DateCreated,
         @MaxLength       = @MaxLength,
         @InitialValue    = @InitialValue,
         @CurrentEditor   = 2,
         @DoubleByte      = @DoubleByte,
         @SamplesInActiveImage = @SamplesInActiveImage,
         @ServerTimeStamp = @ServerTimeStamp,
         @DeadbandType    = @DeadbandType,
         @StorageType     = @StorageType

END
GO

GRANT exec on aaInternalMDASStringTagUpdate to aaAdministrators
GO
GRANT exec on aaInternalMDASStringTagUpdate to aaPowerUsers
go
 
 /**********  aaMessageDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaMessageDelete'))
  DROP PROCEDURE dbo.aaMessageDelete
GO

CREATE PROCEDURE aaMessageDelete 
  @MessageKey int
AS
  DELETE FROM Message WHERE MessageKey = @MessageKey
GO

GRANT  EXECUTE  ON aaMessageDelete  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaMessageDelete  TO aaPowerUsers
go
 
 /**********  aaMessageInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaMessageInsert'))
  DROP PROCEDURE dbo.aaMessageInsert
GO

CREATE PROCEDURE aaMessageInsert 
  @Message0 nvarchar(64) = NULL,
  @Message1 nvarchar(64) = NULL
AS
  DECLARE @MessageKey int

  SELECT @MessageKey = MessageKey
    FROM Message WHERE Message0 = @Message0 AND Message1 = @Message1

  IF @MessageKey IS NULL
  BEGIN
    INSERT INTO Message (Message0, Message1)
      VALUES (@Message0, @Message1)
    SET @MessageKey = SCOPE_IDENTITY()
  END

  RETURN  @MessageKey
GO

GRANT  EXECUTE  ON aaMessageInsert  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaMessageInsert  TO aaPowerUsers
go
 
 /**********  aaMessageSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaMessageSelect'))
  DROP PROCEDURE dbo.aaMessageSelect
GO

CREATE PROCEDURE aaMessageSelect 
  @MessageKey int = NULL
AS
  IF @MessageKey is NULL
  BEGIN
    SELECT MessageKey, RTRIM(Message0), RTRIM(Message1) FROM Message
      ORDER BY Message0, Message1
  END
  ELSE
  BEGIN
    SELECT MessageKey, RTRIM(Message0), RTRIM(Message1) FROM Message
      WHERE MessageKey = @MessageKey
  END
GO

GRANT  EXECUTE  ON aaMessageSelect TO public
go
 
 /**********  aaMessageUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaMessageUpdate'))
  DROP PROCEDURE dbo.aaMessageUpdate
GO

CREATE PROCEDURE aaMessageUpdate 
  @MessageKey int,
  @Message0 nvarchar(64),
  @Message1 nvarchar(64)
AS
BEGIN
  UPDATE Message 
  SET    Message0 = @Message0,
         Message1 = @Message1
  WHERE  MessageKey = @MessageKey
END
GO

GRANT  EXECUTE  ON aaMessageUpdate  TO aaAdministrators
GO
GRANT  EXECUTE  ON aaMessageUpdate  TO aaPowerUsers
go
 
 /**********  aaInternalMessageExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalMessageExport'))
  DROP PROCEDURE dbo.aaInternalMessageExport
GO

CREATE procedure aaInternalMessageExport 
  @Format int=0
AS
--****************************
-- Export Message
--****************************
SELECT [:(Message)Message0]=Message0, 
 Message1 
 from Message
if @@ERROR <> 0
begin
   goto error
end
return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50007
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='Message export failed'
end
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalMessageExport to aaAdministrators
go
 
 /**********  aaInternalMessageImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalMessageImport'))
  DROP PROCEDURE dbo.aaInternalMessageImport
GO

CREATE procedure aaInternalMessageImport 
   @Mode nvarchar(32)='update',
   @Message0 nvarchar(64),
   @Message1 nvarchar(64)
AS
--*****************************
-- Import Message
--*****************************
declare @key int
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

-- Check if Message already exists
-- If so, update or delete it as specified by the mode parameter

select TOP 1 @key=MessageKey from Message 
where Message0=@Message0
and Message1=@Message1

if @key is not null
BEGIN
 if @Mode='delete'
 BEGIN
 exec aaMessageDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50114
  set @errmsg_default='Message import failed (delete failed)'
  goto error
  END
 END
END
else

-- The Message does not exist, insert it if this is what 
-- the user specified, otherwise return an error

BEGIN
if @Mode='delete'
BEGIN
return
END
else
BEGIN
exec aaMessageInsert 
 @Message0,
 @Message1
if @@ERROR <> 0
 BEGIN
 set @errno=50115
 set @errmsg_default='Message import failed (insert failed)'
 goto error
 END
END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalMessageImport to aaAdministrators
go
 
 /**********  aaModLogStatus  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaModLogStatus'))
  DROP PROCEDURE dbo.aaModLogStatus
GO

CREATE procedure aaModLogStatus 
AS
declare @logstatus int
SELECT @logstatus = (SELECT convert(int, Value) FROM SystemParameter WHERE Name = 'ModLogTrackingStatus')
if @logstatus in (1,2,4,3,5,6,7)
begin
  return @logstatus
end
else
begin
  return 0
end

GO
GRANT exec on aaModLogStatus to public
go
 
 /**********  aaPrivateNSAddGroup  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPrivateNSAddGroup'))
  DROP PROCEDURE dbo.aaPrivateNSAddGroup
GO

CREATE PROCEDURE aaPrivateNSAddGroup 
  @Name      nvarchar(255),
  @ParentKey int,
  @Type      int = 1000000
AS
BEGIN
  DECLARE @Result int

  INSERT PrivateNameSpace
    (Type, ParentKey, Name, UserKey)
  VALUES
    (@Type, @ParentKey, @Name, dbo.faaUser_ID())

  IF @@Error = 0
  BEGIN
    SELECT @Result = @@IDENTITY
  END
  ELSE  
  BEGIN
    SELECT @Result = -1
  END
  RETURN @Result
END
GO

GRANT  EXECUTE  ON aaPrivateNSAddGroup  TO public
go
 
 /**********  aaPrivateNSAddLeaf  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPrivateNSAddLeaf'))
  DROP PROCEDURE dbo.aaPrivateNSAddLeaf
GO

CREATE procedure aaPrivateNSAddLeaf 
  @wwTagKey  int,
  @NameKey   int,
  @ServerKey int = 1
AS
BEGIN
  INSERT PrivateGroupTag
      (NameKey, wwDomainTagKey, UserKey)
    SELECT @NameKey, wwDomainTagKey, dbo.faaUser_ID()
    FROM   TagRef 
    WHERE  wwTagKey = @wwTagKey
    AND    ServerKey = @ServerKey

  RETURN @@Error
END
GO

GRANT EXECUTE ON aaPrivateNSAddLeaf TO Public
go
 
 /**********  aaPrivateNSDeleteGroup  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPrivateNSDeleteGroup'))
  DROP PROCEDURE dbo.aaPrivateNSDeleteGroup
GO

CREATE PROCEDURE aaPrivateNSDeleteGroup 
  @NameKey int
AS
BEGIN
  DECLARE @WorkLevel int
  DECLARE @WorkKey   int
  DECLARE @WorkUser  int

  -- Temporary table for deleted groups -------------------------
  CREATE TABLE #DelGroup(NameKey int, TreeLevel int)

  IF EXISTS (SELECT * FROM PrivateNameSpace WHERE NameKey = @NameKey) 
  BEGIN
    -- Load the anchor group details ------------------------------
    SELECT @WorkKey = @NameKey, @WorkLevel = 1, @WorkUser = UserKey
    FROM   PrivateNameSpace
    WHERE  NameKey = @NameKey

    -- Set initial group state ------------------------------------
    INSERT INTO #DelGroup (NameKey, TreeLevel)
      VALUES (@WorkKey, @WorkLevel)

    WHILE @WorkLevel > 0
    BEGIN
      IF EXISTS (SELECT * FROM #DelGroup WHERE TreeLevel = @WorkLevel)
      BEGIN
        -- Get the group ------------------------------------------
        SELECT @WorkLevel = TreeLevel, @WorkKey = NameKey 
        FROM   #DelGroup 
        WHERE  TreeLevel = @WorkLevel

        -- Remove this row from the temp table --------------------
        DELETE FROM #DelGroup WHERE NameKey = @WorkKey

        -- Insert this group's children into the temp table -------
        SELECT @WorkLevel = @WorkLevel + 1
        INSERT INTO #DelGroup (NameKey, TreeLevel)
        SELECT NameKey, @WorkLevel
          FROM   PrivateNameSpace
          WHERE  ParentKey = @WorkKey
          AND    UserKey = @WorkUser

        -- Remove the physical group ------------------------------
        DELETE FROM PrivateNameSpace WHERE NameKey = @WorkKey
      END
      ELSE
      BEGIN
        -- End of branch recurse back up a level ------------------
        SELECT @WorkLevel = @WorkLevel - 1
      END    
    END
  END
END
GO

GRANT  EXECUTE  ON aaPrivateNSDeleteGroup  TO Public
go
 
 /**********  aaPrivateNSDeleteLeaf  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPrivateNSDeleteLeaf'))
  DROP PROCEDURE dbo.aaPrivateNSDeleteLeaf
GO

CREATE PROCEDURE aaPrivateNSDeleteLeaf 
  @NameKey  int,
  @wwTagKey int 
AS
BEGIN 
  /* This proc relies on delete cascade triggers on PrivateNameSpace */
  /*  into itself and onto PrivateGroupTag */

  DECLARE @wwDomainTagKey int

  SELECT @wwDomainTagKey = wwDomainTagKey
  FROM   TagRef
  WHERE  wwTagKey = @wwTagKey

  DELETE PrivateGroupTag
  WHERE  NameKey = @NameKey
  AND    wwDomainTagKey = @wwDomainTagKey
  AND    UserKey = dbo.faaUser_ID()
END
GO

GRANT  EXECUTE  ON aaPrivateNSDeleteLeaf  TO public
go
 
 /**********  aaPrivateNSExpand  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPrivateNSExpand'))
  DROP PROCEDURE dbo.aaPrivateNSExpand
GO

CREATE PROCEDURE aaPrivateNSExpand
  @PKey      int,
  @FilterStr nvarchar(100) = NULL
AS
BEGIN
  IF @PKey = 0
  BEGIN
    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PrivateNameSpace
    WHERE  ParentKey = @PKey

    UNION ALL

    SELECT TypeKey = B.TagType,
           Name = B.TagName,
           ServerKey = B.ServerKey,
           PKey = B.wwTagKey,
           HasChildren = 0
    FROM   PrivateGroupTag A, TagRef B
    WHERE  A.wwDomainTagKey = B.wwDomainTagKey
    AND    A.NameKey = @PKey

    ORDER BY TypeKey DESC, Name
  END

  ELSE

  BEGIN
    IF @FilterStr IS NULL
    BEGIN
      -- Filter not specified -----------------------------
      SELECT TypeKey = Type,
             Name = Name,
             ServerKey = 1,
             PKey = NameKey,
             HasChildren = 1
      FROM   PrivateNameSpace
      WHERE  ParentKey = @PKey
      AND    UserKey = dbo.faaUser_ID()

      UNION ALL

      SELECT TypeKey = B.TagType,
             Name = B.TagName,
             ServerKey = B.ServerKey,
             PKey = B.wwTagKey,
             HasChildren = 0
      FROM   PrivateGroupTag A, TagRef B
      WHERE  A.wwDomainTagKey = B.wwDomainTagKey
      AND    A.NameKey = @PKey
      AND    UserKey = dbo.faaUser_ID()

      ORDER BY TypeKey DESC, Name
    END

    ELSE

    BEGIN
      -- Filter specified - scope result set --------------
      SELECT TypeKey = Type,
             Name = Name,
             ServerKey = 1,
             PKey = NameKey,
             HasChildren = 1
      FROM   PrivateNameSpace
      WHERE  ParentKey = @PKey
      AND    UserKey = dbo.faaUser_ID()

      UNION ALL

      SELECT TypeKey = B.TagType,
             Name = B.TagName,
             ServerKey = B.ServerKey,
             PKey = B.wwTagKey,
             HasChildren = 0
      FROM   PrivateGroupTag A, TagRef B
      WHERE  A.wwDomainTagKey = B.wwDomainTagKey
      AND    A.NameKey = @PKey
      AND    UserKey = dbo.faaUser_ID()
      AND    B.TagName LIKE @FilterStr

      ORDER BY TypeKey DESC, Name
    END
  END
END
GO

GRANT  EXECUTE  ON aaPrivateNSExpand  TO Public
go
 
 /**********  aaPrivateNSSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPrivateNSSelect'))
  DROP PROCEDURE dbo.aaPrivateNSSelect
GO

CREATE PROCEDURE aaPrivateNSSelect
AS
BEGIN
  SELECT   Type,
           [Name],
           PKey = NameKey,
           ParentKey
  FROM     PrivateNameSpace
  WHERE    ParentKey = 0

  UNION ALL

  SELECT   Type,
           Name,
           PKey = NameKey,
           ParentKey
  FROM     PrivateNameSpace
  WHERE    ParentKey > 0
  AND      UserKey = dbo.faaUser_ID()

  ORDER BY [Name]
END
GO

GRANT  EXECUTE  ON aaPrivateNSSelect  TO Public
go
 
 /**********  aaPrivateNSUpdateGroup  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPrivateNSUpdateGroup'))
  DROP PROCEDURE dbo.aaPrivateNSUpdateGroup
GO

CREATE PROCEDURE aaPrivateNSUpdateGroup 
  @NameKey int,
  @Name    nvarchar(255),
  @Type    int
AS 
   IF @Name IS NULL
   BEGIN
     SELECT @Name = Name
     FROM   PrivateNameSpace
     WHERE  NameKey = @NameKey
     AND    UserKey = dbo.faaUser_ID()
   END

   UPDATE PrivateNameSpace
   SET    Name = @Name, Type = @Type
   WHERE  NameKey = @NameKey
   AND    UserKey = dbo.faaUser_ID()
GO

GRANT  EXECUTE  ON aaPrivateNSUpdateGroup  TO public
go
 
 /**********  aaPublicNSAddGroup  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPublicNSAddGroup'))
  DROP PROCEDURE dbo.aaPublicNSAddGroup
GO

CREATE procedure aaPublicNSAddGroup 
  @Name      nvarchar(255),
  @ParentKey int,
  @Type      int = 1000000
AS
BEGIN
  DECLARE @Result int

  INSERT PublicNameSpace (Type, ParentKey, Name)
     VALUES (@Type,@ParentKey,@Name)

  IF @@Error = 0
  BEGIN
    SELECT @Result = @@IDENTITY
  END
  ELSE  
  BEGIN
    SELECT @Result = -1
  END
  RETURN @Result
END
GO

GRANT  EXECUTE  ON aaPublicNSAddGroup TO aaAdministrators
GO
GRANT  EXECUTE  ON aaPublicNSAddGroup TO aaPowerUsers
go
 
 /**********  aaPublicNSAddLeaf  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPublicNSAddLeaf'))
  DROP PROCEDURE dbo.aaPublicNSAddLeaf
GO

CREATE procedure aaPublicNSAddLeaf 
  @wwTagKey  int,
  @NameKey   int,
  @ServerKey int = 1
AS
BEGIN
  INSERT PublicGroupTag (NameKey, wwDomainTagKey)
    SELECT @NameKey, wwDomainTagKey
    FROM   TagRef 
    WHERE  wwTagKey = @wwTagKey
    AND    ServerKey = @ServerKey
  RETURN @@error
END
GO

GRANT  EXECUTE  ON aaPublicNSAddLeaf TO aaAdministrators
GO
GRANT  EXECUTE  ON aaPublicNSAddLeaf TO aaPowerUsers
go
 
 /**********  aaPublicNSDeleteGroup  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPublicNSDeleteGroup'))
  DROP PROCEDURE dbo.aaPublicNSDeleteGroup
GO

CREATE PROCEDURE aaPublicNSDeleteGroup 
  @NameKey int
AS
BEGIN
  DECLARE @WorkLevel int
  DECLARE @WorkKey   int

  -- Temporary table for deleted groups -------------------------
  CREATE TABLE #DelGroup(NameKey int, TreeLevel int)

  IF EXISTS (SELECT * FROM PublicNameSpace WHERE NameKey = @NameKey) 
  BEGIN
    -- Load the anchor group details ------------------------------
    SELECT @WorkKey = @NameKey, @WorkLevel = 1

    -- Set initial group state ------------------------------------
    INSERT INTO #DelGroup (NameKey, TreeLevel)
      VALUES (@WorkKey, @WorkLevel)

    WHILE @WorkLevel > 0
    BEGIN
      IF EXISTS (SELECT * FROM #DelGroup WHERE TreeLevel = @WorkLevel)
      BEGIN
        -- Get the group ------------------------------------------
        SELECT @WorkLevel = TreeLevel, @WorkKey = NameKey 
        FROM   #DelGroup 
        WHERE  TreeLevel = @WorkLevel

        -- Remove this row from the temp table --------------------
        DELETE FROM #DelGroup WHERE NameKey = @WorkKey

        -- Insert this group's children into the temp table -------
        SELECT @WorkLevel = @WorkLevel + 1
        INSERT INTO #DelGroup (NameKey, TreeLevel)
          SELECT NameKey, @WorkLevel
          FROM   PublicNameSpace
          WHERE  ParentKey = @WorkKey

        -- Remove the physical group ------------------------------
        DELETE FROM PublicNameSpace WHERE NameKey = @WorkKey
      END
      ELSE
      BEGIN
        -- End of branch recurse back up a level ------------------
        SELECT @WorkLevel = @WorkLevel - 1
      END    
    END
  END
END
GO

GRANT  EXECUTE  ON aaPublicNSDeleteGroup TO aaAdministrators
GO
GRANT  EXECUTE  ON aaPublicNSDeleteGroup   TO aaPowerUsers
go
 
 /**********  aaPublicNSDeleteLeaf  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPublicNSDeleteLeaf'))
  DROP PROCEDURE dbo.aaPublicNSDeleteLeaf
GO

CREATE PROCEDURE aaPublicNSDeleteLeaf  
  @NameKey int,
  @wwTagKey int 
AS
BEGIN 
  /* This proc relies on delete cascade triggers on PublicNameSpace */
  /*  into itself and onto PublicGroupTag */

  DECLARE @wwDomainTagKey int

  SELECT @wwDomainTagKey =  wwDomainTagKey
  FROM   TagRef
  WHERE  wwTagKey = @wwTagKey

  DELETE PublicGroupTag
  WHERE @NameKey = NameKey
  AND    wwDomainTagKey = @wwDomainTagKey
END
GO

GRANT  EXECUTE  ON aaPublicNSDeleteLeaf TO aaAdministrators
GO
GRANT  EXECUTE  ON aaPublicNSDeleteLeaf TO aaPowerUsers
go
 
 /**********  aaPublicNSExpand  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPublicNSExpand'))
  DROP PROCEDURE dbo.aaPublicNSExpand
GO

CREATE PROCEDURE aaPublicNSExpand
  @PKey      int,
  @FilterStr nvarchar(100) = NULL
AS
BEGIN
  if @FilterStr IS NULL
  BEGIN
    -- No filter specified ------------------------
    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = @PKey

    UNION ALL

    SELECT TypeKey = B.TagType,
           Name = B.TagName,
           ServerKey = B.ServerKey,
           PKey = B.wwTagKey,
           HasChildren = 0
    FROM   PublicGroupTag A, TagRef B
    WHERE  A.wwDomainTagKey = B.wwDomainTagKey
    AND    A.NameKey = @PKey

    ORDER BY TypeKey DESC, Name
  END

  ELSE

  BEGIN
    -- Filter specified - scope result set --------
    SELECT TypeKey = Type,
           Name = Name,
           ServerKey = 1,
           PKey = NameKey,
           HasChildren = 1
    FROM   PublicNameSpace
    WHERE  ParentKey = @PKey

    UNION ALL

    SELECT TypeKey = B.TagType,
           Name = B.TagName,
           ServerKey = B.ServerKey,
           PKey = B.wwTagKey,
           HasChildren = 0
    FROM   PublicGroupTag A, TagRef B
    WHERE  A.wwDomainTagKey = B.wwDomainTagKey
    AND    A.NameKey = @PKey
    AND    B.TagName LIKE @FilterStr

    ORDER BY TypeKey DESC, Name
  END
END
GO

GRANT  EXECUTE  ON aaPublicNSExpand  TO Public
go
 
 /**********  aaPublicNSSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPublicNSSelect'))
  DROP PROCEDURE dbo.aaPublicNSSelect
GO

CREATE PROCEDURE aaPublicNSSelect
AS
BEGIN
  SELECT   Type,
           [Name],
           PKey = NameKey,
           ParentKey
  FROM     PublicNameSpace
  WHERE    ParentKey >= 0
  ORDER BY ParentKey, [Name]
END
GO

GRANT  EXECUTE  ON aaPublicNSSelect  TO Public
go
 
 /**********  aaPublicNSUpdateGroup  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaPublicNSUpdateGroup'))
  DROP PROCEDURE dbo.aaPublicNSUpdateGroup
GO

CREATE PROCEDURE aaPublicNSUpdateGroup 
  @NameKey int,
  @Name  nvarchar(255),
  @Type int
AS
BEGIN 
  IF @Name IS NULL
     SELECT @Name = Name FROM PublicNameSpace WHERE @NameKey = NameKey

  IF @Type IS NULL
     SELECT @Type = Type FROM PublicNameSpace WHERE @NameKey = NameKey

  UPDATE PublicNameSpace SET Name = @Name, Type = @Type
   WHERE @NameKey = NameKey
END
GO

GRANT  EXECUTE  ON aaPublicNSUpdateGroup TO aaAdministrators
GO
GRANT  EXECUTE  ON aaPublicNSUpdateGroup TO aaPowerUsers
go
 
 /**********  aaRedirectToInTouch  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaRedirectToInTouch'))
  DROP PROCEDURE dbo.aaRedirectToInTouch
GO

CREATE PROCEDURE aaRedirectToInTouch
  @IOServerKey int,
  @InTouchNodeKey int
AS
BEGIN
   DECLARE @errno int, @errmsg nvarchar (255)

   IF @IOServerKey = 1
   BEGIN
      set @errno = 17050   
      goto error
   END
   ELSE IF not exists (Select IOServerKey from IOServer where IOServerKey = @IOServerKey)
   BEGIN
      set @errno = 17051   
      goto error
   END
   ELSE IF @IOServerKey = @InTouchNodeKey
   BEGIN
      set @errno = 17052   
      goto error
   END
   ELSE IF   not exists (Select IOServerKey from IOServer where IOServerKey = @InTouchNodeKey)
   BEGIN
      set @errno = 17053   
      goto error
   END
   ELSE
      -- Verify that the @InTouchNodeKey points to View
      IF (select UPPER(ApplicationName) from IOServer where IOServerKey = @InTouchNodeKey) <> 'VIEW'
      BEGIN
         set @errno = 17053   
         goto error
      END
      ELSE
         -- check that the 'VIEW' node came from an imported node
         IF exists (select NodeKey from InTouchNode where UPPER(MachineName) = 
                  (select UPPER(ComputerName) from IOServer where IOServerKey = @InTouchNodeKey))
         BEGIN
            BEGIN TRAN
            declare @thetag nvarchar(256)
            declare @thetagtype  int
            declare taglist_cursor cursor for
               select TagName, TagType from Tag where IOServerKey = @IOServerKey

            open taglist_cursor

            fetch next from taglist_cursor into @thetag, @thetagtype                     

            while @@FETCH_STATUS = 0
            begin 
               update Tag set IOServerKey = @InTouchNodeKey,
                              TopicKey = (select TopicKey from Topic where IOServerKey = @InTouchNodeKey and UPPER(Name) = 'TAGNAME'),
                              ItemName = its.OriginalName
                  from Tag t, InTouchSpecific its
                     where t.TagName = @thetag
                     and   its.TagName = t.TagName

               if @thetagtype = 1   -- Need to reset the Scaling
               begin
                  update AnalogTag set Scaling = 0, MinRaw = MinEU, MaxRaw = MaxEU  
                     from AnalogTag t, InTouchSpecific its
                        where t.TagName = @thetag
                        and   its.TagName = t.TagName
               end
  
               fetch next from taglist_cursor into @thetag, @thetagtype
            end
         
            close taglist_cursor
            deallocate taglist_cursor
            COMMIT TRAN

            /* Cleanup IOServer if not used anymore */
            if (select count(TagName) from Tag where IOServerKey = @IOServerKey) = 0
               BEGIN 
                  delete Topic where IOServerKey = @IOServerKey
                  delete IOServer where IOServerKey = @IOServerKey
               END 
         END
         ELSE
         BEGIN
            set @errno = 17054   
            goto error
         END

   return

   error:
     set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
     if @errmsg  is NULL
     begin
        set @errmsg = 'Error msg not found - Invalid Redirect to InTouch'
     end

     raiserror @errno @errmsg 
END
GO

GRANT EXEC ON aaRedirectToInTouch TO aaAdministrators
go
 
 /**********  aaSetAISamples  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSetAISamples'))
  DROP PROCEDURE dbo.aaSetAISamples
GO

CREATE procedure aaSetAISamples 
  @TagName nvarchar(256), @Samples int
AS
   UPDATE Tag SET SamplesInActiveImage = @Samples
      WHERE UPPER(TagName) like UPPER(@TagName)

GO

GRANT EXEC ON aaSetAISamples TO aaAdministrators
GO
GRANT EXEC ON aaSetAISamples TO aaPowerUsers
go
 
 /**********  aaSetCalculatedAISamples  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSetCalculatedAISamples'))
  DROP PROCEDURE dbo.aaSetCalculatedAISamples
GO

CREATE procedure aaSetCalculatedAISamples 
/* Internal Historian Stored Procedure, do not run manually */
AS
   if (select Value from SystemParameter where [Name] = 'AIAutoResize') = 1
   begin
      update Tag set SamplesInActiveImage = CalculatedAISamples
          where SamplesInActiveImage <> CalculatedAISamples
   end
GO

GRANT EXEC ON aaSetCalculatedAISamples TO aaAdministrators
go
 
 /**********  aaSetServerTimeStamp  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSetServerTimeStamp'))
  DROP PROCEDURE dbo.aaSetServerTimeStamp
GO

CREATE procedure aaSetServerTimeStamp 
  @TopicName nvarchar(80),
  @ServerTimeStamp bit = 0
AS
   UPDATE Tag SET ServerTimeStamp = @ServerTimeStamp
      FROM Tag JOIN Topic
      ON Tag.TopicKey = Topic.TopicKey
      WHERE UPPER(Topic.Name) like UPPER(@TopicName)

GO

GRANT EXEC ON aaSetServerTimeStamp TO aaAdministrators
GO
GRANT EXEC ON aaSetServerTimeStamp TO aaPowerUsers
go
 
 /**********  aaSetStorageRule  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSetStorageRule'))
  DROP PROCEDURE dbo.aaSetStorageRule
GO

CREATE PROCEDURE aaSetStorageRule 
  @type        tinyint,
  @key         int,
  @storagetype tinyint,
  @storagerate int = 0, 
  @timedb      int = -1,
  @valuedb     float = -1,
  @acqtype     smallint = -1,
  @dbtype      smallint = -1,
  @ratedb      float = -1,
  @servertimestamp smallint = -1,
  @latedata    smallint = -1,
  @idleduration int = 60,
  @procinterval int = 120
AS
BEGIN
   /* This stored procedure is used by the configuration editor to set storage rules */
   /*  from various levels of the tag definition.  Parameters are                    */
   /*   @type: 1 = IOServer, 2 = Topic                                               */
   /*   @key: The IDENTITY key of the relevant type                                  */
   /*   @storagetype: 0 = no storage, 1 = cyclic, 2 = delta, 3 = forced              */
   /*   @storagerate: value of cyclic storage rate in seconds                        */
   /*   @timedb:  delta storage time deadband in milliseconds                        */
   /*   @valuedb: delta storage value deadband in percent                            */
   /*   @acqtype: 1 = acquisition on, 0 = acquisition off                            */
   /*   @dbtype:  1 = Time/Value, 2 = Rate  [Tag]                                    */
   /*   @ratedb: delta storage rate deadband in percent  [AnalogTag]                 */
   /*   @servertimestamp:  0 = timestamp at IDAS, 1 = timestamp at server  [Tag]     */
   /*   @latedata:  topic late data enable flag; 0 = off, 1 = on  [Topic]            */
   /*   @idleduration:  topic idle duration in seconds  [Topic]                      */
   /*   @procinterval:  topic processing interval in seconds  [Topic]                */
   /*    -1 means ignore                                                             */

   /* Protection against invalid StorageRate value for future updates */ 
   if @storagerate > -1
   begin
      if (@storagerate < 1000 or @storagerate IS NULL)
      begin
         set @storagerate = 10000
      end
   end

   /* Process AcquisitionType */
   if @acqtype = 0
   begin
      if @type = 1
      begin
         update Tag set AcquisitionType = 0
            where IOServerKey = @key
      end
      else   
         if @type = 2 
      begin
         update Tag set AcquisitionType = 0
            where TopicKey = @key
      end
   end
   else
   if @acqtype = 1
   begin
      if @type = 1
      begin
         if @key = 1 
         begin
            update Tag set AcquisitionType = 3
            where IOServerKey = @key
         end
         else
         begin 
            update Tag set AcquisitionType = 1
            where IOServerKey = @key
         end
      end
      else   
         if @type = 2 
      begin
         if @key = 1
         begin
            update Tag set AcquisitionType = 3
               where TopicKey = @key
         end
         else
         begin 
            update Tag set AcquisitionType = 1
            where TopicKey = @key
         end
      end
   end

   /* Process StorageType */
   if @storagetype = 0    -- no storage
   begin
      if @type = 1
      begin
         update Tag set StorageType = 0
            where IOServerKey = @key
      end
      else   
         if @type = 2 
      begin
         update Tag set StorageType = 0
            where TopicKey = @key
      end
   end 
   else
      if @storagetype = 1    -- cyclic storage
   begin
      if @type = 1
      begin
         update Tag set StorageType = @storagetype,
                        StorageRate = @storagerate
            where TagName IN 
               (select TagName from Tag where TagType in (1) and IOServerKey = @key)
      end
      else
         if @type = 2
      begin
         update Tag set StorageType = @storagetype,
                        StorageRate = @storagerate
            where TagName IN 
               (select TagName from Tag where TagType in (1) and TopicKey = @key)
      end
   end
   else
      if @storagetype = 2    -- delta storage
   begin
      if @type = 1
      begin
         update Tag set StorageType  = @storagetype
            where TagName in
               (select TagName from Tag where TagType in (1,2,3) and IOServerKey = @key)

         if @timedb > -1
         begin
            update Tag set TimeDeadband = @timedb
               where TagName in
                  (select TagName from Tag where TagType in (1,2,3) and IOServerKey = @key)
         end

         if @valuedb > -1
         begin
            update AnalogTag set ValueDeadband = @valuedb
               from Tag inner join AnalogTag on Tag.TagName = AnalogTag.TagName
                 where Tag.TagName in
                    (select TagName from Tag where TagType = 1 and IOServerKey = @key)
         end

         if @ratedb > -1
         begin
            update AnalogTag set RateDeadband = @ratedb
               from Tag inner join AnalogTag on Tag.TagName = AnalogTag.TagName
                 where Tag.TagName in
                    (select TagName from Tag where TagType = 1 and IOServerKey = @key)
         end
      end
      else
         if @type = 2
      begin
         update Tag set StorageType  = @storagetype
            where TagName in
               (select TagName from Tag where TagType in (1,2,3) and TopicKey = @key)

         if   @timedb > -1
         begin
            update Tag set TimeDeadband  = @timedb
               where TagName in
                  (select TagName from Tag where TagType in (1,2,3) and TopicKey = @key)
         end

         if @valuedb > -1
         begin
            update AnalogTag set ValueDeadband = @valuedb
               from Tag inner join AnalogTag on Tag.TagName = AnalogTag.TagName
                 where Tag.TagName in
                    (select TagName from Tag where TagType = 1 and TopicKey = @key)
         end

         if @ratedb > -1
         begin
            update AnalogTag set RateDeadband = @ratedb
               from Tag inner join AnalogTag on Tag.TagName = AnalogTag.TagName
                 where Tag.TagName in
                    (select TagName from Tag where TagType = 1 and TopicKey = @key)
         end
      end
   end
   else
      if @storagetype = 3    -- forced storage
   begin
      if @type = 1
      begin
         update Tag set StorageType = @storagetype,
                        StorageRate = @storagerate
            where TagName IN 
               (select TagName from Tag where TagType in (1) and IOServerKey = @key)
      end
      else
         if @type = 2
      begin
         update Tag set StorageType = @storagetype,
                        StorageRate = @storagerate
            where TagName IN 
               (select TagName from Tag where TagType in (1) and TopicKey = @key)
      end
   end

   /* Process ServerTimeStamp [Tag table] */
   if @servertimestamp = 0 or @servertimestamp = 1
   begin
      if @type = 1
      begin
         update Tag set ServerTimeStamp = @servertimestamp
            where IOServerKey = @key
            and ServerTimeStamp <> @servertimestamp
      end
      else   
      if @type = 2 
      begin
         update Tag set ServerTimeStamp = @servertimestamp
            where TopicKey = @key
            and ServerTimeStamp <> @servertimestamp
      end
   end

   /* Process DeadbandType [Tag table] */
   if @dbtype > -1
   begin
      if @type = 1
      begin
         update Tag set DeadbandType = @dbtype
            where IOServerKey = @key
      end
      else   
      if @type = 2 
      begin
         update Tag set DeadbandType = @dbtype
            where TopicKey = @key
      end
   end

   /* Process LateData, IdleDuration, ProcessingInterval [Topic table] */
   if @latedata = 0 or @latedata = 1
   begin
      if @type = 1
      begin
         update Topic set LateData = @latedata,
            IdleDuration = @idleduration,
            ProcessingInterval = @procinterval
            where IOServerKey = @key
      end
      else   
      if @type = 2 
      begin
         update Topic set LateData = @latedata,
            IdleDuration = @idleduration,
            ProcessingInterval = @procinterval
            where TopicKey = @key
      end
   end

   return 

   error:
     declare @errno int, @errmsg varchar (255)
     set @errno = 17016
     set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
     if @errmsg  is NULL
     begin
        set @errmsg = 'Error msg not found - Invalid <Set Storage Rule> update'
     end

     raiserror @errno @errmsg 
END

GO

GRANT EXEC ON aaSetStorageRule TO aaAdministrators
GO
GRANT EXEC ON aaSetStorageRule TO aaPowerUsers
go
 
 /**********  aaSetTagStorage  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSetTagStorage'))
  DROP PROCEDURE dbo.aaSetTagStorage
GO

CREATE PROCEDURE aaSetTagStorage 
  @type tinyint,
  @list nvarchar(4000),
  @set  varchar(3)
AS
   /* This stored procedure is used by the configuration editor        */
   /*  to set storage On or Off                                        */
   /*   @type: 1 = IOServer, 2 = Topic , 3 = Tag, 4 = PublicGroup      */
   /*   @list: The IDENTITY key list (type 1,2,4), separated by commas */
   /*       or list of tags names (type 3) separated by commas         */
   /*   @set : ON or OFF                                               */
   /*   example: SetTagStorage 2, '3,4', 'OFF'                         */
   /*   or       SetTagStorage 3, 'SysTimeSec, SysTimeHour', 'ON'      */

   declare @in nvarchar(4000)
   declare @statement nvarchar(4000)
   set @in  =''
   set @statement = ''
begin
   /* Check for NULL */
   if @type is NULL or @list is NULL or @set is NULL
   begin
      goto error
   end
   /* Check for ON - OFF */
   if UPPER(@set) not in ('ON', 'OFF') 
   begin
      goto error
   end

   if @type = 1  /*IOServer*/
   begin
      if UPPER(@set) = 'OFF'
      begin
         set @statement = N'
         update Tag set StorageType = 
            CASE StorageType
               WHEN 1 THEN 17
               WHEN 2 THEN 18
               WHEN 3 THEN 19
               ELSE StorageType
            END
         where IOServerKey in ("' + @list + N'") 
         and TagType in (1,2,3,4,7,9)'
         execute(@statement)
      end
      else 
      begin
         set @statement = N'
         update Tag set StorageType = 
            CASE StorageType
               WHEN 17 THEN 1
               WHEN 18 THEN 2
               WHEN 19 THEN 3
               WHEN 0  THEN 2
               ELSE StorageType
            END 
         where IOServerKey in ("' + @list + N'") 
         and TagType in (1,2,3,4,7,9)'
         execute(@statement)
      end
   end
   else
   if @type = 2  /*Topic*/
   begin
      if UPPER(@set) = 'OFF'
      begin
         set @statement = N'
         update Tag set StorageType = 
            CASE StorageType
               WHEN 1 THEN 17
               WHEN 2 THEN 18
               WHEN 3 THEN 19
               ELSE StorageType
            END
          where TopicKey in ("' + @list + N'") 
         and TagType in (1,2,3,4,7,9)'
         execute(@statement)
      end
      else 
      begin
         set @statement = N'  
         update Tag set StorageType = 
            CASE StorageType
               WHEN 17 THEN 1
               WHEN 18 THEN 2
               WHEN 19 THEN 3
               WHEN 0  THEN 2
               ELSE StorageType
            END 
          where TopicKey in ("' + @list + N'") 
              and TagType in (1,2,3,4,7,9)'
         execute(@statement)
      end
   end
   else
   if @type = 3 /*Tag*/
   begin   
      /* Format the list for the in clause */
      set @list = "'" + @list + "'"
      while CHARINDEX(' ', @list) > 0 
      begin
        set @list = STUFF(@list, CHARINDEX(' ', @list), 1, '')    
      end 
      set @list = @list + ','
      while CHARINDEX(',', @list) > 0 
      begin
        set @in = @in + SUBSTRING(@list, 1, CHARINDEX(',', @list) - 1) + "','"
        set @list = SUBSTRING(@list, CHARINDEX(',', @list) + 1, LEN(@list))
      end;
      set @in = SUBSTRING(@in, 1, LEN(@in) - 3) 
      if UPPER(@set) = 'OFF'
      begin
         set @statement = N'
         update Tag set StorageType = 
            CASE StorageType
               WHEN 1 THEN 17
               WHEN 2 THEN 18
               WHEN 3 THEN 19
               ELSE StorageType
            END
         where TagName in (N' + @in + N')'
         execute(@statement)
       end
      else
      begin
         set @statement = N'
         update Tag set StorageType = 
            CASE StorageType
               WHEN 17 THEN 1
               WHEN 18 THEN 2
               WHEN 19 THEN 3
               WHEN 0  THEN 2
               ELSE StorageType
            END 
         where TagName in (N' + @in + N')'
         execute(@statement)
      end
   end   
   if @type = 4  /*Public Group*/
   begin
      if UPPER(@set) = 'OFF'
      begin
         set @statement = N'
         update Tag set StorageType = 
            CASE StorageType
               WHEN 1 THEN 17
               WHEN 2 THEN 18
               WHEN 3 THEN 19
               ELSE StorageType
            END
         from Tag t inner join TagRef tr on t.wwTagKey = tr.wwTagKey 
          inner join PublicGroupTag pgt on tr.wwDomainTagKey = pgt.wwDomainTagKey
         where pgt.NameKey in ("' + @list + N'") 
         and t.TagType in (1,2,3,4,7,9)'
         execute(@statement)
      end
      else 
      begin
         set @statement = N'
         update Tag set StorageType = 
            CASE StorageType
               WHEN 17 THEN 1
               WHEN 18 THEN 2
               WHEN 19 THEN 3
               WHEN 0  THEN 2
               ELSE StorageType
            END 
         from Tag t inner join TagRef tr on t.wwTagKey = tr.wwTagKey 
          inner join PublicGroupTag pgt on tr.wwDomainTagKey = pgt.wwDomainTagKey
         where pgt.NameKey in ("' + @list + N'") 
         and t.TagType in (1,2,3,4,7,9)'
         execute(@statement)
      end
   end

   return

   error:
     declare @errno int, @errmsg nvarchar (255)
     set @errno = 17021
     set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
     if @errmsg  is NULL
     begin
        set @errmsg = 'Error msg not found - Invalid <Set Tag Storage> update'
     end

     raiserror @errno @errmsg 
end
GO

GRANT EXEC ON aaSetTagStorage TO aaAdministrators
GO
GRANT EXEC ON aaSetTagStorage TO aaPowerUsers
go
 
 /**********  aaSnapToSummary  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSnapToSummary'))
  DROP PROCEDURE dbo.aaSnapToSummary
GO

CREATE procedure aaSnapToSummary 
  @opkey int,
  @start datetime,
  @end datetime,
  @datestamp smalldatetime
AS
  declare @newlogkey int

  /* INSERT from AnalogSnapshot into SummaryData */
  begin tran
  /* INSERT a single record into the log table */
  INSERT SummaryHistory ( OperationKey, SummaryDate , Status, OperationStart)
    values (@opkey, @datestamp, 1, getdate())

  SELECT @newlogkey = (SELECT @@IDENTITY)

  INSERT SummaryData (LogKey, SumVarKey, Value, Quality)
    SELECT @newlogkey, sv.SumVarKey, sum(ASnp.Value), max(ASnp.Quality)
      from SummaryTagList sv WITH (NOLOCK),AnalogSnapshot ASnp WITH (NOLOCK), EventHistory eh, SnapshotTag stl
      where sv.OperationKey = @opkey
      and eh.EventLogKey = ASnp.EventLogKey
      and ASnp.SnapshotTagKey = stl.SnapshotTagKey
      and stl.TagName = sv.TagName
      and DateTime > @start
      and DateTime <=  @end 
      and ASnp.Value >= LowerLimit
      and ASnp.Value <= UpperLimit
      group by sv.SumVarKey

  update SummaryHistory 
    set Status = 0, OperationEnd = getdate()
    where LogKey = @newlogkey
  commit tran
GO

GRANT exec on aaSnapToSummary to aaAdministrators
GO
GRANT exec on aaSnapToSummary to aaPowerUsers
go
 
 /**********  aaSnapshotDetailSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSnapshotDetailSelect'))
  DROP PROCEDURE dbo.aaSnapshotDetailSelect
GO

CREATE procedure aaSnapshotDetailSelect 
  @storagesize int = NULL
AS
if @storagesize is null
begin
  select StorageSize, SnapshotSize, ImageTime, ThresholdTime
     from SnapshotDetail
        order by  StorageSize
end
else
begin
  select StorageSize, SnapshotSize, ImageTime, ThresholdTime
     from SnapshotDetail
        where StorageSize = @storagesize
end

return @@ERROR

GO
GRANT exec on aaSnapshotDetailSelect to Public
go
 
 /**********  aaSnapshotDetailUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSnapshotDetailUpdate'))
  DROP PROCEDURE dbo.aaSnapshotDetailUpdate
GO

CREATE procedure aaSnapshotDetailUpdate 
  @storagesize int,
  @snapshotsize int,
  @imagetime int,
  @thresholdtime int
AS
/* Check validity of parameters */
if   (@storagesize is NULL)
  or (@snapshotsize is NULL)
  or (@imagetime is NULL)
  or (@thresholdtime is NULL)
  or not exists (select StorageSize from SnapshotDetail
         where StorageSize = @storagesize)
begin
  goto error
end

update SnapshotDetail
   set SnapshotSize = @snapshotsize,
             ImageTime = @imagetime,
       ThresholdTime = @thresholdtime
     where StorageSize = @storagesize 

if @@ERROR <> 0
begin
   goto error
end

return

error:
  declare @errno int, @errmsg varchar (255)
  set @errno = 17017
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid SnapshotDetail update'
  end

  raiserror @errno @errmsg 

GO
GRANT exec on aaSnapshotDetailUpdate to aaAdministrators
go
 
 /**********  aaInternalSnapshotTagExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalSnapshotTagExport'))
  DROP PROCEDURE dbo.aaInternalSnapshotTagExport
GO

CREATE procedure aaInternalSnapshotTagExport 
  @Format int=0,
  @Filter nvarchar(256)='%'
AS
--****************************
-- Export SnapshotTag
--****************************
SELECT [:(SnapshotTag)TagName]=SnapshotTag.TagName, 
 [EventTag]=SnapshotTag.EventTagName
FROM SnapshotTag
WHERE SnapshotTag.TagName like @Filter

if @@ERROR <> 0
begin
   goto error
end
return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50009
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='SnapshotTag export failed'
end
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalSnapshotTagExport to aaAdministrators
go
 
 /**********  aaInternalSnapshotTagImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalSnapshotTagImport'))
  DROP PROCEDURE dbo.aaInternalSnapshotTagImport
GO

CREATE procedure aaInternalSnapshotTagImport 
  @Mode nvarchar(32)='update',
  @SnapshotTag nvarchar (256),
  @EventTag nvarchar(256)
AS
--*****************************
-- Import SnapshotTag
--*****************************
declare @key int, @tag_type int, @snapshot_key int
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

if len(@SnapshotTag) = 0
 BEGIN
 set @errno=50308
 set @errmsg_default='SnapshotTag import failed (an empty name is not allowed)'
 goto error
 END

-- Check if EventTag exists

if not exists(select TagName from EventTag where TagName=@EventTag)
BEGIN
set @errno=50200
set @errmsg_default='SnapshotTag import failed (event tag does not exist)'
goto error
END

-- EventTag exists, check if snapshot tag is a valid tag

select @tag_type=TagType from Tag where TagName=@SnapshotTag
if @tag_type is null
BEGIN
set @errno=50201
set @errmsg_default='SnapshotTag import failed (snapshot tag does not exist)'
goto error
END

-- Add or delete the snapshot tag to the event tag

if @Mode='delete'
BEGIN
delete SnapshotTag where TagName=@SnapshotTag and EventTagName=@EventTag
END
else
BEGIN
select @snapshot_key=SnapshotTagKey 
from SnapshotTag
where TagName=@SnapshotTag and EventTagName=@EventTag
if @snapshot_key is not null
 BEGIN
 return
 END
else
 BEGIN
 insert SnapshotTag (TagName, EventTagName, TagType)
  values(@SnapshotTag, @EventTag, @tag_type)
 if @@ERROR <> 0
  BEGIN
  set @errno=50203
  set @errmsg_default='SnapshotTag import failed (insert failed)'
  goto error
  END
 END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalSnapshotTagImport to aaAdministrators
go
 
 /**********  aaSpaceManager  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSpaceManager'))
  DROP PROCEDURE dbo.aaSpaceManager
GO

CREATE PROCEDURE aaSpaceManager
AS
   /* This procedure manages the space usage of the SQL Server */
   EXEC aaDeleteOlderEvents
   EXEC aaDeleteOlderSummaries
 
GO
GRANT exec on aaSpaceManager to aaAdministrators
go
 
 /**********  aaStorageLocationSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaStorageLocationSelect'))
  DROP PROCEDURE dbo.aaStorageLocationSelect
GO

CREATE procedure aaStorageLocationSelect 
  @StorageType int = NULL,
  @StorageNodeKey int = 1
AS
   IF @StorageType IS NULL
   BEGIN
      SELECT StorageType, SortOrder, StorageNodeKey, Path, MaxMBSize, MinMBThreshold, MaxAgeThreshold
        FROM StorageLocation
           WHERE StorageNodeKey = @StorageNodeKey
   END
   ELSE
   BEGIN
      SELECT StorageType, SortOrder, StorageNodeKey, Path, MaxMBSize, MinMBThreshold, MaxAgeThreshold
        FROM StorageLocation
           WHERE StorageNodeKey = @StorageNodeKey
              AND StorageType = @StorageType 
   END 
GO

GRANT exec on aaStorageLocationSelect to Public
go
 
 /**********  aaStorageLocationUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaStorageLocationUpdate'))
  DROP PROCEDURE dbo.aaStorageLocationUpdate
GO

CREATE PROCEDURE aaStorageLocationUpdate 
  @StorageType    int,
  @StorageNodeKey int,
  @SortOrder      int, 
  @Path           nvarchar(255),
  @MaxMBSize      int,
  @MinMBThreshold int,
  @MaxAgeThreshold int = 0
AS
BEGIN
  UPDATE StorageLocation
  SET
    StorageType    = @StorageType,
    SortOrder      = @SortOrder,
    Path           = @Path,
    MaxMBSize      = @MaxMBSize,
    MinMBThreshold = @MinMBThreshold,
    MaxAgeThreshold = @MaxAgeThreshold
  WHERE StorageNodeKey = 1
  AND   StorageType = @StorageType
END
GO

GRANT EXEC ON aaStorageLocationUpdate TO aaAdministrators
go
 
 /**********  aaStringDetail  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaStringDetail'))
  DROP PROCEDURE dbo.aaStringDetail
GO

CREATE procedure aaStringDetail 
  @TagList nvarchar(4000)
AS
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ','
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SET @TempChar = @TempChar + SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1) + "','"
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END;
  SET @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SET @SelectStatement = 
           "SELECT Tag.TagName, Tag.Description, Tag.StorageType " + 
           "FROM Tag  " +
           "WHERE Tag.TagName IN ('" + @TempChar + "') AND " +
           "Tag.TagType = 3"

  Execute (@SelectStatement)
GO

GRANT exec on aaStringDetail to Public
go
 
 /**********  aaStringTagDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaStringTagDelete'))
  DROP PROCEDURE dbo.aaStringTagDelete
GO

CREATE procedure aaStringTagDelete 
  @wwTagKey int = NULL
AS
DELETE FROM Tag
WHERE wwTagKey = @wwTagKey
GO

GRANT exec on aaStringTagDelete to aaAdministrators
GO
GRANT exec on aaStringTagDelete to aaPowerUsers
go
 
 /**********  aaStringTagInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaStringTagInsert'))
  DROP PROCEDURE dbo.aaStringTagInsert
GO

CREATE procedure aaStringTagInsert 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @AcquisitionType tinyint = 1,
  @StorageType     smallint = 2,
  @StorageRate     int = 10000,
  @ItemName        nvarchar(256) = '',
  @TimeDeadband    int = 0,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @MaxLength       smallint = 131,
  @InitialValue    nvarchar(512) = '',
  @TopicKey        int = NULL,
  @IOServerKey     int = NULL,
  @CurrentEditor   int = 0 ,
  @DoubleByte tinyint = 0,
  @SamplesInActiveImage int  = 0,
  @ServerTimeStamp bit = 0,
  @DeadbandType    smallint = 1,
  @AIRetrievalMode tinyint = 0
AS
BEGIN
  BEGIN TRAN

  DECLARE @result int

  SELECT @result = 0

  INSERT Tag
    (
    TagName, TopicKey, IOServerKey, StorageNodeKey, Description,
    AcquisitionType, StorageType, AcquisitionRate, StorageRate,
    ItemName, TagType, TimeDeadband, CurrentEditor,
    SamplesInActiveImage, ServerTimeStamp, DeadbandType, AIRetrievalMode
    )
  VALUES
    (
    RTRIM(@TagName), @TopicKey, @IOServerKey, 1, RTRIM(@Description),
    @AcquisitionType, @StorageType, 0, @StorageRate, RTRIM(@ItemName),
    3, @TimeDeadband, @CurrentEditor,
    @SamplesInActiveImage, @ServerTimeStamp, @DeadbandType, @AIRetrievalMode
    )

  IF @@Error = 0
  BEGIN
    INSERT StringTag
      (
      TagName,
      MaxLength,
      InitialValue,
      DoubleByte
      )
    VALUES
      (
      RTRIM(@TagName),
      @MaxLength,
      RTRIM(@InitialValue),
      @DoubleByte
      )
  END

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
    SELECT @result = (SELECT wwTagKey from Tag where TagName = RTRIM(@TagName))
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @result = -1
  END

  RETURN @result
END
GO

GRANT exec on aaStringTagInsert to aaAdministrators
GO
GRANT exec on aaStringTagInsert to aaPowerUsers
go
 
 /**********  aaStringTagSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaStringTagSelect'))
  DROP PROCEDURE dbo.aaStringTagSelect
GO

CREATE procedure aaStringTagSelect 
  @wwTagKey int = NULL
AS
IF @wwTagKey IS NULL 
BEGIN 
  SELECT 
    Tag.wwTagKey wwTagKey,
    Tag.TagName TagName,
    Tag.Description Description,
    AcquisitionType,
    StorageType = 
    CASE StorageType
       WHEN 17 THEN 0
       WHEN 18 THEN 0
       WHEN 19 THEN 0
       ELSE StorageType
    END,
    StorageRate,
    ItemName,
    TimeDeadband,
    CreatedBy,
    DateCreated,
    MaxLength,
    InitialValue,
    TopicKey,
    IOServerKey,
    CurrentEditor,
    DoubleByte,
    SamplesInActiveImage,
    CalculatedAISamples,
    ServerTimeStamp,
    DeadbandType,
    AIRetrievalMode
  FROM
    Tag, StringTag
  WHERE
    Tag.TagName = StringTag.TagName
END
ELSE
BEGIN
  SELECT 
    Tag.wwTagKey wwTagKey,
    Tag.TagName TagName,
    Tag.Description Description,
    AcquisitionType,
    StorageType = 
    CASE StorageType
       WHEN 17 THEN 0
       WHEN 18 THEN 0
       WHEN 19 THEN 0
       ELSE StorageType
    END,
    StorageRate,
    ItemName,
    TimeDeadband,
    CreatedBy,
    DateCreated,
    MaxLength,
    InitialValue,
    TopicKey,
    IOServerKey,
    CurrentEditor,
    DoubleByte,
    SamplesInActiveImage,
    CalculatedAISamples,
    ServerTimeStamp,
    DeadbandType,
    AIRetrievalMode
  FROM
    Tag, StringTag
  WHERE
    Tag.wwTagKey = @wwTagKey
    AND Tag.TagName = StringTag.TagName
END
GO

GRANT EXEC ON aaStringTagSelect TO Public
go
 
 /**********  aaStringTagUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaStringTagUpdate'))
  DROP PROCEDURE dbo.aaStringTagUpdate
GO

CREATE procedure aaStringTagUpdate 
  @wwTagKey        int,
  @TagName         nvarchar(256),
  @Description     nvarchar(512),
  @AcquisitionType tinyint = 1,
  @StorageType     smallint = 2,
  @StorageRate     int,
  @ItemName        nvarchar(256),
  @TimeDeadband    int,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @MaxLength       smallint = 131,
  @InitialValue    nvarchar(512),
  @TopicKey        int,
  @IOServerKey     int,
  @CurrentEditor   int,
  @DoubleByte tinyint = 0,
  @SamplesInActiveImage int = 0,
  @ServerTimeStamp bit = 0,
  @DeadbandType    smallint  = 1,
  @AIRetrievalMode tinyint = 0
AS
BEGIN
  BEGIN TRAN

  DECLARE @nTagName nvarchar(256)

  SELECT @nTagName = (SELECT TagName FROM Tag WHERE wwTagKey = @wwTagKey) 
    
  UPDATE Tag 
  SET
    Description     = RTRIM(@Description),
    AcquisitionType = @AcquisitionType,
    StorageType     = @StorageType,
    StorageRate     = @StorageRate,
    ItemName        = RTRIM(@ItemName),
    TimeDeadband    = @TimeDeadband,
    TopicKey        = @TopicKey,
    IOServerKey     = @IOServerKey,
    CurrentEditor   = @CurrentEditor,
    SamplesInActiveImage = @SamplesInActiveImage,
    ServerTimeStamp = @ServerTimeStamp,
    DeadbandType    = @DeadbandType,
    AIRetrievalMode   = @AIRetrievalMode
  WHERE wwTagKey    = @wwTagKey

  UPDATE StringTag
  SET
    MaxLength    = @MaxLength,
    InitialValue = RTRIM(@InitialValue),
    DoubleByte   = @DoubleByte
  WHERE TagName  = @nTagName

  COMMIT TRAN
END
GO

GRANT EXEC ON aaStringTagUpdate TO aaAdministrators
GO
GRANT EXEC ON aaStringTagUpdate TO aaPowerUsers
go
 
 /**********  aaInternalStringTagExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalStringTagExport'))
  DROP PROCEDURE dbo.aaInternalStringTagExport
GO

CREATE procedure aaInternalStringTagExport 
  @Format int=0,
  @Filter nvarchar(256)='%',
  @AcquisitionType int=0
AS
--****************************
-- Export StringTag
--****************************
declare @acq_type_lo int, @acq_type_hi int
declare @insql_name nvarchar(32)

select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList

set @acq_type_lo=CASE @AcquisitionType
 WHEN 0 THEN 0
 ELSE @AcquisitionType
 END
set @acq_type_hi=CASE @AcquisitionType
 WHEN 0 THEN 2
 ELSE @AcquisitionType
 END

SELECT [:(StringTag)TagName]=Tag.TagName, 
 [Description]=Tag.Description,
 [IOServerComputerName]=CASE LOWER(IOServer.ComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(IOServer.ComputerName)
 END,
 [IOServerAppName]=IOServer.ApplicationName,
 [TopicName]=Topic.Name,
 [ItemName]=ItemName,
 [AcquisitionType]=CASE AcquisitionType
  WHEN 0 THEN 'Not Acquired'
  WHEN 1 THEN 'IOServer'
  WHEN 2 THEN 'Manual'
  WHEN 3 THEN 'System'
  ELSE 'Unknown'
  END,
 [StorageType]=CASE StorageType
  WHEN 2 THEN 'Delta'
  WHEN 3 THEN 'Forced'
  ELSE 'Not Stored'
  END,
 [AcquisitionRate]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),AcquisitionRate))
  ELSE AcquisitionRate
  END,
 [TimeDeadband]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),TimeDeadband))
  ELSE TimeDeadband
  END,
 [SamplesInAI]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),SamplesInActiveImage))
  ELSE SamplesInActiveImage
  END,
 [MaxLength]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),MaxLength))
  ELSE MaxLength
  END,
 [Format]=CASE DoubleByte
  WHEN 1 THEN 'Unicode'
  ELSE 'ASCII'
  END,
 InitialValue,
 [CurrentEditor]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16),CurrentEditor))
  ELSE CurrentEditor
  END,
 [ServerTimeStamp]=CASE ServerTimeStamp
  WHEN 1 THEN 'Yes'
  ELSE 'No'
  END
FROM Tag, StringTag, IOServer, Topic
WHERE StringTag.TagName=Tag.TagName
AND IOServer.IOServerKey=Tag.IOServerKey
AND Topic.IOServerKey=IOServer.IOServerKey
AND Topic.TopicKey=Tag.TopicKey
AND TagType=3
AND Tag.TagName like @Filter
AND AcquisitionType between @acq_type_lo AND @acq_type_hi
AND CurrentEditor != 2

if @@ERROR <> 0
begin
   goto error
end

return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50005
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='StringTag export failed'
end
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalStringTagExport to aaAdministrators
go
 
 /**********  aaInternalStringTagImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalStringTagImport'))
  DROP PROCEDURE dbo.aaInternalStringTagImport
GO

CREATE procedure aaInternalStringTagImport 
  @Mode nvarchar(32)='update',
  @TagName nvarchar(256),
  @Description nvarchar(512),
  @ComputerName nvarchar(256),
  @ApplicationName nvarchar(64),
  @TopicName nvarchar(80),
  @ItemName nvarchar(256),
  @AcquisitionType nvarchar(16),
  @StorageType nvarchar(16),
  @AcquisitionRate nvarchar(32),
  @TimeDeadband nvarchar(16),
  @SamplesInAI nvarchar(16),
  @MaxLength nvarchar(16),
  @Format nvarchar(16),
  @InitialValue nvarchar(64),
  @CurrentEditor nvarchar(16)='0',
  @ServerTimeStamp nvarchar(8)='No'
AS
--*****************************
-- Import StringTag
--*****************************
declare @key int, @storagenode_key int, @ios_key int, @topic_key int
declare @acq_type tinyint, @store_type smallint, @cur_edit int, @maxlen smallint
declare @timedb int, @created_by nvarchar(30), @date_created datetime, @form tinyint
declare @ai_samples int
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)
declare @insql_name nvarchar(32)
declare @server_timestamp bit

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

if len(@TagName) = 0
 BEGIN
 set @errno=50306
 set @errmsg_default='StringTag import failed (an empty TagName is not allowed)'
 goto error
 END
select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList
set @ComputerName=LTRIM(RTRIM(LOWER(@ComputerName)))
if @ComputerName='$local'
BEGIN
 set @ComputerName=@insql_name
END

set @ComputerName=LTRIM(RTRIM(LOWER(@ComputerName)))

-- Convert parameters into expected types and resolve text
-- representations of numerical fields

set @timedb=CONVERT(int, @TimeDeadband)
set @created_by=null
set @date_created=getdate()
set @ai_samples=CONVERT(int, @SamplesInAI)
set @maxlen=CONVERT(smallint, @MaxLength)
set @cur_edit = CONVERT(int, @CurrentEditor)

set @acq_type=CASE LTRIM(RTRIM(LOWER(@AcquisitionType)))
 WHEN 'ioserver' THEN 1
 WHEN 'manual' THEN 2
 ELSE 0
 END
set @store_type=CASE LTRIM(RTRIM(LOWER(@StorageType)))
 WHEN 'delta' THEN 2
 WHEN 'forced' THEN 3
 ELSE 0
 END
set @form=CASE LTRIM(RTRIM(LOWER(@Format)))
 WHEN 'ascii' THEN 0
 ELSE 1
 END
set @server_timestamp=CASE LTRIM(RTRIM(LOWER(@ServerTimeStamp)))
 WHEN 'yes' THEN 1
 ELSE 0
 END

-- Check if the tag exists by getting its tagkey

select @key=wwTagKey from Tag where TagName=@TagName and TagType=3

-- If this is a delete, do it if the tag exists.

if @Mode='delete'
BEGIN
if @key is null
 BEGIN
 return
 END
else
 BEGIN
 exec aaStringTagDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50181
  set @errmsg_default='StringTag import failed (delete failed)'
  goto error
  END
 return
 END
END

-- If this is insert only (no update), and the tag already 
-- exists, we don't need to do anything more.

if (@Mode='insert') AND (@key is not null)
return

-- We need to check the relational integrity to proceed
-- beyond this point. All objects that this tag depends
-- on must already exist, otherwise we return an error.

select @ios_key=IOServerKey 
from IOServer 
where LTRIM(RTRIM(LOWER(ComputerName)))=LTRIM(RTRIM(LOWER(@ComputerName)))
AND LTRIM(RTRIM(LOWER(ApplicationName)))=LTRIM(RTRIM(LOWER(@ApplicationName)))

if @ios_key is null
BEGIN
set @errno=50183
set @errmsg_default='StringTag import failed (IOServer does not exist)'
goto error
END

select @topic_key=TopicKey 
From Topic
where IOServerKey=@ios_key
and Name=@TopicName

if @topic_key is null
BEGIN
set @errno=50184
set @errmsg_default='StringTag import failed (topic does not exist)'
goto error
END

-- Parent objects are all OK, update or insert the tag.

if @key is null
BEGIN
exec aaStringTagInsert
 @TagName,
 @Description,
 @acq_type,
 @store_type,
 0,
 @ItemName,
 @timedb,
 @created_by,
 @date_created,
 @maxlen,
 @InitialValue,
 @topic_key,
 @ios_key,
 @cur_edit,
 @form,
 @ai_samples,
 @server_timestamp
 if @@ERROR <> 0
 BEGIN
  set @errno=50185
  set @errmsg_default='StringTag import failed (insert failed)'
  goto error
 END
END
else
BEGIN
exec aaStringTagUpdate
 @key,
 @TagName,
 @Description,
 @acq_type,
 @store_type,
 0,
 @ItemName,
 @timedb,
 @created_by,
 @date_created,
 @maxlen,
 @InitialValue,
 @topic_key,
 @ios_key,
 @cur_edit,
 @form,
 @ai_samples,
 @server_timestamp
 if @@ERROR <> 0
 BEGIN
  set @errno=50186
  set @errmsg_default='StringTag import failed (update failed)'
  goto error
 END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalStringTagImport to aaAdministrators
go
 
 /**********  aaSummaryActionInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryActionInsert'))
  DROP PROCEDURE dbo.aaSummaryActionInsert
GO

CREATE procedure aaSummaryActionInsert 
  @EventTagName nvarchar(256),
  @SumDateTime datetime
AS
begin
   set quoted_identifier off

   declare @OperationKey int
   declare @Duration int
   declare @Resolution int
   declare @TimeStamp tinyint
   declare @CalcType char(10)
   declare @SumVarKey int
   declare @LogKey int
   declare @Statement nvarchar(1000)

   -- Process the Aggregations 1 by 1
   declare sum_op_list cursor for 
      select OperationKey, Duration, Resolution, TimeStamp, CalcType
         from SummaryOperation where TagName = @EventTagName

   open sum_op_list

   fetch next from sum_op_list
      into @OperationKey, @Duration, @Resolution, @TimeStamp, @CalcType  

   while @@FETCH_STATUS = 0
   begin
      begin tran
      -- Step 1 register the Summary
      insert into SummaryHistory (OperationKey, SummaryDate, Status, OperationStart)
         select @OperationKey,
               case @TimeStamp when 0 then dateadd(ss, -@Duration, @SumDateTime)
                               else @SumDateTime
               end, 1, getdate()

      -- Save the identifier (required for update at end of calculation)
      set @LogKey = @@IDENTITY
     
      -- Build the Aggregation sql statement FOR ANALOG TAGS
      set @Statement = "insert into SummaryData (LogKey, SumVarKey, Value, Quality)
          select " +  RTRIM(convert(varchar(20),@LogKey)) +
          ", SumVarKey, " + RTRIM(@CalcType) + "(Value), MAX(Quality) " + 
          "from Tag inner join SummaryTagList on Tag.TagName = SummaryTagList.TagName " + 
          "inner remote join History " +
          "on SummaryTagList.TagName = History.TagName " +
          "where SummaryTagList.OperationKey = " + 
          RTRIM(convert(varchar(20), @OperationKey)) + 
          " and wwRetrievalMode = 'Cyclic' and wwResolution = " +
          RTRIM(convert(varchar(20), @Resolution)) + 
          " and DateTime >= '" +
          RTRIM(convert(varchar(30), dateadd(ss, -@Duration, @SumDateTime), 109)) +
          "' and DateTime < '" + RTRIM(convert(varchar(30), @SumDateTime, 109)) +
          "' and Value >= LowerLimit and Value <= UpperLimit and Tag.TagType = 1" +
          " GROUP BY SumVarKey"

      -- Proceed with the calculation
      exec (@Statement)                          

      -- Build the Aggregation sql statement FOR DISCRETE TAGS
      set @Statement = "insert into SummaryData (LogKey, SumVarKey, Value, Quality)
          select " +  RTRIM(convert(varchar(20),@LogKey)) +
          ", SumVarKey, " + RTRIM(@CalcType) + "(Value), MAX(Quality) " +
          "from Tag inner join SummaryTagList on Tag.TagName = SummaryTagList.TagName " + 
          "inner remote join History " +
          "on SummaryTagList.TagName = History.TagName " +
          "where SummaryTagList.OperationKey = " + 
          RTRIM(convert(varchar(20), @OperationKey)) + 
          " and wwRetrievalMode = 'Delta' " + 
          " and DateTime >= '" +
          RTRIM(convert(varchar(30), dateadd(ss, -@Duration, @SumDateTime), 109)) +
          "' and DateTime < '" + RTRIM(convert(varchar(30), @SumDateTime, 109)) +
          "' and Value >= LowerLimit and Value <= UpperLimit and Tag.TagType = 2" +
          " GROUP BY SumVarKey"

      -- Proceed with the calculation
      exec (@Statement)                      

      -- Update the Summary History for this calculation
      update SummaryHistory set Status = 0, OperationEnd = getdate()
        where LogKey = @LogKey 

      commit tran

      -- Next one
      fetch next from sum_op_list
         into @OperationKey, @Duration, @Resolution, @TimeStamp, @CalcType  
   end

   close sum_op_list
   deallocate sum_op_list 
end

GO

GRANT  EXECUTE  ON aaSummaryActionInsert TO aaAdministrators
go
 
 /**********  aaSummaryDetail  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryDetail'))
  DROP PROCEDURE dbo.aaSummaryDetail
GO

CREATE procedure aaSummaryDetail 
/*

Parameters:
  1: Semicolon delimited Taglist.  Specific summary operations enclosed in parentheses seperated by comma.
  2: Start SummaryDate
  3: End SummaryDate
  4: Column to order by (optional: defaults to TagName column)

Syntax Examples:

  -- Detailed criteria
  SummaryDetail "ReactTemp('AVG','MIN');ReactLevel('MAX')", "May 12, 1999 12:12:00", "May 12, 1999 14:14:00", "SummaryDate"

  -- Minimum criteria
  SummaryDetail "ReactTemp;ReactLevel", "May 12, 1999 12:12:00", "May 12, 1999 14:14:00"

*/
  @TagList nvarchar(4000),
  @StartTime nvarchar(50),
  @EndTime nvarchar(50),
  @Orderby nvarchar(500) = 'TagName'
AS
  DECLARE @WhereClause nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  DECLARE @TagCriteria nvarchar(500)
  DECLARE @TagName nvarchar(256)
  DECLARE @Summaries nvarchar(100)
  SET @WhereClause = ""
  SET @SelectStatement = ""
  SET @TagCriteria = ""
  SET @TagName = ""
  SET @Summaries = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ';'
  WHILE CHARINDEX(';', @TagList) > 0 
  BEGIN
    -- Get single tag criteria.  Example: ReactTemp('AVG','MIN') 
    SET @TagCriteria = SUBSTRING(@TagList, 1, CHARINDEX(';', @TagList) - 1)
    
    -- Get Tagname from criteria
    IF CHARINDEX('(', @TagCriteria) > 0 
      SET @TagName = '"' + SUBSTRING(@TagCriteria, 1, CHARINDEX('(', @TagList) - 1) + '"'
    ELSE
      SET @TagName = '"' + @TagCriteria + '"'

    -- Remove current tag criteria from list
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(';', @TagList) + 1, LEN(@TagList))

    -- Get summary criteria if it exists, otherwise all summary criteria will be selected
    IF CHARINDEX('(', @TagCriteria) > 0 -- Check for summary operations
      BEGIN
        SET @Summaries = ' and CalcType in ' + SUBSTRING(@TagCriteria, CHARINDEX('(', @TagCriteria), LEN(@TagCriteria))
      END
    ELSE
      BEGIN
        SET @Summaries = ''
      END

    -- Add current tag criteria SQL to WhereClause variable
    SET @WhereClause = @WhereClause + ' or (TagName = ' + @TagName + @Summaries + ')'
  END;

  -- Add Times and OrderBy to WhereClause variable
  SET @WhereClause = '(' + SUBSTRING(@WhereClause, 4, LEN(@WhereClause)) + -- remove leading ' or '
                     ') and SummaryDate >= "' + @StartTime + 
                     '" and SummaryDate <= "' + @EndTime + '"'

  -- Create SelectStatement variable
  IF @Orderby = ''
    SET @Orderby = 'TagName'

  SET @SelectStatement = 
    'SELECT TagName,CalcType,SummaryDate,Value,Quality,Duration,Resolution,TimeStamp,EventTag ' +
    'FROM v_SummaryData ' +
    'WHERE ' + @WhereClause +
    ' ORDER BY ' + @Orderby 

  Execute (@SelectStatement)
GO

GRANT exec on aaSummaryDetail to Public
go
 
 /**********  aaSummaryOperationDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryOperationDelete'))
  DROP PROCEDURE dbo.aaSummaryOperationDelete
GO

CREATE procedure aaSummaryOperationDelete 
  @OperationKey int 
AS
BEGIN
  DELETE SummaryOperation 
  WHERE  OperationKey = @OperationKey
END

GO

GRANT EXEC ON aaSummaryOperationDelete TO aaAdministrators
go
 
 /**********  aaSummaryOperationInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryOperationInsert'))
  DROP PROCEDURE dbo.aaSummaryOperationInsert
GO

CREATE procedure aaSummaryOperationInsert 
  @TagName     nvarchar(256), 
  @CalcType    char(3), 
  @Duration    real,
  @Resolution  int,
  @TimeStamp   tinyint,
  @Description nvarchar(50) = NULL
AS
BEGIN
  INSERT INTO SummaryOperation 
              (TagName, CalcType, Description, Duration,
              Resolution, TimeStamp)
  VALUES      (@TagName, @CalcType, @Description, @Duration,
              @Resolution, @TimeStamp)

    RETURN  SCOPE_IDENTITY()
END
GO

GRANT EXEC ON aaSummaryOperationInsert TO aaAdministrators
go
 
 /**********  aaSummaryOperationSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryOperationSelect'))
  DROP PROCEDURE dbo.aaSummaryOperationSelect
GO

CREATE procedure aaSummaryOperationSelect 
-----------------------------------------------------------------------------
-- The parameters of this stored procedure can be used in 3 ways.
-- 1. No parameters means select all summary operations.
-- 2. @EventTagName parameter means select all summary operations for that Event
--    record.
-- 3. All parameters means select the summary operation that matches the criteria
--    if it exists.
-----------------------------------------------------------------------------
  @EventTagName nvarchar(256) = NULL,
  @CalcType     char(3)      = NULL, 
  @Duration     real         = NULL,
  @Resolution   int          = NULL,
  @TimeStamp    tinyint      = NULL
AS
BEGIN
  IF @EventTagName IS NULL
  BEGIN
     SELECT OperationKey, TagName, CalcType, Description, Duration,
            Resolution, TimeStamp
      FROM  SummaryOperation 
      ORDER BY CalcType
  END
  ELSE
  BEGIN
    IF @CalcType IS NULL AND @Duration IS NULL AND
       @Resolution IS NULL AND @TimeStamp IS NULL
    BEGIN
      SELECT OperationKey, TagName, CalcType, Description, Duration,
             Resolution, TimeStamp
      FROM   SummaryOperation 
      WHERE  TagName = @EventTagName
      ORDER BY CalcType
    END
    ELSE
    BEGIN
      SELECT OperationKey, TagName, CalcType, Description, Duration,
             Resolution, TimeStamp
      FROM   SummaryOperation 
      WHERE  TagName    = @EventTagName 
        AND  CalcType   = @CalcType 
        AND  Duration   = @Duration
        AND  Resolution = @Resolution 
        AND  TimeStamp  = @TimeStamp
      ORDER BY CalcType
    END
  END
END

GO

GRANT EXEC ON aaSummaryOperationSelect TO Public
go
 
 /**********  aaSummaryOperationUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryOperationUpdate'))
  DROP PROCEDURE dbo.aaSummaryOperationUpdate
GO

CREATE procedure aaSummaryOperationUpdate 
  @OperationKey int,
  @TagName     nvarchar(256), 
  @CalcType    char(3), 
  @Duration    real,
  @Resolution  int,
  @TimeStamp   tinyint,
  @Description nvarchar(50) = NULL
AS
BEGIN
  UPDATE SummaryOperation 
     SET TagName     = @TagName, 
         CalcType    = @CalcType, 
         Description = @Description, 
         Duration    = @Duration,
         Resolution  = @Resolution,  
         TimeStamp   = @TimeStamp
  WHERE OperationKey = @OperationKey
END

GO

GRANT EXEC ON aaSummaryOperationUpdate TO aaAdministrators
go
 
 /**********  aaInternalSummaryOperationExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalSummaryOperationExport'))
  DROP PROCEDURE dbo.aaInternalSummaryOperationExport
GO

CREATE procedure aaInternalSummaryOperationExport 
  @Format int=0
AS
--*******************************
-- Export SummaryOperation
--*******************************
SELECT [:(SummaryOperation)EventTagName]=TagName,
 CalcType,
 [Duration]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),Duration)
  ELSE Duration
  END, 
 [Resolution]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),Resolution)
  ELSE Resolution
  END,
 [TimeStamp]=CASE TimeStamp 
  WHEN 0 THEN 'Beginning'
  ELSE 'Ending'
  END,
 Description
FROM SummaryOperation

if @@ERROR <> 0
begin
   goto error
end
return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50010
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='SummaryOperation export failed'
end
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalSummaryOperationExport to aaAdministrators
go
 
 /**********  aaInternalSummaryOperationImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalSummaryOperationImport'))
  DROP PROCEDURE dbo.aaInternalSummaryOperationImport
GO

CREATE procedure aaInternalSummaryOperationImport 
  @Mode nvarchar(32)='update',
  @EventTag nvarchar(256),
  @CalcType nchar(3),
  @Duration nvarchar(32),
  @Resolution nvarchar(16),
  @TimeStamp nvarchar(16),
  @Description nvarchar(50)
AS
--********************************
-- Import SummaryOperation
--********************************
declare @key int, @resol int, @dura real, @tstamp tinyint
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

set @dura=CONVERT(real,@Duration)
set @resol=CONVERT(int,@Resolution)
set @tstamp=CASE RTRIM(LTRIM(LOWER(@TimeStamp)))
 WHEN 'beginning' THEN 0
 ELSE 1
 END

-- Check if EventTag exists

if not exists(select TagName from EventTag where TagName=@EventTag)
BEGIN
set @errno=50210
set @errmsg_default='SummaryOperation import failed (event tag does not exist)'
goto error
END

-- EventTag exists, check if this operation already exists

select @key=OperationKey from SummaryOperation 
where TagName=@EventTag
and LTRIM(RTRIM(LOWER(CalcType)))=LTRIM(RTRIM(LOWER(@CalcType)))
and Duration=@dura
and Resolution=@resol
and TimeStamp=@tstamp

-- Add or delete the snapshot tag to the event tag

if @key is null -- operation does not exist
BEGIN
if @Mode='delete'
 BEGIN
 return
 END
else
 BEGIN
 exec aaSummaryOperationInsert
  @EventTag,
  @CalcType,
  @dura,
  @resol,
  @tstamp,
  @Description
 if @@ERROR <> 0
  BEGIN
  set @errno=50212
  set @errmsg_default='SummaryOperation import failed (insert failed)'
  goto error
  END
 END
END
else -- operation already exists
BEGIN
if @Mode='delete'
 BEGIN
 exec aaSummaryOperationDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50214
  set @errmsg_default='SnapshotTag import failed (delete failed)'
  goto error
  END
 return
 END
END
if @Mode='update'
 BEGIN
 exec aaSummaryOperationUpdate
  @key,
  @EventTag,
  @CalcType,
  @dura,
  @resol,
  @tstamp,
  @Description
 if @@ERROR <> 0
  BEGIN
  set @errno=50213
  set @errmsg_default='SnapshotTag import failed (update failed)'
  goto error
  END
 return
 END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalSummaryOperationImport to aaAdministrators
go
 
 /**********  aaSummaryTagListDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryTagListDelete'))
  DROP PROCEDURE dbo.aaSummaryTagListDelete
GO

CREATE procedure aaSummaryTagListDelete 
  @SumVarKey int    
AS
BEGIN
  DELETE SummaryTagList 
   WHERE SumVarKey = @SumVarKey
END
GO

GRANT exec on aaSummaryTagListDelete to aaAdministrators
go
 
 /**********  aaSummaryTagListInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryTagListInsert'))
  DROP PROCEDURE dbo.aaSummaryTagListInsert
GO

CREATE procedure aaSummaryTagListInsert 
  @TagName      nvarchar(256),
  @OperationKey int,
  @LowerLimit   real        = NULL,
  @UpperLimit   real        = NULL,
  @Description  nvarchar(50) = NULL
AS
BEGIN
 INSERT SummaryTagList (TagName, OperationKey, LowerLimit, UpperLimit, Description)
 VALUES (@TagName, @OperationKey, @LowerLimit, @UpperLimit, @Description)

    RETURN  SCOPE_IDENTITY()
END
go

GRANT exec on aaSummaryTagListInsert to aaAdministrators
go
 
 /**********  aaSummaryTagListSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryTagListSelect'))
  DROP PROCEDURE dbo.aaSummaryTagListSelect
GO

CREATE procedure aaSummaryTagListSelect 
  @OperationKey int,    
  @TagName      nvarchar(256) = NULL
AS
BEGIN
  IF @TagName IS NULL
  BEGIN
    -- Get all of the Tags that are associated with the specified summary operation
    SELECT SummaryTagList.SumVarKey,
           SummaryTagList.TagName, 
           SummaryTagList.OperationKey,
           SummaryOperation = SummaryOperation.TagName,  
           CalcType = SummaryOperation.CalcType,
           SummaryTagList.LowerLimit, 
           SummaryTagList.UpperLimit, 
           SummaryTagList.Description 
    FROM   SummaryTagList, SummaryOperation, Tag
    WHERE  SummaryTagList.OperationKey = @OperationKey
      AND  SummaryOperation.OperationKey = @OperationKey
      AND  Tag.TagName = SummaryTagList.TagName
  END
  ELSE
  BEGIN
    -- Get the specified tag that's associated with the specified summary operation
    SELECT SummaryTagList.SumVarKey,
           SummaryTagList.TagName,
           SummaryTagList.OperationKey, 
           SummaryOperation = SummaryOperation.TagName,  
           CalcType = SummaryOperation.CalcType,
           SummaryTagList.LowerLimit, 
           SummaryTagList.UpperLimit, 
           SummaryTagList.Description 
    FROM   SummaryTagList, SummaryOperation, Tag
    WHERE  SummaryTagList.OperationKey = @OperationKey
      AND  SummaryTagList.TagName = @TagName
      AND  SummaryOperation.OperationKey = @OperationKey
      AND  Tag.TagName = @TagName
  END
END

GO

GRANT exec on aaSummaryTagListSelect to Public
go
 
 /**********  aaSummaryTagListUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSummaryTagListUpdate'))
  DROP PROCEDURE dbo.aaSummaryTagListUpdate
GO

CREATE procedure aaSummaryTagListUpdate 
  @SumVarKey    int,
  @TagName      nvarchar(256),
  @OperationKey int,
  @LowerLimit   real        = NULL,
  @UpperLimit   real        = NULL,
  @Description  nvarchar(50) = NULL
AS
BEGIN
 UPDATE SummaryTagList 
    SET TagName      = @TagName, 
        OperationKey = @OperationKey, 
        LowerLimit   = @LowerLimit, 
        UpperLimit   = @UpperLimit, 
        Description  = @Description
  WHERE SumVarKey    = @SumVarKey
END
GO

GRANT exec on aaSummaryTagListUpdate to aaAdministrators
go
 
 /**********  aaInternalSummaryTagExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalSummaryTagExport'))
  DROP PROCEDURE dbo.aaInternalSummaryTagExport
GO

CREATE procedure aaInternalSummaryTagExport 
  @Format int=0
AS
--****************************
-- Export SummaryTag
--****************************
SELECT [:(SummaryTag)TagName]=SummaryTagList.TagName,
 [EventTagName]=SummaryOperation.TagName,
 CalcType,
 [Duration]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),Duration)
  ELSE Duration
  END, 
 [Resolution]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),Resolution)
  ELSE Resolution
  END,
 [TimeStamp]=CASE TimeStamp 
  WHEN 0 THEN 'Beginning'
  ELSE 'Ending'
  END,
 [LowerLimit]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(32),LowerLimit)
  ELSE LowerLimit
  END, 
 [UpperLimit]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(32),UpperLimit)
  ELSE UpperLimit
  END, 
 [Description]=SummaryTagList.Description
FROM SummaryTagList, SummaryOperation
where SummaryOperation.OperationKey=SummaryTagList.OperationKey

if @@ERROR <> 0
begin
   goto error
end
return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50011
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='SummaryTag export failed'
end
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalSummaryTagExport to aaAdministrators
go
 
 /**********  aaInternalSummaryTagImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalSummaryTagImport'))
  DROP PROCEDURE dbo.aaInternalSummaryTagImport
GO

CREATE procedure aaInternalSummaryTagImport 
  @Mode nvarchar(32)='update',
  @TagName nvarchar(256),
  @EventTag nvarchar(256),
  @CalcType nchar(3),
  @Duration nvarchar(32),
  @Resolution nvarchar(16),
  @TimeStamp nvarchar(16),
  @LowerLimit nvarchar(32),
  @UpperLimit nvarchar(32),
  @Description nvarchar(50)
AS
--*****************************
-- Import SummaryTag
--*****************************
declare @tagkey int, @sumopkey int, @sumvarkey int, @resol int, @dura real, @tstamp tinyint
declare @limit_lo real, @limit_hi real
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

if len(@TagName) = 0
 BEGIN
 set @errno=50309
 set @errmsg_default='SummaryTag import failed (an empty TagName is not allowed)'
 goto error
 END

set @dura=CONVERT(real,@Duration)
set @resol=CONVERT(int,@Resolution)
set @limit_lo=CONVERT(real,@LowerLimit)
set @limit_hi=CONVERT(real,@UpperLimit)
set @tstamp=CASE RTRIM(LTRIM(LOWER(@TimeStamp)))
 WHEN 'beginning' THEN 0
 ELSE 1
 END

-- Check if summary operation exists

select @sumopkey=OperationKey from SummaryOperation 
where TagName=@EventTag
and LTRIM(RTRIM(LOWER(CalcType)))=LTRIM(RTRIM(LOWER(@CalcType)))
and Duration=@dura
and Resolution=@resol
and TimeStamp=@tstamp

if @sumopkey is null
BEGIN
set @errno=50220
set @errmsg_default='SummaryTag import failed (summary operation does not exist)'
goto error
END

-- Check if summary tag exists

select @sumvarkey=SumVarKey from SummaryTagList 
where TagName=@TagName
and OperationKey=@sumopkey

-- If this is a delete, do it now

if @Mode='delete'
BEGIN
if @sumvarkey is not null
BEGIN
exec aaSummaryTagListDelete @sumvarkey
if @@ERROR <> 0
 BEGIN
 set @errno=50222
 set @errmsg_default='SummaryTag import failed (delete failed)'
 goto error
 END
END
return
END

-- Insert or update the summary tag

select @tagkey=wwTagKey from Tag where TagName=@TagName
if @tagkey is null
BEGIN
set @errno=50221
set @errmsg_default='SummaryTag import failed (tag does not exist)'
goto error
END

if @sumvarkey is null
BEGIN
exec aaSummaryTagListInsert
 @TagName,
 @sumopkey,
 @limit_lo,
 @limit_hi,
 @Description
if @@ERROR <> 0
 BEGIN
 set @errno=50223
 set @errmsg_default='SummaryTag import failed (insert failed)'
 goto error
 END
END
else
BEGIN
if @Mode='update'
BEGIN
exec aaSummaryTagListUpdate
 @sumvarkey,
 @TagName,
 @sumopkey,
 @limit_lo,
 @limit_hi,
 @Description
if @@ERROR <> 0
 BEGIN
 set @errno=50224
 set @errmsg_default='SummaryTag import failed (update failed)'
 goto error
 END
END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 

GO

GRANT exec on aaInternalSummaryTagImport to aaAdministrators
go
 
 /**********  aaSystemConfigNSExpand  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSystemConfigNSExpand'))
  DROP PROCEDURE dbo.aaSystemConfigNSExpand
GO

CREATE procedure aaSystemConfigNSExpand
  @PKey  int, 
  @FKey1 int,
  @FKey2 int,
  @FKey3 int,
  @TokenType int,
  @FilterStr nvarchar(100) = NULL
AS
BEGIN
   IF @TokenType = 1000002
   -- System Group ---------------------------------------------------
   BEGIN
      -- Select Groups ------------------------------------------------
      SELECT TypeKey = 1074001,
              Name = 'Parameters',
              ServerKey = 1,
              PKey = 1,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0
      UNION
      SELECT TypeKey = 1074002,
              Name = 'Data Acquisition',
              ServerKey = 1,
              PKey = 2,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 1
      UNION
      SELECT TypeKey = 1074003,
              Name = 'Storage',
              ServerKey = 1,
              PKey = 4,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 1
      UNION
      SELECT TypeKey = 1074004,
              Name = 'Tag Configuration',
              ServerKey = 1,
              PKey = 4,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 1
      UNION
      SELECT TypeKey = 1000005,
              Name = 'Groups/Users',
              ServerKey = 1,
              PKey = 5,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 1
      ORDER BY PKey 
   END

   IF @TokenType = 1000005
   -- User Group -----------------------------------------------------
   BEGIN
      -- Select Users -------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = 6,
             Name = UserName,
             ServerKey = 1,
             PKey = UserKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
         FROM UserDetail
      END
      ELSE
      BEGIN
      -- Filter defined ------------------------------------------
         SELECT TypeKey = 6,
             Name = UserName,
             ServerKey = 1,
             PKey = UserKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
         FROM UserDetail
            WHERE UserName LIKE @FilterStr
      END
   END

   IF @TokenType = 1074003
   -- Storage Group ---------------------------------------------------
   BEGIN
      SELECT TypeKey = 1000007,
           Name = 'Storage Location',
           ServerKey = 1,
           PKey  = 1,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
      UNION
      SELECT TypeKey = 1000013,
           Name = 'Imported Nodes',
           ServerKey = 1,
           PKey  = 3,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0 
      ORDER BY PKey  
   END

   IF @TokenType = 1074004
   -- Tag Configuration-------------------------------------------------
   BEGIN
      SELECT TypeKey = 1000011,
           Name = 'Messages',
           ServerKey = 1,
           PKey  = 1,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
      UNION
      SELECT TypeKey = 1000012,
           Name = 'Engineering Units',
           ServerKey = 1,
           PKey  = 2,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
      UNION
      SELECT TypeKey =  1074008, 
           Name = 'Analog Tags',
           ServerKey = 1,
           PKey  = 3,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0 
      UNION
      SELECT TypeKey =  1074009, 
           Name = 'Discrete Tags',
           ServerKey = 1,
           PKey  = 4,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0 
      UNION
      SELECT TypeKey =  1074010, 
           Name = 'String Tags',
           ServerKey = 1,
           PKey  = 5,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0 
      UNION
      SELECT TypeKey = 1000016,
           Name = 'Event Tags',
           ServerKey = 1,
           PKey  = 6,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0 
      UNION
      SELECT TypeKey = 1074006,
           Name = 'Summaries',
           ServerKey = 1,
           PKey  = 7,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0 
      ORDER BY PKey
   END

   IF @TokenType = 1000007
   -- Storage Location Group -----------------------------------------
   BEGIN
      -- Select StorageLocation ---------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = 8,
           Name = CASE (StorageType)
                        WHEN 1 THEN 'Circular'
                        WHEN 2 THEN 'Alternative'
                        WHEN 3 THEN 'Buffer'
                        WHEN 4 THEN 'Permanent'
                        END,
           ServerKey = 1,
           PKey = StorageType,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0
         FROM StorageLocation
      END
      ELSE
      BEGIN
         -- Filter defined ------------------------------------------
         SELECT TypeKey = 8,
           Name = CASE (StorageType)
                        WHEN 1 THEN 'Circular'
                        WHEN 2 THEN 'Alternative'
                        WHEN 3 THEN 'Buffer'
                        WHEN 4 THEN 'Permanent'
                        END,
           ServerKey = 1,
           PKey = StorageType,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0
         FROM StorageLocation
            WHERE CASE (StorageType)
                        WHEN 1 THEN 'Circular'
                        WHEN 2 THEN 'Alternative'
                        WHEN 3 THEN 'Buffer'
                        WHEN 4 THEN 'Permanent'
                        END LIKE @FilterStr
      END
   END

   IF @TokenType = 1000008
   -- StorageNode Group ----------------------------------------------
   BEGIN
      -- Select StorageNodes ------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = 9,
             Name = ComputerName,
             ServerKey = 1,
             PKey = StorageNodeKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
         FROM StorageNode
      END
      ELSE
      BEGIN
      -- Filter defined ------------------------------------------
         SELECT TypeKey = 9,
             Name = ComputerName,
             ServerKey = 1,
             PKey = StorageNodeKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
         FROM StorageNode
            WHERE ComputerName LIKE @FilterStr
      END
   END

   IF @TokenType = 1000009
   -- I/O Server Type Group ------------------------------------------
   BEGIN
     -- Select I/O Server Type ---------------------------------------
     SELECT TypeKey = 10,
           Name = Description,
           ServerKey = 1,
           PKey = 0,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0
     FROM   IOServerType
   END

   IF @TokenType = 1074002
   -- Data Acquisition Group-------------------------------------------
   -- Select Groups ------------------------------------------------
   BEGIN
      SELECT TypeKey = 1074005,
           Name = 'I/O Server Types',
           ServerKey = 1,
           PKey = -2,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
      UNION
      SELECT TypeKey = 11,
           Name = 'System Driver',
           ServerKey = 1,
           PKey = -1,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
      UNION
      SELECT TypeKey = 15,
           Name = 'MDAS/Manual Tags',
           ServerKey = 1,
           PKey = 2,
           FKey1 = 1,
           FKey2 = 2,
           FKey3 = 0,
           HasChildren = 1
      UNION
      SELECT TypeKey = 1000019,
           Name =
              CASE  ComputerName
                 WHEN @@SERVERNAME THEN ComputerName
                 ELSE ComputerName
              END,   
           ServerKey = 1,
           PKey = IODriverKey,
           FKey1 = StorageNodeKey,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
      FROM IODriver where IODriverKey > 1
      ORDER BY PKey, Name
   END

   IF @TokenType = 1000017
   -- System Driver-----------------------------------------------------
   BEGIN
      SELECT TypeKey = 11,
           Name = '\\' + ComputerName + '\' + ApplicationName,
           ServerKey = 1,
             PKey  = IOServerKey,
             FKey1 = StorageNodeKey,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
      FROM   IOServer
      WHERE    ApplicationName = 'SysDrv'            
   END

   IF @TokenType = 1000018
   -- List IO Drivers--------------------------------------------------
   BEGIN
     SELECT TypeKey = 1000019,
           Name = ComputerName,
           ServerKey = 1,
             PKey  =  IODriverKey,
             FKey1 = StorageNodeKey,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
      FROM   IODriver            
   END

   IF @TokenType = 1000019
   -- IO Servers-----------------------------------------------------
   BEGIN
      SELECT TypeKey = 11,
           Name = '\\' + ComputerName + '\' + ApplicationName,
           ServerKey = 1,
             PKey  = IOServerKey,
             FKey1 = StorageNodeKey,
             FKey2 = IODriverKey,
             FKey3 = 0,
             HasChildren = 1
      FROM IOServer
         WHERE  IODriverKey = @PKey
         AND StorageNodeKey = @FKey1
            
   END


   IF @TokenType = 1000011
   -- Message Group --------------------------------------------------
   BEGIN
      -- Select Message -----------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = 12,
             Name = RTRIM(Message0) + ' / ' + RTRIM(Message1),
             ServerKey = 1,
             PKey = MessageKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
         FROM Message
      END
      ELSE
      BEGIN
         -- Filter defined ------------------------------------------
         SELECT TypeKey = 12,
             Name = RTRIM(Message0) + ' / ' + RTRIM(Message1),
             ServerKey = 1,
             PKey = MessageKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
         FROM   Message
         WHERE  (RTRIM(Message0) + ' / ' + RTRIM(Message1)) LIKE @FilterStr
      END
   END

   IF @TokenType = 1000012
   -- Engineering Unit Group -----------------------------------------
   BEGIN
      -- Select EngineeringUnit ---------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = 13,
             Name = Unit,
             ServerKey = 1,
             PKey = EUKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
         FROM EngineeringUnit
      END
      ELSE
      BEGIN
         -- Filter defined ------------------------------------------
         SELECT TypeKey = 13,
             Name = Unit,
             ServerKey = 1,
             PKey = EUKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
         FROM EngineeringUnit
            WHERE Unit LIKE @FilterStr
      END
   END

   IF @TokenType = 1000013
   -- InTouch Node Group ---------------------------------------------
   BEGIN
      -- Select InTouch Nodes -----------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = 14,
             Name = MachineName,
             ServerKey = 1,
             PKey = NodeKey,       
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
         FROM InTouchNode
      END
      ELSE
      BEGIN
         -- Filter defined ------------------------------------------
         SELECT TypeKey = 14,
             Name = MachineName,
             ServerKey = 1,
             PKey = NodeKey,       
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
         FROM InTouchNode
            WHERE MachineName LIKE @FilterStr
      END
   END

   IF @TokenType = 1074008
   -- Events Group ---------------------------------------------------
   BEGIN
      -- Select Events ------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         SELECT TypeKey = 1,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
         FROM Tag        
            WHERE  TagType = 1
               ORDER BY TagName
      END
      ELSE
      BEGIN
         SELECT TypeKey = 1,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
         FROM Tag        
            WHERE TagType = 1
              AND TagName LIKE @FilterStr
            ORDER BY TagName
      END
   END
  
   IF @TokenType = 1074009
   -- Events Group ---------------------------------------------------
   BEGIN
      -- Select Events ------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         SELECT TypeKey = 2,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
         FROM Tag        
            WHERE  TagType = 2
               ORDER BY TagName
      END
      ELSE
      BEGIN
         SELECT TypeKey = 2,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
         FROM Tag        
            WHERE TagType = 2
              AND TagName LIKE @FilterStr
            ORDER BY TagName
      END
   END

   IF @TokenType = 1074010
   -- Events Group ---------------------------------------------------
   BEGIN
      -- Select Events ------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         SELECT TypeKey = 3,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
         FROM Tag        
            WHERE  TagType = 3
               ORDER BY TagName
      END
      ELSE
      BEGIN
         SELECT TypeKey = 3,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
         FROM Tag        
            WHERE TagType = 3
              AND TagName LIKE @FilterStr
            ORDER BY TagName
      END
   END

 IF @TokenType = 1000016
   -- Events Group ---------------------------------------------------
   BEGIN
      -- Select Events ------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         SELECT TypeKey = 5,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
         FROM Tag        
            WHERE  TagType = 5
               ORDER BY TagName
      END
      ELSE
      BEGIN
         SELECT TypeKey = 5,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
         FROM Tag        
            WHERE TagType = 5
              AND TagName LIKE @FilterStr
            ORDER BY TagName
      END
   END

   IF @TokenType = 11
   -- IO Server ------------------------------------------------------   
   BEGIN
      -- Select Topic -------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = 15,
                Name = 'Topic : ' + LTRIM(Name),
                ServerKey = 1,
                PKey = TopicKey,
                FKey1 = StorageNodeKey,
                FKey2 = IOServerKey,
                FKey3 = 0,
                HasChildren = 1
         FROM   Topic
            WHERE  StorageNodeKey = @FKey1
            AND    IOServerKey = @PKey
      END
      ELSE
      BEGIN
         -- Filter defined ------------------------------------------
         SELECT TypeKey = 15,
                Name = 'Topic : ' + LTRIM(Name),
                ServerKey = 1,
                PKey = TopicKey,
                FKey1 = StorageNodeKey,
                FKey2 = IOServerKey,
                FKey3 = 0,
                HasChildren = 1
         FROM   Topic
            WHERE  StorageNodeKey = @FKey1
            AND    IOServerKey = @PKey
            AND    ('Topic : ' + LTRIM(Name)) LIKE @FilterStr
      END
   END

   IF @TokenType = 12
   -- Message --------------------------------------------------------
   BEGIN
      -- Select Tag ---------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = t.TagType,
                Name = t.TagName,
                ServerKey = 1,
                PKey = wwTagKey,
                FKey1 = StorageNodeKey,
                FKey2 = 0,
                FKey3 = 0,
                HasChildren = 0
         FROM   Tag t, DiscreteTag d
            WHERE  StorageNodeKey = @FKey1
            AND    MessageKey = @PKey
            AND    t.TagName = d.TagName  
              ORDER BY t.TagName
      END   
      ELSE
      BEGIN
         -- Filter defined - scope on FilterStr ------------------------
         SELECT TypeKey = t.TagType,
                Name = t.TagName,
                ServerKey = 1,
                PKey = wwTagKey,
                FKey1 = StorageNodeKey,
                FKey2 = 0,
                FKey3 = 0,
                HasChildren = 0
         FROM   Tag t, DiscreteTag d
            WHERE  StorageNodeKey = @FKey1
            AND    MessageKey = @PKey
            AND    t.TagName = d.TagName  
            AND    d.TagName LIKE @FilterStr
               ORDER BY t.TagName
      END
   END

   IF @TokenType = 13
   -- Engineering Unit -------------------------------------------------
   BEGIN
      -- Select Tag ---------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = t.TagType,
                Name = t.TagName,
                ServerKey = 1,
                PKey = wwTagKey,
                FKey1 = StorageNodeKey,
                FKey2 = 0,
                FKey3 = 0,
                HasChildren = 0
         FROM   Tag t, AnalogTag a
            WHERE  StorageNodeKey = @FKey1
            AND    EUKey = @PKey
            AND    t.TagName = a.TagName  
              ORDER BY t.TagName
      END   
      ELSE
      BEGIN
         -- Filter defined - scope on FilterStr ------------------------
         SELECT TypeKey = t.TagType,
                Name = t.TagName,
                ServerKey = 1,
                PKey = wwTagKey,
                FKey1 = StorageNodeKey,
                FKey2 = 0,
                FKey3 = 0,
                HasChildren = 0
         FROM   Tag t, AnalogTag a
            WHERE  StorageNodeKey = @FKey1
            AND    EUKey = @PKey
            AND    t.TagName = a.TagName  
            AND    a.TagName LIKE @FilterStr
               ORDER BY t.TagName
      END
   END

  IF @TokenType = 14
  -- InTouch Node---------------------------------------------
  BEGIN
     -- Select Tag ----------------------------------------------
     IF @FilterStr IS NULL
     BEGIN
        -- No Filter defined ----------------------------------
        SELECT TagKey = TagType,
                Name = Tag.TagName,
                ServerKey = 1,
                PKey = wwTagKey,
                FKey1 = StorageNodeKey,
                FKey2 = IOServerKey,
                FKey3 = TopicKey,
                HasChildren = 0
         FROM   Tag, InTouchSpecific
            WHERE Tag.TagName = InTouchSpecific.TagName
              AND StorageNodeKey = @FKey1
              AND NodeKey = @PKey  
              ORDER BY Tag.TagName
        END
        ELSE
        BEGIN
         -- Filter defined - scope on FilterStr ------------------------
         SELECT TagKey = TagType,
                Name = Tag.TagName,
                ServerKey = 1,
                PKey = wwTagKey,
                FKey1 = StorageNodeKey,
                FKey2 = IOServerKey,
                FKey3 = TopicKey,
                HasChildren = 0
         FROM   Tag, InTouchSpecific
            WHERE Tag.TagName = InTouchSpecific.TagName
              AND StorageNodeKey = @FKey1
              AND NodeKey = @PKey 
              AND Tag.TagName LIKE @FilterStr
              ORDER BY Tag.TagName
        END
     END

   IF @TokenType = 15
   -- Topic ----------------------------------------------------------
   BEGIN
      -- Select Tag ---------------------------------------------------
      IF @FilterStr IS NULL
      BEGIN
         -- No Filter defined ------------------------------------------
         SELECT TypeKey = TagType,
                Name = TagName,
                ServerKey = 1,
                PKey = wwTagKey,
                FKey1 = StorageNodeKey,
                FKey2 = IOServerKey,
                FKey3 = TopicKey,
                HasChildren = 0
         FROM   Tag
            WHERE  StorageNodeKey = @FKey1
            AND    IOServerKey = @FKey2
            AND    TopicKey = @PKey  
              ORDER BY TagName
      END
      ELSE
      BEGIN
         -- Filter defined - scope on FilterStr ------------------------
         SELECT TypeKey = TagType,
                Name = TagName,
                ServerKey = 1,
                PKey = wwTagKey,
                FKey1 = StorageNodeKey,
                FKey2 = IOServerKey,
                FKey3 = TopicKey,
                HasChildren = 0
         FROM   Tag
            WHERE  StorageNodeKey = @FKey1
            AND    IOServerKey = @FKey2
            AND    TopicKey = @PKey  
            AND    TagName LIKE @FilterStr
               ORDER BY TagName
      END
   END

   IF @TokenType = 1074005
   -- IOServer Types  -----------------------------------------------------
   BEGIN
      SELECT TypeKey = 1074005,
           Name = ApplicationName,
           ServerKey = 1,
             PKey  = 0,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   IOServerType
         ORDER BY ApplicationName            
   END

END

GO

GRANT EXECUTE ON aaSystemConfigNSExpand TO Public
go
 
 /**********  aaSystemNSExpand  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSystemNSExpand'))
  DROP PROCEDURE dbo.aaSystemNSExpand
GO

CREATE procedure aaSystemNSExpand
  @PKey  int, 
  @FKey1 int,
  @FKey2 int,
  @FKey3 int,
  @TokenType int,
  @FilterStr nvarchar(100) = NULL
AS
BEGIN
  IF @TokenType = 1000002
  -- System Group ---------------------------------------------------
  BEGIN
    -- Select Groups ------------------------------------------------
    SELECT TypeKey = 1000005,
           Name = 'Groups/Users',
           ServerKey = 1,
           PKey = 1,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
    UNION
    SELECT TypeKey = 1000006,
           Name = 'Servers',
           ServerKey = 1,
           PKey = 2,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
  END

  IF @TokenType = 1000005
  -- User Group -----------------------------------------------------
  BEGIN
    -- Select Users -------------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 6,
             Name = UserName,
             ServerKey = 1,
             PKey = UserKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   UserDetail
    END
    ELSE
    BEGIN
    -- Filter defined ------------------------------------------
      SELECT TypeKey = 6,
             Name = UserName,
             ServerKey = 1,
             PKey = UserKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   UserDetail
     WHERE    UserName LIKE @FilterStr
    END
  END

  IF @TokenType = 1000006
  -- Server Group ---------------------------------------------------
  BEGIN
    -- Select Server ------------------------------------------------
    SELECT TypeKey = 7,
           Name = ComputerName,
           ServerKey = 1,
           PKey = ServerKey,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
    FROM   ServerList
  END

  IF @TokenType = 1000007
  -- Storage Location Group -----------------------------------------
  BEGIN
    -- Select StorageLocation ---------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
    SELECT TypeKey = 8,
           Name = CASE (StorageType)
                        WHEN 1 THEN 'Circular'
                        WHEN 2 THEN 'Alternative'
                        WHEN 3 THEN 'Buffer'
                        WHEN 4 THEN 'Permanent'
                        END,
           ServerKey = 1,
           PKey = StorageType,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0
    FROM   StorageLocation
    END
    ELSE
    BEGIN
    -- Filter defined ------------------------------------------
    SELECT TypeKey = 8,
           Name = CASE (StorageType)
                        WHEN 1 THEN 'Circular'
                        WHEN 2 THEN 'Alternative'
                        WHEN 3 THEN 'Buffer'
                        WHEN 4 THEN 'Permanent'
                        END,
           ServerKey = 1,
           PKey = StorageType,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0
    FROM   StorageLocation
   WHERE CASE (StorageType)
                        WHEN 1 THEN 'Circular'
                        WHEN 2 THEN 'Alternative'
                        WHEN 3 THEN 'Buffer'
                        WHEN 4 THEN 'Permanent'
                        END LIKE @FilterStr
    END
  END

  IF @TokenType = 1000008
  -- StorageNode Group ----------------------------------------------
  BEGIN
    -- Select StorageNodes ------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 9,
             Name = ComputerName,
             ServerKey = 1,
             PKey = StorageNodeKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
      FROM   StorageNode
    END
    ELSE
    BEGIN
    -- Filter defined ------------------------------------------
      SELECT TypeKey = 9,
             Name = ComputerName,
             ServerKey = 1,
             PKey = StorageNodeKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
      FROM StorageNode
      WHERE ComputerName LIKE @FilterStr
    END
  END

  IF @TokenType = 1000009
  -- I/O Server Type Group ------------------------------------------
  BEGIN
    -- Select I/O Server Type ---------------------------------------
    SELECT TypeKey = 10,
           Name = Description,
           ServerKey = 1,
           PKey = 0,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 0
    FROM   IOServerType
  END

  IF @TokenType = 1000010
  -- Data Acquisition Group-------------------------------------------
    -- Select Groups ------------------------------------------------
  BEGIN
    SELECT TypeKey = 1000017,
           Name = 'System Driver',
           ServerKey = 1,
           PKey = 1,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
    UNION
    SELECT TypeKey = 1000018,
           Name = 'IO Drivers',
           ServerKey = 1,
           PKey = 2,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
  END

IF @TokenType = 1000017
  -- System Driver-----------------------------------------------------
  BEGIN
     SELECT TypeKey = 11,
           Name = '\\' + ComputerName + '\' + ApplicationName,
           ServerKey = 1,
             PKey  = IOServerKey,
             FKey1 = StorageNodeKey,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
      FROM   IOServer
      WHERE    ApplicationName = 'SysDrv'            
  END

IF @TokenType = 1000018
  -- List IO Drivers--------------------------------------------------
  BEGIN
     SELECT TypeKey = 1000019,
           Name = ComputerName,
           ServerKey = 1,
             PKey  =  IODriverKey,
             FKey1 = StorageNodeKey,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 1
      FROM   IODriver            
  END

IF @TokenType = 1000019
  -- IO Servers-----------------------------------------------------
  BEGIN
     SELECT TypeKey = 11,
           Name = '\\' + ComputerName + '\' + ApplicationName,
           ServerKey = 1,
             PKey  = IOServerKey,
             FKey1 = StorageNodeKey,
             FKey2 = IODriverKey,
             FKey3 = 0,
             HasChildren = 1
      FROM   IOServer
         WHERE  IODriverKey = @PKey
         AND StorageNodeKey = @FKey1
            
  END


  IF @TokenType = 1000011
  -- Message Group --------------------------------------------------
  BEGIN
    -- Select Message -----------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 12,
             Name = Message0 + ' / ' + Message1,
             ServerKey = 1,
             PKey = MessageKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   Message
    END
    ELSE
    BEGIN
    -- Filter defined ------------------------------------------
      SELECT TypeKey = 12,
             Name = Message0 + ' / ' + Message1,
             ServerKey = 1,
             PKey = MessageKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   Message
      WHERE    (Message0 + ' / ' + Message1) LIKE @FilterStr
    END
  END

  IF @TokenType = 1000012
  -- Engineering Unit Group -----------------------------------------
  BEGIN
    -- Select EngineeringUnit ---------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 13,
             Name = Unit,
             ServerKey = 1,
             PKey = EUKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   EngineeringUnit
    END
    ELSE
    BEGIN
    -- Filter defined ------------------------------------------
      SELECT TypeKey = 13,
             Name = Unit,
             ServerKey = 1,
             PKey = EUKey,
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   EngineeringUnit
     WHERE    Unit LIKE @FilterStr
    END
  END

  IF @TokenType = 1000013
  -- InTouch Node Group ---------------------------------------------
  BEGIN
    -- Select InTouch Nodes -----------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 14,
             Name = MachineName,
             ServerKey = 1,
             PKey = NodeKey,       
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   InTouchNode
    END
    ELSE
    BEGIN
    -- Filter defined ------------------------------------------
      SELECT TypeKey = 14,
             Name = MachineName,
             ServerKey = 1,
             PKey = NodeKey,       
             FKey1 = 0,
             FKey2 = 0,
             FKey3 = 0,
             HasChildren = 0
      FROM   InTouchNode
     WHERE MachineName LIKE @FilterStr
    END
  END

  IF @TokenType = 1000016
  -- Events Group ---------------------------------------------------
  BEGIN
    -- Select Events ------------------------------------------------
     IF @FilterStr IS NULL
     BEGIN
       SELECT TypeKey = 5,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
       FROM   Tag        
       WHERE  TagType = 5
       ORDER BY TagName
     END
     ELSE
    BEGIN
       SELECT TypeKey = 5,
              Name = TagName,
              ServerKey = 1,
              PKey = wwTagKey,
              FKey1 = 0,
              FKey2 = 0,
              FKey3 = 0,
              HasChildren = 0     
      FROM   Tag        
       WHERE  TagType = 5
            AND    TagName LIKE @FilterStr
       ORDER BY TagName
    END
  END

  IF @TokenType = 7
  -- Server ---------------------------------------------------------
  BEGIN
    -- Select Groups ------------------------------------------------
    SELECT TypeKey = 1000007,    
           Name = 'Storage Locations',
           ServerKey = 1,
           PKey = 1,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
    UNION ALL
    SELECT TypeKey = 1000013,
           Name = 'Imported Nodes',
           ServerKey = 1,
           PKey = 2,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
    UNION ALL
    SELECT TypeKey = 1000010,
           Name = 'Data Acquisition',
           ServerKey = 1,
           PKey = 3,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
    UNION ALL
    SELECT TypeKey = 1000016,
           Name = 'Events',
           ServerKey = 1,
           PKey = 5,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
    UNION ALL
    SELECT TypeKey = 1000011,
           Name = 'Messages',
           ServerKey = 1,
           PKey = 6,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
    UNION ALL
    SELECT TypeKey = 1000012,
           Name = 'Engineering Units',
           ServerKey = 1,
           PKey = 7,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
  END

  IF @TokenType = 9
  -- Storage Node ---------------------------------------------------
  BEGIN
    -- Select Groups ------------------------------------------------
    SELECT TypeKey = 1000010,
           Name = 'Data Acquisition',
           ServerKey = 1,
           PKey = @FKey1,
           FKey1 = 0,
           FKey2 = 0,
           FKey3 = 0,
           HasChildren = 1
  END

  IF @TokenType = 11
  -- IO Server ------------------------------------------------------   
  BEGIN
    -- Select Topic -------------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 15,
             Name = 'Topic : ' + LTRIM(Name),
             ServerKey = 1,
             PKey = TopicKey,
             FKey1 = StorageNodeKey,
             FKey2 = IOServerKey,
             FKey3 = 0,
             HasChildren = 1
      FROM   Topic
      WHERE  StorageNodeKey = @FKey1
      AND    IOServerKey = @PKey
    END
    ELSE
    BEGIN
    -- Filter defined ------------------------------------------
      SELECT TypeKey = 15,
             Name = 'Topic : ' + LTRIM(Name),
             ServerKey = 1,
             PKey = TopicKey,
             FKey1 = StorageNodeKey,
             FKey2 = IOServerKey,
             FKey3 = 0,
             HasChildren = 1
      FROM   Topic
      WHERE  StorageNodeKey = @FKey1
      AND    IOServerKey = @PKey
      AND    ('Topic : ' + LTRIM(Name)) LIKE @FilterStr
    END
  END

  IF @TokenType = 15
  -- Topic ----------------------------------------------------------
  BEGIN
    -- Select Tag ---------------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = TagType,
             Name = TagName,
             ServerKey = 1,
             PKey = wwTagKey,
             FKey1 = StorageNodeKey,
             FKey2 = IOServerKey,
             FKey3 = TopicKey,
             HasChildren = 0
      FROM   Tag
      WHERE  StorageNodeKey = @FKey1
      AND    IOServerKey = @FKey2
      AND    TopicKey = @PKey  
      ORDER BY TagName
    END

    ELSE

    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT TypeKey = TagType,
             Name = TagName,
             ServerKey = 1,
             PKey = wwTagKey,
             FKey1 = StorageNodeKey,
             FKey2 = IOServerKey,
             FKey3 = TopicKey,
             HasChildren = 0
      FROM   Tag
      WHERE  StorageNodeKey = @FKey1
      AND    IOServerKey = @FKey2
      AND    TopicKey = @PKey  
      AND    TagName LIKE @FilterStr
      ORDER BY TagName
    END
    
  END
END

GO

GRANT EXECUTE ON aaSystemNSExpand TO Public
go
 
 /**********  aaSystemNSExpand2  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSystemNSExpand2'))
  DROP PROCEDURE dbo.aaSystemNSExpand2
GO

CREATE procedure aaSystemNSExpand2
  @PKey      int,
  @FilterStr nvarchar(100) = NULL
AS

DECLARE @IsTopicTagQuery bit
BEGIN
  -- Determine if this is a topic tag query request.
  SELECT @IsTopicTagQuery = 0 /* Initialize to false */
  SELECT @IsTopicTagQuery = 1 WHERE EXISTS 
         (SELECT * FROM SystemNameSpace 
          WHERE NameKey = @PKey AND Type = 15)  /* Type 15 is a Topic */

  IF @IsTopicTagQuery = 0 AND (@PKey IN (0, 1, 5) OR (@PKey > 8 AND @PKey < 1000))
  -- System Group ---------------------------------------------------
  BEGIN
    -- Select Groups ------------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = Type,
             Name = Name,
            ServerKey = 1,
             PKey = NameKey,
             HasChildren = 1
      FROM   SystemNameSpace
      WHERE  ParentKey = @PKey
      ORDER  BY TypeKey DESC, Name
    END
   ELSE
    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT TypeKey = Type,
             Name = Name,
            ServerKey = 1,
             PKey = NameKey,
             HasChildren = 1
      FROM   SystemNameSpace
      WHERE  ParentKey = @PKey
       AND Name LIKE @FilterStr
      ORDER  BY TypeKey DESC, Name
    END
    RETURN
  END

  IF @PKey = 2
  -- User Group -----------------------------------------------------
  BEGIN
    -- Select Users -------------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 6,
             Name = UserName,
             ServerKey = 1,
             PKey = UserKey,
             HasChildren = 0
      FROM   UserDetail
      RETURN
    END
   ELSE
    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT TypeKey = 6,
             Name = UserName,
             ServerKey = 1,
             PKey = UserKey,
             HasChildren = 0
      FROM   UserDetail
       WHERE  UserName LIKE @FilterStr
      RETURN
    END
  END

  IF @PKey = 3
  -- Storage Location Group -----------------------------------------
  BEGIN
    -- Select StorageLocation ---------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 8,
             Name = CASE (StorageType)
                          WHEN 1 THEN 'Circular'
                          WHEN 2 THEN 'Alternative'
                          WHEN 3 THEN 'Buffer'
                          WHEN 4 THEN 'Permanent'
                          END,
             ServerKey = 1,
             PKey = StorageType,
             HasChildren = 0
      FROM   StorageLocation
      RETURN
    END
   ELSE
    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT TypeKey = 8,
             Name = CASE (StorageType)
                          WHEN 1 THEN 'Circular'
                          WHEN 2 THEN 'Alternative'
                          WHEN 3 THEN 'Buffer'
                          WHEN 4 THEN 'Permanent'
                          END,
             ServerKey = 1,
             PKey = StorageType,
             HasChildren = 0
      FROM   StorageLocation
       WHERE   CASE (StorageType)
                          WHEN 1 THEN 'Circular'
                          WHEN 2 THEN 'Alternative'
                          WHEN 3 THEN 'Buffer'
                          WHEN 4 THEN 'Permanent'
                          END LIKE @FilterStr
      RETURN
    END
  END

  IF @PKey = 4
  -- InTouch Node Group ---------------------------------------------
  BEGIN
    -- Select InTouch Nodes -----------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 14,
             Name = MachineName,
             ServerKey = 1,
             PKey = NodeKey,  
             HasChildren = 0
      FROM   InTouchNode
      RETURN
    END
    ELSE
    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT TypeKey = 14,
             Name = MachineName,
             ServerKey = 1,
             PKey = NodeKey,  
             HasChildren = 0
      FROM   InTouchNode
      WHERE   MachineName LIKE @FilterStr
      RETURN
    END
  END

  IF @PKey =  6
  -- Events Group ---------------------------------------------------
  BEGIN
    -- Select Events ------------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 5,
             Name = TagName,
             ServerKey = 1,
             PKey = wwTagKey,
             HasChildren = 0 
      FROM   Tag        
      WHERE  TagType = 5
      ORDER  BY TagName
    END
   ELSE
    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT TypeKey = 5,
             Name = TagName,
             ServerKey = 1,
             PKey = wwTagKey,
             HasChildren = 0 
      FROM   Tag        
      WHERE  TagType = 5
      AND  TagName LIKE @FilterStr
      ORDER  BY TagName
    END
      RETURN
  END

  IF @PKey = 7
  -- Message Group --------------------------------------------------
  BEGIN
    -- Select Message -----------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 12,
             Name = Message0 + ' / ' + Message1,
             ServerKey = 1,
             PKey = MessageKey,
             HasChildren = 0
      FROM   Message
    END
   ELSE
    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT TypeKey = 12,
             Name = Message0 + ' / ' + Message1,
             ServerKey = 1,
             PKey = MessageKey,
             HasChildren = 0
      FROM   Message
       WHERE    (Message0 + ' / ' + Message1) LIKE @FilterStr
    END
    RETURN
  END

  IF @PKey =  8
  -- Engineering Unit Group -----------------------------------------
  BEGIN
    -- Select EngineeringUnit ---------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT TypeKey = 13,
              Name = Unit,
             ServerKey = 1,
             PKey = EUKey,
             HasChildren = 0
      FROM   EngineeringUnit
    END
   ELSE
    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT TypeKey = 13,
              Name = Unit,
             ServerKey = 1,
             PKey = EUKey,
             HasChildren = 0
      FROM   EngineeringUnit
       WHERE    Unit LIKE @FilterStr
    END
    RETURN
  END

  IF @PKey = 1000 /* old value 100009 */
  -- I/O Server Type Group ------------------------------------------
  BEGIN
    -- Select I/O Server Type ---------------------------------------
    SELECT TypeKey = 10,
           Name = Description,
           ServerKey = 1,
           PKey = 0,
           HasChildren = 0
    FROM   IOServerType
    RETURN
  END

  IF @IsTopicTagQuery = 1
  -- Topic ----------------------------------------------------------
  BEGIN
    -- Select Tag ---------------------------------------------------
    IF @FilterStr IS NULL
    BEGIN
      -- No Filter defined ------------------------------------------
      SELECT  TypeKey = Tag.TagType,
              Name = Tag.TagName,
              ServerKey = 1,
              PKey = Tag.wwTagKey,
              HasChildren = 0
      FROM  SystemNameSpace S, Topic T, Tag   
      WHERE T.TopicKey = S.PKey
        AND T.IOServerKey = Tag.IOServerKey  
        AND T.StorageNodeKey  = Tag.StorageNodeKey 
        AND T.TopicKey  = Tag.TopicKey 
        AND S.NameKey = @PKey
      ORDER BY TagName
    END
    ELSE
    BEGIN
      -- Filter defined - scope on FilterStr ------------------------
      SELECT  TypeKey = Tag.TagType,
              Name = Tag.TagName,
              ServerKey = 1,
              PKey = Tag.wwTagKey,
              HasChildren = 0
      FROM  SystemNameSpace S, Topic T, Tag   
      WHERE T.TopicKey = S.PKey
        AND T.IOServerKey = Tag.IOServerKey  
        AND T.StorageNodeKey  = Tag.StorageNodeKey 
        AND T.TopicKey  = Tag.TopicKey 
        AND S.NameKey = @PKey
        AND    TagName LIKE @FilterStr
      ORDER BY TagName
    END
  END
END

GO

GRANT EXECUTE ON aaSystemNSExpand2 TO Public
go
 
 /**********  aaSystemParameterSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSystemParameterSelect'))
  DROP PROCEDURE dbo.aaSystemParameterSelect
GO

CREATE procedure aaSystemParameterSelect 
  @name nvarchar(50) = NULL
AS 
if @name is null
begin
  select Name, Value, Description, Status, Editable
     from SystemParameter where Name <> 'SystemVersion'
        order by Name
end
else
begin
  select Name, Value,  Description, Status, Editable
     from SystemParameter
        where Name = @name
end

return @@ERROR

GO
GRANT exec on aaSystemParameterSelect to Public
go
 
 /**********  aaSystemParameterUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaSystemParameterUpdate'))
  DROP PROCEDURE dbo.aaSystemParameterUpdate
GO

CREATE procedure aaSystemParameterUpdate 
  @name nvarchar(50),
  @value sql_variant,
  @description nvarchar(255) = NULL
AS
declare @type   char(7)
declare @numval real

/* Check validity of parameters */
if   (@value is NULL)
  or (@name is NULL)
  or not exists (select Name from SystemParameter
         where Name = @name)
  or (select Editable from SystemParameter
         where Name = @name) = 0 
begin
  goto error
end

if @description is NULL /* Keep previous desc */
begin
   set @description = (select Description from SystemParameter
            where Name = @name)
end

/* Update */
update SystemParameter
         set Value  = @value,
               Description  = @description
     where Name = @name 


if @@ERROR <> 0
begin
   goto error
end

return

error:
  declare @errno int, @errmsg varchar (255)
  set @errno = 17005
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid SystemParameter update'
  end

  raiserror @errno @errmsg 

GO
GRANT exec on aaSystemParameterUpdate to aaAdministrators
GO
GRANT exec on aaSystemParameterUpdate to aaPowerUsers
go
 
 /**********  aaTagConfig  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTagConfig'))
  DROP PROCEDURE dbo.aaTagConfig
GO

CREATE procedure aaTagConfig 
AS

select
wwTagKey, 
RTRIM(Tag.TagName) as TagName,
Tag.TagType,
Tag.StorageNodeKey,
IOServer.IODriverKey,
Tag.IOServerKey,
Tag.TopicKey,
RTRIM(ItemName) as ItemName,
AcquisitionRate,
AcquisitionType,
StorageRate,
StorageType,
StorageSize =
CASE TagType
 WHEN 1 THEN    -- analog tag
  CASE AnalogTag.RawType
   WHEN 1 THEN 4
   WHEN 2 THEN 4
   WHEN 3 THEN    -- integer raw type
   CASE AnalogTag.IntegerSize
    WHEN 12 THEN 2
    WHEN 15 THEN 2
    WHEN 16 THEN 2
    WHEN 32 THEN 4
    WHEN 64 THEN 8
   END
   WHEN 4 THEN 8
   WHEN 5 THEN 0
   WHEN 7 THEN 8
   WHEN 8 THEN 8
  END
 WHEN 2 THEN 1  -- discrete tag
 WHEN 3 THEN    -- string tag
  CASE StringTag.DoubleByte
   WHEN 0 THEN 
    StringTag.MaxLength
   ELSE
    StringTag.MaxLength * 2
  END
-- WHEN 7 THEN BlobTag.MaxLength    -- blob tag
-- WHEN 9 THEN 4    -- enumerated tag; use 4-byte storage
 ELSE 0
END,
MinEU,
MaxEU,
MinRaw,
MaxRaw,
TimeDeadband,
ValueDeadband,
RateDeadband,
IntegerSize,
Scaling,
RawType,
SignedInteger=convert(int, SignedInteger),
SamplesInActiveImage=
CASE 
 WHEN SamplesInActiveImage is null THEN 65
 WHEN SamplesInActiveImage = 0 THEN 65
 ELSE SamplesInActiveImage
END,
StringTag.DoubleByte,
AIRetrievalMode,
NULL as EnumerationID,
LicenseOrder = 
CASE Tag.IOServerKey
 when 1 then wwTagKey * -1
 else wwTagKey
END,
InterpolationType,
RolloverValue,
DeadbandType,
ServerTimeStamp,
EUKey,
LateData,
CurrentEditor
from Tag inner join Topic
 on (Topic.TopicKey        = Tag.TopicKey
 and Topic.IOServerKey     = Tag.IOServerKey
 and Topic.StorageNodeKey  = Tag.StorageNodeKey)
inner join IOServer
 on Topic.IOServerKey = IOServer.IOServerKey
left outer join AnalogTag
 on AnalogTag.TagName = Tag.TagName
left outer join DiscreteTag
 on DiscreteTag.TagName = Tag.TagName
left outer join StringTag
 on StringTag.TagName = Tag.TagName
where Tag.TagType in (1,2,3,4)
order by LicenseOrder

GO

GRANT exec on aaTagConfig to Public
go
 
 /**********  aaTagConfigModified  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTagConfigModified'))
  DROP PROCEDURE dbo.aaTagConfigModified
GO

CREATE procedure aaTagConfigModified 
AS

select
wwTagKey, 
RTRIM(Tag.TagName) as TagName,
Tag.TagType,
Tag.StorageNodeKey,
IOServer.IODriverKey,
Tag.IOServerKey,
Tag.TopicKey,
RTRIM(ItemName) as ItemName,
AcquisitionRate,
AcquisitionType,
StorageRate,
StorageType,
StorageSize =
CASE TagType
 WHEN 1 THEN    -- analog tag
  CASE AnalogTag.RawType
   WHEN 1 THEN 4
   WHEN 2 THEN 4
   WHEN 3 THEN    -- integer raw type
   CASE AnalogTag.IntegerSize
    WHEN 12 THEN 2
    WHEN 15 THEN 2
    WHEN 16 THEN 2
    WHEN 32 THEN 4
    WHEN 64 THEN 8
   END
   WHEN 4 THEN 8
   WHEN 5 THEN 0
   WHEN 7 THEN 8
   WHEN 8 THEN 8
  END
 WHEN 2 THEN 1  -- discrete tag
 WHEN 3 THEN    -- string tag
  CASE StringTag.DoubleByte
   WHEN 0 THEN 
    StringTag.MaxLength
   ELSE
    StringTag.MaxLength * 2
  END
-- WHEN 7 THEN BlobTag.MaxLength    -- blob tag
-- WHEN 9 THEN 4    -- enumerated tag; use 4-byte storage
 ELSE 0
END,
MinEU,
MaxEU,
MinRaw,
MaxRaw,
TimeDeadband,
ValueDeadband,
RateDeadband,
IntegerSize,
Scaling,
RawType,
SignedInteger=convert(int, SignedInteger),
SamplesInActiveImage=
CASE 
 WHEN SamplesInActiveImage is null THEN 65
 WHEN SamplesInActiveImage = 0 THEN 65
 ELSE SamplesInActiveImage
END,
StringTag.DoubleByte,
AIRetrievalMode,
ConfigStatusSnapshot.Status,
NULL as EnumerationID,
LicenseOrder = 
CASE Tag.IOServerKey
 when 1 then wwTagKey * -1
 else wwTagKey
END,
InterpolationType,
RolloverValue,
DeadbandType,
ServerTimeStamp,
EUKey,
LateData,
CurrentEditor
from Tag inner join Topic
 on (Topic.TopicKey        = Tag.TopicKey
 and Topic.IOServerKey     = Tag.IOServerKey
 and Topic.StorageNodeKey  = Tag.StorageNodeKey)
inner join IOServer
 on Topic.IOServerKey = IOServer.IOServerKey
left outer join AnalogTag
 on AnalogTag.TagName = Tag.TagName
left outer join DiscreteTag
 on DiscreteTag.TagName = Tag.TagName
left outer join StringTag
 on StringTag.TagName = Tag.TagName
inner join ConfigStatusSnapshot
 on Tag.wwTagKey = ConfigStatusSnapshot.ObjectKey
where Tag.TagType in (1,2,3,4)
and ConfigStatusSnapshot.Type = 3
order by LicenseOrder

GO

GRANT exec on aaTagConfigModified to Public
go
 
 /**********  aaTagConfigSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTagConfigSelect'))
  DROP PROCEDURE dbo.aaTagConfigSelect
GO

CREATE PROCEDURE aaTagConfigSelect 
  @tagtype int,
  @key   int,
  @FilterStr nvarchar(100) = N'%'
AS
BEGIN
   IF @tagtype =  1 /* AnalogTag*/
   BEGIN
     SELECT t.TagName, t.Description, MinEU, MaxEU, MinRaw, MaxRaw, Scaling, RawType,
                    ValueDeadband, InitialValue, IntegerSize, SignedInteger, wwTagKey
        FROM AnalogTag a, Tag t
           WHERE a.TagName = t.TagName
                 AND EUKey = @key
                 AND a.TagName LIKE @FilterStr
   END
   ELSE
       IF @tagtype = 2 /* Discrete tag */
   BEGIN
      SELECT t.TagName, t.Description, InitialValue, wwTagKey 
         FROM DiscreteTag d, Tag t
            WHERE d.TagName = t.TagName 
                  AND MessageKey = @key
                 AND d.TagName LIKE @FilterStr
   END
END

GO

GRANT  EXECUTE  ON aaTagConfigSelect TO Public
go
 
 /**********  aaTagInfo  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTagInfo'))
  DROP PROCEDURE dbo.aaTagInfo
GO

CREATE procedure aaTagInfo
  @TagList nvarchar(4000)
AS
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ','
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SET @TempChar = @TempChar + SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1) + "','"
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END;
  SET @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SET @SelectStatement = 
    "SELECT Tag.TagName, Tag.TagType, Tag.Description, Tag.wwTagKey FROM Tag WHERE TagName in ('" + @TempChar + "')"
  Execute (@SelectStatement)
GO

GRANT exec on aaTagInfo to Public
go
 
 /**********  aaTagType  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTagType'))
  DROP PROCEDURE dbo.aaTagType
GO

CREATE procedure aaTagType
  @TagList nvarchar(4000)
AS
  DECLARE @TempChar nvarchar(4000)
  DECLARE @SelectStatement nvarchar(4000)
  SET @TempChar = ""
  WHILE CHARINDEX(' ', @TagList) > 0 
  BEGIN
    SET @TagList = STUFF(@TagList, CHARINDEX(' ', @TagList), 1, '')    
  END 

  SET @TagList = @TagList + ','
  WHILE CHARINDEX(',', @TagList) > 0 
  BEGIN
    SET @TempChar = @TempChar + SUBSTRING(@TagList, 1, CHARINDEX(',', @TagList) - 1) + "','"
    SET @TagList = SUBSTRING(@TagList, CHARINDEX(',', @TagList) + 1, LEN(@TagList))
  END
  SET @TempChar = SUBSTRING(@TempChar, 1, LEN(@TempChar) - 3)

  SET @SelectStatement = 
     "Select TagName, TagType, StorageType from Tag where TagName IN ('" + @TempChar + "')"
  Execute (@SelectStatement)
GO

GRANT exec on aaTagType to Public
go
 
 /**********  aaTimeDetectorDetailInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTimeDetectorDetailInsert'))
  DROP PROCEDURE dbo.aaTimeDetectorDetailInsert
GO

CREATE procedure aaTimeDetectorDetailInsert 
  @FrequencyID      int, 
  @TagName          nvarchar(256),
  @Periodicity      int,
  @StartDateTime    DateTime,
  @RunTimeDay       tinyint,
  @RunTimeHour      tinyint,
  @RunTimeMin       tinyint
AS
BEGIN
  BEGIN TRAN
  Declare @Result int

  INSERT INTO TimeDetectorDetail 
              (TagName, FrequencyID, Periodicity, StartDateTime, RunTimeDay,
               RunTimeHour, RunTimeMin) 
  VALUES      (@TagName, @FrequencyID, @Periodicity, @StartDateTime, @RunTimeDay, 
               @RunTimeHour, @RunTimeMin)

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @Result = -1
  END
  RETURN @Result
END

GO

GRANT  EXECUTE  ON aaTimeDetectorDetailInsert TO aaAdministrators
GO
GRANT  EXECUTE  ON aaTimeDetectorDetailInsert TO aaPowerUsers
go
 
 /**********  aaTimeDetectorDetailSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTimeDetectorDetailSelect'))
  DROP PROCEDURE dbo.aaTimeDetectorDetailSelect
GO

CREATE procedure aaTimeDetectorDetailSelect 
  @TagName nvarchar(256) = NULL
AS
BEGIN
  IF @TagName IS NULL 
  BEGIN
    SELECT FrequencyID, Periodicity, StartDateTime, RunTimeDay,RunTimeHour, RunTimeMin 
    FROM   TimeDetectorDetail 
  END
  ELSE
  BEGIN
    SELECT FrequencyID, Periodicity, StartDateTime, RunTimeDay,RunTimeHour, RunTimeMin 
    FROM   TimeDetectorDetail 
    WHERE  TagName =@TagName
  END
END
GO

GRANT  EXECUTE  ON aaTimeDetectorDetailSelect TO Public
go
 
 /**********  aaTimeDetectorDetailUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTimeDetectorDetailUpdate'))
  DROP PROCEDURE dbo.aaTimeDetectorDetailUpdate
GO

CREATE procedure aaTimeDetectorDetailUpdate 
  @FrequencyID    int, 
  @TagName        nvarchar(256),
  @Periodicity    int,
  @StartDateTime  DateTime,
  @RunTimeDay     tinyint,
  @RunTimeHour    tinyint,
  @RunTimeMin     tinyint
AS
BEGIN
  BEGIN TRAN
  Declare @Result int

  UPDATE TimeDetectorDetail 
  SET    FrequencyID   = @FrequencyID,
             Periodicity   = @Periodicity, 
             StartDateTime = @StartDateTime,
             RunTimeDay    = @RunTimeDay,
             RunTimeHour   = @RunTimeHour,
             RunTimeMin    = @RunTimeMin
  WHERE  TagName       = @TagName

  IF @@Error = 0
  BEGIN
    COMMIT TRAN
  END
  ELSE
  BEGIN
    ROLLBACK TRAN
    SELECT @Result = -1
  END
  RETURN @Result
END

GO

GRANT  EXECUTE  ON aaTimeDetectorDetailUpdate TO aaAdministrators
GO
GRANT  EXECUTE  ON aaTimeDetectorDetailUpdate TO aaPowerUsers
go
 
 /**********  aaTopicDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTopicDelete'))
  DROP PROCEDURE dbo.aaTopicDelete
GO

CREATE procedure aaTopicDelete 
  @TopicKey int
AS
  DELETE FROM Topic
    WHERE  TopicKey = @TopicKey
GO

GRANT exec on aaTopicDelete to aaAdministrators
GO
GRANT exec on aaTopicDelete to aaPowerUsers
go
 
 /**********  aaTopicInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTopicInsert'))
  DROP PROCEDURE dbo.aaTopicInsert
GO

CREATE procedure aaTopicInsert 
  @StorageNodeKey int, 
  @IOServerKey    int, 
  @Name           nvarchar(80), 
  @TimeOut        int = 60000,
  @LateData       bit = 0,
  @IdleDuration   int = 60,
  @ProcessingInterval  int = 120
AS 

BEGIN
  DECLARE @result int

  INSERT INTO Topic
    (
    IOServerKey, 
    StorageNodeKey, 
    Name, 
    TimeOut,
    LateData,
    IdleDuration,
    ProcessingInterval
    )
  VALUES
    (
    @IOServerKey, 
    1, 
    @Name, 
    @TimeOut,
    @LateData,
    @IdleDuration,
    @ProcessingInterval
    )

   if @@ERROR <> 0
   begin
      goto error
   end

   /* Need to return the IODriverKey */
   /* @@IDENTITY cannot be used because of Insert trigger actions */
   set @result = (select TopicKey from Topic
                        where IOServerKey = @IOServerKey
                        and     Name = @Name)

   return @result

   error:
     declare @errno int, @errmsg varchar (255)
     set @errno = 17020
     set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
     if @errmsg  is NULL
     begin
        set @errmsg = 'Error msg not found - Invalid Topic insert'
     end

     raiserror @errno @errmsg 
END

GO

GRANT exec on aaTopicInsert to aaAdministrators
GO
GRANT exec on aaTopicInsert to aaPowerUsers
go
 
 /**********  aaTopicSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTopicSelect'))
  DROP PROCEDURE dbo.aaTopicSelect
GO

CREATE procedure aaTopicSelect 
  @TopicKey int = NULL
AS
IF @TopicKey IS NULL 
BEGIN 
   SELECT TopicKey, StorageNodeKey, IOServerKey, Name, TimeOut, LateData, IdleDuration, ProcessingInterval
   FROM   Topic
END
ELSE
BEGIN
   SELECT TopicKey, StorageNodeKey, IOServerKey, Name, TimeOut, LateData, IdleDuration, ProcessingInterval
   FROM   Topic
   WHERE  TopicKey = @TopicKey
END
GO

GRANT exec on aaTopicSelect to Public
go
 
 /**********  aaTopicUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaTopicUpdate'))
  DROP PROCEDURE dbo.aaTopicUpdate
GO

CREATE procedure aaTopicUpdate 
  @TopicKey       int, 
  @StorageNodeKey int, 
  @IOServerKey    int, 
  @Name           nvarchar(80), 
  @TimeOut        int = 60000,
  @LateData       bit = 0,
  @IdleDuration   int = 60,
  @ProcessingInterval  int = 120
AS 
BEGIN
  UPDATE Topic
  SET
    IOServerKey    = @IOServerKey,
    StorageNodeKey = 1, 
    Name           = @Name, 
    TimeOut        = @TimeOut,
    LateData       = @LateData,
    IdleDuration   = @IdleDuration,
    ProcessingInterval = @ProcessingInterval
  WHERE TopicKey = @TopicKey

  RETURN @@Error
END
GO

GRANT exec on aaTopicUpdate to aaAdministrators
GO
GRANT exec on aaTopicUpdate to aaPowerUsers
go
 
 /**********  aaInternalTopicExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalTopicExport'))
  DROP PROCEDURE dbo.aaInternalTopicExport
GO

CREATE procedure aaInternalTopicExport 
  @Format int=0
AS
--**************************
-- Export Topic
--**************************
declare @insql_name nvarchar(32)

select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList

SELECT [:(Topic)Name]=Name, 
 IOServer.ApplicationName, 
 [ComputerName]=CASE LOWER(IOServer.ComputerName)
 WHEN @insql_name THEN '$local'
 ELSE LOWER(IOServer.ComputerName)
 END,
 [TimeOut]=CASE @Format
  WHEN 0 THEN RTRIM(CONVERT(nvarchar(16), TimeOut))
  ELSE TimeOut
  END,
 [LateData]=CASE LateData
  WHEN 1 THEN 'Yes'
  ELSE 'No'
  END,
 [IdleDuration]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),IdleDuration)
  ELSE IdleDuration
  END,
 [ProcessingInterval]=CASE @Format
  WHEN 0 THEN CONVERT(nvarchar(16),ProcessingInterval)
  ELSE ProcessingInterval
  END
FROM Topic, IOServer
WHERE TopicKey > 2 and IOServer.IOServerKey=Topic.IOServerKey

if @@ERROR <> 0
begin
   goto error
end
return

error:
declare @errno int, @errmsg nvarchar (255)
set @errno=50002
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
begin
set @errmsg='Topic export failed'
end
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalTopicExport to aaAdministrators
go
 
 /**********  aaInternalTopicImport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalTopicImport'))
  DROP PROCEDURE dbo.aaInternalTopicImport
GO

CREATE procedure aaInternalTopicImport 
  @Mode nvarchar(32)='update',
  @Name nvarchar(80),
  @ApplicationName nvarchar(64),
  @ComputerName nvarchar(256),
  @TimeOut nvarchar(32),
  @LateData nvarchar(8)='No',
  @IdleDuration nvarchar(16)='60',
  @ProcessingInterval nvarchar(16)='120'
AS
--**************************
-- Import Topic
--**************************
declare @key int, @storagenode_key int, @ios_key int, @time_out int
declare @errno int, @errmsg nvarchar(255), @errmsg_default nvarchar(255)
declare @insql_name nvarchar(32)
declare @late_data bit, @idle_duration int, @processing_interval int

set @Mode=LTRIM(RTRIM(LOWER(@Mode)))

-- If set to ignore, we don't do anything

if @Mode='ignore'
return

set @Name=LTRIM(RTRIM(@Name))
if len(@Name) = 0
 BEGIN
 set @errno=50303
 set @errmsg_default='Topic import failed (an empty Name is not allowed)'
 goto error
 END
select @insql_name = LOWER(CONVERT(nvarchar(32), ComputerName)) from ServerList
set @ComputerName=LTRIM(RTRIM(LOWER(@ComputerName)))
if @ComputerName='$local'
BEGIN
 set @ComputerName=@insql_name
END

set @time_out=CONVERT(int, @TimeOut)
set @late_data=CASE LTRIM(RTRIM(LOWER(@LateData)))
  WHEN 'yes' THEN 1
  ELSE 0
  END
set @idle_duration=CONVERT(int, @IdleDuration)
set @processing_interval=CONVERT(int, @ProcessingInterval)

-- Get the key of the IOServer to which this Topic is supposed to belong.
-- If the IOServer does not exist, and the user is not deleting this Topic, 
-- return an error.

select @ios_key=IOServerKey 
from IOServer 
where LTRIM(RTRIM(LOWER(ComputerName)))=LTRIM(RTRIM(LOWER(@ComputerName)))
AND LTRIM(RTRIM(LOWER(ApplicationName)))=LTRIM(RTRIM(LOWER(@ApplicationName)))

if (@ios_key is null) AND (@Mode <> 'delete')
BEGIN
 set @errno=50107
 set @errmsg_default='Topic import failed (IOServer does not exist)'
 goto error
END

-- Check if a Topic with this name/IOServerKey already exists
-- If so, update or delete it as specified by the mode parameter

select @key=TopicKey, @storagenode_key=StorageNodeKey
from Topic 
where LTRIM(RTRIM(LOWER(Name)))=LTRIM(RTRIM(LOWER(@Name)))
and IOServerKey=@ios_key

if @key is not null
BEGIN
 if @Mode='update'
 BEGIN
 exec aaTopicUpdate 
  @key,
  @storagenode_key,
  @ios_key,
  @Name,
  @time_out,
  @late_data,
  @idle_duration,
  @processing_interval
 if @@ERROR <> 0
  BEGIN
  set @errno=50108
  set @errmsg_default='Topic import failed (update failed)'
  goto error
  END
 END
 else if @Mode='delete'
 BEGIN
 exec aaTopicDelete @key
 if @@ERROR <> 0
  BEGIN
  set @errno=50109
  set @errmsg_default='Topic import failed (delete failed)'
  goto error
  END
 END
END
else

-- The Topic does not exist, insert it if this is what 
-- the user specified, otherwise return an error

BEGIN
if @Mode='delete'
BEGIN
return
END
else
BEGIN
exec aaTopicInsert 
 1,
 @ios_key,
 @Name,
 @time_out,
 @late_data,
 @idle_duration,
 @processing_interval
if @@ERROR <> 0
 BEGIN
 set @errno=50110
 set @errmsg_default='Topic import failed (insert failed)'
 goto error
 END
END
END
return

error:
set @errmsg=(select LocalizedText from LocalizedText where TextKey=@errno 
and LanguageID=(select lcid from master..syslanguages where langid=@@LANGID))
if @errmsg  is NULL
raiserror @errno @errmsg_default
else
raiserror @errno @errmsg 
GO

GRANT exec on aaInternalTopicImport to aaAdministrators
go
 
 /**********  aaUpdateCalculatedAISamples  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaUpdateCalculatedAISamples'))
  DROP PROCEDURE dbo.aaUpdateCalculatedAISamples
GO

CREATE procedure aaUpdateCalculatedAISamples 
  @tagkey int, @samples int
/* Internal Historian Stored Procedure, do not run manually */
AS
   update Tag set CalculatedAISamples = @samples
      where wwTagKey = @tagkey

GO

GRANT EXEC ON aaUpdateCalculatedAISamples TO aaAdministrators
GO
GRANT EXEC ON aaUpdateCalculatedAISamples TO aaPowerUsers
go
 
 /**********  aaUserAccessLevelSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaUserAccessLevelSelect'))
  DROP PROCEDURE dbo.aaUserAccessLevelSelect
GO

CREATE procedure aaUserAccessLevelSelect 
AS

BEGIN
  DECLARE @AccessLevel int

  SELECT @AccessLevel = 1

  SELECT @AccessLevel = AccessLevel
  FROM   UserDetail
  WHERE  uid = USER_ID()

  IF @AccessLevel = 1
  BEGIN
    SELECT UserDetail.AccessLevel
    FROM   sysusers, UserDetail
    WHERE  sysusers.uid = USER_ID()
    AND    sysusers.gid = UserDetail.uid
  END

  RETURN @AccessLevel
END
GO

GRANT EXEC ON aaUserAccessLevelSelect TO Public
go
 
 /**********  aaUserDetailUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaUserDetailUpdate'))
  DROP PROCEDURE dbo.aaUserDetailUpdate
GO

CREATE procedure aaUserDetailUpdate 
AS

BEGIN
  INSERT UserDetail (UserKey,UserName, AccessLevel, uid, gid)
    (SELECT uid, name, 1, uid, gid  from sysusers
       WHERE name NOT IN ('INFORMATION_SCHEMA', 'guest')
       AND name NOT LIKE ('db_%')
       OR name = 'dbo' 
         GROUP BY uid, name, gid
           HAVING name <> ALL
                (SELECT UserName from UserDetail))

  DELETE UserDetail
      WHERE  UserName NOT IN 
         (SELECT name from sysusers)
END

GO

GRANT EXEC ON aaUserDetailUpdate TO aaAdministrators
go
 
 /**********  aaInternalLocalizedTextExport  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalLocalizedTextExport'))
  DROP PROCEDURE dbo.aaInternalLocalizedTextExport
GO

CREATE procedure aaInternalLocalizedTextExport 
  @MsgFileName nvarchar(256)
AS

BEGIN
  if (select LocalizedText from LocalizedText where TextKey = 0) <> '0'
  BEGIN
    update LocalizedText set LocalizedText = '0'
      where TextKey = 0

    declare @cmdstring nvarchar(512)
    set @cmdstring = N'bcp "select TextKey, LanguageID, LocalizedText from Runtime.dbo.LocalizedText order by TextKey" queryout "' + @MsgFileName + N'" -T -w'
    exec master..xp_cmdshell @cmdstring
  END
END
GO

GRANT EXEC ON aaInternalLocalizedTextExport TO aaAdministrators
go
 
 /**********  aaInternalHistoryModTrack  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalHistoryModTrack'))
  DROP PROCEDURE dbo.aaInternalHistoryModTrack
GO

CREATE procedure aaInternalHistoryModTrack 
  @LogUsername nvarchar(256),
  @LogModType nchar(1),
  @LogCount int = 1,
  @LogFileOrTag nvarchar(256) = N'N/A',
  @LogStartTime nvarchar(50) = N'N/A'

AS
begin
   declare @res int
   exec @res = aaModLogStatus
-- @LogModType has the following values
--  1 SQL insert
--  2 SQL original insert
--  3 SQL update
--  4 CSV insert
--  5 CSV original insert
--  6 CSV update
--  7 CSV multi-point update
--  8 CSV FastLoad insert
--  These values supplement I, U and D which are used in ModLogTable for mod tracking of configuration data.
   if ((@LogModType in (N'1', N'2', N'4', N'5', N'8')) and (@res in (1, 3, 5, 7))) or
      ((@LogModType in (N'3', N'6', N'7')) and (@res in (2, 3, 6, 7)))
   begin
      declare @thetable int
      set @thetable = (select id from HistorianSysObjects 
              where Name = 'History_OLEDB' and Type = 'U')

      insert ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, convert(char(1), @LogModType), @LogFileOrTag, USER_ID(), getdate(), @LogUsername

      -- The count of the number of inserts/updates is logged to the NewValue column.
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
         select SCOPE_IDENTITY(), 'vValue', @LogStartTime, @LogCount
   end
end
GO

GRANT EXEC ON aaInternalHistoryModTrack TO aaAdministrators, aaPowerUsers
go
 
 /**********  aaInternalSetServerName  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalSetServerName'))
  DROP PROCEDURE dbo.aaInternalSetServerName
GO

CREATE procedure aaInternalSetServerName 
  @Command nvarchar(10) = NULL,
  @VirtualHistName nvarchar(100) = NULL

AS
  IF (@Command IS NULL) OR (UPPER(@Command) <> 'RENAME')
  BEGIN
    PRINT 'This procedure is used to update the appropriate InSQL system tables after' 
    PRINT 'the server node has been renamed.'
    PRINT 'This procedure should be used only on instructions of Wonderware Technical'
    PRINT 'Support personnel, or if you have carefully read Wonderware Tech Note 299.'
    PRINT ''
    PRINT 'The procedure assumes that you have already:'
    PRINT ' - changed the Windows computer name and rebooted.'
    PRINT ' - changed the SQL Server name using the Microsoft documented procedure.'
    PRINT ' - stopped and restarted your SQL Server (IMPORTANT!)'
    PRINT ''
    PRINT 'By displaying this statement, you have NOT executed the rename procedure.'
    PRINT 'In order to execute the rename procedure, enter:'
    PRINT ' exec aaInternalSetServerName ''rename'', [''<virtual_name>'']'
  END
  ELSE
  BEGIN
    DECLARE @NewName nvarchar(100)
    DECLARE @OldName nvarchar(100)

    IF serverproperty('IsClustered') = 0
    BEGIN
      SET @NewName = @@ServerName
    END
    ELSE
    BEGIN
      IF @VirtualHistName IS NOT NULL
      BEGIN
        SET @NewName = @VirtualHistName
      END
      ELSE
      BEGIN
        PRINT 'By displaying this statement, you have NOT executed the rename procedure.'
        PRINT 'In order to execute the rename procedure on a clustered server, enter:'
        PRINT ' exec aaInternalSetServerName ''rename'', ''<virtual_name>'''
        RETURN
      END
    END

    SELECT @OldName = ComputerName FROM ServerList

    IF UPPER(@NewName) <> UPPER(@OldName)
    BEGIN
      UPDATE StorageNode
        SET ComputerName = @NewName
        WHERE ComputerName = @OldName
        AND StorageNodeKey = 1

      UPDATE ServerList
        SET ComputerName = @NewName
        WHERE ComputerName = @OldName
        AND ServerKey = 1

      UPDATE InTouchNode
        SET MachineName = @NewName
        WHERE MachineName = @OldName

      UPDATE IOServer
        SET ComputerName = @NewName
        WHERE ComputerName = @OldName
        AND IOServerKey IN (1,2)

      UPDATE IODriver
        SET ComputerName = @NewName
        WHERE ComputerName = @OldName
    END
  END

GO

-- GRANT EXEC ON aaInternalSetServerName TO aaAdministrators
go
 
 /**********  aaInternalTagDetails  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalTagDetails'))
  DROP PROCEDURE dbo.aaInternalTagDetails
GO

CREATE procedure aaInternalTagDetails 
  @TagKey int=1,
  @TagType int=0
AS
  IF @TagType = 1     -- E_TTANALOG
  BEGIN
    select Description, Unit, DefaultTagRate, IntegralDivisor, '', '', 0 from Tag, AnalogTag, EngineeringUnit
      where Tag.wwTagKey=@TagKey and AnalogTag.TagName=Tag.TagName
      and EngineeringUnit.EUKey=AnalogTag.EUKey
  END
  ELSE
  IF @TagType = 2     -- E_TTDISCRETE
  BEGIN
    select Description, '', 0, 0, Message0, Message1, 0 from Tag, DiscreteTag, Message
      where Tag.wwTagKey=@TagKey and DiscreteTag.TagName=Tag.TagName
      and Message.MessageKey=DiscreteTag.MessageKey
  END
  ELSE
  IF (@TagType = 3) OR (@TagType = 8)     -- E_TTSTRING or E_TTSTRINGFIXED
  BEGIN
    select Description, '', 0, 0, '', '', MaxLength from Tag, StringTag
      where Tag.wwTagKey=@TagKey and StringTag.TagName=Tag.TagName
  END
  ELSE
  BEGIN
    select Description, '', 0, 0, '', '', 0 from Tag where Tag.wwTagKey=@TagKey
  END

return

GO

GRANT exec on aaInternalTagDetails to aaAdministrators
go
 
 /**********  aaInternalAreaVersion  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAreaVersion'))
  DROP PROCEDURE dbo.aaInternalAreaVersion
GO

CREATE procedure aaInternalAreaVersion 
AS
  select top 1 Version from aaAreaXML
GO

GRANT exec on aaInternalAreaVersion to public
go
 
 /**********  aaInternalAreaVersionInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAreaVersionInsert'))
  DROP PROCEDURE dbo.aaInternalAreaVersionInsert
GO

CREATE procedure aaInternalAreaVersionInsert
  @Version bigint
AS
  truncate table aaAreaXML
  insert aaAreaXML (Version) values (@Version)
GO

GRANT exec on aaInternalAreaVersionInsert to aaAdministrators
go
 
 /**********  aaInternalAreaXMLInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAreaXMLInsert'))
  DROP PROCEDURE dbo.aaInternalAreaXMLInsert
GO

CREATE procedure aaInternalAreaXMLInsert 
  @XMLtext ntext
AS
  insert aaAreaXML (AreaXML) values (@XMLtext)
GO

GRANT exec on aaInternalAreaXMLInsert to aaAdministrators
go
 
 /**********  aaInternalAreaDataInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAreaDataInsert'))
  DROP PROCEDURE dbo.aaInternalAreaDataInsert
GO

CREATE procedure aaInternalAreaDataInsert 
  @AreaKey int,
  @AreaName nvarchar(256),
  @ContainedName nvarchar(256),
  @Category int,
  @ParentKey int
AS
  insert aaAreaData (AreaKey, AreaName, ContainedName, Category, ParentKey)
    values (@AreaKey, @AreaName, @ContainedName, @Category, @ParentKey)
GO

GRANT exec on aaInternalAreaDataInsert to aaAdministrators
go
 
 /**********  aaInternalAreaDataClear  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAreaDataClear'))
  DROP PROCEDURE dbo.aaInternalAreaDataClear
GO

CREATE procedure aaInternalAreaDataClear 
AS
  truncate table aaAreaData
GO

GRANT exec on aaInternalAreaDataClear to aaAdministrators
go
 
 /**********  aaInternalNSAreaUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalNSAreaUpdate'))
  DROP PROCEDURE dbo.aaInternalNSAreaUpdate
GO

CREATE procedure aaInternalNSAreaUpdate 
AS

  declare @aaPNS table
  (
    NameKey int,
    [Name]  nvarchar(255),
    ParentKey int
  )

  declare @AreaExists table
  (
    AreaKey  int,
    Category int,
    AreaName nvarchar(255),
    ContainedName nvarchar(255),
    ParentKey int
  )

  declare @AreaInserted table
  (
    AreaKey  int,
    Category int,
    AreaName nvarchar(255),
    ContainedName nvarchar(255),
    ParentKey int
  )

  declare @AreaMoved table
  (
    NameKey  int,
    AreaKey  int,
    Category int,
    AreaName nvarchar(255),
    ContainedName nvarchar(255),
    ParentKey int
  )

  declare @AreaDeleted table
  (
    NameKey int,
    [Name]  nvarchar(255)
  )

  declare @ObjectDeleted table
  (
    ObjectKey int
  )

  declare @WorkTbl table
  (
    Category int, 
    AreaName nvarchar(255),
    DisplayName nvarchar(255),
    ParentName nvarchar(255)
  )

  begin tran

  -- Do we need to provide an Unassigned Area?
  -- Entities which are not areas, directly under the galaxy level, go to the Unassigned Area
  declare @GalaxyKey int
  select @GalaxyKey = AreaKey from aaAreaData
    where ParentKey = 0

  if exists (select * from aaAreaData 
      where ParentKey = @GalaxyKey
      and Category <> 13)
  begin
    declare @UAKey int

    if not exists (select * from aaAreaData where AreaName = 'Unassigned Area')
    begin
      -- Add 'Unassigned Area' and assign its children
      select @UAKey = max(AreaKey)+1 from aaAreaData

      insert aaAreaData (AreaKey, Category, AreaName, ContainedName, ParentKey)
        values (@UAKey, 13, 'Unassigned Area', '', @GalaxyKey)
    end
    else
    begin
      select @UAKey = AreaKey from aaAreaData where AreaName = 'Unassigned Area'
    end

    update aaAreaData set ParentKey = @UAKey
      where ParentKey = @GalaxyKey
      and Category <> 13
  end

  -- Copy data from PublicNameSpace, stripping off [ contained name ] suffix, if present
  insert @aaPNS (NameKey, [Name], ParentKey)
    select NameKey, dbo.faaObjectTagName([Name]), ParentKey
      from PublicNameSpace
      where Type >= 1999000
      and Type <= 1999100

  insert @AreaExists (AreaKey, Category, AreaName, ContainedName, ParentKey)
    select a.AreaKey, a.Category, a.AreaName, a.ContainedName, a.ParentKey
      from aaAreaData a inner join @aaPNS p
      on a.AreaName = p.[Name]

  -- If the area already exists, check for changed parent
  insert @AreaMoved (NameKey, AreaKey, Category, AreaName, ContainedName, ParentKey)
    select p1.NameKey, a2.AreaKey, a2.Category, a2.AreaName, a2.ContainedName, a2.ParentKey
      from @AreaExists ae join @aaPNS p1
      on ae.AreaName = p1.[Name]
      join @aaPNS p2
      on p1.ParentKey = p2.NameKey
      join aaAreaData a1
      on ae.ParentKey = a1.AreaKey
      join aaAreaData a2
      on ae.AreaKey = a2.AreaKey
      where p2.[Name] <> a1.AreaName

  -- These areas are to be deleted
  insert @AreaDeleted (NameKey, [Name])
    select NameKey, [Name]
      from @aaPNS
      where [Name] not in (select AreaName from aaAreaData)

  -- These objects are to be deleted from aaObjectData
  insert @ObjectDeleted (ObjectKey)
    select o.ObjectKey
      from aaObjectData o inner join @AreaDeleted a
      on o.aaTagName = a.[Name]
      and o.ParentKey = 0

  -- Add the areas from @AreaMoved
  insert @AreaDeleted (NameKey, [Name])
    select NameKey, AreaName
      from @AreaMoved
      where AreaName not in (select AreaName from @AreaDeleted)

  -- Perform the area deletion
  if exists (select * from PublicNameSpace where NameKey in (select NameKey from @AreaDeleted)) 
  begin
    declare @WorkLevel int
    declare @WorkKey table
    (
      WorkKey int
    )

    -- Temporary table for deleted groups -------------------------
    declare @DelGroup table 
    (
      NameKey int,
      TreeLevel int
    )

    -- Load the anchor group details ------------------------------
    set @WorkLevel = 1

    -- Set initial group state ------------------------------------
    insert @DelGroup (NameKey, TreeLevel)
      select NameKey, @WorkLevel from @AreaDeleted

    while @WorkLevel > 0
    begin
      if exists (select * from @DelGroup where TreeLevel = @WorkLevel)
      begin
        -- Get the groups -----------------------------------------
        insert @WorkKey (WorkKey)
          select NameKey 
            from   @DelGroup 
            where  TreeLevel = @WorkLevel

        -- Remove the rows from the temp table --------------------
        delete @DelGroup where TreeLevel = @WorkLevel

        -- Insert this group's children into the temp table -------
        set @WorkLevel = @WorkLevel + 1
        insert @DelGroup (NameKey, TreeLevel)
          select NameKey, @WorkLevel
          from   PublicNameSpace
          where  ParentKey in (select WorkKey from @WorkKey)

        -- Remove the physical group ------------------------------
        delete PublicNameSpace where NameKey in (select WorkKey from @WorkKey)
        delete @WorkKey
      end
      else
      begin
        -- End of branch recurse back up a level ------------------
        select @WorkLevel = @WorkLevel - 1
      end    
    end    -- while
  end  -- perform the area deletion

  -- Perform the object deletion
  if exists (select * from aaObjectData where ObjectKey in (select ObjectKey from @ObjectDeleted))
  begin
    declare @WorkLevelO int
    declare @WorkKeyO table
    (
      WorkKey int
    )

    -- Temporary table for deleted groups -------------------------
    declare @DelGroupO table 
    (
      ObjectKey int,
      TreeLevel int
    )

    -- Load the anchor group details ------------------------------
    set @WorkLevelO = 1

    -- Set initial group state ------------------------------------
    insert @DelGroupO (ObjectKey, TreeLevel)
      select ObjectKey, @WorkLevelO from @ObjectDeleted

    while @WorkLevelO > 0
    begin
      if exists (select * from @DelGroupO where TreeLevel = @WorkLevelO)
      begin
        -- Get the groups -----------------------------------------
        insert @WorkKeyO (WorkKey)
          select ObjectKey 
            from   @DelGroupO 
            where  TreeLevel = @WorkLevelO

        -- Remove the rows from the temp table --------------------
        delete @DelGroupO where TreeLevel = @WorkLevelO

        -- Insert this group's children into the temp table -------
        set @WorkLevelO = @WorkLevelO + 1
        insert @DelGroupO (ObjectKey, TreeLevel)
          select ObjectKey, @WorkLevelO
          from   aaObjectData
          where  ParentKey in (select WorkKey from @WorkKeyO)

        -- Remove the physical group ------------------------------
        delete aaObjectData where ObjectKey in (select WorkKey from @WorkKeyO)
        delete @WorkKeyO
      end
      else
      begin
        -- End of branch recurse back up a level ------------------
        select @WorkLevelO = @WorkLevelO - 1
      end    
    end    -- while
  end  -- perform the object deletion

  -- After deleting data from the public namespace, repopulate aaPNS
  delete @aaPNS

  insert @aaPNS (NameKey, [Name], ParentKey)
    select NameKey, dbo.faaObjectTagName([Name]), ParentKey
      from PublicNameSpace
      where Type >= 1999000
      and Type <= 1999100

  -- These areas are to be added
  insert @AreaInserted (AreaKey, Category, AreaName, ContainedName, ParentKey)
    select a.AreaKey, a.Category, a.AreaName, a.ContainedName, a.ParentKey
      from aaAreaData a
      where a.AreaName not in (select [Name] from @aaPNS)

  -- Perform the area insertion
  -- insert the galaxy level, if it's in @AreaInserted
  insert PublicNameSpace (Type, ParentKey, [Name])
    select 1999023, 1, AreaName from @AreaInserted
      where ParentKey = 0

  insert @WorkTbl (Category, AreaName, DisplayName, ParentName)
    select ai.Category,
      ai.AreaName,
      DisplayName = case
        when ai.Category <> 13 then ai.AreaName  -- not an area
        when a.ParentKey = 0 then ai.AreaName    -- directly under the root
        when ai.ContainedName is NULL or ai.ContainedName = ''
          then ai.AreaName + ' [ ' + ai.AreaName + ' ]'
        else ai.AreaName + ' [ ' + ai.ContainedName + ' ]'
        end,
      a.AreaName ParentName
      from @AreaInserted ai inner join aaAreaData a
      on ai.ParentKey = a.AreaKey
      where ai.ParentKey >= 0

  while exists (select * from PublicNameSpace p inner join @WorkTbl w
                on w.ParentName = dbo.faaObjectTagName(p.[Name]))
  begin
    insert PublicNameSpace (Type, ParentKey, [Name])
      select 1999000+w.Category, p.NameKey, w.DisplayName
        from @WorkTbl w inner join PublicNameSpace p
        on w.ParentName = dbo.faaObjectTagName(p.[Name])

    delete @WorkTbl where AreaName in
      (select w.AreaName from @WorkTbl w inner join PublicNameSpace p
        on w.DisplayName = p.[Name]
        where p.Type >= 1999000
        and p.Type <= 1999100)
  end

  commit tran

  -- Populate the public namespace table
  exec aaInternalNSObjectPopulate

GO

GRANT exec on aaInternalNSAreaUpdate to aaAdministrators
go
 
 /**********  aaInternalAttributeDataInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAttributeDataInsert'))
  DROP PROCEDURE dbo.aaInternalAttributeDataInsert
GO

CREATE procedure aaInternalAttributeDataInsert 
  @AttributeName nvarchar(256),
  @ObjectKey int
AS
  insert aaAttributeDataPending (AttributeName, ObjectKey)
    values (@AttributeName, @ObjectKey)
GO

GRANT exec on aaInternalAttributeDataInsert to aaAdministrators
go
 
 /**********  aaInternalObjectDataInsert  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalObjectDataInsert'))
  DROP PROCEDURE dbo.aaInternalObjectDataInsert
GO

CREATE procedure aaInternalObjectDataInsert 
  @ObjectKey int,
  @aaTagName nvarchar(256),
  @ContainedName nvarchar(256),
  @ParentKey int,
  @Type int
AS
  insert aaObjectDataPending (ObjectKey, Type, aaTagName, ContainedName, ParentKey)
    values (@ObjectKey, @Type, @aaTagName, @ContainedName, @ParentKey)
GO

GRANT exec on aaInternalObjectDataInsert to aaAdministrators
go
 
 /**********  aaInternalAttrObjectDataClear  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalAttrObjectDataClear'))
  DROP PROCEDURE dbo.aaInternalAttrObjectDataClear
GO

CREATE procedure aaInternalAttrObjectDataClear 
AS
  truncate table aaObjectDataPending
  truncate table aaAttributeDataPending
GO

GRANT exec on aaInternalAttrObjectDataClear to aaAdministrators
go
 
 /**********  aaInternalNSObjectUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalNSObjectUpdate'))
  DROP PROCEDURE dbo.aaInternalNSObjectUpdate
GO

CREATE procedure aaInternalNSObjectUpdate 
AS

-- This stored procedure populates or updates the aaObjectData and aaAttributeData tables,
-- based on data in the aaObjectDataPending and aaAttributeDataPending tables.

  declare @TransTbl table
  (
    ObjectKey            int NOT NULL,
    ObjectKeyPend        int NOT NULL
  )

  declare @ODPWork table
  (
    aaTagName            nvarchar(256) NULL,
    ContainedName        nvarchar(256) NULL
  )

  declare @TagExists table
  (
    ObjectKey            int NOT NULL,
    Type                 int NOT NULL,
    aaTagName            nvarchar(256) NULL,
    ContainedName        nvarchar(256) NULL,
    ParentKey            int NOT NULL,
    ObjectKeyPend        int NOT NULL,
    ParentKeyPend        int NOT NULL
  )

  declare @TagNotExists table
  (
    ObjectKeyPend        int NOT NULL,
    Type                 int NOT NULL,
    aaTagName            nvarchar(256) NULL,
    ContainedName        nvarchar(256) NULL,
    ParentKeyPend        int NOT NULL
  )

  declare @TagMoved table
  (
    ObjectKey            int NOT NULL,
    aaTagName            nvarchar(256) NULL,
    ParentKeyMoved       int NOT NULL
  )

  declare @TagnameUpdated table
  (
    ObjectKey            int NOT NULL,
    aaTagName            nvarchar(256) NULL  -- new (updated) tagname
  )

  declare @TagnameUpdateWork table
  (
    ObjectKey            int NOT NULL,
    aaTagName            nvarchar(256) NULL
  )

  declare @WorkTbl table
  (
    ObjectKeyPend        int NOT NULL,
    Type                 int NOT NULL,
    aaTagName            nvarchar(256) NULL,
    ContainedName        nvarchar(256) NULL,
    ParentName           nvarchar(256) NULL
  )

  begin tran

  -- Find the tags from aaObjectDataPending which already exist in aaObjectData
  insert @TagExists (ObjectKey, Type, aaTagName, ContainedName, ParentKey, ObjectKeyPend,
      ParentKeyPend)
    select o.ObjectKey, o.Type, o.aaTagName, o.ContainedName, o.ParentKey,
        op.ObjectKey, op.ParentKey 
      from aaObjectData o inner join aaObjectDataPending op
      on o.aaTagName = op.aaTagName

  -- Work table with non-blank ContainedName
  insert @ODPWork(aaTagName, ContainedName)
    select aaTagName,
      ContainedName = case
        when ContainedName is NULL or ContainedName = ''
          then aaTagName
        else ContainedName
        end
      from aaObjectDataPending

  -- Tagnames are the same, but Contained name has changed; apply the change
  update aaObjectData set ContainedName = op.ContainedName, Status = 2
    from aaObjectData o join @ODPWork op
      on o.aaTagName = op.aaTagName
      where o.ContainedName <> op.ContainedName

  -- Collect translation details for the tags that already exist (areas included)
  insert @TransTbl (ObjectKey, ObjectKeyPend)
    select ObjectKey, ObjectKeyPend
      from @TagExists

  -- Find the tags from aaObjectDataPending which do not exist in aaObjectData.
  insert @TagNotExists(ObjectKeyPend, Type, aaTagName, ContainedName, ParentKeyPend)
    select ObjectKey, Type, aaTagName,
      ContainedName = case
        when ContainedName is NULL or ContainedName = ''
          then aaTagName
        else ContainedName
        end,
      ParentKey
      from aaObjectDataPending
      where aaTagName not in (select aaTagName from @TagExists)

  -- Find objects which have differing tag names but the same contained name, at the same
  -- level of the hierarchy.  This indicates that the aaTagName has changed; mark these
  -- for update.
  insert @TagnameUpdateWork(ObjectKey, aaTagName)
    select o1.ObjectKey, tne.aaTagName
      from @TagNotExists tne inner join aaObjectData o1
      on tne.ContainedName = o1.ContainedName
      inner join aaObjectData o2
      on o2.ObjectKey = o1.ParentKey
      inner join aaObjectDataPending op
      on op.ObjectKey = tne.ParentKeyPend
      where o2.aaTagName = op.aaTagName

  while exists (select * from @TagnameUpdateWork)
  begin
    insert @TagnameUpdated(ObjectKey, aaTagName)
      select ObjectKey, aaTagName from @TagnameUpdateWork

    -- Apply the tag name updates
    update aaObjectData set aaTagName = u.aaTagName, Status = 1
      from @TagnameUpdateWork u, aaObjectData o
      where u.ObjectKey = o.ObjectKey

    -- Remove from TagNotExists ...
    delete @TagNotExists where aaTagName in (select aaTagName from @TagnameUpdateWork)

    -- ... and add to TransTbl
    insert @TransTbl (ObjectKey, ObjectKeyPend)
      select o.ObjectKey, op.ObjectKey
        from @TagnameUpdateWork u inner join aaObjectData o
        on u.ObjectKey = o.ObjectKey
        inner join aaObjectDataPending op
        on u.aaTagName = op.aaTagName
    -- We deliberately do not add to @TagExists, as this may trigger a false move operation below.

    delete @TagnameUpdateWork

    insert @TagnameUpdateWork(ObjectKey, aaTagName)
      select o1.ObjectKey, tne.aaTagName
        from @TagNotExists tne inner join aaObjectData o1
        on tne.ContainedName = o1.ContainedName
        inner join aaObjectData o2
        on o2.ObjectKey = o1.ParentKey
        inner join aaObjectDataPending op
        on op.ObjectKey = tne.ParentKeyPend
        where o2.aaTagName = op.aaTagName
  end

  -- insert the new tags into the object table

  -- insert new areas (ParentKey is 0 for areas)
  insert aaObjectData (Type, aaTagName, ContainedName, ParentKey)
    select Type, aaTagName, ContainedName, ParentKeyPend from @TagNotExists
      where ParentKeyPend = 0

  insert @TransTbl (ObjectKey, ObjectKeyPend)
    select o.ObjectKey, tne.ObjectKeyPend
      from @TagNotExists tne inner join aaObjectData o
      on tne.aaTagName = o.aaTagName
      where tne.ParentKeyPend = 0

  -- insert new objects which are not areas
  insert @WorkTbl(ObjectKeyPend, Type, aaTagName, ContainedName, ParentName)
    select tne.ObjectKeyPend, tne.Type, tne.aaTagName, tne.ContainedName, op.aaTagName 
      from @TagNotExists tne inner join aaObjectDataPending op
      on tne.ParentKeyPend = op.ObjectKey
      where tne.aaTagName not in (select aaTagName from @TagnameUpdated)

  -- Process WorkTbl
  while exists (select * from aaObjectData o inner join @WorkTbl w on w.ParentName = o.aaTagName)
  begin
    insert aaObjectData (Type, aaTagName, ContainedName, ParentKey)
      select w.Type, w.aaTagName, w.ContainedName, o.ObjectKey
        from @WorkTbl w inner join aaObjectData o
        on w.ParentName = o.aaTagName

    insert @TransTbl (ObjectKey, ObjectKeyPend)
      select o.ObjectKey, w.ObjectKeyPend
        from @WorkTbl w inner join aaObjectData o
        on w.aaTagName = o.aaTagName

    delete @WorkTbl
      from @WorkTbl w inner join aaObjectData o
      on w.aaTagName = o.aaTagName
  end

  -- Process any tags that moved.  This must be done here, as the tag may have
  -- been moved under a new object, added above.

  -- If the tag already exists, check for changed parent
  insert @TagMoved (ObjectKey, aaTagName, ParentKeyMoved)
    select t1.ObjectKey, t1.aaTagName, o.ObjectKey 
      from @TagExists t1 inner join aaObjectData p1
      on t1.ParentKey = p1.ObjectKey
      inner join aaObjectDataPending p2
      on t1.ParentKeyPend = p2.ObjectKey
      inner join aaObjectData o
      on p2.aaTagName = o.aaTagName
      where t1.ParentKey <> 0 
      and t1.ParentKeyPend <> 0
      and p1.aaTagName <> p2.aaTagName

  -- Move the objects in aaObjectData which are matched by the ObjectKeys from @TagMoved.
  update aaObjectData set ParentKey = tm.ParentKeyMoved
    from aaObjectData o inner join @TagMoved tm
    on o.ObjectKey = tm.ObjectKey

  -- Handle attributes
  -- new attributes
  insert aaAttributeData (AttributeName, ObjectKey, wwDomainTagKey)
    select ap.AttributeName, tt.ObjectKey, tr.wwDomainTagKey
      from aaAttributeDataPending ap inner join @TransTbl tt
      on ap.ObjectKey = tt.ObjectKeyPend
      inner join Tag tag
      on ap.AttributeName = tag.TagName
      inner join TagRef tr
      on tag.wwTagKey = tr.wwTagKey
      where tr.ServerKey = 1
      and ap.AttributeName not in (select AttributeName from aaAttributeData)

  -- moved attributes
  update aaAttributeData set ObjectKey = tt.ObjectKey
    from aaAttributeData a inner join aaAttributeDataPending ap
    on a.AttributeName = ap.AttributeName
    inner join @TransTbl tt
    on ap.ObjectKey = tt.ObjectKeyPend
    where a.ObjectKey <> tt.ObjectKey

  commit tran

  exec aaInternalNSObjectPopulate

GO

GRANT exec on aaInternalNSObjectUpdate to aaAdministrators
go
 
 /**********  aaInternalNSObjectPopulate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalNSObjectPopulate'))
  DROP PROCEDURE dbo.aaInternalNSObjectPopulate
GO

CREATE procedure aaInternalNSObjectPopulate 
AS

  declare @NameChanged table
  (
    [Name]               nvarchar(256) NULL,
    ContainedName        nvarchar(256) NULL,
    DisplayName          nvarchar(256) NULL,
    Type                 int NULL
  )

  declare @aaPNS table
  (
    NameKey              int,
    [Name]               nvarchar(255),
    ParentKey            int
  )

  declare @TagExists table
  (
    NameKey              int NOT NULL,
    Type                 int NOT NULL,
    [Name]               nvarchar(256) NULL,
    ParentKey            int NOT NULL,
    ContainedName        nvarchar(256) NULL,
    ObjectKey            int NOT NULL,
    ParentObjectKey      int NOT NULL
  )

  declare @TagInserted table
  (
    ObjectKey            int NOT NULL,
    Type                 int NOT NULL,
    aaTagName            nvarchar(256) NULL,
    ContainedName        nvarchar(256) NULL,
    ParentObjectKey      int NOT NULL
  )

  declare @TagMoved table
  (
    NameKey              int NOT NULL,
    [Name]               nvarchar(256) NULL,
    DisplayName          nvarchar(256) NULL
  )

  declare @TagDeleted table
  (
    NameKey              int NOT NULL,
    [Name]               nvarchar(256) NULL
  )

  declare @WorkTbl table
  (
    ObjectKey            int NOT NULL,
    Type                 int NOT NULL,
    aaTagName            nvarchar(256) NULL,
    DisplayName          nvarchar(256) NULL,
    ParentName           nvarchar(256) NULL
    PRIMARY KEY(ObjectKey)
  )

  declare @TransTbl table
  (
    NameKey              int NOT NULL,
    ObjectKey            int NOT NULL
    PRIMARY KEY(ObjectKey)  -- helps dramatically
  )

  declare @AllCandidateAttributes table
  (
    NameKey              int NOT NULL,
    wwDomainTagKey       int NOT NULL
    PRIMARY KEY(wwDomainTagKey)
  )

  declare @AttributeExists table
  (
    NameKey              int NOT NULL,
    wwDomainTagKey       int NOT NULL
    PRIMARY KEY(wwDomainTagKey)
  )

  begin tran

  if exists (select * from aaObjectData where Status in (1, 2))
  begin
    -- Handle change of tagname and change of contained name here.
    -- Status = 1 or 2 indicates in-place updating of PublicNameSpace.
    -- Parsing is expensive, so skip it if not necessary.
    insert @NameChanged([Name], ContainedName, DisplayName, Type)
      select ti.aaTagName, ti.ContainedName,
        DisplayName = case
          when o.Type = 0 then ti.aaTagName    -- directly under an area
          when ti.ContainedName is NULL or ti.ContainedName = ''
            then ti.aaTagName + ' [ ' + ti.aaTagName + ' ]'
          else ti.aaTagName + ' [ ' + ti.ContainedName + ' ]'
          end,
        ti.Type
        from aaObjectData ti join aaObjectData o
        on ti.ParentKey = o.ObjectKey
        where ti.Status in (1, 2)

    if exists (select * from aaObjectData where Status = 1)
    begin
      -- Object name changed; match on contained name
      update PublicNameSpace set [Name] = n.DisplayName,
        Type = case
          when charindex('.', n.DisplayName) = 0 then 1999900 + n.Type
          else 1999932 + n.Type    -- '.' in name: synthesized name, change the type to indicate
          end
        from PublicNameSpace p join @NameChanged n
        on n.[ContainedName] = dbo.faaContainedName(p.[Name])
        where p.Type >= 1999900   --  objects only
        and p.Type <= 1999999
    end
    else
    begin
      -- Contained name changed; match on object name
      update PublicNameSpace set [Name] = n.DisplayName
        from PublicNameSpace p join @NameChanged n
        on n.[Name] = dbo.faaObjectTagName(p.[Name])
        where p.Type >= 1999900   --  objects only
        and p.Type <= 1999999
    end

    update aaObjectData set Status = 0
      where Status in (1, 2)
  end

  -- Copy data from PublicNameSpace, stripping off [ contained name ] suffix, if present
  insert @aaPNS (NameKey, [Name], ParentKey)
    select NameKey, dbo.faaObjectTagName([Name]), ParentKey
      from PublicNameSpace
      where Type >= 1999900   --  objects only
      and Type <= 1999999

  -- Find the tags from aaObjectData which already exist in PublicNameSpace
  insert @TagExists (NameKey, Type, [Name], ParentKey, ContainedName, ObjectKey, ParentObjectKey)
    select p.NameKey, o.Type, p.[Name], p.ParentKey, o.ContainedName, o.ObjectKey, o.ParentKey
    from aaObjectData o join @aaPNS p
      on o.aaTagName = p.[Name]

  -- If the tag already exists, check for changed parent
  insert @TagMoved(NameKey, [Name], DisplayName)
    select t1.NameKey, t1.[Name],
      DisplayName = case
        when p2.Type = 0 then t1.[Name]    -- directly under an area
        when t1.ContainedName is NULL or t1.ContainedName = ''
          then t1.[Name] + ' [ ' + t1.[Name] + ' ]'
        else t1.[Name] + ' [ ' + t1.[Name] + ' ]'
        end
      from @TagExists t1 join PublicNameSpace p1
      on t1.ParentKey = p1.NameKey
      join aaObjectData p2
      on t1.ParentObjectKey = p2.ObjectKey
      where t1.ParentKey <> 0
      and t1.ParentObjectKey <> 0
      and dbo.faaObjectTagName(p1.[Name]) <> p2.aaTagName

  -- Move operation is performed by deletion, followed by insertion
  insert @TagDeleted (NameKey, [Name])
    select NameKey, [Name]
      from @TagMoved

  -- Perform the object deletion
  if exists (select * from PublicNameSpace where NameKey in (select NameKey from @TagDeleted)) 
  begin
    declare @WorkLevel int
    declare @WorkKey table
    (
      WorkKey int
    )

    -- Temporary table for deleted groups -------------------------
    declare @DelGroup table 
    (
      NameKey int,
      TreeLevel int
    )

    -- Load the anchor group details ------------------------------
    set @WorkLevel = 1

    -- Set initial group state ------------------------------------
    insert @DelGroup (NameKey, TreeLevel)
      select NameKey, @WorkLevel from @TagDeleted

    while @WorkLevel > 0
    begin
      if exists (select * from @DelGroup where TreeLevel = @WorkLevel)
      begin
        -- Get the groups -----------------------------------------
        insert @WorkKey (WorkKey)
          select NameKey 
            from   @DelGroup 
            where  TreeLevel = @WorkLevel

        -- Remove the rows from the temp table --------------------
        delete @DelGroup where TreeLevel = @WorkLevel

        -- Insert this group's children into the temp table -------
        set @WorkLevel = @WorkLevel + 1
        insert @DelGroup (NameKey, TreeLevel)
          select NameKey, @WorkLevel
          from   PublicNameSpace
          where  ParentKey in (select WorkKey from @WorkKey)

        -- Remove the physical group ------------------------------
        delete PublicNameSpace where NameKey in (select WorkKey from @WorkKey)
        delete @WorkKey
      end
      else
      begin
        -- End of branch recurse back up a level ------------------
        select @WorkLevel = @WorkLevel - 1
      end    
    end    -- while
  end  -- perform the tag deletion

  -- After deleting data from the public namespace, repopulate aaPNS
  delete @aaPNS

  insert @aaPNS (NameKey, [Name], ParentKey)
    select NameKey, dbo.faaObjectTagName([Name]), ParentKey
      from PublicNameSpace
      where Type >= 1999000    -- all NS types
      and Type <= 1999999

  -- Find the tags from aaObjectData which do not exist in PublicNameSpace.
  insert @TagInserted (ObjectKey, Type, aaTagName, ContainedName, ParentObjectKey)
    select ObjectKey, Type, aaTagName, ContainedName, ParentKey
      from aaObjectData
      where aaTagName not in (select [Name] from @aaPNS)

  -- Collect translation details for the tags that already exist (areas included)
  insert @TransTbl (NameKey, ObjectKey)
    select p.NameKey, o.ObjectKey
      from aaObjectData o join @aaPNS p
      on o.aaTagName = p.[Name]

  -- Perform the tag insertion

  insert @WorkTbl(ObjectKey, Type, aaTagName, DisplayName, ParentName)
    select ti.ObjectKey, ti.Type, ti.aaTagName,
      DisplayName = case
        when o.Type = 0 then ti.aaTagName    -- directly under an area
        when ti.ContainedName is NULL or ti.ContainedName = ''
          then ti.aaTagName + ' [ ' + ti.aaTagName + ' ]'
        else ti.aaTagName + ' [ ' + ti.ContainedName + ' ]'
        end,
      o.aaTagName
      from @TagInserted ti join aaObjectData o
      on ti.ParentObjectKey = o.ObjectKey

-- Insert special object types (aaObjectData.Type = 3) directly under the galaxy level.
-- Insert only the top level here; lower levels are handled by the normal logic.
-- Also insert "orphaned" areas which do not appear in aaAreaData.
-- NOTE: do not make these areas look like regular areas (Type = 1999013), or
-- they will be deleted in aaInternalNSAreaUpdate!
  declare @GalaxyKey int
  select @GalaxyKey = NameKey from PublicNameSpace where Type = 1999023
  insert PublicNameSpace (Type, [Name], ParentKey)
    select 1999900 + Type, aaTagName, @GalaxyKey
      from @TagInserted
      where Type in (0, 3)
      and ParentObjectKey = 0
      and @GalaxyKey is not NULL
      and aaTagName not in 
        (select [Name] from PublicNameSpace where Type = 1999013 or ParentKey = @GalaxyKey)

  while exists (select * from PublicNameSpace p join @WorkTbl w
                on w.ParentName = dbo.faaObjectTagName(p.[Name]))
  begin
    insert PublicNameSpace (Type, [Name], ParentKey)
      select Type = case
            -- '.' in name: synthesized name, change the type to indicate
          when charindex('.', w.DisplayName) > 0 and w.Type <> 3 then 1999932 + w.Type
          else 1999900 + w.Type
          end,
        w.DisplayName, p.NameKey
        from @WorkTbl w join PublicNameSpace p
        on w.ParentName = dbo.faaObjectTagName(p.[Name])
        where p.Type >= 1999000
        and p.Type <= 1999999

    insert @TransTbl (NameKey, ObjectKey)
      select p.NameKey, w.ObjectKey
        from @WorkTbl w join PublicNameSpace p
        on w.DisplayName = p.[Name]

    delete @WorkTbl
        from @WorkTbl w join PublicNameSpace p
        on w.DisplayName = p.[Name]
  end

  -- Handle attributes
  -- First, handle any moved attributes
  update PublicGroupTag set NameKey = tt.NameKey
    from PublicGroupTag p join aaAttributeData a
    on p.wwDomainTagKey = a.wwDomainTagKey
    join @TransTbl tt
    on a.ObjectKey = tt.ObjectKey
    join PublicNameSpace pns
    on p.NameKey = pns.NameKey
    where p.NameKey <> tt.NameKey
    and pns.Type >= 1999000
    and pns.Type <= 1999999

  -- Inserted attributes
  -- all candidate attributes:
  insert @AllCandidateAttributes(NameKey, wwDomainTagKey)
    select tt.NameKey, a.wwDomainTagKey
      from aaObjectData o join aaAttributeData a
      on o.ObjectKey = a.ObjectKey
      join @TransTbl tt
      on o.ObjectKey = tt.ObjectKey

  -- attribute exists in PublicGroupTag
  insert @AttributeExists(NameKey, wwDomainTagKey)
    select a.NameKey, a.wwDomainTagKey
      from @AllCandidateAttributes a join PublicGroupTag p
      on a.NameKey = p.NameKey
      join PublicNameSpace pns
      on p.NameKey = pns.NameKey
      where p.wwDomainTagKey = a.wwDomainTagKey
      and pns.Type >= 1999000
      and pns.Type <= 1999999
  
  -- attributes to add:
 insert PublicGroupTag (NameKey, wwDomainTagKey)
    select a.NameKey, a.wwDomainTagKey
      from @AllCandidateAttributes a left outer join @AttributeExists e
      on a.wwDomainTagKey = e.wwDomainTagKey
      where e.NameKey is NULL

  commit tran

GO

GRANT exec on aaInternalNSObjectPopulate to aaAdministrators
go
 
 /**********  aaArchestrANSClear  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaArchestrANSClear'))
  DROP PROCEDURE dbo.aaArchestrANSClear
GO

CREATE procedure aaArchestrANSClear 
AS

  declare @GalaxyID int
  select @GalaxyID = NameKey from PublicNameSpace where Type = 1999023
  exec aaPublicNSDeleteGroup @GalaxyID

  -- clear the work tables
  begin tran
  truncate table aaAreaData
  truncate table aaAreaXML
  insert aaAreaXML(Version) values (0)

  truncate table aaObjectData
  truncate table aaObjectDataPending
  truncate table aaAttributeData
  truncate table aaAttributeDataPending
  commit tran

GO

GRANT exec on aaArchestrANSClear to aaAdministrators
go
 
 /**********  aaInternalLicenseParametersUpdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalLicenseParametersUpdate'))
  DROP PROCEDURE dbo.aaInternalLicenseParametersUpdate
GO

CREATE procedure aaInternalLicenseParametersUpdate
  @LicenseTagCount int,
  @LicenseRemoteIDASCount int
AS
  update SystemParameter set Value = @LicenseTagCount
    where Name = N'LicenseTagCount'
  update SystemParameter set Value = 
    case @LicenseRemoteIDASCount
      when 0 then convert(sql_variant, 'None (Unlicensed)')
      when 65536 then convert(sql_variant, N'Unlimited')
      else convert(int, @LicenseRemoteIDASCount)
    end
    where Name = N'LicenseRemoteIDASCount'
GO

GRANT exec on aaInternalLicenseParametersUpdate to aaAdministrators
go
 
 /**********  aaInternalLicensedObjectCount  **********/
if exists (select * from sysobjects where id = object_id('dbo.aaInternalLicensedObjectCount'))
  DROP PROCEDURE dbo.aaInternalLicensedObjectCount
GO

CREATE procedure aaInternalLicensedObjectCount
AS
  declare @TotalTags int
  declare @CheckedTags int
  declare @CheckedIDAS int
  declare @servername sysname

  select @TotalTags = count(*) from Tag where TagType <> 5
  select @CheckedTags = count(*) from Tag where IOServerKey <> 1 and TagType <> 5

  -- Allow for a clustered historian system
  select @servername = ComputerName from ServerList
  select @CheckedIDAS = count(*) from IODriver where IODriverKey >= 2
    and upper(ComputerName) <> upper(@servername)

  select TotalTagCount=@TotalTags, CheckedTagCount=@CheckedTags, CheckedIDASCount=@CheckedIDAS
GO

GRANT exec on aaInternalLicensedObjectCount to public
go
 
 
 
 create trigger tU_aaAttributeData on aaAttributeData for UPDATE as
/* Historian UPDATE trigger on aaAttributeData */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* aaObjectData R/24 aaAttributeData ON CHILD UPDATE RESTRICT */
  if
    /* update(ObjectKey) */
    update(ObjectKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,aaObjectData
        where
          /* inserted.ObjectKey = aaObjectData.ObjectKey */
          inserted.ObjectKey = aaObjectData.ObjectKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE aaAttributeData because aaObjectData does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_aaAttributeDataPending on aaAttributeDataPending for UPDATE as
/* Historian UPDATE trigger on aaAttributeDataPending */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* aaObjectDataPending R/26 aaAttributeDataPending ON CHILD UPDATE RESTRICT */
  if
    /* update(ObjectKey) */
    update(ObjectKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,aaObjectDataPending
        where
          /* inserted.ObjectKey = aaObjectDataPending.ObjectKey */
          inserted.ObjectKey = aaObjectDataPending.ObjectKey
    /* select @nullcnt = count(*) from inserted where
         inserted.ObjectKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.ObjectKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE aaAttributeDataPending because aaObjectDataPending does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_aaObjectData on aaObjectData for DELETE as
/* Historian DELETE trigger on aaObjectData */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* aaObjectData R/24 aaAttributeData ON PARENT DELETE CASCADE */
    delete aaAttributeData
      from aaAttributeData,deleted
      where
        /*  aaAttributeData.ObjectKey = deleted.ObjectKey */
        aaAttributeData.ObjectKey = deleted.ObjectKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_ActionType on ActionType for DELETE as
/* Historian DELETE trigger on ActionType */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* ActionType R/198 EventTag ON PARENT DELETE CASCADE */
    delete EventTag
      from EventTag,deleted
      where
        /*  EventTag.ActionTypeKey = deleted.ActionTypeKey */
        EventTag.ActionTypeKey = deleted.ActionTypeKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_AnalogSnapshot on AnalogSnapshot for UPDATE as
/* Historian UPDATE trigger on AnalogSnapshot */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insSnapshotTagKey int, 
           @insEventLogKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EventHistory lins to AnalogSnapshot ON CHILD UPDATE RESTRICT */
  if
    /* update(EventLogKey) */
    update(EventLogKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventHistory
        where
          /* inserted.EventLogKey = EventHistory.EventLogKey */
          inserted.EventLogKey = EventHistory.EventLogKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE AnalogSnapshot because EventHistory does not exist.'
      goto error
    end
  end

  /* SnapshotTag R/89 AnalogSnapshot ON CHILD UPDATE RESTRICT */
  if
    /* update(SnapshotTagKey) */
    update(SnapshotTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SnapshotTag
        where
          /* inserted.SnapshotTagKey = SnapshotTag.SnapshotTagKey */
          inserted.SnapshotTagKey = SnapshotTag.SnapshotTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE AnalogSnapshot because SnapshotTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_AnalogTag on AnalogTag
  for DELETE
  as
/* DELETE trigger on AnalogTag */
/* default body for tD_AnalogTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* AnalogTag has Deviation ON PARENT DELETE CASCADE */
    delete Deviation
      from Deviation,deleted
      where
        /*  Deviation.TagName = deleted.TagName */
        Deviation.TagName = deleted.TagName

/* AnalogTag has RateOfChange ON PARENT DELETE CASCADE */
    delete RateOfChange
      from RateOfChange,deleted
      where
        /*  RateOfChange.TagName = deleted.TagName */
        RateOfChange.TagName = deleted.TagName

/* AnalogTag has Limit ON PARENT DELETE CASCADE */
    delete Limit
      from Limit,deleted
      where
        /*  Limit.TagName = deleted.TagName */
        Limit.TagName = deleted.TagName



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin 
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'AnalogTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TagName', old.TagName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'EUKey', old.EUKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MinEU', old.MinEU
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MaxEU', old.MaxEU
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MinRaw', old.MinRaw
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MaxRaw', old.MaxRaw
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Scaling', old.Scaling
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'RawType', old.RawType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ValueDeadband', old.ValueDeadband
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'InitialValue', old.InitialValue
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'IntegerSize', old.IntegerSize
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'SignedInteger', old.SignedInteger
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'RateDeadband', old.RateDeadband
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'InterpolationType', old.InterpolationType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'RolloverValue', old.RolloverValue
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go



create trigger tI_AnalogTag on AnalogTag
  for INSERT
  as
/* INSERT trigger on AnalogTag */
/* default body for tI_AnalogTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* Tag  AnalogTag ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT AnalogTag because Tag does not exist.'
      goto error
    end
  end

/* EngineeringUnit Of_Type AnalogTag ON CHILD INSERT RESTRICT */
  if
    /* update(EUKey) */
    update(EUKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EngineeringUnit
        where
          /* inserted.EUKey = EngineeringUnit.EUKey */
          inserted.EUKey = EngineeringUnit.EUKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT AnalogTag because EngineeringUnit does not exist.'
      goto error
    end
  end




/* Integer Size Validation                */
/* if invalid force size =32, scaling = 1 */
if exists (select RawType, IntegerSize from inserted
            where RawType = 3 and IntegerSize = 0) 
begin
   update AnalogTag set IntegerSize = 32, Scaling = 1
     from AnalogTag a, inserted i
       where a.TagName = i.TagName
       and i.RawType = 3
       and i.IntegerSize = 0
end

/* MinEU - MaxEU / MinRaw - MaxRaw validation */
if exists (select TagName from inserted 
            where MinEU = MaxEU or MinRaw = MaxRaw)
begin
   update AnalogTag set MaxEU = MinEU + 1
       where MaxEU = MinEU
   update AnalogTag set MaxRaw = MinRaw + 1
       where MaxRaw = MinRaw
end

/* Disallow scaling for the data types TimeStamp, ElapsedTime */
if exists (select TagName from inserted
            where Scaling <> 0 and RawType in (7, 8))
begin
   update AnalogTag set Scaling = 0 where Scaling <> 0 and RawType in (7, 8)
end

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'AnalogTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TagName', new.TagName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'EUKey', new.EUKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MinEU', new.MinEU
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MaxEU', new.MaxEU
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MinRaw', new.MinRaw
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MaxRaw', new.MaxRaw
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Scaling', new.Scaling
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'RawType', new.RawType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ValueDeadband', new.ValueDeadband
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'InitialValue', new.InitialValue
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'IntegerSize', new.IntegerSize
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'SignedInteger', new.SignedInteger
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'RateDeadband', new.RateDeadband
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'InterpolationType', new.InterpolationType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'RolloverValue', new.RolloverValue
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_AnalogTag on AnalogTag
  for UPDATE
  as
/* Historian table specific trigger for table AnalogTag  */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* Tag  AnalogTag ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE AnalogTag because Tag does not exist.'
      goto error
    end
  end

/* EngineeringUnit Of_Type AnalogTag ON CHILD UPDATE RESTRICT */
  if
    /* update(EUKey) */
    update(EUKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EngineeringUnit
        where
          /* inserted.EUKey = EngineeringUnit.EUKey */
          inserted.EUKey = EngineeringUnit.EUKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE AnalogTag because EngineeringUnit does not exist.'
      goto error
    end
  end


/* AnalogTag R/216 ManualAnalogHistory ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update ManualAnalogHistory
      set
        /*  ManualAnalogHistory.TagName = @insTagName */
        ManualAnalogHistory.TagName = @insTagName
      from ManualAnalogHistory,inserted,deleted
      where
        /*  ManualAnalogHistory.TagName = deleted.TagName */
        ManualAnalogHistory.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade AnalogTag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* AnalogTag has Deviation ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update Deviation
      set
        /*  Deviation.TagName = @insTagName */
        Deviation.TagName = @insTagName
      from Deviation,inserted,deleted
      where
        /*  Deviation.TagName = deleted.TagName */
        Deviation.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade AnalogTag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* AnalogTag has RateOfChange ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update RateOfChange
      set
        /*  RateOfChange.TagName = @insTagName */
        RateOfChange.TagName = @insTagName
      from RateOfChange,inserted,deleted
      where
        /*  RateOfChange.TagName = deleted.TagName */
        RateOfChange.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade AnalogTag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* AnalogTag has Limit ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update Limit
      set
        /*  Limit.TagName = @insTagName */
        Limit.TagName = @insTagName
      from Limit,inserted,deleted
      where
        /*  Limit.TagName = deleted.TagName */
        Limit.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade AnalogTag UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* Integer Size Validation                */
/* if invalid force size =32, scaling = 1 */
if exists (select RawType, IntegerSize from inserted
            where RawType = 3 and IntegerSize = 0) 
begin
   update AnalogTag set IntegerSize = 32, Scaling = 1
     from AnalogTag a, inserted i
       where a.TagName = i.TagName
       and i.RawType = 3
       and i.IntegerSize = 0
end

/* 12 or 15 bit integer storage is unsigned */
if exists (select TagName from inserted
            where IntegerSize in (12, 15) and SignedInteger = 1) 
begin
   update AnalogTag set SignedInteger = 0
     from AnalogTag a, inserted i
       where a.TagName = i.TagName
       and i.IntegerSize in (12, 15)
       and i.SignedInteger = 1
end

/* MinEU - MaxEU / MinRaw - MaxRaw validation */
if exists (select TagName from inserted 
            where MinEU = MaxEU or MinRaw = MaxRaw)
begin
   update AnalogTag set MaxEU = MinEU + 1
       where MaxEU = MinEU
   update AnalogTag set MaxRaw = MinRaw + 1
       where MaxRaw = MinRaw
end

/* Disallow scaling for the data types TimeStamp, ElapsedTime */
if exists (select TagName from inserted
            where Scaling <> 0 and RawType in (7, 8))
begin
   update AnalogTag set Scaling = 0 where Scaling <> 0 and RawType in (7, 8)
end

/* Dynamic Reconfig */
/* We cannot use the if update(XXX) as the config editor sends an update for all columns */

insert into ConfigStatusPending (Type, ObjectKey, Status)
   select 3, t.wwTagKey, 2
      from Tag t, inserted i, deleted d
         where t.TagName = i.TagName
         and i.TagName = d.TagName
         and t.Status not in (1, 2)
         and (i.MinEU <> d.MinEU or i.MaxEU <> d.MaxEU or i.Scaling <> d.Scaling
          or  ISNULL(i.MinRaw, 999999) <> ISNULL(d.MinRaw, 999999)
          or  ISNULL(i.MaxRaw, 999999) <> ISNULL(d.MaxRaw, 999999)   
          or  i.RawType <> d.RawType or i.IntegerSize <> d.IntegerSize
          or  i.SignedInteger <> d.SignedInteger
          or  i.ValueDeadband <> d.ValueDeadband
          or  i.RateDeadband <> d.RateDeadband
          or  i.InterpolationType <> d.InterpolationType
          or  i.RolloverValue <> d.RolloverValue)

update Tag set Status = 2
   from Tag t, inserted i, deleted d
         where t.TagName = i.TagName
         and i.TagName = d.TagName
         and t.Status not in (1, 2)
         and (i.MinEU <> d.MinEU or i.MaxEU <> d.MaxEU or i.Scaling <> d.Scaling
          or  ISNULL(i.MinRaw, 999999) <> ISNULL(d.MinRaw, 999999)
          or  ISNULL(i.MaxRaw, 999999) <> ISNULL(d.MaxRaw, 999999)   
          or  i.RawType <> d.RawType or i.IntegerSize <> d.IntegerSize
          or  i.SignedInteger <> d.SignedInteger
          or  i.ValueDeadband <> d.ValueDeadband
          or  i.RateDeadband <> d.RateDeadband
          or  i.InterpolationType <> d.InterpolationType
          or  i.RolloverValue <> d.RolloverValue)

/* end of Dynamic Reconfig */
   

/* start of mod tracking */ 
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'AnalogTag' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      if update(TagName)
      begin
         if @numrows = 1  /* We can get a PK mod */
         begin
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.TagName <> old.TagName
                             or (new.TagName is NULL and  old.TagName is not NULL)
                             or (old.TagName is NULL and  new.TagName is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'EUKey', old.EUKey, new.EUKey
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.EUKey <> old.EUKey
                             or (new.EUKey is NULL and  old.EUKey is not NULL)
                             or (old.EUKey is NULL and  new.EUKey is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'MinEU', old.MinEU, new.MinEU
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.MinEU <> old.MinEU
                             or (new.MinEU is NULL and  old.MinEU is not NULL)
                             or (old.MinEU is NULL and  new.MinEU is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'MaxEU', old.MaxEU, new.MaxEU
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.MaxEU <> old.MaxEU
                             or (new.MaxEU is NULL and  old.MaxEU is not NULL)
                             or (old.MaxEU is NULL and  new.MaxEU is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'MinRaw', old.MinRaw, new.MinRaw
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.MinRaw <> old.MinRaw
                             or (new.MinRaw is NULL and  old.MinRaw is not NULL)
                             or (old.MinRaw is NULL and  new.MinRaw is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'MaxRaw', old.MaxRaw, new.MaxRaw
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.MaxRaw <> old.MaxRaw
                             or (new.MaxRaw is NULL and  old.MaxRaw is not NULL)
                             or (old.MaxRaw is NULL and  new.MaxRaw is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'Scaling', old.Scaling, new.Scaling
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.Scaling <> old.Scaling
                             or (new.Scaling is NULL and  old.Scaling is not NULL)
                             or (old.Scaling is NULL and  new.Scaling is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'RawType', old.RawType, new.RawType
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.RawType <> old.RawType
                             or (new.RawType is NULL and  old.RawType is not NULL)
                             or (old.RawType is NULL and  new.RawType is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'ValueDeadband', old.ValueDeadband, new.ValueDeadband
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.ValueDeadband <> old.ValueDeadband
                             or (new.ValueDeadband is NULL and  old.ValueDeadband is not NULL)
                             or (old.ValueDeadband is NULL and  new.ValueDeadband is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'InitialValue', old.InitialValue, new.InitialValue
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.InitialValue <> old.InitialValue
                             or (new.InitialValue is NULL and  old.InitialValue is not NULL)
                             or (old.InitialValue is NULL and  new.InitialValue is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'IntegerSize', old.IntegerSize, new.IntegerSize
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.IntegerSize <> old.IntegerSize
                             or (new.IntegerSize is NULL and  old.IntegerSize is not NULL)
                             or (old.IntegerSize is NULL and  new.IntegerSize is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'SignedInteger', old.SignedInteger, new.SignedInteger
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.SignedInteger <> old.SignedInteger
                             or (new.SignedInteger is NULL and  old.SignedInteger is not NULL)
                             or (old.SignedInteger is NULL and  new.SignedInteger is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'RateDeadband', old.RateDeadband, new.RateDeadband
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.RateDeadband <> old.RateDeadband
                             or (new.RateDeadband is NULL and  old.RateDeadband is not NULL)
                             or (old.RateDeadband is NULL and  new.RateDeadband is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'InterpolationType', old.InterpolationType, new.InterpolationType
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.InterpolationType <> old.InterpolationType
                             or (new.InterpolationType is NULL and  old.InterpolationType is not NULL)
                             or (old.InterpolationType is NULL and  new.InterpolationType is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'RolloverValue', old.RolloverValue, new.RolloverValue
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.RolloverValue <> old.RolloverValue
                             or (new.RolloverValue is NULL and  old.RolloverValue is not NULL)
                             or (old.RolloverValue is NULL and  new.RolloverValue is not NULL))
                     and   mlt.ModTableKey = @mltkey 
            
         end
      end
      else
      begin  /* PK columns are still there because of the script template, not an issue */
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TagName <> old.TagName
                          or (new.TagName is NULL and  old.TagName is not NULL)
                          or (old.TagName is NULL and  new.TagName is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'EUKey', old.EUKey, new.EUKey
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.EUKey <> old.EUKey
                          or (new.EUKey is NULL and  old.EUKey is not NULL)
                          or (old.EUKey is NULL and  new.EUKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'MinEU', old.MinEU, new.MinEU
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.MinEU <> old.MinEU
                          or (new.MinEU is NULL and  old.MinEU is not NULL)
                          or (old.MinEU is NULL and  new.MinEU is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'MaxEU', old.MaxEU, new.MaxEU
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.MaxEU <> old.MaxEU
                          or (new.MaxEU is NULL and  old.MaxEU is not NULL)
                          or (old.MaxEU is NULL and  new.MaxEU is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'MinRaw', old.MinRaw, new.MinRaw
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.MinRaw <> old.MinRaw
                          or (new.MinRaw is NULL and  old.MinRaw is not NULL)
                          or (old.MinRaw is NULL and  new.MinRaw is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'MaxRaw', old.MaxRaw, new.MaxRaw
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.MaxRaw <> old.MaxRaw
                          or (new.MaxRaw is NULL and  old.MaxRaw is not NULL)
                          or (old.MaxRaw is NULL and  new.MaxRaw is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Scaling', old.Scaling, new.Scaling
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Scaling <> old.Scaling
                          or (new.Scaling is NULL and  old.Scaling is not NULL)
                          or (old.Scaling is NULL and  new.Scaling is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'RawType', old.RawType, new.RawType
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.RawType <> old.RawType
                          or (new.RawType is NULL and  old.RawType is not NULL)
                          or (old.RawType is NULL and  new.RawType is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ValueDeadband', old.ValueDeadband, new.ValueDeadband
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ValueDeadband <> old.ValueDeadband
                          or (new.ValueDeadband is NULL and  old.ValueDeadband is not NULL)
                          or (old.ValueDeadband is NULL and  new.ValueDeadband is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'InitialValue', old.InitialValue, new.InitialValue
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.InitialValue <> old.InitialValue
                          or (new.InitialValue is NULL and  old.InitialValue is not NULL)
                          or (old.InitialValue is NULL and  new.InitialValue is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'IntegerSize', old.IntegerSize, new.IntegerSize
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.IntegerSize <> old.IntegerSize
                          or (new.IntegerSize is NULL and  old.IntegerSize is not NULL)
                          or (old.IntegerSize is NULL and  new.IntegerSize is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'SignedInteger', old.SignedInteger, new.SignedInteger
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.SignedInteger <> old.SignedInteger
                          or (new.SignedInteger is NULL and  old.SignedInteger is not NULL)
                          or (old.SignedInteger is NULL and  new.SignedInteger is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'RateDeadband', old.RateDeadband, new.RateDeadband
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.RateDeadband <> old.RateDeadband
                          or (new.RateDeadband is NULL and  old.RateDeadband is not NULL)
                          or (old.RateDeadband is NULL and  new.RateDeadband is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'InterpolationType', old.InterpolationType, new.InterpolationType
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.InterpolationType <> old.InterpolationType
                          or (new.InterpolationType is NULL and  old.InterpolationType is not NULL)
                          or (old.InterpolationType is NULL and  new.InterpolationType is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'RolloverValue', old.RolloverValue, new.RolloverValue
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.RolloverValue <> old.RolloverValue
                          or (new.RolloverValue is NULL and  old.RolloverValue is not NULL)
                          or (old.RolloverValue is NULL and  new.RolloverValue is not NULL))
                  and   mlt.ModTableKey = @mltkey
         
      end
   end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go




create trigger tI_Annotation on Annotation for INSERT as
/* Historian INSERT trigger on Annotation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* UserDetail makes Annotation ON CHILD INSERT RESTRICT */
  if
    /* update(UserKey) */
    update(UserKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,UserDetail
        where
          /* inserted.UserKey = UserDetail.UserKey */
          inserted.UserKey = UserDetail.UserKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT Annotation because UserDetail does not exist.'
      goto error
    end
  end

  /* Tag has Annotation ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT Annotation because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_Annotation on Annotation for UPDATE as
/* Historian UPDATE trigger on Annotation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insAnnotationKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* UserDetail makes Annotation ON CHILD UPDATE RESTRICT */
  if
    /* update(UserKey) */
    update(UserKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,UserDetail
        where
          /* inserted.UserKey = UserDetail.UserKey */
          inserted.UserKey = UserDetail.UserKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Annotation because UserDetail does not exist.'
      goto error
    end
  end

  /* Tag has Annotation ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Annotation because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_BlobTag on BlobTag for INSERT as
/* Historian INSERT trigger on BlobTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Tag  BlobTag ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT BlobTag because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_BlobTag on BlobTag for UPDATE as
/* Historian UPDATE trigger on BlobTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Tag  BlobTag ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE BlobTag because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_CalcType on CalcType for DELETE as
/* Historian DELETE trigger on CalcType */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* CalcType Sets type of calculation SummaryOperation ON PARENT DELETE CASCADE */
    delete SummaryOperation
      from SummaryOperation,deleted
      where
        /*  SummaryOperation.CalcType = deleted.CalcType */
        SummaryOperation.CalcType = deleted.CalcType


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_CalcType on CalcType for UPDATE as
/* Historian UPDATE trigger on CalcType */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insCalcType CalcTypes,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* CalcType Sets type of calculation SummaryOperation ON PARENT UPDATE CASCADE */
  if
    /* update(CalcType) */
    update(CalcType)
  begin
    if @numrows = 1
    begin
      select @insCalcType = inserted.CalcType
        from inserted
      update SummaryOperation
      set
        /*  SummaryOperation.CalcType = @insCalcType */
        SummaryOperation.CalcType = @insCalcType
      from SummaryOperation,inserted,deleted
      where
        /*  SummaryOperation.CalcType = deleted.CalcType */
        SummaryOperation.CalcType = deleted.CalcType
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade CalcType UPDATE because more than one row has been affected.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_ComplexHistory on ComplexHistory for INSERT as
/* Historian INSERT trigger on ComplexHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* ComplexTag did ComplexHistory ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,ComplexTag
        where
          /* inserted.TagName = ComplexTag.TagName */
          inserted.TagName = ComplexTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT ComplexHistory because ComplexTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_ComplexHistory on ComplexHistory for UPDATE as
/* Historian UPDATE trigger on ComplexHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256), 
           @insDateTime datetime,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* ComplexTag did ComplexHistory ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,ComplexTag
        where
          /* inserted.TagName = ComplexTag.TagName */
          inserted.TagName = ComplexTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE ComplexHistory because ComplexTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_ComplexTag on ComplexTag for INSERT as
/* Historian INSERT trigger on ComplexTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Tag  ComplexTag ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT ComplexTag because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_ComplexTag on ComplexTag for UPDATE as
/* Historian UPDATE trigger on ComplexTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Tag  ComplexTag ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE ComplexTag because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_ConfigStatusPending on ConfigStatusPending
  for INSERT
  as
/* Historian INSERT trigger on ConfigStatusPending */
/* default body for tI_ConfigStatusPending */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insID int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* Check insert when value already exists and object is being deleted */
if @numrows = 1
begin
   if (select Status from inserted) = 3 and (select Type from inserted) <> 3
        -- Type 3 (tags) handled from the source of the change  
   begin
      /* item was inserted then deleted */
      if exists (select CSP.ID from ConfigStatusPending CSP, inserted i 
              where CSP.Type = i.Type and CSP.ObjectKey = i.ObjectKey
              and CSP.Status = 1)
      begin  
         delete ConfigStatusPending from ConfigStatusPending CSP, inserted i
           where CSP.Type = i.Type and CSP.ObjectKey = i.ObjectKey                     
      end

      /* item was modified then deleted */
      if exists (select CSP.ID from ConfigStatusPending CSP, inserted i 
              where CSP.Type = i.Type and CSP.ObjectKey = i.ObjectKey
              and CSP.Status = 2)
      begin  
         delete from ConfigStatusPending
            where ID in
              (select CSP.ID from ConfigStatusPending CSP, inserted i
                 where CSP.Type = i.Type
                 and   CSP.ObjectKey = i.ObjectKey
                 and   CSP.Status = 2)             
            and Status = 2        
      end
   end
end
else
begin
   /* Multiple row insert need to go through them 1 by 1*/
   declare @status int, @objectkey int, @type int

   declare CSPlist cursor for
     select i.Type, i.ObjectKey, i.Status from inserted i
     
   open CSPlist
   fetch next from CSPlist into @type, @objectkey, @status
   while @@FETCH_STATUS = 0
    begin
       if @status = 3 and @type <> 3  -- Type 3 (tags) handled from the source
       begin
          /* item was inserted then deleted */                       
          if exists (select CSP.ID from ConfigStatusPending CSP
                where CSP.Type = @type and CSP.ObjectKey = @objectkey
                   and CSP.Status = 1)
          begin
            delete ConfigStatusPending 
              where Type = @type and ObjectKey = @objectkey                     
          end              
          else
          /* item was modified then deleted */
          if exists (select CSP.ID from ConfigStatusPending CSP
                where CSP.Type = @type and CSP.ObjectKey = @objectkey
                   and CSP.Status = 2)
          begin          
             delete ConfigStatusPending
                where Type = @type and ObjectKey = @objectkey and Status = 2                                      
          end
       end 
       fetch next from CSPlist into @type, @objectkey, @status
    end
   close CSPlist
   deallocate CSPlist    
end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go



create trigger tD_Context on Context
  for DELETE
  as
/* Historian specific */
/* DELETE trigger on Context */
/* default body for tD_Context */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insContextKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* Context R/201 Deviation ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,Deviation
      where
        /*  Deviation.ContextKey = deleted.ContextKey */
        Deviation.ContextKey = deleted.ContextKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE Context because Deviation exists.'
      goto error
    end

/* Context R/196 RateOfChange ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,RateOfChange
      where
        /*  RateOfChange.ContextKey = deleted.ContextKey */
        RateOfChange.ContextKey = deleted.ContextKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE Context because RateOfChange exists.'
      goto error
    end

/* Context gives meaning Limit ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,Limit
      where
        /*  Limit.ContextKey = deleted.ContextKey */
        Limit.ContextKey = deleted.ContextKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE Context because Limit exists.'
      goto error
    end



/* Cannot delete the InTouch Context */
/* will be the first one in the list */
if exists (select ContextKey from deleted where ContextKey = 1)
begin
  set @errno = 17062
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Cannot delete the default InTouch Context.'
  end
  goto error  
end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go






create trigger tU_Context on Context
  for UPDATE
  as
/* Historian specific */
/* UPDATE trigger on Context */
/* default body for tU_Context */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insContextKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* Context R/201 Deviation ON PARENT UPDATE CASCADE */
  if
    /* update(ContextKey) */
    update(ContextKey)
  begin
    if @numrows = 1
    begin
      select @insContextKey = inserted.ContextKey
        from inserted
      update Deviation
      set
        /*  Deviation.ContextKey = @insContextKey */
        Deviation.ContextKey = @insContextKey
      from Deviation,inserted,deleted
      where
        /*  Deviation.ContextKey = deleted.ContextKey */
        Deviation.ContextKey = deleted.ContextKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Context UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Context R/196 RateOfChange ON PARENT UPDATE CASCADE */
  if
    /* update(ContextKey) */
    update(ContextKey)
  begin
    if @numrows = 1
    begin
      select @insContextKey = inserted.ContextKey
        from inserted
      update RateOfChange
      set
        /*  RateOfChange.ContextKey = @insContextKey */
        RateOfChange.ContextKey = @insContextKey
      from RateOfChange,inserted,deleted
      where
        /*  RateOfChange.ContextKey = deleted.ContextKey */
        RateOfChange.ContextKey = deleted.ContextKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Context UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Context gives meaning Limit ON PARENT UPDATE CASCADE */
  if
    /* update(ContextKey) */
    update(ContextKey)
  begin
    if @numrows = 1
    begin
      select @insContextKey = inserted.ContextKey
        from inserted
      update Limit
      set
        /*  Limit.ContextKey = @insContextKey */
        Limit.ContextKey = @insContextKey
      from Limit,inserted,deleted
      where
        /*  Limit.ContextKey = deleted.ContextKey */
        Limit.ContextKey = deleted.ContextKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Context UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* Cannot update the InTouch Context */
/* will be the first one in the list */
if exists (select ContextKey from deleted where ContextKey = 1)
begin
  set @errno = 17063
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Cannot update the default InTouch Context.'
  end
  goto error  
end

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go





create trigger tD_DetectorType on DetectorType for DELETE as
/* Historian DELETE trigger on DetectorType */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* DetectorType R/199 EventTag ON PARENT DELETE CASCADE */
    delete EventTag
      from EventTag,deleted
      where
        /*  EventTag.DetectorTypeKey = deleted.DetectorTypeKey */
        EventTag.DetectorTypeKey = deleted.DetectorTypeKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_Deviation on Deviation for UPDATE as
/* Historian UPDATE trigger on Deviation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256), 
           @insContextKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Context R/201 Deviation ON CHILD UPDATE RESTRICT */
  if
    /* update(ContextKey) */
    update(ContextKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Context
        where
          /* inserted.ContextKey = Context.ContextKey */
          inserted.ContextKey = Context.ContextKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Deviation because Context does not exist.'
      goto error
    end
  end

  /* AnalogTag has Deviation ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,AnalogTag
        where
          /* inserted.TagName = AnalogTag.TagName */
          inserted.TagName = AnalogTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Deviation because AnalogTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_DiscreteSnapshot on DiscreteSnapshot for UPDATE as
/* Historian UPDATE trigger on DiscreteSnapshot */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insSnapshotTagKey int, 
           @insEventLogKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EventHistory links to DiscreteSnapshot ON CHILD UPDATE RESTRICT */
  if
    /* update(EventLogKey) */
    update(EventLogKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventHistory
        where
          /* inserted.EventLogKey = EventHistory.EventLogKey */
          inserted.EventLogKey = EventHistory.EventLogKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE DiscreteSnapshot because EventHistory does not exist.'
      goto error
    end
  end

  /* SnapshotTag R/113 DiscreteSnapshot ON CHILD UPDATE RESTRICT */
  if
    /* update(SnapshotTagKey) */
    update(SnapshotTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SnapshotTag
        where
          /* inserted.SnapshotTagKey = SnapshotTag.SnapshotTagKey */
          inserted.SnapshotTagKey = SnapshotTag.SnapshotTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE DiscreteSnapshot because SnapshotTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_DiscreteTag on DiscreteTag
  for DELETE
  as
/* DELETE trigger on DiscreteTag */
/* default body for tD_DiscreteTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin 
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'DiscreteTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TagName', old.TagName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MessageKey', old.MessageKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'InitialValue', old.InitialValue
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_DiscreteTag on DiscreteTag
  for INSERT
  as
/* INSERT trigger on DiscreteTag */
/* default body for tI_DiscreteTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* Message used by DiscreteTag ON CHILD INSERT RESTRICT */
  if
    /* update(MessageKey) */
    update(MessageKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Message
        where
          /* inserted.MessageKey = Message.MessageKey */
          inserted.MessageKey = Message.MessageKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT DiscreteTag because Message does not exist.'
      goto error
    end
  end

/* Tag  DiscreteTag ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT DiscreteTag because Tag does not exist.'
      goto error
    end
  end




/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'DiscreteTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TagName', new.TagName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MessageKey', new.MessageKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'InitialValue', new.InitialValue
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_DiscreteTag on DiscreteTag
  for UPDATE
  as
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* Message used by DiscreteTag ON CHILD UPDATE RESTRICT */
  if
    /* update(MessageKey) */
    update(MessageKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Message
        where
          /* inserted.MessageKey = Message.MessageKey */
          inserted.MessageKey = Message.MessageKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE DiscreteTag because Message does not exist.'
      goto error
    end
  end

/* Tag  DiscreteTag ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE DiscreteTag because Tag does not exist.'
      goto error
    end
  end


/* DiscreteTag R/217 ManualDiscreteHistory ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update ManualDiscreteHistory
      set
        /*  ManualDiscreteHistory.TagName = @insTagName */
        ManualDiscreteHistory.TagName = @insTagName
      from ManualDiscreteHistory,inserted,deleted
      where
        /*  ManualDiscreteHistory.TagName = deleted.TagName */
        ManualDiscreteHistory.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade DiscreteTag UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* start of mod tracking */ 
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
           where Name =  'DiscreteTag' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      if update(TagName)
      begin
         if @numrows = 1  /* We can get a PK mod */
         begin
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.TagName <> old.TagName
                             or (new.TagName is NULL and  old.TagName is not NULL)
                             or (old.TagName is NULL and  new.TagName is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'MessageKey', old.MessageKey, new.MessageKey
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.MessageKey <> old.MessageKey
                             or (new.MessageKey is NULL and  old.MessageKey is not NULL)
                             or (old.MessageKey is NULL and  new.MessageKey is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'InitialValue', old.InitialValue, new.InitialValue
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.InitialValue <> old.InitialValue
                             or (new.InitialValue is NULL and  old.InitialValue is not NULL)
                             or (old.InitialValue is NULL and  new.InitialValue is not NULL))
                     and   mlt.ModTableKey = @mltkey
            
         end
      end
      else
      begin  /* PK columns are still there because of the script template, not an issue */
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TagName <> old.TagName
                          or (new.TagName is NULL and  old.TagName is not NULL)
                          or (old.TagName is NULL and  new.TagName is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'MessageKey', old.MessageKey, new.MessageKey
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.MessageKey <> old.MessageKey
                          or (new.MessageKey is NULL and  old.MessageKey is not NULL)
                          or (old.MessageKey is NULL and  new.MessageKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'InitialValue', old.InitialValue, new.InitialValue
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.InitialValue <> old.InitialValue
                          or (new.InitialValue is NULL and  old.InitialValue is not NULL)
                          or (old.InitialValue is NULL and  new.InitialValue is not NULL))
                  and   mlt.ModTableKey = @mltkey
         
      end
   end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_EngineeringUnit on EngineeringUnit
  for DELETE
  as
/* DELETE trigger on EngineeringUnit */
/* default body for tD_EngineeringUnit */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insEUKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* EngineeringUnit Of_Type AnalogTag ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,AnalogTag
      where
        /*  AnalogTag.EUKey = deleted.EUKey */
        AnalogTag.EUKey = deleted.EUKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE EngineeringUnit because AnalogTag exists.'
      goto error
    end



/* Signal handler for system reinitialization */
insert into ConfigStatusPending (Type, ObjectKey, Status)
     select 7, EUKey, 3 from deleted

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'EngineeringUnit' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.EUKey, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'EUKey', old.EUKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Unit', old.Unit
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'DefaultTagRate', old.DefaultTagRate
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'IntegralDivisor', old.IntegralDivisor
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go



create trigger tI_EngineeringUnit on EngineeringUnit
  for INSERT
  as
/* INSERT trigger on EngineeringUnit */
/* default body for tI_EngineeringUnit */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insEUKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* Signal handler for system reinitialization */
insert into ConfigStatusPending (Type, ObjectKey, Status)
    select 7, EUKey, 1 from inserted 

update EngineeringUnit set Status = 1 where EUKey in (select EUKey from inserted)

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'EngineeringUnit' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.EUKey, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'EUKey', new.EUKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Unit', new.Unit
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'DefaultTagRate', new.DefaultTagRate
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'IntegralDivisor', new.IntegralDivisor
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.EUKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go





create trigger tU_EngineeringUnit on EngineeringUnit
  for UPDATE
  as
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insEUKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* EngineeringUnit Of_Type AnalogTag ON PARENT UPDATE RESTRICT */
  if
    /* update(EUKey) */
    update(EUKey)
  begin
    if exists (
      select * from deleted,AnalogTag
      where
        /*  AnalogTag.EUKey = deleted.EUKey */
        AnalogTag.EUKey = deleted.EUKey
    )
    begin
      select @errno  = 30005,
             @errmsg = 'Cannot UPDATE EngineeringUnit because AnalogTag exists.'
      goto error
    end
  end



/*  Signal handler for system reinitialization */
if update(IntegralDivisor)
begin
   insert into ConfigStatusPending (Type, ObjectKey, Status)
      select 7, i.EUKey, 2
         from inserted i, deleted d
            where i.EUKey = d.EUKey

  update EngineeringUnit set Status = 2 where EUKey in (select i.EUKey from inserted i, deleted d
            where i.EUKey = d.EUKey)
end

/* start of mod tracking */ 
if not update(Status)
begin
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'EngineeringUnit' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.EUKey, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'EUKey', old.EUKey, new.EUKey
            from inserted new, deleted old, ModLogTable mlt
               where new.EUKey = old.EUKey
               and   mlt.RowKey = new.EUKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.EUKey <> old.EUKey
                       or (new.EUKey is NULL and  old.EUKey is not NULL)
                       or (old.EUKey is NULL and  new.EUKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Unit', old.Unit, new.Unit
            from inserted new, deleted old, ModLogTable mlt
               where new.EUKey = old.EUKey
               and   mlt.RowKey = new.EUKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Unit <> old.Unit
                       or (new.Unit is NULL and  old.Unit is not NULL)
                       or (old.Unit is NULL and  new.Unit is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'DefaultTagRate', old.DefaultTagRate, new.DefaultTagRate
            from inserted new, deleted old, ModLogTable mlt
               where new.EUKey = old.EUKey
               and   mlt.RowKey = new.EUKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.DefaultTagRate <> old.DefaultTagRate
                       or (new.DefaultTagRate is NULL and  old.DefaultTagRate is not NULL)
                       or (old.DefaultTagRate is NULL and  new.DefaultTagRate is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'IntegralDivisor', old.IntegralDivisor, new.IntegralDivisor
            from inserted new, deleted old, ModLogTable mlt
               where new.EUKey = old.EUKey
               and   mlt.RowKey = new.EUKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.IntegralDivisor <> old.IntegralDivisor
                       or (new.IntegralDivisor is NULL and  old.IntegralDivisor is not NULL)
                       or (old.IntegralDivisor is NULL and  new.IntegralDivisor is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Status', old.Status, new.Status
            from inserted new, deleted old, ModLogTable mlt
               where new.EUKey = old.EUKey
               and   mlt.RowKey = new.EUKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Status <> old.Status
                       or (new.Status is NULL and  old.Status is not NULL)
                       or (old.Status is NULL and  new.Status is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go




create trigger tD_EnumeratedTag on EnumeratedTag for DELETE as
/* Historian DELETE trigger on EnumeratedTag */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


    /* ERwin Builtin Wed Jul 13 12:15:38 2005 */
    /* EnumerationType R/18 EnumeratedTag ON CHILD DELETE CASCADE */
    delete EnumerationType
      from EnumerationType,deleted
      where
        /* deleted.EnumerationTypeKey = EnumerationType.EnumerationTypeKey */
        deleted.EnumerationTypeKey = EnumerationType.EnumerationTypeKey and
        not exists (
          select * from EnumeratedTag
          where
            /* EnumeratedTag.EnumerationTypeKey = EnumerationType.EnumerationTypeKey */
            EnumeratedTag.EnumerationTypeKey = EnumerationType.EnumerationTypeKey
        )


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_EnumeratedTag on EnumeratedTag for INSERT as
/* Historian INSERT trigger on EnumeratedTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Tag  EnumeratedTag ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT EnumeratedTag because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_EnumeratedTag on EnumeratedTag for UPDATE as
/* Historian UPDATE trigger on EnumeratedTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EnumerationType R/18 EnumeratedTag ON CHILD UPDATE RESTRICT */
  if
    /* update(EnumerationTypeKey) */
    update(EnumerationTypeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EnumerationType
        where
          /* inserted.EnumerationTypeKey = EnumerationType.EnumerationTypeKey */
          inserted.EnumerationTypeKey = EnumerationType.EnumerationTypeKey
    /* select @nullcnt = count(*) from inserted where
         inserted.EnumerationTypeKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.EnumerationTypeKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE EnumeratedTag because EnumerationType does not exist.'
      goto error
    end
  end

  /* Tag  EnumeratedTag ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE EnumeratedTag because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_EnumerationType on EnumerationType for DELETE as
/* Historian DELETE trigger on EnumerationType */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


    /* EnumerationType R/18 EnumeratedTag ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,EnumeratedTag
      where
        /*  EnumeratedTag.EnumerationTypeKey = deleted.EnumerationTypeKey */
        EnumeratedTag.EnumerationTypeKey = deleted.EnumerationTypeKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE EnumerationType because EnumeratedTag exists.'
      goto error
    end


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_EnumerationType on EnumerationType for UPDATE as
/* Historian UPDATE trigger on EnumerationType */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insEnumerationTypeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EnumerationType R/18 EnumeratedTag ON PARENT UPDATE CASCADE */
  if
    /* update(EnumerationTypeKey) */
    update(EnumerationTypeKey)
  begin
    if @numrows = 1
    begin
      select @insEnumerationTypeKey = inserted.EnumerationTypeKey
        from inserted
      update EnumeratedTag
      set
        /*  EnumeratedTag.EnumerationTypeKey = @insEnumerationTypeKey */
        EnumeratedTag.EnumerationTypeKey = @insEnumerationTypeKey
      from EnumeratedTag,inserted,deleted
      where
        /*  EnumeratedTag.EnumerationTypeKey = deleted.EnumerationTypeKey */
        EnumeratedTag.EnumerationTypeKey = deleted.EnumerationTypeKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade EnumerationType UPDATE because more than one row has been affected.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_EventHistory on EventHistory for DELETE as
/* Historian DELETE trigger on EventHistory */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* EventHistory R/226 StringSnapshot ON PARENT DELETE CASCADE */
    delete StringSnapshot
      from StringSnapshot,deleted
      where
        /*  StringSnapshot.EventLogKey = deleted.EventLogKey */
        StringSnapshot.EventLogKey = deleted.EventLogKey

     /* EventHistory links to DiscreteSnapshot ON PARENT DELETE CASCADE */
    delete DiscreteSnapshot
      from DiscreteSnapshot,deleted
      where
        /*  DiscreteSnapshot.EventLogKey = deleted.EventLogKey */
        DiscreteSnapshot.EventLogKey = deleted.EventLogKey

     /* EventHistory lins to AnalogSnapshot ON PARENT DELETE CASCADE */
    delete AnalogSnapshot
      from AnalogSnapshot,deleted
      where
        /*  AnalogSnapshot.EventLogKey = deleted.EventLogKey */
        AnalogSnapshot.EventLogKey = deleted.EventLogKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_EventHistory on EventHistory for INSERT as
/* Historian INSERT trigger on EventHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EventTag logged as EventHistory ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTag
        where
          /* inserted.TagName = EventTag.TagName */
          inserted.TagName = EventTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT EventHistory because EventTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_EventHistory on EventHistory for UPDATE as
/* Historian UPDATE trigger on EventHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insEventLogKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EventTag logged as EventHistory ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTag
        where
          /* inserted.TagName = EventTag.TagName */
          inserted.TagName = EventTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE EventHistory because EventTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_EventTag on EventTag
  for DELETE
  as
/* DELETE trigger on EventTag */
/* default body for tD_EventTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* EventTag R/230 SummaryOperation ON PARENT DELETE CASCADE */
    delete SummaryOperation
      from SummaryOperation,deleted
      where
        /*  SummaryOperation.TagName = deleted.TagName */
        SummaryOperation.TagName = deleted.TagName

/* EventTag R/227 TimeDetectorDetail ON PARENT DELETE CASCADE */
    delete TimeDetectorDetail
      from TimeDetectorDetail,deleted
      where
        /*  TimeDetectorDetail.TagName = deleted.TagName */
        TimeDetectorDetail.TagName = deleted.TagName

/* EventTag has SnapshotTag ON PARENT DELETE CASCADE */
    delete SnapshotTag
      from SnapshotTag,deleted
      where
        /*  SnapshotTag.EventTagName = deleted.TagName */
        SnapshotTag.EventTagName = deleted.TagName

/* EventTag logged as EventHistory ON PARENT DELETE CASCADE */
    delete EventHistory
      from EventHistory,deleted
      where
        /*  EventHistory.TagName = deleted.TagName */
        EventHistory.TagName = deleted.TagName



Begin
  /* Business rule for event system to see that a tag has been deleted */
  /* Place the deleted row into the DeletePending table */
insert into EventTagPendingDelete
(TagName, TimeDeadband, Logged, Status, PostDetectorDelay, UseThreadPool, Priority, Edge, DetectorTypeKey, ActionTypeKey)
select TagName, TimeDeadband, Logged, Status, PostDetectorDelay, UseThreadPool, Priority, Edge, DetectorTypeKey, ActionTypeKey
from deleted d
where d.Status != 1  /* exclude new entries */
End

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'EventTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TagName', old.TagName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'DetectorTypeKey', old.DetectorTypeKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ActionTypeKey', old.ActionTypeKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ScanRate', old.ScanRate
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TimeDeadband', old.TimeDeadband
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Logged', old.Logged
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'PostDetectorDelay', old.PostDetectorDelay
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'UseThreadPool', old.UseThreadPool
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'DetectorString', old.DetectorString
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ActionString', old.ActionString
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Priority', old.Priority
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Edge', old.Edge
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_EventTag on EventTag
  for INSERT
  as
/* INSERT trigger on EventTag */
/* default body for tI_EventTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* DetectorType R/199 EventTag ON CHILD INSERT RESTRICT */
  if
    /* update(DetectorTypeKey) */
    update(DetectorTypeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,DetectorType
        where
          /* inserted.DetectorTypeKey = DetectorType.DetectorTypeKey */
          inserted.DetectorTypeKey = DetectorType.DetectorTypeKey
    /* select @nullcnt = count(*) from inserted where
         inserted.DetectorTypeKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.DetectorTypeKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT EventTag because DetectorType does not exist.'
      goto error
    end
  end

/* ActionType R/198 EventTag ON CHILD INSERT RESTRICT */
  if
    /* update(ActionTypeKey) */
    update(ActionTypeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,ActionType
        where
          /* inserted.ActionTypeKey = ActionType.ActionTypeKey */
          inserted.ActionTypeKey = ActionType.ActionTypeKey
    /* select @nullcnt = count(*) from inserted where
         inserted.ActionTypeKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.ActionTypeKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT EventTag because ActionType does not exist.'
      goto error
    end
  end

/* Tag  EventTag ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT EventTag because Tag does not exist.'
      goto error
    end
  end




Begin
update EventTag
set Status = 2  /* mark as updated */
from EventTag e, inserted i, EventTagPendingDelete ed 
where e.Status != 99 and e.TagName = i.TagName and i.TagName = ed.TagName 

update EventTag
set Status = 1  /* mark as new */
from EventTag e, inserted i
where e.Status != 99 and e.Status != 2 and e.TagName = i.TagName
  /* 99 means disabled. Disabled entries should not change status. */

delete EventTagPendingDelete 
from EventTagPendingDelete ed, inserted i
where ed.TagName = i.TagName
End
/*************************/

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'EventTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TagName', new.TagName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'DetectorTypeKey', new.DetectorTypeKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ActionTypeKey', new.ActionTypeKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ScanRate', new.ScanRate
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TimeDeadband', new.TimeDeadband
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Logged', new.Logged
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'PostDetectorDelay', new.PostDetectorDelay
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'UseThreadPool', new.UseThreadPool
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'DetectorString', new.DetectorString
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ActionString', new.ActionString
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Priority', new.Priority
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Edge', new.Edge
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_EventTag on EventTag
  for UPDATE
  as
/* UPDATE trigger on EventTag */
/* default body for tU_EventTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* DetectorType R/199 EventTag ON CHILD UPDATE RESTRICT */
  if
    /* update(DetectorTypeKey) */
    update(DetectorTypeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,DetectorType
        where
          /* inserted.DetectorTypeKey = DetectorType.DetectorTypeKey */
          inserted.DetectorTypeKey = DetectorType.DetectorTypeKey
    /* select @nullcnt = count(*) from inserted where
         inserted.DetectorTypeKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.DetectorTypeKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE EventTag because DetectorType does not exist.'
      goto error
    end
  end

/* ActionType R/198 EventTag ON CHILD UPDATE RESTRICT */
  if
    /* update(ActionTypeKey) */
    update(ActionTypeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,ActionType
        where
          /* inserted.ActionTypeKey = ActionType.ActionTypeKey */
          inserted.ActionTypeKey = ActionType.ActionTypeKey
    /* select @nullcnt = count(*) from inserted where
         inserted.ActionTypeKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.ActionTypeKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE EventTag because ActionType does not exist.'
      goto error
    end
  end

/* Tag  EventTag ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE EventTag because Tag does not exist.'
      goto error
    end
  end


/* EventTag R/230 SummaryOperation ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update SummaryOperation
      set
        /*  SummaryOperation.TagName = @insTagName */
        SummaryOperation.TagName = @insTagName
      from SummaryOperation,inserted,deleted
      where
        /*  SummaryOperation.TagName = deleted.TagName */
        SummaryOperation.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade EventTag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* EventTag R/227 TimeDetectorDetail ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update TimeDetectorDetail
      set
        /*  TimeDetectorDetail.TagName = @insTagName */
        TimeDetectorDetail.TagName = @insTagName
      from TimeDetectorDetail,inserted,deleted
      where
        /*  TimeDetectorDetail.TagName = deleted.TagName */
        TimeDetectorDetail.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade EventTag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* EventTag has SnapshotTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update SnapshotTag
      set
        /*  SnapshotTag.EventTagName = @insTagName */
        SnapshotTag.EventTagName = @insTagName
      from SnapshotTag,inserted,deleted
      where
        /*  SnapshotTag.EventTagName = deleted.TagName */
        SnapshotTag.EventTagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade EventTag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* EventTag logged as EventHistory ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update EventHistory
      set
        /*  EventHistory.TagName = @insTagName */
        EventHistory.TagName = @insTagName
      from EventHistory,inserted,deleted
      where
        /*  EventHistory.TagName = deleted.TagName */
        EventHistory.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade EventTag UPDATE because more than one row has been affected.'
      goto error
    end
  end


IF (not UPDATE (Status))
Begin
update EventTag
set Status = 2  /* event updated */
from EventTag e,inserted i
where e.TagName = i.TagName and e.Status != 99 
End

/* Cleanup of TimeDetectorDetail when changing DetectorType */
if (select count(*) from inserted) = 1 --  do not run in case of batch insert 
begin
   if (select DetectorTypeKey from deleted)  = 6  -- was a Time Detector
   begin
      if (select DetectorTypeKey from inserted) <> 6  -- not a Time Detector
      begin
         delete from TimeDetectorDetail
            where TagName = (select TagName from deleted) 
      end
   end
end


/* start of mod tracking */ 
/* Note: The Status column is tracked as it has a different functionality than for the */
/*       other Status columns used for dynamic reconfiguration */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (2,3,6,7))
begin 
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'EventTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'U', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   if update(TagName)
   begin
      if @numrows = 1  /* We can get a PK mod */
      begin
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TagName <> old.TagName
                          or (new.TagName is NULL and  old.TagName is not NULL)
                          or (old.TagName is NULL and  new.TagName is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'DetectorTypeKey', old.DetectorTypeKey, new.DetectorTypeKey
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.DetectorTypeKey <> old.DetectorTypeKey
                          or (new.DetectorTypeKey is NULL and  old.DetectorTypeKey is not NULL)
                          or (old.DetectorTypeKey is NULL and  new.DetectorTypeKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ActionTypeKey', old.ActionTypeKey, new.ActionTypeKey
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ActionTypeKey <> old.ActionTypeKey
                          or (new.ActionTypeKey is NULL and  old.ActionTypeKey is not NULL)
                          or (old.ActionTypeKey is NULL and  new.ActionTypeKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ScanRate', old.ScanRate, new.ScanRate
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ScanRate <> old.ScanRate
                          or (new.ScanRate is NULL and  old.ScanRate is not NULL)
                          or (old.ScanRate is NULL and  new.ScanRate is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TimeDeadband', old.TimeDeadband, new.TimeDeadband
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TimeDeadband <> old.TimeDeadband
                          or (new.TimeDeadband is NULL and  old.TimeDeadband is not NULL)
                          or (old.TimeDeadband is NULL and  new.TimeDeadband is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Logged', old.Logged, new.Logged
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Logged <> old.Logged
                          or (new.Logged is NULL and  old.Logged is not NULL)
                          or (old.Logged is NULL and  new.Logged is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Status', old.Status, new.Status
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Status <> old.Status
                          or (new.Status is NULL and  old.Status is not NULL)
                          or (old.Status is NULL and  new.Status is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'PostDetectorDelay', old.PostDetectorDelay, new.PostDetectorDelay
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.PostDetectorDelay <> old.PostDetectorDelay
                          or (new.PostDetectorDelay is NULL and  old.PostDetectorDelay is not NULL)
                          or (old.PostDetectorDelay is NULL and  new.PostDetectorDelay is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'UseThreadPool', old.UseThreadPool, new.UseThreadPool
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.UseThreadPool <> old.UseThreadPool
                          or (new.UseThreadPool is NULL and  old.UseThreadPool is not NULL)
                          or (old.UseThreadPool is NULL and  new.UseThreadPool is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'DetectorString', old.DetectorString, new.DetectorString
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.DetectorString <> old.DetectorString
                          or (new.DetectorString is NULL and  old.DetectorString is not NULL)
                          or (old.DetectorString is NULL and  new.DetectorString is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ActionString', old.ActionString, new.ActionString
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ActionString <> old.ActionString
                          or (new.ActionString is NULL and  old.ActionString is not NULL)
                          or (old.ActionString is NULL and  new.ActionString is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Priority', old.Priority, new.Priority
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Priority <> old.Priority
                          or (new.Priority is NULL and  old.Priority is not NULL)
                          or (old.Priority is NULL and  new.Priority is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Edge', old.Edge, new.Edge
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Edge <> old.Edge
                          or (new.Edge is NULL and  old.Edge is not NULL)
                          or (old.Edge is NULL and  new.Edge is not NULL))
                  and   mlt.ModTableKey = @mltkey
         
      end
   end
   else
   begin  /* PK columns are still there because of the script template, not an issue */
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.TagName <> old.TagName
                       or (new.TagName is NULL and  old.TagName is not NULL)
                       or (old.TagName is NULL and  new.TagName is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'DetectorTypeKey', old.DetectorTypeKey, new.DetectorTypeKey
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.DetectorTypeKey <> old.DetectorTypeKey
                       or (new.DetectorTypeKey is NULL and  old.DetectorTypeKey is not NULL)
                       or (old.DetectorTypeKey is NULL and  new.DetectorTypeKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ActionTypeKey', old.ActionTypeKey, new.ActionTypeKey
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ActionTypeKey <> old.ActionTypeKey
                       or (new.ActionTypeKey is NULL and  old.ActionTypeKey is not NULL)
                       or (old.ActionTypeKey is NULL and  new.ActionTypeKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ScanRate', old.ScanRate, new.ScanRate
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ScanRate <> old.ScanRate
                       or (new.ScanRate is NULL and  old.ScanRate is not NULL)
                       or (old.ScanRate is NULL and  new.ScanRate is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'TimeDeadband', old.TimeDeadband, new.TimeDeadband
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.TimeDeadband <> old.TimeDeadband
                       or (new.TimeDeadband is NULL and  old.TimeDeadband is not NULL)
                       or (old.TimeDeadband is NULL and  new.TimeDeadband is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Logged', old.Logged, new.Logged
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Logged <> old.Logged
                       or (new.Logged is NULL and  old.Logged is not NULL)
                       or (old.Logged is NULL and  new.Logged is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Status', old.Status, new.Status
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Status <> old.Status
                       or (new.Status is NULL and  old.Status is not NULL)
                       or (old.Status is NULL and  new.Status is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'PostDetectorDelay', old.PostDetectorDelay, new.PostDetectorDelay
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.PostDetectorDelay <> old.PostDetectorDelay
                       or (new.PostDetectorDelay is NULL and  old.PostDetectorDelay is not NULL)
                       or (old.PostDetectorDelay is NULL and  new.PostDetectorDelay is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'UseThreadPool', old.UseThreadPool, new.UseThreadPool
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.UseThreadPool <> old.UseThreadPool
                       or (new.UseThreadPool is NULL and  old.UseThreadPool is not NULL)
                       or (old.UseThreadPool is NULL and  new.UseThreadPool is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'DetectorString', old.DetectorString, new.DetectorString
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.DetectorString <> old.DetectorString
                       or (new.DetectorString is NULL and  old.DetectorString is not NULL)
                       or (old.DetectorString is NULL and  new.DetectorString is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ActionString', old.ActionString, new.ActionString
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ActionString <> old.ActionString
                       or (new.ActionString is NULL and  old.ActionString is not NULL)
                       or (old.ActionString is NULL and  new.ActionString is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Priority', old.Priority, new.Priority
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Priority <> old.Priority
                       or (new.Priority is NULL and  old.Priority is not NULL)
                       or (old.Priority is NULL and  new.Priority is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Edge', old.Edge, new.Edge
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Edge <> old.Edge
                       or (new.Edge is NULL and  old.Edge is not NULL)
                       or (old.Edge is NULL and  new.Edge is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
end
/* end of mod tracking */ 

return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_EventTagPendingDelete on EventTagPendingDelete for DELETE as
/* Historian DELETE trigger on EventTagPendingDelete */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* EventTagPendingDelete R/237 TimeDetectorDetailPendingDelete ON PARENT DELETE CASCADE */
    delete TimeDetectorDetailPendingDelete
      from TimeDetectorDetailPendingDelete,deleted
      where
        /*  TimeDetectorDetailPendingDelete.TagName = deleted.TagName */
        TimeDetectorDetailPendingDelete.TagName = deleted.TagName


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_Frequency on Frequency for DELETE as
/* Historian DELETE trigger on Frequency */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* Frequency R/228 TimeDetectorDetail ON PARENT DELETE CASCADE */
    delete TimeDetectorDetail
      from TimeDetectorDetail,deleted
      where
        /*  TimeDetectorDetail.FrequencyID = deleted.FrequencyID */
        TimeDetectorDetail.FrequencyID = deleted.FrequencyID


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_Frequency on Frequency for UPDATE as
/* Historian UPDATE trigger on Frequency */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insFrequencyID int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Frequency R/228 TimeDetectorDetail ON PARENT UPDATE CASCADE */
  if
    /* update(FrequencyID) */
    update(FrequencyID)
  begin
    if @numrows = 1
    begin
      select @insFrequencyID = inserted.FrequencyID
        from inserted
      update TimeDetectorDetail
      set
        /*  TimeDetectorDetail.FrequencyID = @insFrequencyID */
        TimeDetectorDetail.FrequencyID = @insFrequencyID
      from TimeDetectorDetail,inserted,deleted
      where
        /*  TimeDetectorDetail.FrequencyID = deleted.FrequencyID */
        TimeDetectorDetail.FrequencyID = deleted.FrequencyID
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Frequency UPDATE because more than one row has been affected.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_GroupTagList on GroupTagList for INSERT as
/* Historian INSERT trigger on GroupTagList */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* TagRef member of GroupTagList ON CHILD INSERT RESTRICT */
  if
    /* update(wwDomainTagKey) */
    update(wwDomainTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,TagRef
        where
          /* inserted.wwDomainTagKey = TagRef.wwDomainTagKey */
          inserted.wwDomainTagKey = TagRef.wwDomainTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT GroupTagList because TagRef does not exist.'
      goto error
    end
  end

  /* TagGroup contains GroupTagList ON CHILD INSERT RESTRICT */
  if
    /* update(GroupID) */
    update(GroupID)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,TagGroup
        where
          /* inserted.GroupID = TagGroup.GroupID */
          inserted.GroupID = TagGroup.GroupID
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT GroupTagList because TagGroup does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_GroupTagList on GroupTagList for UPDATE as
/* Historian UPDATE trigger on GroupTagList */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insGroupID int, 
           @inswwDomainTagKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* TagRef member of GroupTagList ON CHILD UPDATE RESTRICT */
  if
    /* update(wwDomainTagKey) */
    update(wwDomainTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,TagRef
        where
          /* inserted.wwDomainTagKey = TagRef.wwDomainTagKey */
          inserted.wwDomainTagKey = TagRef.wwDomainTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE GroupTagList because TagRef does not exist.'
      goto error
    end
  end

  /* TagGroup contains GroupTagList ON CHILD UPDATE RESTRICT */
  if
    /* update(GroupID) */
    update(GroupID)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,TagGroup
        where
          /* inserted.GroupID = TagGroup.GroupID */
          inserted.GroupID = TagGroup.GroupID
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE GroupTagList because TagGroup does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_InTouchNode on InTouchNode for DELETE as
/* Historian DELETE trigger on InTouchNode */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* InTouchNode has TopicImportInfo ON PARENT DELETE CASCADE */
    delete TopicImportInfo
      from TopicImportInfo,deleted
      where
        /*  TopicImportInfo.NodeKey = deleted.NodeKey */
        TopicImportInfo.NodeKey = deleted.NodeKey

     /* InTouchNode has InTouchSpecific ON PARENT DELETE CASCADE */
    delete InTouchSpecific
      from InTouchSpecific,deleted
      where
        /*  InTouchSpecific.NodeKey = deleted.NodeKey */
        InTouchSpecific.NodeKey = deleted.NodeKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_InTouchSpecific on InTouchSpecific for INSERT as
/* Historian INSERT trigger on InTouchSpecific */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* InTouchNode has InTouchSpecific ON CHILD INSERT RESTRICT */
  if
    /* update(NodeKey) */
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchNode
        where
          /* inserted.NodeKey = InTouchNode.NodeKey */
          inserted.NodeKey = InTouchNode.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT InTouchSpecific because InTouchNode does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_InTouchSpecific on InTouchSpecific for UPDATE as
/* Historian UPDATE trigger on InTouchSpecific */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insNodeKey int, 
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* InTouchNode has InTouchSpecific ON CHILD UPDATE RESTRICT */
  if
    /* update(NodeKey) */
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchNode
        where
          /* inserted.NodeKey = InTouchNode.NodeKey */
          inserted.NodeKey = InTouchNode.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE InTouchSpecific because InTouchNode does not exist.'
      goto error
    end
  end

  /* Tag R/161 InTouchSpecific ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE InTouchSpecific because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_IODriver on IODriver
  for DELETE
  as
/* DELETE trigger on IODriver */
/* default body for tD_IODriver */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insIODriverKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* IODriver gets data from IOServer ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,IOServer
      where
        /*  IOServer.IODriverKey = deleted.IODriverKey and
            IOServer.StorageNodeKey = deleted.StorageNodeKey */
        IOServer.IODriverKey = deleted.IODriverKey and
        IOServer.StorageNodeKey = deleted.StorageNodeKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE IODriver because IOServer exists.'
      goto error
    end



/* Check that there is still at least 1 IODriver excluding System and MDAS IODrivers */
if (select count(IODriverKey) from IODriver where IODriverKey > 1) < 1
begin
  set @errno = 17007
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid IODriver delete'
  end
  goto error  
end

/*  Signal handler for system reinitialization */

   insert into ConfigStatusPending (Type, ObjectKey, Status)
      select 0, IODriverKey, 3 from deleted


/* remove associated System Tags */
if @numrows = 1
begin
   declare @iodrivertag nvarchar(256)
   set @iodrivertag = RTRIM('SysDataAcq' + (select convert(char, IODriverKey) from deleted))
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysDataAcqRxItemsPerSec' + (select convert(char, IODriverKey) from deleted))
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysDataAcqRxTotalItems' + (select convert(char, IODriverKey) from deleted))
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from deleted)) + 'CPU')
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from deleted)) + 'PrivateBytes')
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from deleted)) + 'VirtualBytes')
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from deleted)) + 'ThreadCount')
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from deleted)) + 'HandleCount')
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from deleted)) + 'PageFaults')
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysDataAcq' + RTRIM((select convert(char, IODriverKey) from deleted)) + 'BadValues')
   delete from Tag where TagName = @iodrivertag 
   set @iodrivertag = RTRIM('SysDataAcq' + RTRIM((select convert(char, IODriverKey) from deleted)) + 'OutsideRealtime')
   delete from Tag where TagName = @iodrivertag 
end
else
begin
  declare @iokey int
  declare @thetag nvarchar(256) 

  declare thelist cursor for
    select IODriverKey from deleted
  for read only

  open thelist
  fetch next from thelist into @iokey
  while @@FETCH_STATUS = 0
  begin
   set @thetag = RTRIM('SysDataAcq' +  convert(char, @iokey))
   delete from Tag where TagName = @thetag 
   set @thetag = RTRIM('SysDataAcqRxItemsPerSec' +  convert(char, @iokey))
   delete from Tag where TagName = @thetag
   set @thetag = RTRIM('SysDataAcqRxTotalItems' +  convert(char, @iokey))
   delete from Tag where TagName = @thetag
   set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @iokey)) + 'CPU')
   delete from Tag where TagName = @thetag 
   set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @iokey)) + 'PrivateBytes')
   delete from Tag where TagName = @thetag 
   set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @iokey)) + 'VirtualBytes')
   delete from Tag where TagName = @thetag 
   set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @iokey)) + 'ThreadCount')
   delete from Tag where TagName = @thetag 
   set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @iokey)) + 'HandleCount')
   delete from Tag where TagName = @thetag 
   set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @iokey)) + 'PageFaults')
   delete from Tag where TagName = @thetag 
   set @thetag = RTRIM('SysDataAcq' + RTRIM(convert(char, @iokey)) + 'BadValues')
   delete from Tag where TagName = @thetag 
   set @thetag = RTRIM('SysDataAcq' + RTRIM(convert(char, @iokey)) + 'OutsideRealtime')
   delete from Tag where TagName = @thetag 

   fetch next from thelist into @iokey       
  end 
  close thelist
  deallocate thelist     
end

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'IODriver' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.IODriverKey, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'IODriverKey', old.IODriverKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ComputerName', old.ComputerName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'AltComputerName', old.AltComputerName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StoreForwardMode', old.StoreForwardMode
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StoreForwardPath', old.StoreForwardPath
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MinMBThreshold', old.MinMBThreshold
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Enabled', old.Enabled
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StoreForwardDuration', old.StoreForwardDuration
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'AutonomousStartupTimeout', old.AutonomousStartupTimeout
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'BufferCount', old.BufferCount
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'FileChunkSize', old.FileChunkSize
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ForwardingDelay', old.ForwardingDelay
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ConnectionTimeout', old.ConnectionTimeout
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

/* Check if there were IDAS in License Violation */
/* Maybe some can now be enabled.                */
declare @servername sysname
declare @licensecheck int
declare @sysparam  sql_variant
declare @sysparamstring  nvarchar(20)
declare @allowedidas  int
select @servername = ComputerName from ServerList

/* Get the License count */
select @sysparam = Value from SystemParameter
                     where [Name] = 'LicenseRemoteIDASCount'
select @sysparamstring = convert(nvarchar(20), @sysparam)

set @allowedidas = 
case lower(@sysparamstring)
  when N'none (unlicensed)' then 0
  when N'unlimited' then 65536
  else 
    case sql_variant_property(@sysparam, 'BaseType')
      when 'int' then convert(int, @sysparamstring)
      else 0
    end
end

/* Get what is there after the delete */
select @licensecheck = count(IODriverKey) from IODriver where IODriverKey >= 2
  and upper(ComputerName) <> upper(@servername)

/* Add the deleted IDAS */
set @licensecheck = @licensecheck +
         (select count(IODriverKey) from deleted where IODriverKey >= 2
            and upper(ComputerName) <> upper(@servername))

/* How many IDAS were in violation */
set @licensecheck = @licensecheck - @allowedidas

if (@licensecheck > 0) -- System was in license Violation
begin
  /* We can enable as many IDAS which were not loaded */
  /* because of the license violation                 */
  declare @idaskey int
  declare @rowcount int
  set @rowcount = 1

  declare csrIDAS scroll cursor for
      select IODriverKey from IODriver
         where IODriverKey >= 2 and upper(ComputerName) <> upper(@servername)
      union
      select IODriverKey from deleted
         where IODriverKey >= 2 and upper(ComputerName) <> upper(@servername)
      order by IODriverKey
    for read only

  open csrIDAS
  set @allowedidas = @allowedidas + 1 -- next IDAS to enable

  fetch absolute @allowedidas from csrIDAS into @idaskey

  while (@rowcount <= @licensecheck and @rowcount <= @numrows)  
            and @@FETCH_STATUS = 0 
  begin
      if not exists (select IODriverKey from deleted where IODriverKey = @idaskey)
      begin
         update IODriver set Status = 1 where IODriverKey = @idaskey
         insert ConfigStatusPending (Type, ObjectKey, Status)
           values (0, @idaskey, 1)
         set @rowcount = @rowcount + 1
      end
 
      fetch next from csrIDAS into @idaskey
  end

  close csrIDAS
  deallocate csrIDAS
end
/* End of License Checking */

return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go



create trigger tI_IODriver on IODriver
  for INSERT
  as
/* INSERT trigger on IODriver */
/* default body for tI_IODriver */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insIODriverKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* StorageNode gets data from IODriver ON CHILD INSERT RESTRICT */
  if
    /* update(StorageNodeKey) */
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,StorageNode
        where
          /* inserted.StorageNodeKey = StorageNode.StorageNodeKey */
          inserted.StorageNodeKey = StorageNode.StorageNodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT IODriver because StorageNode does not exist.'
      goto error
    end
  end




/* Validate the computer names : no \\ */
if exists (select IODriverKey from inserted 
             where ComputerName like '%\%' or AltComputerName like '%\%')
begin
   set @errno = 17036
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg  is NULL
   begin
      set @errmsg = 'Error msg not found - Invalid insert or update. Do not include \\ in machine names.'
   end      
   goto error     
end

/* Check Validity of this IODriver */
/* Check that this IODriver does not already exist (for case sensitive database) */
if @numrows = 1
begin
   if (select count(UPPER(IODriver.ComputerName)) from IODriver, inserted
                 where UPPER(IODriver.ComputerName) = UPPER(inserted.ComputerName)) > @numrows
   begin
      set @errno = 17014
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid insert or update, IODriver already exists as Primary IODriver'
      end      
      goto error
   end   
end

/* Cannot already be defined as an Alternative IODriver and vice-versa */
if @numrows = 1
begin
   if exists (select UPPER(IODriver.AltComputerName) from IODriver, inserted
                 where UPPER(IODriver.AltComputerName) = UPPER(inserted.ComputerName))
   begin
      set @errno = 17010
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid insert, IODriver already exists as Alternate IODriver'
      end      
      goto error
   end   
   else
   if exists (select UPPER(IODriver.ComputerName) from IODriver, inserted
                 where UPPER(IODriver.ComputerName) = UPPER(inserted.AltComputerName))
   begin
      set @errno = 17011
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid insert, Alternate IODriver already exists as defined IODriver'
      end      
      goto error
   end   
end

/*  Signal handler for system reinitialization */

insert into ConfigStatusPending (Type, ObjectKey, Status)
   select 0, IODriverKey, 1 from inserted

update IODriver set Status = 1 where IODriverKey in (select IODriverKey from inserted)


/* Create associated System driver tags */
if (select IODriverKey from inserted) < 2
begin
   goto BypassTagInsert 
end

declare @iodrivertag nvarchar(256)
declare @desc nvarchar(512)

set @iodrivertag = RTRIM('SysDataAcq' + (select convert(char, IODriverKey) from inserted))
set @desc = RTRIM('Data Acquisition Status for ' + (select UPPER(ComputerName) from inserted))

EXEC aaDiscreteTagInsert 
  @TagName         = @iodrivertag,
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = @desc, 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = @iodrivertag,
  @MessageKey      = 1

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 15, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysDataAcqRxTotalItems' + (select convert(char, IODriverKey) from inserted))
set @desc = RTRIM('Total items received from ' + (select UPPER(RTRIM(ComputerName)) from inserted)) + ' since startup'

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 10000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 200000000000,
  @MinRaw          = 0,
  @MaxRaw          = 200000000000,
  @Scaling         = 0,
  @RawType         = 2,
  @IntegerSize     = 0,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 13, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysDataAcqRxItemsPerSec' + (select convert(char, IODriverKey) from inserted))
set @desc = RTRIM('Items per second received from ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 10000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 50000,
  @MinRaw          = 0,
  @MaxRaw          = 50000,
  @Scaling         = 0,
  @RawType         = 2,
  @IntegerSize     = 0,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 13, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

/* Performance Counters */
set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from inserted)) + 'CPU')
set @desc = RTRIM('% CPU Load for Data Acquisition on ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 1,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from inserted)) + 'PrivateBytes')
set @desc = RTRIM('Private Bytes for Data Acquisition on ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 10,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from inserted)) + 'VirtualBytes')
set @desc = RTRIM('Virtual Bytes for Data Acquisition on ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 10,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from inserted)) + 'ThreadCount')
set @desc = RTRIM('Thread count for Data Acquisition on ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from inserted)) + 'HandleCount')
set @desc = RTRIM('Handle count for Data Acquisition on ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysPerfDataAcq' + RTRIM((select convert(char, IODriverKey) from inserted)) + 'PageFaults')
set @desc = RTRIM('Page faults per second for Data Acquisition on ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysDataAcq' + RTRIM((select convert(char, IODriverKey) from inserted)) + 'BadValues')
set @desc = RTRIM('Bad quality points per second for Data Acquisition on ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 1000000,
  @MinRaw          = 0,
  @MaxRaw          = 1000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 13, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

set @iodrivertag = RTRIM('SysDataAcq' + RTRIM((select convert(char, IODriverKey) from inserted)) + 'OutsideRealtime')
set @desc = RTRIM('Discarded points per second for Data Acquisition on ' + (select UPPER(ComputerName) from inserted))

EXEC aaAnalogTagInsert
  @TagName         = @iodrivertag,
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = @desc,
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = @iodrivertag,
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 1000000,
  @MinRaw          = 0,
  @MaxRaw          = 1000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 13, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = @iodrivertag

BypassTagInsert:


/**********************************/

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'IODriver' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.IODriverKey, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'IODriverKey', new.IODriverKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageNodeKey', new.StorageNodeKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ComputerName', new.ComputerName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'AltComputerName', new.AltComputerName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StoreForwardMode', new.StoreForwardMode
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StoreForwardPath', new.StoreForwardPath
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MinMBThreshold', new.MinMBThreshold
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Enabled', new.Enabled
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StoreForwardDuration', new.StoreForwardDuration
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'AutonomousStartupTimeout', new.AutonomousStartupTimeout
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'BufferCount', new.BufferCount
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'FileChunkSize', new.FileChunkSize
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ForwardingDelay', new.ForwardingDelay
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ConnectionTimeout', new.ConnectionTimeout
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IODriverKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

return

error:
    raiserror @errno @errmsg
    rollback transaction

end
go


create trigger tU_IODriver on IODriver
  for UPDATE
  as
/* UPDATE trigger on IODriver */
/* default body for tU_IODriver */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insIODriverKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* StorageNode gets data from IODriver ON CHILD UPDATE RESTRICT */
  if
    /* update(StorageNodeKey) */
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,StorageNode
        where
          /* inserted.StorageNodeKey = StorageNode.StorageNodeKey */
          inserted.StorageNodeKey = StorageNode.StorageNodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE IODriver because StorageNode does not exist.'
      goto error
    end
  end


/* IODriver gets data from IOServer ON PARENT UPDATE CASCADE */
  if
    /* update(IODriverKey) or
       update(StorageNodeKey) */
    update(IODriverKey) or
    update(StorageNodeKey)
  begin
    if @numrows = 1
    begin
      select @insIODriverKey = inserted.IODriverKey, 
             @insStorageNodeKey = inserted.StorageNodeKey
        from inserted
      update IOServer
      set
        /*  IOServer.IODriverKey = @insIODriverKey,
            IOServer.StorageNodeKey = @insStorageNodeKey */
        IOServer.IODriverKey = @insIODriverKey,
        IOServer.StorageNodeKey = @insStorageNodeKey
      from IOServer,inserted,deleted
      where
        /*  IOServer.IODriverKey = deleted.IODriverKey and
            IOServer.StorageNodeKey = deleted.StorageNodeKey */
        IOServer.IODriverKey = deleted.IODriverKey and
        IOServer.StorageNodeKey = deleted.StorageNodeKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade IODriver UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* Validate the computer names : no \\ */
if exists (select IODriverKey from inserted 
             where ComputerName like '%\%' or AltComputerName like '%\%')
begin
   set @errno = 17036
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg  is NULL
   begin
      set @errmsg = 'Error msg not found - Invalid insert or update. Do not include \\ in machine names.'
   end      
   goto error     
end

/* Check Validity of this IODriver */
/* Check that this IODriver does not already exist (for case sensitive database) */
if not update(Status) and (select count(UPPER(IODriver.ComputerName)) from IODriver, inserted
              where UPPER(IODriver.ComputerName) = UPPER(inserted.ComputerName)) > @numrows
begin
   set @errno = 17014
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg  is NULL
   begin
      set @errmsg = 'Error msg not found - Invalid insert or update, IODriver already exists as Primary IODriver'
   end      
   goto error
end   


/* Cannot already be defined as an Alternative IODriver */
if @numrows = 1
begin
   if exists (select UPPER(IODriver.AltComputerName) from IODriver, inserted
                 where UPPER(IODriver.AltComputerName) = UPPER(inserted.ComputerName))
   begin
      set @errno = 17019
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid insert, IODriver already exists as Alternate IODriver'
      end      
      goto error
   end   
   else
   if exists (select UPPER(IODriver.ComputerName) from IODriver, inserted
                 where UPPER(IODriver.ComputerName) = UPPER(inserted.AltComputerName))
   begin
      set @errno = 17018
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid update, Alternate IODriver already exists as defined IODriver'
      end      
      goto error
   end   
end


/*  Signal handler for system reinitialization                    */
if not update(Status)
begin
   declare @dcompname nvarchar(255), @icompname nvarchar(255)
   declare @daltcompname nvarchar(255), @ialtcompname nvarchar(255)
   declare @dsfmode tinyint, @isfmode tinyint
   declare @dsfpath nvarchar(255), @isfpath nvarchar(255)
   declare @dminmb int, @iminmb int  
   declare @denabled int, @ienabled int  
   declare @dsfduration int, @isfduration int  
   declare @dastimeout int, @iastimeout int  
   declare @dbufcount int, @ibufcount int  
   declare @dfcsize int, @ifcsize int  
   declare @dfwddelay int, @ifwddelay int  
   declare @dctimeout int, @ictimeout int  

   if @numrows = 1
   begin
      /* Only 1 row affected */
      /* no need to update if new or already modified */
      if (select Status from deleted) not in (1, 2)
      begin
         set @dcompname = (select ComputerName from deleted)
         set @icompname = (select ComputerName from inserted)
         set @daltcompname = (select AltComputerName from deleted)
         set @ialtcompname = (select AltComputerName from inserted)
         set @dsfmode = (select StoreForwardMode from deleted)
         set @isfmode = (select StoreForwardMode from inserted)
         set @dsfpath = (select StoreForwardPath from deleted)
         set @isfpath = (select StoreForwardPath from inserted)
         set @dminmb = (select MinMBThreshold from deleted)
         set @iminmb = (select MinMBThreshold from inserted)
         set @denabled = (select Enabled from deleted)
         set @ienabled = (select Enabled from inserted)
         set @dsfduration = (select StoreForwardDuration from deleted)
         set @isfduration = (select StoreForwardDuration from inserted)
         set @dastimeout = (select AutonomousStartupTimeout from deleted)
         set @iastimeout = (select AutonomousStartupTimeout from inserted)
         set @dbufcount = (select BufferCount from deleted)
         set @ibufcount = (select BufferCount from inserted)
         set @dfcsize = (select FileChunkSize from deleted)
         set @ifcsize = (select FileChunkSize from inserted)
         set @dfwddelay = (select ForwardingDelay from deleted)
         set @ifwddelay = (select ForwardingDelay from inserted)
         set @dctimeout = (select ConnectionTimeout from deleted)
         set @ictimeout = (select ConnectionTimeout from inserted)

         /* Must be able to catch changes to or from NULL on Nullable columns */
         if @daltcompname is NULL set @daltcompname = 'was NULL'
         if @ialtcompname is NULL set @ialtcompname = 'was NULL'
         if @dsfpath is NULL set @dsfpath = 'was NULL'
         if @isfpath is NULL set @isfpath = 'was NULL'

         if (@dcompname <> @icompname) or (@daltcompname <> @ialtcompname) 
            or (@dsfmode <> @isfmode) or (@dsfpath <> @isfpath)
            or (@dminmb <> @iminmb) or (@denabled <> @ienabled)
            or (@dsfduration <> @isfduration) or (@dastimeout <> @iastimeout)
            or (@dbufcount <> @ibufcount) or (@dfcsize <> @ifcsize)
            or (@dfwddelay <> @ifwddelay) or (@dctimeout <> @ictimeout)
         begin
            insert into ConfigStatusPending (Type, ObjectKey, Status)
             select 0, IODriverKey, 2 from inserted

           update IODriver set Status = 2 from IODriver, inserted
               where IODriver.IODriverKey = inserted.IODriverKey
         end
      end 

     /* if computer name has changed, need to update system Tag Description */
     if (select ComputerName from deleted) <> (select ComputerName from inserted)
     begin
        declare @thekey int
        declare @desc nvarchar(512)
        declare @thetag nvarchar(256)
        set @thekey = (select IODriverKey from inserted)
        set @thetag = RTRIM('SysDataAcq' + RTRIM(convert(char, @thekey))) 
        set @desc = RTRIM('Data Acquistion Status for ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysDataAcqRxItemsPerSec' + RTRIM(convert(char, @thekey))) 
        set @desc = RTRIM('Items per second received from ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysDataAcqRxTotalItems' + RTRIM(convert(char, @thekey))) 
        set @desc = RTRIM('Total items received from ' + (select RTRIM(ComputerName) + ' since startup' from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @thekey)) + 'CPU') 
        set @desc = RTRIM('% CPU Load for Data Acquisition on ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @thekey)) + 'PrivateBytes') 
        set @desc = RTRIM('Private bytes for Data Acquisition on ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @thekey)) + 'VirtualBytes') 
        set @desc = RTRIM('Virtual bytes for Data Acquisition on ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @thekey)) + 'ThreadCount') 
        set @desc = RTRIM('Thread count for Data Acquisition on ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @thekey)) + 'HandleCount') 
        set @desc = RTRIM('Handle count for Data Acquisition on ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysPerfDataAcq' + RTRIM(convert(char, @thekey)) + 'PageFaults') 
        set @desc = RTRIM('Page faults per second for Data Acquisition on ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysDataAcq' + RTRIM(convert(char, @thekey)) + 'BadValues') 
        set @desc = RTRIM('Bad quality points per second for Data Acquisition on ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
        set @thetag = RTRIM('SysDataAcq' + RTRIM(convert(char, @thekey)) + 'OutsideRealtime') 
        set @desc = RTRIM('Discarded points per second for Data Acquisition on ' + (select ComputerName from inserted))
        update Tag set Description = @desc where TagName = @thetag
     end

   end
   else
   begin
      /* Multiple rows need to go through them 1 by 1 */
      declare @key int, @status int   
 
      declare thelist cursor for
        select d.IODriverKey, d.Status 
           from deleted d where d.IODriverKey > 0
            
     open thelist
     fetch next from thelist into @key, @status
     while @@FETCH_STATUS = 0
        begin
           /* no need to update if new or already modified */ 
           if @status not in (1, 2)
           begin
              set @dcompname = (select ComputerName from deleted where IODriverKey = @key)
              set @icompname = (select ComputerName from inserted where IODriverKey = @key)
              set @daltcompname = (select AltComputerName from deleted where IODriverKey = @key)
              set @ialtcompname = (select AltComputerName from inserted where IODriverKey = @key)
              set @dsfmode = (select StoreForwardMode from deleted where IODriverKey = @key)
              set @isfmode = (select StoreForwardMode from inserted where IODriverKey = @key)
              set @dsfpath = (select StoreForwardPath from deleted where IODriverKey = @key)
              set @isfpath = (select StoreForwardPath from inserted where IODriverKey = @key)
              set @dminmb = (select MinMBThreshold from deleted where IODriverKey = @key)
              set @iminmb = (select MinMBThreshold from inserted where IODriverKey = @key)
              set @denabled = (select Enabled from deleted)
              set @ienabled = (select Enabled from inserted)
              set @dsfduration = (select StoreForwardDuration from deleted)
              set @isfduration = (select StoreForwardDuration from inserted)
              set @dastimeout = (select AutonomousStartupTimeout from deleted)
              set @iastimeout = (select AutonomousStartupTimeout from inserted)
              set @dbufcount = (select BufferCount from deleted)
              set @ibufcount = (select BufferCount from inserted)
              set @dfcsize = (select FileChunkSize from deleted)
              set @ifcsize = (select FileChunkSize from inserted)
              set @dfwddelay = (select ForwardingDelay from deleted)
              set @ifwddelay = (select ForwardingDelay from inserted)
              set @dctimeout = (select ConnectionTimeout from deleted)
              set @ictimeout = (select ConnectionTimeout from inserted)

              /* Must be able to catch changes to or from NULL on Nullable columns */
              if @daltcompname is NULL set @daltcompname = 'was NULL'
              if @ialtcompname is NULL set @ialtcompname = 'was NULL'
              if @dsfpath is NULL set @dsfpath = 'was NULL'
              if @isfpath is NULL set @isfpath = 'was NULL'

              if (@dcompname <> @icompname) or (@daltcompname <> @ialtcompname) 
                 or (@dsfmode <> @isfmode) or (@dsfpath <> @isfpath)
                 or (@dminmb <> @iminmb) or (@denabled <> @ienabled)
                 or (@dsfduration <> @isfduration) or (@dastimeout <> @iastimeout)
                 or (@dbufcount <> @ibufcount) or (@dfcsize <> @ifcsize)
                 or (@dfwddelay <> @ifwddelay) or (@dctimeout <> @ictimeout)
              begin
                 insert into ConfigStatusPending (Type, ObjectKey, Status)
                   values (0, @key, 2)

                 update IODriver set Status = 2 
                     where IODriverKey = @key         
              end
           end           
           fetch next from thelist into @key, @status
        end     
     close thelist
     deallocate thelist
   end
end

/* start of mod tracking */ 
if not update(Status)
begin
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'IODriver' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.IODriverKey, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'IODriverKey', old.IODriverKey, new.IODriverKey
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.IODriverKey <> old.IODriverKey
                       or (new.IODriverKey is NULL and  old.IODriverKey is not NULL)
                       or (old.IODriverKey is NULL and  new.IODriverKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey, new.StorageNodeKey
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StorageNodeKey <> old.StorageNodeKey
                       or (new.StorageNodeKey is NULL and  old.StorageNodeKey is not NULL)
                       or (old.StorageNodeKey is NULL and  new.StorageNodeKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ComputerName', old.ComputerName, new.ComputerName
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ComputerName <> old.ComputerName
                       or (new.ComputerName is NULL and  old.ComputerName is not NULL)
                       or (old.ComputerName is NULL and  new.ComputerName is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'AltComputerName', old.AltComputerName, new.AltComputerName
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.AltComputerName <> old.AltComputerName
                       or (new.AltComputerName is NULL and  old.AltComputerName is not NULL)
                       or (old.AltComputerName is NULL and  new.AltComputerName is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StoreForwardMode', old.StoreForwardMode, new.StoreForwardMode
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StoreForwardMode <> old.StoreForwardMode
                       or (new.StoreForwardMode is NULL and  old.StoreForwardMode is not NULL)
                       or (old.StoreForwardMode is NULL and  new.StoreForwardMode is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StoreForwardPath', old.StoreForwardPath, new.StoreForwardPath
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StoreForwardPath <> old.StoreForwardPath
                       or (new.StoreForwardPath is NULL and  old.StoreForwardPath is not NULL)
                       or (old.StoreForwardPath is NULL and  new.StoreForwardPath is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'MinMBThreshold', old.MinMBThreshold, new.MinMBThreshold
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.MinMBThreshold <> old.MinMBThreshold
                       or (new.MinMBThreshold is NULL and  old.MinMBThreshold is not NULL)
                       or (old.MinMBThreshold is NULL and  new.MinMBThreshold is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Status', old.Status, new.Status
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Status <> old.Status
                       or (new.Status is NULL and  old.Status is not NULL)
                       or (old.Status is NULL and  new.Status is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Enabled', old.Enabled, new.Enabled
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Enabled <> old.Enabled
                       or (new.Enabled is NULL and  old.Enabled is not NULL)
                       or (old.Enabled is NULL and  new.Enabled is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StoreForwardDuration', old.StoreForwardDuration, new.StoreForwardDuration
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StoreForwardDuration <> old.StoreForwardDuration
                       or (new.StoreForwardDuration is NULL and  old.StoreForwardDuration is not NULL)
                       or (old.StoreForwardDuration is NULL and  new.StoreForwardDuration is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'AutonomousStartupTimeout', old.AutonomousStartupTimeout, new.AutonomousStartupTimeout
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.AutonomousStartupTimeout <> old.AutonomousStartupTimeout
                       or (new.AutonomousStartupTimeout is NULL and  old.AutonomousStartupTimeout is not NULL)
                       or (old.AutonomousStartupTimeout is NULL and  new.AutonomousStartupTimeout is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'BufferCount', old.BufferCount, new.BufferCount
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.BufferCount <> old.BufferCount
                       or (new.BufferCount is NULL and  old.BufferCount is not NULL)
                       or (old.BufferCount is NULL and  new.BufferCount is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'FileChunkSize', old.FileChunkSize, new.FileChunkSize
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.FileChunkSize <> old.FileChunkSize
                       or (new.FileChunkSize is NULL and  old.FileChunkSize is not NULL)
                       or (old.FileChunkSize is NULL and  new.FileChunkSize is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ForwardingDelay', old.ForwardingDelay, new.ForwardingDelay
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ForwardingDelay <> old.ForwardingDelay
                       or (new.ForwardingDelay is NULL and  old.ForwardingDelay is not NULL)
                       or (old.ForwardingDelay is NULL and  new.ForwardingDelay is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ConnectionTimeout', old.ConnectionTimeout, new.ConnectionTimeout
            from inserted new, deleted old, ModLogTable mlt
               where new.IODriverKey = old.IODriverKey
               and   mlt.RowKey = new.IODriverKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ConnectionTimeout <> old.ConnectionTimeout
                       or (new.ConnectionTimeout is NULL and  old.ConnectionTimeout is not NULL)
                       or (old.ConnectionTimeout is NULL and  new.ConnectionTimeout is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_IOServer on IOServer
  for DELETE
  as
/* DELETE trigger on IOServer */
/* default body for tD_IOServer */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insIOServerKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* IOServer Reads data from Topic ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,Topic
      where
        /*  Topic.IOServerKey = deleted.IOServerKey and
            Topic.StorageNodeKey = deleted.StorageNodeKey */
        Topic.IOServerKey = deleted.IOServerKey and
        Topic.StorageNodeKey = deleted.StorageNodeKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE IOServer because Topic exists.'
      goto error
    end


/*  Signal handler for system reinitialization */

   insert into ConfigStatusPending (Type, ObjectKey, Status)
      select 1, IOServerKey, 3 from deleted

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'IOServer' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.IOServerKey, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'IOServerKey', old.IOServerKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'IODriverKey', old.IODriverKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ApplicationName', old.ApplicationName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Path', old.Path
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ComputerName', old.ComputerName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'AltComputerName', old.AltComputerName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'AutoStart', old.AutoStart
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ExeType', old.ExeType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'InitializationStatus', old.InitializationStatus
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ProtocolType', old.ProtocolType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Description', old.Description
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_IOServer on IOServer
  for INSERT
  as
/* INSERT trigger on IOServer */
/* default body for tI_IOServer */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insIOServerKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* IOServerType R/165 IOServer ON CHILD INSERT RESTRICT */
  if
    /* update(ApplicationName) */
    update(ApplicationName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,IOServerType
        where
          /* inserted.ApplicationName = IOServerType.ApplicationName */
          inserted.ApplicationName = IOServerType.ApplicationName
    /* select @nullcnt = count(*) from inserted where
         inserted.ApplicationName is null */
    select @nullcnt = count(*) from inserted where
      inserted.ApplicationName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT IOServer because IOServerType does not exist.'
      goto error
    end
  end




/* Validate the computer names : no \\ */
if exists (select IOServerKey from inserted 
             where ComputerName like '%\%' or AltComputerName like '%\%')
begin
   set @errno = 17036
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg  is NULL
   begin
      set @errmsg = 'Error msg not found - Invalid insert or update. Do not include \\ in machine names.'
   end      
   goto error     
end

if @numrows = 1
begin
/*  Signal handler for system reinitialization */
   insert into ConfigStatusPending (Type, ObjectKey, Status)
      select 1, IOServerKey, 1 from inserted

   update IOServer set Status = 1 where IOServerKey in (select IOServerKey from inserted)

   /* Validation of Primary / ALt Locations */
   if (select UPPER(ComputerName) from inserted) = (select UPPER(AltComputerName) from inserted)
   begin
      set @errno = 17035
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid insert or update, same Primary/Alternate location.'
      end      
      goto error
   end

   /* Validation of IODriverKey for IOServers */
   /* Need to by-pass this logic when inserting the System tags IOServer */
   if exists (select IODriverKey from inserted where IOServerKey > 2 and IODriverKey < 2)
   begin
      set @errno = 17015
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid IOServer insert'
      end      
      goto error
   end

   /* Duplication validation for case sensitive servers */
   if ( select count(UPPER(RTRIM(ios.ComputerName)) + UPPER(RTRIM(ios.ApplicationName))) from IOServer ios, inserted i
        where UPPER(RTRIM(ios.ComputerName)) + UPPER(RTRIM(ios.ApplicationName)) 
             = UPPER(RTRIM(i.ComputerName)) + UPPER(RTRIM(i.ApplicationName)) ) > @numrows
   begin
      set @errno = 17023
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages    where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid IOServer insert or update, combination ComputerName + ApplicationName already exists'
      end      
      goto error
   end

end

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'IOServer' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.IOServerKey, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'IOServerKey', new.IOServerKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageNodeKey', new.StorageNodeKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'IODriverKey', new.IODriverKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ApplicationName', new.ApplicationName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Path', new.Path
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ComputerName', new.ComputerName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'AltComputerName', new.AltComputerName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'AutoStart', new.AutoStart
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ExeType', new.ExeType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'InitializationStatus', new.InitializationStatus
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ProtocolType', new.ProtocolType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Description', new.Description
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.IOServerKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_IOServer on IOServer
  for UPDATE
  as
/* UPDATE trigger on IOServer */
/* default body for tU_IOServer */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insIOServerKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* IODriver gets data from IOServer ON CHILD UPDATE RESTRICT */
  if
    /* update(IODriverKey) or
       update(StorageNodeKey) */
    update(IODriverKey) or
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,IODriver
        where
          /* inserted.IODriverKey = IODriver.IODriverKey and
             inserted.StorageNodeKey = IODriver.StorageNodeKey */
          inserted.IODriverKey = IODriver.IODriverKey and
          inserted.StorageNodeKey = IODriver.StorageNodeKey
    /* select @nullcnt = count(*) from inserted where
         inserted.IODriverKey is null and
         inserted.StorageNodeKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.IODriverKey is null and
      inserted.StorageNodeKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE IOServer because IODriver does not exist.'
      goto error
    end
  end

/* IOServerType R/165 IOServer ON CHILD UPDATE RESTRICT */
  if
    /* update(ApplicationName) */
    update(ApplicationName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,IOServerType
        where
          /* inserted.ApplicationName = IOServerType.ApplicationName */
          inserted.ApplicationName = IOServerType.ApplicationName
    /* select @nullcnt = count(*) from inserted where
         inserted.ApplicationName is null */
    select @nullcnt = count(*) from inserted where
      inserted.ApplicationName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE IOServer because IOServerType does not exist.'
      goto error
    end
  end


/* IOServer Reads data from Topic ON PARENT UPDATE CASCADE */
  if
    /* update(IOServerKey) or
       update(StorageNodeKey) */
    update(IOServerKey) or
    update(StorageNodeKey)
  begin
    if @numrows = 1
    begin
      select @insIOServerKey = inserted.IOServerKey, 
             @insStorageNodeKey = inserted.StorageNodeKey
        from inserted
      update Topic
      set
        /*  Topic.IOServerKey = @insIOServerKey,
            Topic.StorageNodeKey = @insStorageNodeKey */
        Topic.IOServerKey = @insIOServerKey,
        Topic.StorageNodeKey = @insStorageNodeKey
      from Topic,inserted,deleted
      where
        /*  Topic.IOServerKey = deleted.IOServerKey and
            Topic.StorageNodeKey = deleted.StorageNodeKey */
        Topic.IOServerKey = deleted.IOServerKey and
        Topic.StorageNodeKey = deleted.StorageNodeKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade IOServer UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* Validate the computer names : no \\ */
if exists (select IOServerKey from inserted 
             where ComputerName like '%\%' or AltComputerName like '%\%')
begin
   set @errno = 17036
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg  is NULL
   begin
      set @errmsg = 'Error msg not found - Invalid insert or update. Do not include \\ in machine names.'
   end      
   goto error     
end

/* Validation of IODriverKey for IOServers */
/* Need to by-pass this logic when inserting the System tags IOServer */
if update(IODriverKey)
begin
   if exists (select IODriverKey from inserted where IOServerKey > 2 and IODriverKey < 2)
   begin
      set @errno = 17013
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid IOServer update'
      end      
      goto error
   end
end

/* Duplication validation for case sensitive servers */
if not update(Status) and ( select count(UPPER(RTRIM(ios.ComputerName)) + UPPER(RTRIM(ios.ApplicationName))) from IOServer ios, inserted i
     where UPPER(RTRIM(ios.ComputerName)) + UPPER(RTRIM(ios.ApplicationName)) 
          = UPPER(RTRIM(i.ComputerName)) + UPPER(RTRIM(i.ApplicationName)) ) > @numrows
begin
   set @errno = 17023
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg  is NULL
   begin
      set @errmsg = 'Error msg not found - Invalid IOServer insert or update, combination ComputerName + ApplicationName already exists'
   end      
   goto error
end

/*  Signal handler for system reinitialization */
/* start Dynamic Reconfiguration               */
if not update(Status)
begin
   /* Check for ComputerName case sensitivity */
   if exists (select IOServerKey from inserted
                 where UPPER(ComputerName) = UPPER(AltComputerName))
   begin
       goto alt_main_error
   end

   insert into ConfigStatusPending (Type, ObjectKey, Status)
      select 1, i.IOServerKey, 2
         from inserted i, deleted d
            where i.IOServerKey = d.IOServerKey
            and d.Status not in (1, 2)
            and (ISNULL(i.IODriverKey, 99999) <> ISNULL(d.IODriverKey, 99999)
             or  ISNULL(i.ComputerName, 'wasnull') <> ISNULL(d.ComputerName, 'wasnull')
             or  ISNULL(i.AltComputerName, 'wasnull') <> ISNULL(d.AltComputerName, 'wasnull')
             or  ISNULL(i.ApplicationName, 'wasnull') <> ISNULL(d.ApplicationName, 'wasnull')
             or  i.ProtocolType <> d.ProtocolType)

   update IOServer set Status = 2 from IOServer ios, inserted i, deleted d
      where ios.IOServerKey = i.IOServerKey
      and i.IOServerKey = d.IOServerKey
      and d.Status not in (1, 2)
      and (ISNULL(i.IODriverKey, 99999) <> ISNULL(d.IODriverKey, 99999)
       or  ISNULL(i.ComputerName, 'wasnull') <> ISNULL(d.ComputerName, 'wasnull')
       or  ISNULL(i.AltComputerName, 'wasnull') <> ISNULL(d.AltComputerName, 'wasnull')
       or  ISNULL(i.ApplicationName, 'wasnull') <> ISNULL(d.ApplicationName, 'wasnull')
       or  i.ProtocolType <> d.ProtocolType)

   /* Need to flag the Tags affected by this */
   if exists (select i.IOServerKey from inserted i, deleted d
               where i.IOServerKey = d.IOServerKey and i.IODriverKey <> d.IODriverKey)
   begin
      insert into ConfigStatusPending (Type, ObjectKey, Status)
         select 3, t.wwTagKey, 6
            from inserted i, deleted d, Tag t
               where i.IOServerKey = d.IOServerKey
               and   t.IOServerKey = d.IOServerKey
               and   i.IODriverKey <> d.IODriverKey
               and   wwTagKey not in (select ObjectKey from ConfigStatusPending where Type = 3)
  
      update Tag set Status = 2
         from Tag t, inserted i, deleted d
               where i.IOServerKey = d.IOServerKey
               and   t.IOServerKey = d.IOServerKey
               and   i.IODriverKey <> d.IODriverKey
   end
end

/* start of mod tracking */ 
if not update(Status)
begin
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'IOServer' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.IOServerKey, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'IOServerKey', old.IOServerKey, new.IOServerKey
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.IOServerKey <> old.IOServerKey
                       or (new.IOServerKey is NULL and  old.IOServerKey is not NULL)
                       or (old.IOServerKey is NULL and  new.IOServerKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey, new.StorageNodeKey
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StorageNodeKey <> old.StorageNodeKey
                       or (new.StorageNodeKey is NULL and  old.StorageNodeKey is not NULL)
                       or (old.StorageNodeKey is NULL and  new.StorageNodeKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'IODriverKey', old.IODriverKey, new.IODriverKey
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.IODriverKey <> old.IODriverKey
                       or (new.IODriverKey is NULL and  old.IODriverKey is not NULL)
                       or (old.IODriverKey is NULL and  new.IODriverKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ApplicationName', old.ApplicationName, new.ApplicationName
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ApplicationName <> old.ApplicationName
                       or (new.ApplicationName is NULL and  old.ApplicationName is not NULL)
                       or (old.ApplicationName is NULL and  new.ApplicationName is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Path', old.Path, new.Path
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Path <> old.Path
                       or (new.Path is NULL and  old.Path is not NULL)
                       or (old.Path is NULL and  new.Path is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ComputerName', old.ComputerName, new.ComputerName
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ComputerName <> old.ComputerName
                       or (new.ComputerName is NULL and  old.ComputerName is not NULL)
                       or (old.ComputerName is NULL and  new.ComputerName is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'AltComputerName', old.AltComputerName, new.AltComputerName
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.AltComputerName <> old.AltComputerName
                       or (new.AltComputerName is NULL and  old.AltComputerName is not NULL)
                       or (old.AltComputerName is NULL and  new.AltComputerName is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'AutoStart', old.AutoStart, new.AutoStart
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.AutoStart <> old.AutoStart
                       or (new.AutoStart is NULL and  old.AutoStart is not NULL)
                       or (old.AutoStart is NULL and  new.AutoStart is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ExeType', old.ExeType, new.ExeType
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ExeType <> old.ExeType
                       or (new.ExeType is NULL and  old.ExeType is not NULL)
                       or (old.ExeType is NULL and  new.ExeType is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'InitializationStatus', old.InitializationStatus, new.InitializationStatus
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.InitializationStatus <> old.InitializationStatus
                       or (new.InitializationStatus is NULL and  old.InitializationStatus is not NULL)
                       or (old.InitializationStatus is NULL and  new.InitializationStatus is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ProtocolType', old.ProtocolType, new.ProtocolType
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ProtocolType <> old.ProtocolType
                       or (new.ProtocolType is NULL and  old.ProtocolType is not NULL)
                       or (old.ProtocolType is NULL and  new.ProtocolType is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Description', old.Description, new.Description
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Description <> old.Description
                       or (new.Description is NULL and  old.Description is not NULL)
                       or (old.Description is NULL and  new.Description is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Status', old.Status, new.Status
            from inserted new, deleted old, ModLogTable mlt
               where new.IOServerKey = old.IOServerKey
               and   mlt.RowKey = new.IOServerKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Status <> old.Status
                       or (new.Status is NULL and  old.Status is not NULL)
                       or (old.Status is NULL and  new.Status is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
end
/* end of mod tracking */ 

  return

alt_main_error:
      set @errno = 17035
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
         set @errmsg = 'Error msg not found - Invalid insert or update, same Primary/Alternate location.'
      end      
      goto error

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_IOServerType on IOServerType
  for DELETE
  as
/* DELETE trigger on IOServerType */
/* default body for tD_IOServerType */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insApplicationName nvarchar(32),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* IOServerType R/165 IOServer ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,IOServer
      where
        /*  IOServer.ApplicationName = deleted.ApplicationName */
        IOServer.ApplicationName = deleted.ApplicationName
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE IOServerType because IOServer exists.'
      goto error
    end



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'IOServerType' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.ApplicationName, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ApplicationName', old.ApplicationName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Description', old.Description
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ExeName', old.ExeName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Revision', old.Revision
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Platform', old.Platform
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_IOServerType on IOServerType
  for INSERT
  as
/* INSERT trigger on IOServerType */
/* default body for tI_IOServerType */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insApplicationName nvarchar(32),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'IOServerType' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.ApplicationName, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ApplicationName', new.ApplicationName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Description', new.Description
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ExeName', new.ExeName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Revision', new.Revision
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Platform', new.Platform
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.ApplicationName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 
  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_IOServerType on IOServerType
  for UPDATE
  as
/* UPDATE trigger on IOServerType */
/* default body for tU_IOServerType */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insApplicationName nvarchar(32),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* IOServerType R/165 IOServer ON PARENT UPDATE CASCADE */
  if
    /* update(ApplicationName) */
    update(ApplicationName)
  begin
    if @numrows = 1
    begin
      select @insApplicationName = inserted.ApplicationName
        from inserted
      update IOServer
      set
        /*  IOServer.ApplicationName = @insApplicationName */
        IOServer.ApplicationName = @insApplicationName
      from IOServer,inserted,deleted
      where
        /*  IOServer.ApplicationName = deleted.ApplicationName */
        IOServer.ApplicationName = deleted.ApplicationName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade IOServerType UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* start of mod tracking */ 
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'IOServerType' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.ApplicationName, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      if update(ApplicationName)
      begin
         if @numrows = 1  /* We can get a PK mod */
         begin
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'ApplicationName', old.ApplicationName, new.ApplicationName
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.ApplicationName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.ApplicationName <> old.ApplicationName
                             or (new.ApplicationName is NULL and  old.ApplicationName is not NULL)
                             or (old.ApplicationName is NULL and  new.ApplicationName is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'Description', old.Description, new.Description
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.ApplicationName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.Description <> old.Description
                             or (new.Description is NULL and  old.Description is not NULL)
                             or (old.Description is NULL and  new.Description is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'ExeName', old.ExeName, new.ExeName
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.ApplicationName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.ExeName <> old.ExeName
                             or (new.ExeName is NULL and  old.ExeName is not NULL)
                             or (old.ExeName is NULL and  new.ExeName is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'Revision', old.Revision, new.Revision
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.ApplicationName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.Revision <> old.Revision
                             or (new.Revision is NULL and  old.Revision is not NULL)
                             or (old.Revision is NULL and  new.Revision is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'Platform', old.Platform, new.Platform
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.ApplicationName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.Platform <> old.Platform
                             or (new.Platform is NULL and  old.Platform is not NULL)
                             or (old.Platform is NULL and  new.Platform is not NULL))
                     and   mlt.ModTableKey = @mltkey
            
         end
      end
      else
      begin  /* PK columns are still there because of the script template, not an issue */
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ApplicationName', old.ApplicationName, new.ApplicationName
               from inserted new, deleted old, ModLogTable mlt
                  where new.ApplicationName = old.ApplicationName
                  and   mlt.RowKey = new.ApplicationName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ApplicationName <> old.ApplicationName
                          or (new.ApplicationName is NULL and  old.ApplicationName is not NULL)
                          or (old.ApplicationName is NULL and  new.ApplicationName is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Description', old.Description, new.Description
               from inserted new, deleted old, ModLogTable mlt
                  where new.ApplicationName = old.ApplicationName
                  and   mlt.RowKey = new.ApplicationName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Description <> old.Description
                          or (new.Description is NULL and  old.Description is not NULL)
                          or (old.Description is NULL and  new.Description is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ExeName', old.ExeName, new.ExeName
               from inserted new, deleted old, ModLogTable mlt
                  where new.ApplicationName = old.ApplicationName
                  and   mlt.RowKey = new.ApplicationName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ExeName <> old.ExeName
                          or (new.ExeName is NULL and  old.ExeName is not NULL)
                          or (old.ExeName is NULL and  new.ExeName is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Revision', old.Revision, new.Revision
               from inserted new, deleted old, ModLogTable mlt
                  where new.ApplicationName = old.ApplicationName
                  and   mlt.RowKey = new.ApplicationName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Revision <> old.Revision
                          or (new.Revision is NULL and  old.Revision is not NULL)
                          or (old.Revision is NULL and  new.Revision is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Platform', old.Platform, new.Platform
               from inserted new, deleted old, ModLogTable mlt
                  where new.ApplicationName = old.ApplicationName
                  and   mlt.RowKey = new.ApplicationName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Platform <> old.Platform
                          or (new.Platform is NULL and  old.Platform is not NULL)
                          or (old.Platform is NULL and  new.Platform is not NULL))
                  and   mlt.ModTableKey = @mltkey
         
      end
   end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_Limit on Limit for INSERT as
/* Historian INSERT trigger on Limit */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* LimitName describes Limit ON CHILD INSERT RESTRICT */
  if
    /* update(LimitNameKey) */
    update(LimitNameKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,LimitName
        where
          /* inserted.LimitNameKey = LimitName.LimitNameKey */
          inserted.LimitNameKey = LimitName.LimitNameKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT Limit because LimitName does not exist.'
      goto error
    end
  end

  /* Context gives meaning Limit ON CHILD INSERT RESTRICT */
  if
    /* update(ContextKey) */
    update(ContextKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Context
        where
          /* inserted.ContextKey = Context.ContextKey */
          inserted.ContextKey = Context.ContextKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT Limit because Context does not exist.'
      goto error
    end
  end

  /* AnalogTag has Limit ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,AnalogTag
        where
          /* inserted.TagName = AnalogTag.TagName */
          inserted.TagName = AnalogTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT Limit because AnalogTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_Limit on Limit for UPDATE as
/* Historian UPDATE trigger on Limit */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256), 
           @insContextKey int, 
           @insLimitType tinyint, 
           @insValue float(25), 
           @insLimitNameKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* LimitName describes Limit ON CHILD UPDATE RESTRICT */
  if
    /* update(LimitNameKey) */
    update(LimitNameKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,LimitName
        where
          /* inserted.LimitNameKey = LimitName.LimitNameKey */
          inserted.LimitNameKey = LimitName.LimitNameKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Limit because LimitName does not exist.'
      goto error
    end
  end

  /* Context gives meaning Limit ON CHILD UPDATE RESTRICT */
  if
    /* update(ContextKey) */
    update(ContextKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Context
        where
          /* inserted.ContextKey = Context.ContextKey */
          inserted.ContextKey = Context.ContextKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Limit because Context does not exist.'
      goto error
    end
  end

  /* AnalogTag has Limit ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,AnalogTag
        where
          /* inserted.TagName = AnalogTag.TagName */
          inserted.TagName = AnalogTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Limit because AnalogTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_LimitName on LimitName
  for DELETE
  as
/* Historian DELETE trigger on LimitName */
/* default body for tD_LimitName */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insLimitNameKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* LimitName describes Limit ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,Limit
      where
        /*  Limit.LimitNameKey = deleted.LimitNameKey */
        Limit.LimitNameKey = deleted.LimitNameKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE LimitName because Limit exists.'
      goto error
    end



/* Cannot delete the InTouch Limits */
/* will be the first 4 in the list  */
if exists (select LimitNameKey from deleted where LimitNameKey <= 4)
begin
  set @errno = 17060
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Cannot delete the default InTouch Limit Names.'
  end
  goto error  
end

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_LimitName on LimitName
  for UPDATE
  as
/* Historian UPDATE trigger on LimitName */
/* default body for tU_LimitName */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insLimitNameKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* LimitName describes Limit ON PARENT UPDATE CASCADE */
  if
    /* update(LimitNameKey) */
    update(LimitNameKey)
  begin
    if @numrows = 1
    begin
      select @insLimitNameKey = inserted.LimitNameKey
        from inserted
      update Limit
      set
        /*  Limit.LimitNameKey = @insLimitNameKey */
        Limit.LimitNameKey = @insLimitNameKey
      from Limit,inserted,deleted
      where
        /*  Limit.LimitNameKey = deleted.LimitNameKey */
        Limit.LimitNameKey = deleted.LimitNameKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade LimitName UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* Do not allow modifications of the Default InTouch Limits */
if exists (select LimitNameKey from deleted where LimitNameKey <= 4)
begin
  set @errno = 17061
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Cannot update the default InTouch Limit Names.'
  end
  goto error  
end

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_LocalizedText on LocalizedText
  for DELETE
  as
/* ERwin Builtin Wed Jul 13 12:15:38 2005 */
/* DELETE trigger on LocalizedText */
/* default body for tD_LocalizedText */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTextKey int, 
           @insLanguageID int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



  -- This records the type of the first edit action only.
  if not exists (select TextKey from LocalizedText where TextKey = 0)
    and (select TextKey from deleted) <> 0
      insert LocalizedText (TextKey, LanguageID, LocalizedText) values (0, 0, '3')
  else
    if (select LocalizedText from LocalizedText where TextKey = 0) = '0'
      update LocalizedText set LocalizedText = '3'
        where TextKey = 0

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go




create trigger tI_LocalizedText on LocalizedText
  for INSERT
  as
/* ERwin Builtin Wed Jul 13 12:15:38 2005 */
/* INSERT trigger on LocalizedText */
/* default body for tI_LocalizedText */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTextKey int, 
           @insLanguageID int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



  -- This records the type of the first edit action only.
  if not exists (select TextKey from LocalizedText where TextKey = 0)
    insert LocalizedText (TextKey, LanguageID, LocalizedText) values (0, 0, '1')
  else
    if (select LocalizedText from LocalizedText where TextKey = 0) = '0'
      update LocalizedText set LocalizedText = '1'
        where TextKey = 0

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_LocalizedText on LocalizedText
  for UPDATE
  as
/* ERwin Builtin Wed Jul 13 12:15:38 2005 */
/* UPDATE trigger on LocalizedText */
/* default body for tU_LocalizedText */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTextKey int, 
           @insLanguageID int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



  -- This records the type of the first edit action only.
  if not exists (select TextKey from LocalizedText where TextKey = 0)
    insert LocalizedText (TextKey, LanguageID, LocalizedText) values (0, 0, '2')
  else
    if ( ((select LocalizedText from LocalizedText where TextKey = 0) = '0') and 
        ((select TextKey from inserted) <> 0) )
      update LocalizedText set LocalizedText = '2'
        where TextKey = 0

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_ManualAnalogHistory on ManualAnalogHistory for UPDATE as
/* Historian UPDATE trigger on ManualAnalogHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insDateTime datetime, 
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* AnalogTag R/216 ManualAnalogHistory ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,AnalogTag
        where
          /* inserted.TagName = AnalogTag.TagName */
          inserted.TagName = AnalogTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE ManualAnalogHistory because AnalogTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_ManualDiscreteHistory on ManualDiscreteHistory for UPDATE as
/* Historian UPDATE trigger on ManualDiscreteHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insDateTime datetime, 
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* DiscreteTag R/217 ManualDiscreteHistory ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,DiscreteTag
        where
          /* inserted.TagName = DiscreteTag.TagName */
          inserted.TagName = DiscreteTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE ManualDiscreteHistory because DiscreteTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_ManualStringHistory on ManualStringHistory for UPDATE as
/* Historian UPDATE trigger on ManualStringHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insDateTime datetime, 
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* StringTag R/254 ManualStringHistory ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,StringTag
        where
          /* inserted.TagName = StringTag.TagName */
          inserted.TagName = StringTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE ManualStringHistory because StringTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_Message on Message
  for DELETE
  as
/* DELETE trigger on Message */
/* default body for tD_Message */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insMessageKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* Message used by DiscreteTag ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,DiscreteTag
      where
        /*  DiscreteTag.MessageKey = deleted.MessageKey */
        DiscreteTag.MessageKey = deleted.MessageKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE Message because DiscreteTag exists.'
      goto error
    end



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'Message' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.MessageKey, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MessageKey', old.MessageKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.MessageKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Message0', old.Message0
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.MessageKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Message1', old.Message1
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.MessageKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_Message on Message
  for INSERT
  as
/* INSERT trigger on Message */
/* default body for tI_Message */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insMessageKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'Message' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.MessageKey, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MessageKey', new.MessageKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.MessageKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Message0', new.Message0
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.MessageKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Message1', new.Message1
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.MessageKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_Message on Message
  for UPDATE
  as
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insMessageKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* Message used by DiscreteTag ON PARENT UPDATE RESTRICT */
  if
    /* update(MessageKey) */
    update(MessageKey)
  begin
    if exists (
      select * from deleted,DiscreteTag
      where
        /*  DiscreteTag.MessageKey = deleted.MessageKey */
        DiscreteTag.MessageKey = deleted.MessageKey
    )
    begin
      select @errno  = 30005,
             @errmsg = 'Cannot UPDATE Message because DiscreteTag exists.'
      goto error
    end
  end



/* start of mod tracking */ 
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'Message' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.MessageKey, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'MessageKey', old.MessageKey, new.MessageKey
            from inserted new, deleted old, ModLogTable mlt
               where new.MessageKey = old.MessageKey
               and   mlt.RowKey = new.MessageKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.MessageKey <> old.MessageKey
                       or (new.MessageKey is NULL and  old.MessageKey is not NULL)
                       or (old.MessageKey is NULL and  new.MessageKey is not NULL))
                and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Message0', old.Message0, new.Message0
            from inserted new, deleted old, ModLogTable mlt
               where new.MessageKey = old.MessageKey
               and   mlt.RowKey = new.MessageKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Message0 <> old.Message0
                       or (new.Message0 is NULL and  old.Message0 is not NULL)
                       or (old.Message0 is NULL and  new.Message0 is not NULL))
                and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Message1', old.Message1, new.Message1
            from inserted new, deleted old, ModLogTable mlt
               where new.MessageKey = old.MessageKey
               and   mlt.RowKey = new.MessageKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Message1 <> old.Message1
                       or (new.Message1 is NULL and  old.Message1 is not NULL)
                       or (old.Message1 is NULL and  new.Message1 is not NULL))
                and   mlt.ModTableKey = @mltkey
      
   end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_ModLogColumn on ModLogColumn for DELETE as
/* Historian DELETE trigger on ModLogColumn */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


    /* ModLogTable R/275 ModLogColumn ON CHILD DELETE RESTRICT */
    if exists (select * from deleted,ModLogTable
      where
        /* deleted.ModTableKey = ModLogTable.ModTableKey */
        deleted.ModTableKey = ModLogTable.ModTableKey and
        not exists (
          select * from ModLogColumn
          where
            /* ModLogColumn.ModTableKey = ModLogTable.ModTableKey */
            ModLogColumn.ModTableKey = ModLogTable.ModTableKey
        )
    )
    begin
      select @errno  = 30010,
             @errmsg = 'Cannot DELETE last ModLogColumn because ModLogTable exists.'
      goto error
    end


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_ModLogTable on ModLogTable for DELETE as
/* Historian DELETE trigger on ModLogTable */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* ModLogTable R/275 ModLogColumn ON PARENT DELETE CASCADE */
    delete ModLogColumn
      from ModLogColumn,deleted
      where
        /*  ModLogColumn.ModTableKey = deleted.ModTableKey */
        ModLogColumn.ModTableKey = deleted.ModTableKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_PrivateGroupTag on PrivateGroupTag for INSERT as
/* Historian INSERT trigger on PrivateGroupTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* TagRef member of PrivateGroupTag ON CHILD INSERT RESTRICT */
  if
    /* update(wwDomainTagKey) */
    update(wwDomainTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,TagRef
        where
          /* inserted.wwDomainTagKey = TagRef.wwDomainTagKey */
          inserted.wwDomainTagKey = TagRef.wwDomainTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT PrivateGroupTag because TagRef does not exist.'
      goto error
    end
  end

  /* PrivateNameSpace has members PrivateGroupTag ON CHILD INSERT RESTRICT */
  if
    /* update(UserKey) or
       update(NameKey) */
    update(UserKey) or
    update(NameKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,PrivateNameSpace
        where
          /* inserted.UserKey = PrivateNameSpace.UserKey and
             inserted.NameKey = PrivateNameSpace.NameKey */
          inserted.UserKey = PrivateNameSpace.UserKey and
          inserted.NameKey = PrivateNameSpace.NameKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT PrivateGroupTag because PrivateNameSpace does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_PrivateGroupTag on PrivateGroupTag for UPDATE as
/* Historian UPDATE trigger on PrivateGroupTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insNameKey int, 
           @insUserKey int, 
           @inswwDomainTagKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* TagRef member of PrivateGroupTag ON CHILD UPDATE RESTRICT */
  if
    /* update(wwDomainTagKey) */
    update(wwDomainTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,TagRef
        where
          /* inserted.wwDomainTagKey = TagRef.wwDomainTagKey */
          inserted.wwDomainTagKey = TagRef.wwDomainTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE PrivateGroupTag because TagRef does not exist.'
      goto error
    end
  end

  /* PrivateNameSpace has members PrivateGroupTag ON CHILD UPDATE RESTRICT */
  if
    /* update(UserKey) or
       update(NameKey) */
    update(UserKey) or
    update(NameKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,PrivateNameSpace
        where
          /* inserted.UserKey = PrivateNameSpace.UserKey and
             inserted.NameKey = PrivateNameSpace.NameKey */
          inserted.UserKey = PrivateNameSpace.UserKey and
          inserted.NameKey = PrivateNameSpace.NameKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE PrivateGroupTag because PrivateNameSpace does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_PrivateNameSpace on PrivateNameSpace
  for INSERT
  as
/* Historian INSERT trigger on PrivateNameSpace */
/* default body for tI_PrivateNameSpace */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insUserKey int, 
           @insNameKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/*  Allow parentless children if the ParentKey is 0 */
declare @parentkey int
select @parentkey = ParentKey from inserted
if (@parentkey in (0,1)) goto checkname

/* UserDetail owns PrivateNameSpace ON CHILD INSERT RESTRICT */
  if
    /* update(UserKey) */
    update(UserKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,UserDetail
        where
          /* inserted.UserKey = UserDetail.UserKey */
          inserted.UserKey = UserDetail.UserKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT PrivateNameSpace because UserDetail does not exist.'
      goto error
    end
  end

/* PrivateNameSpace R/107 PrivateNameSpace ON CHILD INSERT RESTRICT */
  if
    /* update(UserKey) or
       update(ParentKey) */
    update(UserKey) or
    update(ParentKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,PrivateNameSpace
        where
          /* inserted.UserKey = PrivateNameSpace.UserKey and
             inserted.ParentKey = PrivateNameSpace.NameKey */
          inserted.UserKey = PrivateNameSpace.UserKey and
          inserted.ParentKey = PrivateNameSpace.NameKey
    /* select @nullcnt = count(*) from inserted where
         inserted.UserKey is null and
         inserted.ParentKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.UserKey is null and
      inserted.ParentKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT PrivateNameSpace because PrivateNameSpace does not exist.'
      goto error
    end
  end





checkname:
if @numrows = 1
begin
  if (select count(*) from inserted, PrivateNameSpace where inserted.ParentKey = PrivateNameSpace.ParentKey
            and inserted.Name = PrivateNameSpace.Name
            and inserted.UserKey = PrivateNameSpace.UserKey ) > 1
  begin
    select @errno = 30006
    select @errmsg = 'This name already exists in this group.  The group will not be created' 
    goto error
  end
end

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_PrivateNameSpace on PrivateNameSpace
  for UPDATE
  as
/* Historian UPDATE trigger on PrivateNameSpace */
/* default body for tU_PrivateNameSpace */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insUserKey int, 
           @insNameKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* UserDetail owns PrivateNameSpace ON CHILD UPDATE RESTRICT */
  if
    /* update(UserKey) */
    update(UserKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,UserDetail
        where
          /* inserted.UserKey = UserDetail.UserKey */
          inserted.UserKey = UserDetail.UserKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE PrivateNameSpace because UserDetail does not exist.'
      goto error
    end
  end

/* PrivateNameSpace R/107 PrivateNameSpace ON CHILD UPDATE SET NULL */
  if
    /* update(UserKey) or
       update(ParentKey) */
    update(UserKey) or
    update(ParentKey)
  begin
    update PrivateNameSpace
      set
        /* PrivateNameSpace.UserKey = NULL,
           PrivateNameSpace.ParentKey = NULL */
        PrivateNameSpace.UserKey = NULL,
        PrivateNameSpace.ParentKey = NULL
      from PrivateNameSpace,inserted
      where
        /* PrivateNameSpace.UserKey = inserted.UserKey and
           PrivateNameSpace.NameKey = inserted.NameKey */
        PrivateNameSpace.UserKey = inserted.UserKey and
        PrivateNameSpace.NameKey = inserted.NameKey and 
        not exists (
          select * from PrivateNameSpace
          where
            /* inserted.UserKey = PrivateNameSpace.UserKey and
               inserted.ParentKey = PrivateNameSpace.NameKey */
            inserted.UserKey = PrivateNameSpace.UserKey and
            inserted.ParentKey = PrivateNameSpace.NameKey
        )
  end


/* PrivateNameSpace has members PrivateGroupTag ON PARENT UPDATE CASCADE */
  if
    /* update(UserKey) or
       update(NameKey) */
    update(UserKey) or
    update(NameKey)
  begin
    if @numrows = 1
    begin
      select @insUserKey = inserted.UserKey, 
             @insNameKey = inserted.NameKey
        from inserted
      update PrivateGroupTag
      set
        /*  PrivateGroupTag.UserKey = @insUserKey,
            PrivateGroupTag.NameKey = @insNameKey */
        PrivateGroupTag.UserKey = @insUserKey,
        PrivateGroupTag.NameKey = @insNameKey
      from PrivateGroupTag,inserted,deleted
      where
        /*  PrivateGroupTag.UserKey = deleted.UserKey and
            PrivateGroupTag.NameKey = deleted.NameKey */
        PrivateGroupTag.UserKey = deleted.UserKey and
        PrivateGroupTag.NameKey = deleted.NameKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade PrivateNameSpace UPDATE because more than one row has been affected.'
      goto error
    end
  end


  if (select count(*) from inserted, PrivateNameSpace where inserted.ParentKey = PrivateNameSpace.ParentKey
            and inserted.Name = PrivateNameSpace.Name
            and inserted.UserKey = PrivateNameSpace.UserKey ) > 1
  begin
    select @errno = 30006
    select @errmsg = 'This name already exists in this group.  The group will not be created' 
    goto error
  end

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_PrivateNameSpace on PrivateNameSpace for DELETE as
/* Historian DELETE trigger on PrivateNameSpace */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* PrivateNameSpace has members PrivateGroupTag ON PARENT DELETE CASCADE */
    delete PrivateGroupTag
      from PrivateGroupTag,deleted
      where
        /*  PrivateGroupTag.UserKey = deleted.UserKey and
            PrivateGroupTag.NameKey = deleted.NameKey */
        PrivateGroupTag.UserKey = deleted.UserKey and
        PrivateGroupTag.NameKey = deleted.NameKey

     /* PrivateNameSpace R/107 PrivateNameSpace ON PARENT DELETE CASCADE */
    delete PrivateNameSpace
      from PrivateNameSpace,deleted
      where
        /*  PrivateNameSpace.UserKey = deleted.UserKey and
            PrivateNameSpace.ParentKey = deleted.NameKey */
        PrivateNameSpace.UserKey = deleted.UserKey and
        PrivateNameSpace.ParentKey = deleted.NameKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_PublicGroupTag on PublicGroupTag for INSERT as
/* Historian INSERT trigger on PublicGroupTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* PublicNameSpace has members PublicGroupTag ON CHILD INSERT RESTRICT */
  if
    /* update(NameKey) */
    update(NameKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,PublicNameSpace
        where
          /* inserted.NameKey = PublicNameSpace.NameKey */
          inserted.NameKey = PublicNameSpace.NameKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT PublicGroupTag because PublicNameSpace does not exist.'
      goto error
    end
  end

  /* TagRef member of PublicGroupTag ON CHILD INSERT RESTRICT */
  if
    /* update(wwDomainTagKey) */
    update(wwDomainTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,TagRef
        where
          /* inserted.wwDomainTagKey = TagRef.wwDomainTagKey */
          inserted.wwDomainTagKey = TagRef.wwDomainTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT PublicGroupTag because TagRef does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_PublicGroupTag on PublicGroupTag for UPDATE as
/* Historian UPDATE trigger on PublicGroupTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insNameKey int, 
           @inswwDomainTagKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* PublicNameSpace has members PublicGroupTag ON CHILD UPDATE RESTRICT */
  if
    /* update(NameKey) */
    update(NameKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,PublicNameSpace
        where
          /* inserted.NameKey = PublicNameSpace.NameKey */
          inserted.NameKey = PublicNameSpace.NameKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE PublicGroupTag because PublicNameSpace does not exist.'
      goto error
    end
  end

  /* TagRef member of PublicGroupTag ON CHILD UPDATE RESTRICT */
  if
    /* update(wwDomainTagKey) */
    update(wwDomainTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,TagRef
        where
          /* inserted.wwDomainTagKey = TagRef.wwDomainTagKey */
          inserted.wwDomainTagKey = TagRef.wwDomainTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE PublicGroupTag because TagRef does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_PublicNameSpace on PublicNameSpace
  for INSERT
  as
/* Historian INSERT trigger on PublicNameSpace */
/* default body for tI_PublicNameSpace */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insNameKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/*  Allow parentless children if the ParentKey is 0 */
declare @parentkey int
select @parentkey = ParentKey from inserted
if (@parentkey in (0,-1)) return

/* PublicNameSpace child_of PublicNameSpace ON CHILD INSERT RESTRICT */
  if
    /* update(ParentKey) */
    update(ParentKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,PublicNameSpace
        where
          /* inserted.ParentKey = PublicNameSpace.NameKey */
          inserted.ParentKey = PublicNameSpace.NameKey
    /* select @nullcnt = count(*) from inserted where
         inserted.ParentKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.ParentKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT PublicNameSpace because PublicNameSpace does not exist.'
      goto error
    end
  end




if (select count(*) from inserted) = 1
begin
  if (select count(*) from inserted, PublicNameSpace where inserted.ParentKey = PublicNameSpace.ParentKey
            and inserted.Name = PublicNameSpace.Name ) > 1
  begin
    select @errno = 30006
    select @errmsg = 'This name already exists in this group.  The group will not be created' 
    goto error
  end
end
return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_PublicNameSpace on PublicNameSpace
  for UPDATE
  as
/* Historian UPDATE trigger on PublicNameSpace */
/* default body for tU_PublicNameSpace */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insNameKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* PublicNameSpace child_of PublicNameSpace ON CHILD UPDATE SET NULL */
  if
    /* update(ParentKey) */
    update(ParentKey)
  begin
    update PublicNameSpace
      set
        /* PublicNameSpace.ParentKey = NULL */
        PublicNameSpace.ParentKey = NULL
      from PublicNameSpace,inserted
      where
        /* PublicNameSpace.NameKey = inserted.NameKey */
        PublicNameSpace.NameKey = inserted.NameKey and 
        not exists (
          select * from PublicNameSpace
          where
            /* inserted.ParentKey = PublicNameSpace.NameKey */
            inserted.ParentKey = PublicNameSpace.NameKey
        )
  end


/* PublicNameSpace has members PublicGroupTag ON PARENT UPDATE CASCADE */
  if
    /* update(NameKey) */
    update(NameKey)
  begin
    if @numrows = 1
    begin
      select @insNameKey = inserted.NameKey
        from inserted
      update PublicGroupTag
      set
        /*  PublicGroupTag.NameKey = @insNameKey */
        PublicGroupTag.NameKey = @insNameKey
      from PublicGroupTag,inserted,deleted
      where
        /*  PublicGroupTag.NameKey = deleted.NameKey */
        PublicGroupTag.NameKey = deleted.NameKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade PublicNameSpace UPDATE because more than one row has been affected.'
      goto error
    end
  end


if (select count(*) from inserted) = 1
begin
  if (select count(*) from inserted, PublicNameSpace where inserted.ParentKey = PublicNameSpace.ParentKey
            and inserted.Name = PublicNameSpace.Name ) > 1
  begin
    select @errno = 30006
    select @errmsg = 'This name already exists in this group.  The group will not be created' 
    goto error
  end
end
return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_PublicNameSpace on PublicNameSpace for DELETE as
/* Historian DELETE trigger on PublicNameSpace */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* PublicNameSpace child_of PublicNameSpace ON PARENT DELETE CASCADE */
    delete PublicNameSpace
      from PublicNameSpace,deleted
      where
        /*  PublicNameSpace.ParentKey = deleted.NameKey */
        PublicNameSpace.ParentKey = deleted.NameKey

     /* PublicNameSpace has members PublicGroupTag ON PARENT DELETE CASCADE */
    delete PublicGroupTag
      from PublicGroupTag,deleted
      where
        /*  PublicGroupTag.NameKey = deleted.NameKey */
        PublicGroupTag.NameKey = deleted.NameKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_RateOfChange on RateOfChange for INSERT as
/* Historian INSERT trigger on RateOfChange */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Context R/196 RateOfChange ON CHILD INSERT RESTRICT */
  if
    /* update(ContextKey) */
    update(ContextKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Context
        where
          /* inserted.ContextKey = Context.ContextKey */
          inserted.ContextKey = Context.ContextKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT RateOfChange because Context does not exist.'
      goto error
    end
  end

  /* AnalogTag has RateOfChange ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,AnalogTag
        where
          /* inserted.TagName = AnalogTag.TagName */
          inserted.TagName = AnalogTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT RateOfChange because AnalogTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_RateOfChange on RateOfChange for UPDATE as
/* Historian UPDATE trigger on RateOfChange */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256), 
           @insContextKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Context R/196 RateOfChange ON CHILD UPDATE RESTRICT */
  if
    /* update(ContextKey) */
    update(ContextKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Context
        where
          /* inserted.ContextKey = Context.ContextKey */
          inserted.ContextKey = Context.ContextKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE RateOfChange because Context does not exist.'
      goto error
    end
  end

  /* AnalogTag has RateOfChange ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,AnalogTag
        where
          /* inserted.TagName = AnalogTag.TagName */
          inserted.TagName = AnalogTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE RateOfChange because AnalogTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_ServerList on ServerList for DELETE as
/* Historian DELETE trigger on ServerList */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* ServerList contains TagRef ON PARENT DELETE CASCADE */
    delete TagRef
      from TagRef,deleted
      where
        /*  TagRef.ServerKey = deleted.ServerKey */
        TagRef.ServerKey = deleted.ServerKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_ServerList on ServerList for UPDATE as
/* Historian UPDATE trigger on ServerList */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insServerKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* ServerList contains TagRef ON PARENT UPDATE RESTRICT */
  if
    /* update(ServerKey) */
    update(ServerKey)
  begin
    if exists (
      select * from deleted,TagRef
      where
        /*  TagRef.ServerKey = deleted.ServerKey */
        TagRef.ServerKey = deleted.ServerKey
    )
    begin
      select @errno  = 30005,
             @errmsg = 'Cannot UPDATE ServerList because TagRef exists.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_SnapshotDetail on SnapshotDetail
  for DELETE
  as
/* DELETE trigger on SnapshotDetail */
/* default body for tD_SnapshotDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insStorageSize int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'SnapshotDetail' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.StorageSize, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageSize', old.StorageSize
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'SnapshotSize', old.SnapshotSize
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ImageTime', old.ImageTime
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ThresholdTime', old.ThresholdTime
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_SnapshotDetail on SnapshotDetail
  for INSERT
  as
/* INSERT trigger on SnapshotDetail */
/* default body for tI_SnapshotDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insStorageSize int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'SnapshotDetail' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.StorageSize, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageSize', new.StorageSize
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'SnapshotSize', new.SnapshotSize
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ImageTime', new.ImageTime
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ThresholdTime', new.ThresholdTime
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageSize
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_SnapshotDetail on SnapshotDetail
  for UPDATE
  as
/* UPDATE trigger on SnapshotDetail */
/* default body for tU_SnapshotDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insStorageSize int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* Config Status */
if not update(Status)
begin
   insert into ConfigStatusPending (Type, ObjectKey, Status)
      select 5, i.StorageSize, 2 from inserted i, deleted d
         where i.StorageSize = d.StorageSize
         and   d.Status not in (1,2)
         and   (i.SnapshotSize <> d.SnapshotSize or i.ThresholdTime <> d.ThresholdTime 
            or  i.ImageTime <> d.ImageTime)

   update SnapshotDetail set Status = 2 from SnapshotDetail ss, inserted i, deleted d
      where ss.StorageSize = i.StorageSize
      and  i.StorageSize = d.StorageSize
      and  d.Status not in (1,2)
      and  (i.SnapshotSize <> d.SnapshotSize or i.ThresholdTime <> d.ThresholdTime 
        or  i.ImageTime <> d.ImageTime)
end

/* start of mod tracking */ 
if not update(Status)
begin
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'SnapshotDetail' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.StorageSize, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StorageSize', old.StorageSize, new.StorageSize
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageSize = old.StorageSize
               and   mlt.RowKey = new.StorageSize
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StorageSize <> old.StorageSize
                       or (new.StorageSize is NULL and  old.StorageSize is not NULL)
                       or (old.StorageSize is NULL and  new.StorageSize is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'SnapshotSize', old.SnapshotSize, new.SnapshotSize
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageSize = old.StorageSize
               and   mlt.RowKey = new.StorageSize
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.SnapshotSize <> old.SnapshotSize
                       or (new.SnapshotSize is NULL and  old.SnapshotSize is not NULL)
                       or (old.SnapshotSize is NULL and  new.SnapshotSize is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ImageTime', old.ImageTime, new.ImageTime
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageSize = old.StorageSize
               and   mlt.RowKey = new.StorageSize
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ImageTime <> old.ImageTime
                       or (new.ImageTime is NULL and  old.ImageTime is not NULL)
                       or (old.ImageTime is NULL and  new.ImageTime is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ThresholdTime', old.ThresholdTime, new.ThresholdTime
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageSize = old.StorageSize
               and   mlt.RowKey = new.StorageSize
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ThresholdTime <> old.ThresholdTime
                       or (new.ThresholdTime is NULL and  old.ThresholdTime is not NULL)
                       or (old.ThresholdTime is NULL and  new.ThresholdTime is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Status', old.Status, new.Status
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageSize = old.StorageSize
               and   mlt.RowKey = new.StorageSize
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Status <> old.Status
                       or (new.Status is NULL and  old.Status is not NULL)
                       or (old.Status is NULL and  new.Status is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_SnapshotTag on SnapshotTag for DELETE as
/* Historian DELETE trigger on SnapshotTag */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* SnapshotTag R/225 StringSnapshot ON PARENT DELETE CASCADE */
    delete StringSnapshot
      from StringSnapshot,deleted
      where
        /*  StringSnapshot.SnapshotTagKey = deleted.SnapshotTagKey */
        StringSnapshot.SnapshotTagKey = deleted.SnapshotTagKey

     /* SnapshotTag R/113 DiscreteSnapshot ON PARENT DELETE CASCADE */
    delete DiscreteSnapshot
      from DiscreteSnapshot,deleted
      where
        /*  DiscreteSnapshot.SnapshotTagKey = deleted.SnapshotTagKey */
        DiscreteSnapshot.SnapshotTagKey = deleted.SnapshotTagKey

     /* SnapshotTag R/89 AnalogSnapshot ON PARENT DELETE CASCADE */
    delete AnalogSnapshot
      from AnalogSnapshot,deleted
      where
        /*  AnalogSnapshot.SnapshotTagKey = deleted.SnapshotTagKey */
        AnalogSnapshot.SnapshotTagKey = deleted.SnapshotTagKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_SnapshotTag on SnapshotTag for INSERT as
/* Historian INSERT trigger on SnapshotTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EventTag has SnapshotTag ON CHILD INSERT RESTRICT */
  if
    /* update(EventTagName) */
    update(EventTagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTag
        where
          /* inserted.EventTagName = EventTag.TagName */
          inserted.EventTagName = EventTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT SnapshotTag because EventTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_SnapshotTag on SnapshotTag for UPDATE as
/* Historian UPDATE trigger on SnapshotTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insSnapshotTagKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EventTag has SnapshotTag ON CHILD UPDATE RESTRICT */
  if
    /* update(EventTagName) */
    update(EventTagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTag
        where
          /* inserted.EventTagName = EventTag.TagName */
          inserted.EventTagName = EventTag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SnapshotTag because EventTag does not exist.'
      goto error
    end
  end

  /* Tag linked to SnapshotTag ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SnapshotTag because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_StorageLocation on StorageLocation
  for DELETE
  as
/* DELETE trigger on StorageLocation */
/* default body for tD_StorageLocation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insStorageType int, 
           @insSortOrder int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'StorageLocation' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.StorageType, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageType', old.StorageType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'SortOrder', old.SortOrder
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Path', old.Path
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MaxMBSize', old.MaxMBSize
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MinMBThreshold', old.MinMBThreshold
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MaxAgeThreshold', old.MaxAgeThreshold
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_StorageLocation on StorageLocation
  for INSERT
  as
/* INSERT trigger on StorageLocation */
/* default body for tI_StorageLocation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insStorageType int, 
           @insSortOrder int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* StorageNode stores to StorageLocation ON CHILD INSERT RESTRICT */
  if
    /* update(StorageNodeKey) */
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,StorageNode
        where
          /* inserted.StorageNodeKey = StorageNode.StorageNodeKey */
          inserted.StorageNodeKey = StorageNode.StorageNodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT StorageLocation because StorageNode does not exist.'
      goto error
    end
  end




/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'StorageLocation' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.StorageType, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageType', new.StorageType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'SortOrder', new.SortOrder
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageNodeKey', new.StorageNodeKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Path', new.Path
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MaxMBSize', new.MaxMBSize
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MinMBThreshold', new.MinMBThreshold
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MaxAgeThreshold', new.MaxAgeThreshold
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.StorageType
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_StorageLocation on StorageLocation
  for UPDATE
  as
/* UPDATE trigger on StorageLocation */
/* default body for tU_StorageLocation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insStorageType int, 
           @insSortOrder int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* StorageNode stores to StorageLocation ON CHILD UPDATE RESTRICT */
  if
    /* update(StorageNodeKey) */
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,StorageNode
        where
          /* inserted.StorageNodeKey = StorageNode.StorageNodeKey */
          inserted.StorageNodeKey = StorageNode.StorageNodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE StorageLocation because StorageNode does not exist.'
      goto error
    end
  end




/*  Signal handler for system reinitialization */
/* Config Status */
if not update(Status)
begin
   /* Flag for Circular path modification, needs complete restart */
   if exists (select i.StorageType from inserted i, deleted d
                where i.StorageType = d.StorageType
                and   i.StorageType = 1
                and   i.Path <> d.Path)
   begin
      insert into ConfigStatusPending (Type, ObjectKey, Status)
         values (4, 1, 99)
   end

   insert into ConfigStatusPending (Type, ObjectKey, Status)
      select 4, i.StorageType, 2 from inserted i, deleted d
         where i.StorageType = d.StorageType
         and d.Status not in (1, 2)
         and (i.Path <> d.Path or i.MinMBThreshold <> d.MinMBThreshold
             or i.MaxMBSize <> d.MaxMBSize or i.MaxAgeThreshold <> d.MaxAgeThreshold)

   update StorageLocation set Status = 2 from StorageLocation sl, inserted i, deleted d
      where sl.StorageType = i.StorageType
      and i.StorageType = d.StorageType
      and d.Status not in (1,2)
      and (i.Path <> d.Path or i.MinMBThreshold <> d.MinMBThreshold
           or i.MaxMBSize <> d.MaxMBSize or i.MaxAgeThreshold <> d.MaxAgeThreshold)
end

/* start of mod tracking */ 
if not update(Status)
begin
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'StorageLocation' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.StorageType, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StorageType', old.StorageType, new.StorageType
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageType = old.StorageType
               and   mlt.RowKey = new.StorageType
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StorageType <> old.StorageType
                       or (new.StorageType is NULL and  old.StorageType is not NULL)
                       or (old.StorageType is NULL and  new.StorageType is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'SortOrder', old.SortOrder, new.SortOrder
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageType = old.StorageType
               and   mlt.RowKey = new.StorageType
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.SortOrder <> old.SortOrder
                       or (new.SortOrder is NULL and  old.SortOrder is not NULL)
                       or (old.SortOrder is NULL and  new.SortOrder is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey, new.StorageNodeKey
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageType = old.StorageType
               and   mlt.RowKey = new.StorageType
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StorageNodeKey <> old.StorageNodeKey
                       or (new.StorageNodeKey is NULL and  old.StorageNodeKey is not NULL)
                       or (old.StorageNodeKey is NULL and  new.StorageNodeKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Path', old.Path, new.Path
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageType = old.StorageType
               and   mlt.RowKey = new.StorageType
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Path <> old.Path
                       or (new.Path is NULL and  old.Path is not NULL)
                       or (old.Path is NULL and  new.Path is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'MaxMBSize', old.MaxMBSize, new.MaxMBSize
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageType = old.StorageType
               and   mlt.RowKey = new.StorageType
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.MaxMBSize <> old.MaxMBSize
                       or (new.MaxMBSize is NULL and  old.MaxMBSize is not NULL)
                       or (old.MaxMBSize is NULL and  new.MaxMBSize is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'MinMBThreshold', old.MinMBThreshold, new.MinMBThreshold
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageType = old.StorageType
               and   mlt.RowKey = new.StorageType
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.MinMBThreshold <> old.MinMBThreshold
                       or (new.MinMBThreshold is NULL and  old.MinMBThreshold is not NULL)
                       or (old.MinMBThreshold is NULL and  new.MinMBThreshold is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Status', old.Status, new.Status
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageType = old.StorageType
               and   mlt.RowKey = new.StorageType
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Status <> old.Status
                       or (new.Status is NULL and  old.Status is not NULL)
                       or (old.Status is NULL and  new.Status is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'MaxAgeThreshold', old.MaxAgeThreshold, new.MaxAgeThreshold
            from inserted new, deleted old, ModLogTable mlt
               where new.StorageType = old.StorageType
               and   mlt.RowKey = new.StorageType
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.MaxAgeThreshold <> old.MaxAgeThreshold
                       or (new.MaxAgeThreshold is NULL and  old.MaxAgeThreshold is not NULL)
                       or (old.MaxAgeThreshold is NULL and  new.MaxAgeThreshold is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_StorageNode on StorageNode
  for UPDATE
  as
/* Historian UPDATE trigger on StorageNode */
/* default body for tU_StorageNode */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



if (select DbStatus from inserted) = 2
/* New Db Revision */
begin
   if (select DbStatus from deleted) <> 2
   /* no need to do it if already in re-init needed mode */
   begin
      Update StorageNode
         set DbRevision = DbRevision + 1
   end
end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_StorageNode on StorageNode for DELETE as
/* Historian DELETE trigger on StorageNode */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* StorageNode stores to StorageLocation ON PARENT DELETE CASCADE */
    delete StorageLocation
      from StorageLocation,deleted
      where
        /*  StorageLocation.StorageNodeKey = deleted.StorageNodeKey */
        StorageLocation.StorageNodeKey = deleted.StorageNodeKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_StringSnapshot on StringSnapshot for UPDATE as
/* Historian UPDATE trigger on StringSnapshot */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insSnapshotTagKey int, 
           @insEventLogKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EventHistory R/226 StringSnapshot ON CHILD UPDATE RESTRICT */
  if
    /* update(EventLogKey) */
    update(EventLogKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventHistory
        where
          /* inserted.EventLogKey = EventHistory.EventLogKey */
          inserted.EventLogKey = EventHistory.EventLogKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE StringSnapshot because EventHistory does not exist.'
      goto error
    end
  end

  /* SnapshotTag R/225 StringSnapshot ON CHILD UPDATE RESTRICT */
  if
    /* update(SnapshotTagKey) */
    update(SnapshotTagKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SnapshotTag
        where
          /* inserted.SnapshotTagKey = SnapshotTag.SnapshotTagKey */
          inserted.SnapshotTagKey = SnapshotTag.SnapshotTagKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE StringSnapshot because SnapshotTag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_StringTag on StringTag
  for DELETE
  as
/* DELETE trigger on StringTag */
/* default body for tD_StringTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'StringTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TagName', old.TagName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'MaxLength', old.MaxLength
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'InitialValue', old.InitialValue
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'DoubleByte', old.DoubleByte
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_StringTag on StringTag
  for INSERT
  as
/* INSERT trigger on StringTag */
/* default body for tI_StringTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* Tag  StringTag ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT StringTag because Tag does not exist.'
      goto error
    end
  end




/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'StringTag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TagName', new.TagName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'MaxLength', new.MaxLength
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'InitialValue', new.InitialValue
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'DoubleByte', new.DoubleByte
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_StringTag on StringTag
  for UPDATE
  as
/* UPDATE trigger on StringTag */
/* default body for tU_StringTag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* Tag  StringTag ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE StringTag because Tag does not exist.'
      goto error
    end
  end


/* StringTag R/254 ManualStringHistory ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update ManualStringHistory
      set
        /*  ManualStringHistory.TagName = @insTagName */
        ManualStringHistory.TagName = @insTagName
      from ManualStringHistory,inserted,deleted
      where
        /*  ManualStringHistory.TagName = deleted.TagName */
        ManualStringHistory.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade StringTag UPDATE because more than one row has been affected.'
      goto error
    end
  end



/*  Dynamic Reconfiguration */
/*  We cannot use the if update(XXX) as the config editor sends an update for all columns */
insert into ConfigStatusPending (Type, ObjectKey, Status)
   select 3, t.wwTagKey, 2
      from Tag t, inserted i, deleted d
         where t.TagName = i.TagName
         and i.TagName = d.TagName
         and t.Status not in (1, 2)
         and (i.DoubleByte <> d.DoubleByte or i.MaxLength <> d.MaxLength)

update Tag set Status = 2
   from Tag t, inserted i, deleted d
         where t.TagName = i.TagName
         and i.TagName = d.TagName
         and t.Status not in (1, 2)
         and (i.DoubleByte <> d.DoubleByte or i.MaxLength <> d.MaxLength)
/* End of Dynamic Reconfiguration */

/* start of mod tracking */ 
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'StringTag' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      if update(TagName)
      begin
         if @numrows = 1  /* We can get a PK mod */
         begin
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.TagName <> old.TagName
                             or (new.TagName is NULL and  old.TagName is not NULL)
                             or (old.TagName is NULL and  new.TagName is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'MaxLength', old.MaxLength, new.MaxLength
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.MaxLength <> old.MaxLength
                             or (new.MaxLength is NULL and  old.MaxLength is not NULL)
                             or (old.MaxLength is NULL and  new.MaxLength is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'InitialValue', old.InitialValue, new.InitialValue
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.InitialValue <> old.InitialValue
                             or (new.InitialValue is NULL and  old.InitialValue is not NULL)
                             or (old.InitialValue is NULL and  new.InitialValue is not NULL))
                     and   mlt.ModTableKey = @mltkey
            insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
                select mlt.ModTableKey, 'DoubleByte', old.DoubleByte, new.DoubleByte
                  from inserted new, deleted old, ModLogTable mlt
                     where mlt.RowKey = new.TagName
                     and   mlt.DateTime = @thetime
                     and   mlt.id = @thetable
                     and   (new.DoubleByte <> old.DoubleByte
                             or (new.DoubleByte is NULL and  old.DoubleByte is not NULL)
                             or (old.DoubleByte is NULL and  new.DoubleByte is not NULL))
                     and   mlt.ModTableKey = @mltkey
            
         end
      end
      else
      begin  /* PK columns are still there because of the script template, not an issue */
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TagName <> old.TagName
                          or (new.TagName is NULL and  old.TagName is not NULL)
                          or (old.TagName is NULL and  new.TagName is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'MaxLength', old.MaxLength, new.MaxLength
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.MaxLength <> old.MaxLength
                          or (new.MaxLength is NULL and  old.MaxLength is not NULL)
                          or (old.MaxLength is NULL and  new.MaxLength is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'InitialValue', old.InitialValue, new.InitialValue
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.InitialValue <> old.InitialValue
                          or (new.InitialValue is NULL and  old.InitialValue is not NULL)
                          or (old.InitialValue is NULL and  new.InitialValue is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'DoubleByte', old.DoubleByte, new.DoubleByte
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.DoubleByte <> old.DoubleByte
                          or (new.DoubleByte is NULL and  old.DoubleByte is not NULL)
                          or (old.DoubleByte is NULL and  new.DoubleByte is not NULL))
                  and   mlt.ModTableKey = @mltkey
         
      end
   end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_SummaryData on SummaryData for INSERT as
/* Historian INSERT trigger on SummaryData */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* SummaryTagList Stored for each operation into SummaryData ON CHILD INSERT RESTRICT */
  if
    /* update(SumVarKey) */
    update(SumVarKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SummaryTagList
        where
          /* inserted.SumVarKey = SummaryTagList.SumVarKey */
          inserted.SumVarKey = SummaryTagList.SumVarKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT SummaryData because SummaryTagList does not exist.'
      goto error
    end
  end

  /* SummaryHistory Links operations with their results SummaryData ON CHILD INSERT RESTRICT */
  if
    /* update(LogKey) */
    update(LogKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SummaryHistory
        where
          /* inserted.LogKey = SummaryHistory.LogKey */
          inserted.LogKey = SummaryHistory.LogKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT SummaryData because SummaryHistory does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_SummaryData on SummaryData for UPDATE as
/* Historian UPDATE trigger on SummaryData */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insLogKey int, 
           @insSumVarKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* SummaryTagList Stored for each operation into SummaryData ON CHILD UPDATE RESTRICT */
  if
    /* update(SumVarKey) */
    update(SumVarKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SummaryTagList
        where
          /* inserted.SumVarKey = SummaryTagList.SumVarKey */
          inserted.SumVarKey = SummaryTagList.SumVarKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SummaryData because SummaryTagList does not exist.'
      goto error
    end
  end

  /* SummaryHistory Links operations with their results SummaryData ON CHILD UPDATE RESTRICT */
  if
    /* update(LogKey) */
    update(LogKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SummaryHistory
        where
          /* inserted.LogKey = SummaryHistory.LogKey */
          inserted.LogKey = SummaryHistory.LogKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SummaryData because SummaryHistory does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_SummaryHistory on SummaryHistory
  for INSERT
  as
/* Historian INSERT trigger on SummaryHistory */
/* default body for tI_SummaryHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insLogKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* SummaryOperation R/99 SummaryHistory ON CHILD INSERT RESTRICT */
  if
    /* update(OperationKey) */
    update(OperationKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SummaryOperation
        where
          /* inserted.OperationKey = SummaryOperation.OperationKey */
          inserted.OperationKey = SummaryOperation.OperationKey
    /* select @nullcnt = count(*) from inserted where
         inserted.OperationKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.OperationKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT SummaryHistory because SummaryOperation does not exist.'
      goto error
    end
  end




/* Get the configuration of this particular summary */
/* works only for single insert */

if (select count(*) from inserted) = 1
begin
  declare @duration real,
          @resolution int,
          @timestamp tinyint,
          @calctype varchar(3)
 
  select @duration = so.Duration, @resolution = so.Resolution,
         @timestamp = so.TimeStamp, @calctype = so.CalcType
     from SummaryOperation so, inserted i
        where so.OperationKey = i.OperationKey

  update SummaryHistory set SumDateDuration = @duration, SumDateResolution = @resolution,
             SumDateTimeStamp = @timestamp, SumDateCalcType = @calctype
     from SummaryHistory so, inserted i
        where so.LogKey = i.LogKey                
end
  return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_SummaryHistory on SummaryHistory for DELETE as
/* Historian DELETE trigger on SummaryHistory */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* SummaryHistory Links operations with their results SummaryData ON PARENT DELETE CASCADE */
    delete SummaryData
      from SummaryData,deleted
      where
        /*  SummaryData.LogKey = deleted.LogKey */
        SummaryData.LogKey = deleted.LogKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_SummaryHistory on SummaryHistory for UPDATE as
/* Historian UPDATE trigger on SummaryHistory */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insLogKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* SummaryHistory Links operations with their results SummaryData ON PARENT UPDATE CASCADE */
  if
    /* update(LogKey) */
    update(LogKey)
  begin
    if @numrows = 1
    begin
      select @insLogKey = inserted.LogKey
        from inserted
      update SummaryData
      set
        /*  SummaryData.LogKey = @insLogKey */
        SummaryData.LogKey = @insLogKey
      from SummaryData,inserted,deleted
      where
        /*  SummaryData.LogKey = deleted.LogKey */
        SummaryData.LogKey = deleted.LogKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade SummaryHistory UPDATE because more than one row has been affected.'
      goto error
    end
  end

  /* SummaryOperation R/99 SummaryHistory ON CHILD UPDATE RESTRICT */
  if
    /* update(OperationKey) */
    update(OperationKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SummaryOperation
        where
          /* inserted.OperationKey = SummaryOperation.OperationKey */
          inserted.OperationKey = SummaryOperation.OperationKey
    /* select @nullcnt = count(*) from inserted where
         inserted.OperationKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.OperationKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SummaryHistory because SummaryOperation does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_SummaryOperation on SummaryOperation
  for DELETE
  as
/* Historian DELETE trigger on SummaryOperation */
/* default body for tD_SummaryOperation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insOperationKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* SummaryOperation R/99 SummaryHistory ON PARENT DELETE CASCADE */
    delete SummaryHistory
      from SummaryHistory,deleted
      where
        /*  SummaryHistory.OperationKey = deleted.OperationKey */
        SummaryHistory.OperationKey = deleted.OperationKey

/* SummaryOperation Performs operation on these variables SummaryTagList ON PARENT DELETE CASCADE */
    delete SummaryTagList
      from SummaryTagList,deleted
      where
        /*  SummaryTagList.OperationKey = deleted.OperationKey */
        SummaryTagList.OperationKey = deleted.OperationKey



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'SummaryOperation' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.OperationKey, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'OperationKey', old.OperationKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TagName', old.TagName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'CalcType', old.CalcType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Description', old.Description
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Duration', old.Duration
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Resolution', old.Resolution
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TimeStamp', old.TimeStamp
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Frequency', old.Frequency
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'SourceType', old.SourceType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_SummaryOperation on SummaryOperation
  for INSERT
  as
/* Historian INSERT trigger on SummaryOperation */
/* default body for tI_SummaryOperation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insOperationKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* EventTag R/230 SummaryOperation ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTag
        where
          /* inserted.TagName = EventTag.TagName */
          inserted.TagName = EventTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT SummaryOperation because EventTag does not exist.'
      goto error
    end
  end

/* CalcType Sets type of calculation SummaryOperation ON CHILD INSERT RESTRICT */
  if
    /* update(CalcType) */
    update(CalcType)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,CalcType
        where
          /* inserted.CalcType = CalcType.CalcType */
          inserted.CalcType = CalcType.CalcType
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT SummaryOperation because CalcType does not exist.'
      goto error
    end
  end




/* IndustrialWorkbook 7.0 Support */

DECLARE @TagName nvarchar(256)

if @@ROWCOUNT = 1   -- Single Insert
BEGIN
   update SummaryOperation set Frequency = f.Frequency, SourceType = 'DYN' 
      from TimeDetectorDetail tdd, Frequency f, inserted i  
         where i.TagName = tdd.TagName
         and   tdd.FrequencyID = f.FrequencyID
         and SummaryOperation.TagName = i.TagName
END
ELSE   -- Multiple Insert
BEGIN
   DECLARE sumtaglist CURSOR FOR
        SELECT DISTINCT TagName FROM inserted 
   OPEN sumtaglist
   FETCH NEXT FROM sumtaglist INTO @TagName
   WHILE @@FETCH_STATUS = 0
   BEGIN
      update SummaryOperation set Frequency = f.Frequency, SourceType = 'DYN' 
         from TimeDetectorDetail tdd, Frequency f, inserted i  
            where @TagName = tdd.TagName
            and   tdd.FrequencyID = f.FrequencyID
            and   SummaryOperation.TagName = @TagName
      FETCH NEXT FROM sumtaglist  INTO @TagName
   END
   CLOSE sumtaglist
   DEALLOCATE sumtaglist
END

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'SummaryOperation' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.OperationKey, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'OperationKey', new.OperationKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TagName', new.TagName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'CalcType', new.CalcType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Description', new.Description
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Duration', new.Duration
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Resolution', new.Resolution
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TimeStamp', new.TimeStamp
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Frequency', new.Frequency
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'SourceType', new.SourceType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.OperationKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_SummaryOperation on SummaryOperation
  for UPDATE
  as
/* Historian UPDATE trigger on SummaryOperation */
/* default body for tU_SummaryOperation */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insOperationKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* EventTag R/230 SummaryOperation ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTag
        where
          /* inserted.TagName = EventTag.TagName */
          inserted.TagName = EventTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SummaryOperation because EventTag does not exist.'
      goto error
    end
  end

/* CalcType Sets type of calculation SummaryOperation ON CHILD UPDATE RESTRICT */
  if
    /* update(CalcType) */
    update(CalcType)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,CalcType
        where
          /* inserted.CalcType = CalcType.CalcType */
          inserted.CalcType = CalcType.CalcType
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SummaryOperation because CalcType does not exist.'
      goto error
    end
  end


/* SummaryOperation Performs operation on these variables SummaryTagList ON PARENT UPDATE CASCADE */
  if
    /* update(OperationKey) */
    update(OperationKey)
  begin
    if @numrows = 1
    begin
      select @insOperationKey = inserted.OperationKey
        from inserted
      update SummaryTagList
      set
        /*  SummaryTagList.OperationKey = @insOperationKey */
        SummaryTagList.OperationKey = @insOperationKey
      from SummaryTagList,inserted,deleted
      where
        /*  SummaryTagList.OperationKey = deleted.OperationKey */
        SummaryTagList.OperationKey = deleted.OperationKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade SummaryOperation UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* IndustrialWorkbook 7.0 Support */

DECLARE @TagName nvarchar(256)

if @@ROWCOUNT = 1   -- Single Insert
BEGIN
   update SummaryOperation set Frequency = f.Frequency, SourceType = 'DYN' 
      from TimeDetectorDetail tdd, Frequency f, inserted i  
         where i.TagName = tdd.TagName
         and   tdd.FrequencyID = f.FrequencyID
         and SummaryOperation.TagName = i.TagName
END
ELSE   -- Multiple Insert
BEGIN
   DECLARE taglist CURSOR FOR
        SELECT DISTINCT TagName FROM inserted 
   OPEN taglist
   FETCH NEXT FROM taglist INTO @TagName
   WHILE @@FETCH_STATUS = 0
   BEGIN
      update SummaryOperation set Frequency = f.Frequency, SourceType = 'DYN' 
         from TimeDetectorDetail tdd, Frequency f, inserted i  
            where @TagName = tdd.TagName
            and   tdd.FrequencyID = f.FrequencyID
            and   SummaryOperation.TagName = i.TagName
      FETCH NEXT FROM taglist  INTO @TagName
   END
   CLOSE taglist
   DEALLOCATE taglist
END

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (2,3,6,7))
begin 
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'SummaryOperation' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'U', i.OperationKey, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'OperationKey', old.OperationKey, new.OperationKey
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.OperationKey <> old.OperationKey
                    or (new.OperationKey is NULL and  old.OperationKey is not NULL)
                    or (old.OperationKey is NULL and  new.OperationKey is not NULL))
            and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.TagName <> old.TagName
                    or (new.TagName is NULL and  old.TagName is not NULL)
                    or (old.TagName is NULL and  new.TagName is not NULL))
            and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'CalcType', old.CalcType, new.CalcType
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.CalcType <> old.CalcType
                    or (new.CalcType is NULL and  old.CalcType is not NULL)
                    or (old.CalcType is NULL and  new.CalcType is not NULL))
            and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'Description', old.Description, new.Description
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.Description <> old.Description
                    or (new.Description is NULL and  old.Description is not NULL)
                    or (old.Description is NULL and  new.Description is not NULL))
            and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'Duration', old.Duration, new.Duration
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.Duration <> old.Duration
                    or (new.Duration is NULL and  old.Duration is not NULL)
                    or (old.Duration is NULL and  new.Duration is not NULL))
            and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'Resolution', old.Resolution, new.Resolution
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.Resolution <> old.Resolution
                    or (new.Resolution is NULL and  old.Resolution is not NULL)
                    or (old.Resolution is NULL and  new.Resolution is not NULL))
            and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'TimeStamp', old.TimeStamp, new.TimeStamp
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.TimeStamp <> old.TimeStamp
                    or (new.TimeStamp is NULL and  old.TimeStamp is not NULL)
                    or (old.TimeStamp is NULL and  new.TimeStamp is not NULL))
            and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'Frequency', old.Frequency, new.Frequency
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.Frequency <> old.Frequency
                    or (new.Frequency is NULL and  old.Frequency is not NULL)
                    or (old.Frequency is NULL and  new.Frequency is not NULL))
            and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
       select mlt.ModTableKey, 'SourceType', old.SourceType, new.SourceType
         from inserted new, deleted old, ModLogTable mlt
            where new.OperationKey = old.OperationKey
            and   mlt.RowKey = new.OperationKey
            and   mlt.DateTime = @thetime
            and   mlt.id = @thetable
            and   (new.SourceType <> old.SourceType
                    or (new.SourceType is NULL and  old.SourceType is not NULL)
                    or (old.SourceType is NULL and  new.SourceType is not NULL))
            and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_SummaryTagList on SummaryTagList for DELETE as
/* Historian DELETE trigger on SummaryTagList */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* SummaryTagList Stored for each operation into SummaryData ON PARENT DELETE CASCADE */
    delete SummaryData
      from SummaryData,deleted
      where
        /*  SummaryData.SumVarKey = deleted.SumVarKey */
        SummaryData.SumVarKey = deleted.SumVarKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_SummaryTagList on SummaryTagList for INSERT as
/* Historian INSERT trigger on SummaryTagList */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Tag to be summarized  listed in SummaryTagList ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT SummaryTagList because Tag does not exist.'
      goto error
    end
  end

  /* SummaryOperation Performs operation on these variables SummaryTagList ON CHILD INSERT RESTRICT */
  if
    /* update(OperationKey) */
    update(OperationKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SummaryOperation
        where
          /* inserted.OperationKey = SummaryOperation.OperationKey */
          inserted.OperationKey = SummaryOperation.OperationKey
    /* select @nullcnt = count(*) from inserted where
         inserted.OperationKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.OperationKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT SummaryTagList because SummaryOperation does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_SummaryTagList on SummaryTagList for UPDATE as
/* Historian UPDATE trigger on SummaryTagList */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insSumVarKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* SummaryTagList Stored for each operation into SummaryData ON PARENT UPDATE CASCADE */
  if
    /* update(SumVarKey) */
    update(SumVarKey)
  begin
    if @numrows = 1
    begin
      select @insSumVarKey = inserted.SumVarKey
        from inserted
      update SummaryData
      set
        /*  SummaryData.SumVarKey = @insSumVarKey */
        SummaryData.SumVarKey = @insSumVarKey
      from SummaryData,inserted,deleted
      where
        /*  SummaryData.SumVarKey = deleted.SumVarKey */
        SummaryData.SumVarKey = deleted.SumVarKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade SummaryTagList UPDATE because more than one row has been affected.'
      goto error
    end
  end

  /* Tag to be summarized  listed in SummaryTagList ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SummaryTagList because Tag does not exist.'
      goto error
    end
  end

  /* SummaryOperation Performs operation on these variables SummaryTagList ON CHILD UPDATE RESTRICT */
  if
    /* update(OperationKey) */
    update(OperationKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,SummaryOperation
        where
          /* inserted.OperationKey = SummaryOperation.OperationKey */
          inserted.OperationKey = SummaryOperation.OperationKey
    /* select @nullcnt = count(*) from inserted where
         inserted.OperationKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.OperationKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE SummaryTagList because SummaryOperation does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_SystemParameter on SystemParameter
  for DELETE
  as
/* DELETE trigger on SystemParameter */
/* default body for tD_SystemParameter */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insName nvarchar(50),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* Check that user does not delete critical parameter */
if (select count(Name) from deleted where Name in
         ( 'AIAutoResize'              , 'AIResizeInterval'          ,
           'AllowOriginals'            , 'AutoStart'                 ,
           'QualityRule'               , 'TimeStampRule'             ,
           'DatabaseVersion'           , 'DataImportPath'            ,
           'EventStorageDuration'      , 'HeadroomAnalog2'           ,
           'HeadroomAnalog4'           , 'HeadroomAnalog8'           ,
           'HeadroomDiscrete'          , 'HeadroomString'            ,
           'HistoryCacheSize'          , 'HistoryDaysAlwaysCached'   ,
           'HoursPerBlock'             , 'InterpolationTypeInteger'  ,
           'InterpolationTypeReal'     , 'LicenseTagCount'           ,
           'LicenseRemoteIDASCount',
           'LogPath'                   , 'RealTimeWindow'            ,
           'ModLogTrackingStatus'      , 'SuiteLinkTimeSyncInterval' ,
           'SummaryStorageDuration'    , 'SysPerfTags'               ,
           'SystemVersion'             , 'HistorianVersion'          ,
           'ConfigEditorVersion',
           'TimeSyncIODrivers'         , 'TimeSyncMaster')) > 0
begin
   goto invaliddelete
end

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'SystemParameter' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.Name, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Name', old.Name
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Value', old.Value
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Editable', old.Editable
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Description', old.Description
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return

invaliddelete:
    set @errno = 17030
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
    if @errmsg  is NULL
    begin
       set @errmsg = 'Error msg not found - Invalid SystemParameter Delete: Cannot delete Historian System Parameter.'
    end
    goto error

error:
    raiserror @errno @errmsg
    rollback transaction
end
go



create trigger tI_SystemParameter on SystemParameter
  for INSERT
  as
/* INSERT trigger on SystemParameter */
/* default body for tI_SystemParameter */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insName nvarchar(50),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'SystemParameter' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.Name, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Name', new.Name
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Value', new.Value
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Editable', new.Editable
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Description', new.Description
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.Name
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_SystemParameter on SystemParameter
  for UPDATE
  as
/* UPDATE trigger on SystemParameter */
/* default body for tU_SystemParameter */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insName nvarchar(50),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* Allow only Updates on 1 row at the time */
/* Unless it is a Status Update            */
/* Because of various validation rules     */
if not update(Status)
begin
   if @numrows > 1
   begin
     goto nomultipleupdate
   end
end

/* Do not allow update of Name column */
if update(Name)
begin
   goto noupdatename
end

/* Some value validation */
if not update(Status)
begin
   if @numrows = 1
   begin
      if update(Value)
      begin
         if (select Name from inserted) = 'ModLogTrackingStatus'
         begin
            if (select convert(int,Value) from inserted) not in (0,1,2,3,4,5,6,7)
            begin
               goto invalidvalue
            end
         end
         else
         /* Check computer names: no \\ */
         if (select Name from inserted) = 'TimeSyncMaster'
         begin
            if exists (select Value from inserted where convert(nvarchar(30), Value) like '%\%')
               begin
                  set @errno = 17036
                  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
                  if @errmsg  is NULL
                  begin
                     set @errmsg = 'Error msg not found - Invalid insert or update. Do not include \\ in machine names.'
                  end      
                  goto error     
               end
         end
         else
         /* Check that we have a valid History Block Duration */
         if (select Name from inserted) = 'HoursPerBlock'
         begin
            if (select convert(real,Value) from inserted) not in (1,2,3,4,6,8,12,24)
            begin
               goto invalidvalue
            end
         end
         else
         /* Check that we have a valid RealTimeWindow duration */
         if (select Name from inserted) = 'RealTimeWindow'
         begin
            if (select convert(int,Value) from inserted) < 0
            begin
               goto invalidvalue
            end
            if (select convert(int,Value) from inserted) > 300
            begin
               goto invalidvalue
            end
            if ((select convert(int,Value) from inserted) % 30) > 0
            begin
               goto invalidvalue
            end
         end
         else
         /* Bit type parameters */
         if (select Name from inserted) in ('AIAutoResize',
                   'TimeSyncIODrivers', 'SysPerfTags', 'AutoStart', 'AllowOriginals',
                   'QualityRule', 'TimeStampRule',
                   'InterpolationTypeInteger', 'InterpolationTypeReal')
         begin
            if (select convert(int,Value) from inserted) not in (0,1)
            begin
               goto invalidvalue
            end
         end
         else
         /* Headroom parameters */
         if (select Name from inserted) like 'Headroom%'
         begin
            if (select convert(int, Value) from inserted) < 0
            begin
               goto invalidvalue
            end
         end
         else
         /* >= 0 Numbers */
         if (select Name from inserted) in ('EventStorageDuration',
                   'SummaryStorageDuration', 'SuiteLinkTimeSyncInterval',
                   'HistoryCacheSize', 'HistoryDaysAlwaysCached')
         begin
            if (select convert(int, Value) from inserted) < 0
            begin
               goto invalidvalue
            end
         end
         else
         /* > 0 Numbers */
         if (select Name from inserted) in ('AIResizeInterval')
         begin
            if (select convert(int, Value) from inserted) <= 0
            begin
               goto invalidvalue
            end
         end
         else                         
         /* License tag count validation */
         if (select Name from inserted) = 'LicenseTagCount'
         begin
            /* Let's check if we can enable some unlicensed tags */
            declare @allowedtags int
            select @allowedtags = convert(int, Value) from inserted

            declare @previousallowedtags int
            select @previousallowedtags = convert(int, Value) from deleted

            declare @tagkey int
            declare @enabletagfrom int

            if @allowedtags > @previousallowedtags  -- New license increased tag count
                -- Check if we were in license violation
               and ((select count(wwTagKey) from Tag where TagType <> 5
                      and IOServerKey <> 1) > @previousallowedtags)
            begin
               /* We can enable some tags */
               declare csrTags scroll cursor for
                  select wwTagKey from Tag
                     where IOServerKey <> 1 and TagType <> 5
                  order by wwTagKey
                  for read only
               open csrTags

               set @previousallowedtags = @previousallowedtags + 1 -- next tag to enable

               fetch absolute @previousallowedtags from csrTags into @tagkey

               /* That the tag we can enable from */
               set @enabletagfrom = @tagkey

               while @previousallowedtags < @allowedtags and @@FETCH_STATUS = 0
               begin
                  set @previousallowedtags = @previousallowedtags + 1
                  fetch next from csrTags into @tagkey 
               end
               /* the last @tagkey is the key we can enable to */
               close csrTags
               deallocate csrTags

               /* Now enable the tags */
               declare @AffectedTagkeys table ( wwTagKey int NOT NULL )

               insert @AffectedTagkeys(wwTagKey)
                 select wwTagKey from Tag
                   where wwTagKey between @enabletagfrom and @tagkey
                   and IOServerKey <> 1 and TagType <> 5
                   and wwTagKey not in
                   (select ObjectKey from ConfigStatusSnapshot where Type = 3 and Status = 1)

               update Tag set Status = 1 
                 where wwTagKey in (select wwTagKey from @AffectedTagkeys)

               insert ConfigStatusPending (Type, ObjectKey, Status)
                 select 3, wwTagKey, 1 from @AffectedTagkeys
            end
            else /* perhaps the License Tag count was reduced... */
            if @allowedtags < @previousallowedtags
               -- Check if we will be in license violation
                 and ((select count(wwTagKey) from Tag where TagType <> 5
                         and IOServerKey <> 1) > @allowedtags)
            begin
               /* We disable some tags */
               declare csrTags scroll cursor for
                  select wwTagKey from Tag
                     where IOServerKey <> 1 and TagType <> 5
                  order by wwTagKey
                  for read only
               open csrTags

               set @allowedtags = @allowedtags + 1 -- first tag to disable

               fetch absolute @allowedtags from csrTags into @tagkey
               /* That the wwTagkey we disable from */

               close csrTags
               deallocate csrTags
               
               insert ConfigStatusPending (Type, ObjectKey, Status)
                  select 3, wwTagKey, 3 from Tag
                     where wwTagKey >= @tagkey
                     and IOServerKey <> 1 and TagType <> 5

               /* Now remove any insert/update from previous mods  */
               /* Found that it was a better option than a trigger */
               /* on the ConfigStatusPending table                 */ 
               delete ConfigStatusPending
                  from ConfigStatusPending c, Tag t
                    where t.wwTagKey = c.ObjectKey
                    and   c.Type = 3
                    and   c.Status in (1,2)  -- insert / mod
                    and   c.ObjectKey >= @tagkey
                    and   t.IOServerKey <> 1
                    and   t.TagType <> 5
            end
         end
         else                         
         /* License IDAS count validation */
         if (select Name from inserted) = 'LicenseRemoteIDASCount'
         begin
            /* Let's check if we can enable some unlicensed remote IDAS */
            declare @sysparam sql_variant
            declare @sysparamstring nvarchar(20)
            declare @allowedidas int

            select @sysparam = Value from inserted
            select @sysparamstring = convert(nvarchar(20), @sysparam)

            set @allowedidas = 
            case lower(@sysparamstring)
              when N'none (unlicensed)' then 0
              when N'unlimited' then 65536
              else 
                case sql_variant_property(@sysparam, 'BaseType')
                  when 'int' then convert(int, @sysparamstring)
                  else 0
                end
            end

            declare @previousallowedidas int
            select @sysparam = Value from deleted
            select @sysparamstring = convert(nvarchar(20), @sysparam)

            set @previousallowedidas = 
            case lower(@sysparamstring)
              when N'none (unlicensed)' then 0
              when N'unlimited' then 65536
              else 
                case sql_variant_property(@sysparam, 'BaseType')
                  when 'int' then convert(int, @sysparamstring)
                  else 0
                end
            end

            declare @servername sysname
            declare @idaskey int
            declare @enableidasfrom int
            select @servername = ComputerName from ServerList

            if @allowedidas > @previousallowedidas  -- New license increased IDAS count
                -- Check if we were in license violation
               and ((select count(IODriverKey) from IODriver where IODriverKey >= 2
                      and upper(ComputerName) <> upper(@servername)) > @previousallowedidas)
            begin
               /* We can enable some IDAS */
               declare csrIDAS scroll cursor for
                  select IODriverKey from IODriver where IODriverKey >= 2
                     and upper(ComputerName) <> upper(@servername)
                  order by IODriverKey
               open csrIDAS

               set @previousallowedidas = @previousallowedidas + 1 -- next IDAS to enable

               fetch absolute @previousallowedidas from csrIDAS into @idaskey

               /* That the IDAS we can enable from */
               set @enableidasfrom = @idaskey

               while @previousallowedidas < @allowedidas and @@FETCH_STATUS = 0
               begin
                  set @previousallowedidas = @previousallowedidas + 1
                  fetch next from csrIDAS into @idaskey 
               end
               /* the last @idaskey is the key we can enable to */
               close csrIDAS
               deallocate csrIDAS

               /* Now enable the IDAS */
               declare @AffectedIODriverKeys table ( IODriverKey int NOT NULL )

               insert @AffectedIODriverKeys(IODriverKey)
                 select IODriverKey from IODriver
                   where IODriverKey between @enableidasfrom and @idaskey
                   and upper(ComputerName) <> upper(@servername)
                   and IODriverKey not in
                   (select ObjectKey from ConfigStatusSnapshot where Type = 0 and Status = 1)

               update IODriver set Status = 1 
                 where IODriverKey in (select IODriverKey from @AffectedIODriverKeys)

               insert ConfigStatusPending (Type, ObjectKey, Status)
                 select 0, IODriverKey, 1 from @AffectedIODriverKeys
            end
            else /* perhaps the License IDAS count was reduced... */
            if @allowedidas < @previousallowedidas
               -- Check if we will be in license violation
                 and ((select count(IODriverKey) from IODriver where IODriverKey >= 2
                        and upper(ComputerName) <> upper(@servername)) > @allowedidas)
            begin
               /* We disable some IDAS */
               declare csrIDAS scroll cursor for
                  select IODriverKey from IODriver where IODriverKey >= 2
                     and upper(ComputerName) <> upper(@servername)
                  order by IODriverKey
               open csrIDAS

               set @allowedidas = @allowedidas + 1 -- first IDAS to disable

               fetch absolute @allowedidas from csrIDAS into @idaskey
               /* That the IODriverKey we disable from */

               close csrIDAS
               deallocate csrIDAS
               
               insert ConfigStatusPending (Type, ObjectKey, Status)
                  select 0, IODriverKey, 3 from IODriver
                     where IODriverKey >= @idaskey
                     and upper(ComputerName) <> upper(@servername)

               /* Now remove any insert/update from previous mods  */
               /* Found that it was a better option than a trigger */
               /* on the ConfigStatusPending table                 */ 
               delete ConfigStatusPending
                  from ConfigStatusPending c, IODriver i
                    where i.IODriverKey = c.ObjectKey
                    and   c.Type = 0
                    and   c.Status in (1,2)  -- insert / mod
                    and   c.ObjectKey >= @idaskey
                    and upper(i.ComputerName) <> upper(@servername)
            end
         end
      end
   end
end

/* Config Status */
if not update(Status)
begin
   declare @dstringval sql_variant, @istringval sql_variant
   if @numrows = 1
   begin
      /* Want to be sure that values were changed. Update(***) not good enough */
      select @dstringval = Value from deleted
      select @istringval = Value from inserted

      /* Need to overide the NULL value of nullable column */
      if @dstringval is NULL set @dstringval = 'was NULL'
      if @istringval is NULL set @istringval = 'was NULL'

      if (select Name from deleted) in
         ('AIAutoResize', 'AIResizeInterval',
          'HoursPerBlock', 'SuiteLinkTimeSyncInterval',
          'TimeSyncMaster', 'TimeSyncIODrivers', 'SysPerfTags',
          'AllowOriginals', 'AutoStart',
          -- new parameters
          'QualityRule', 'HistoryCacheSize', 'HistoryDaysAlwaysCached',
          'InterpolationTypeInteger', 'InterpolationTypeReal',
          'TimeStampRule', 'RealTimeWindow', 'ModLogTrackingStatus')
         or (select Name from deleted) like 'Headroom%'
      begin
         if (@dstringval <> @istringval)
         begin
            if (select t.Status from SystemParameter t, inserted i
                   where t.Name = i.Name) not in (1, 2)
            begin
               insert into ConfigStatusPending (Type, ObjectKey, Status)
                  values (6, -1, 2) 

               update SystemParameter set Status = 2 from SystemParameter, inserted
                 where SystemParameter.Name = inserted.Name
            end

            if (select Name from deleted) = 'AutoStart'
            begin
               if @istringval = '1'
               begin
                  exec master..xp_SetAutoStart 1
               end
               else
               if @istringval = '0'
               begin
                  exec master..xp_SetAutoStart 0
               end
            end  
         end 
      end
   end
end

/* start of mod tracking */ 
if not update(Status)
begin
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   /* CR 20943- 21175 need to catch ALL changes to mod tracking param */ 
      OR exists (select i.Value   
         from inserted i, deleted d 
            where i.Name  =  d.Name      
              and i.Name  =  'ModLogTrackingStatus'
              and i.Value <> d.Value) 
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
           where Name =  'SystemParameter' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.Name, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Name', old.Name, new.Name
            from inserted new, deleted old, ModLogTable mlt
               where new.Name = old.Name
               and   mlt.RowKey = new.Name
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Name <> old.Name
                       or (new.Name is NULL and  old.Name is not NULL)
                       or (old.Name is NULL and  new.Name is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Value', old.Value, new.Value
            from inserted new, deleted old, ModLogTable mlt
               where new.Name = old.Name
               and   mlt.RowKey = new.Name
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Value <> old.Value
                       or (new.Value is NULL and  old.Value is not NULL)
                       or (old.Value is NULL and  new.Value is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Editable', old.Editable, new.Editable
            from inserted new, deleted old, ModLogTable mlt
               where new.Name = old.Name
               and   mlt.RowKey = new.Name
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Editable <> old.Editable
                       or (new.Editable is NULL and  old.Editable is not NULL)
                       or (old.Editable is NULL and  new.Editable is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Description', old.Description, new.Description
            from inserted new, deleted old, ModLogTable mlt
               where new.Name = old.Name
               and   mlt.RowKey = new.Name
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Description <> old.Description
                       or (new.Description is NULL and  old.Description is not NULL)
                       or (old.Description is NULL and  new.Description is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Status', old.Status, new.Status
            from inserted new, deleted old, ModLogTable mlt
               where new.Name = old.Name
               and   mlt.RowKey = new.Name
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Status <> old.Status
                       or (new.Status is NULL and  old.Status is not NULL)
                       or (old.Status is NULL and  new.Status is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
end
/* end of mod tracking */ 

  return

invalidvalue:
    set @errno = 17005
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
    if @errmsg  is NULL
    begin
       set @errmsg = 'Error msg not found - Invalid SystemParameter update: value not allowed.'
    end
    goto error

nomultipleupdate:
    set @errno = 17012
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
    if @errmsg  is NULL
    begin
       set @errmsg = 'Error msg not found - Invalid SystemParameter update: only single row updates are permitted.'
    end
    goto error

noupdatename:
    set @errno = 17024
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
    if @errmsg  is NULL
    begin
       set @errmsg = 'Error msg not found - Invalid SystemParameter update: Name column cannot be updated.'
    end
    goto error

error:
    raiserror @errno @errmsg
    rollback transaction
end
go




create trigger tD_Tag on Tag
  for DELETE
  as
/* DELETE trigger on Tag */
/* default body for tD_Tag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* Tag seen_in WideTableDictionary ON PARENT DELETE CASCADE */
    delete WideTableDictionary
      from WideTableDictionary,deleted
      where
        /*  WideTableDictionary.TagName = deleted.TagName */
        WideTableDictionary.TagName = deleted.TagName

/* Tag equivalent to TagRef ON PARENT DELETE CASCADE */
    delete TagRef
      from TagRef,deleted
      where
        /*  TagRef.TagName = deleted.TagName */
        TagRef.TagName = deleted.TagName

/* Tag to be summarized  listed in SummaryTagList ON PARENT DELETE CASCADE */
    delete SummaryTagList
      from SummaryTagList,deleted
      where
        /*  SummaryTagList.TagName = deleted.TagName */
        SummaryTagList.TagName = deleted.TagName

/* Tag linked to SnapshotTag ON PARENT DELETE CASCADE */
    delete SnapshotTag
      from SnapshotTag,deleted
      where
        /*  SnapshotTag.TagName = deleted.TagName */
        SnapshotTag.TagName = deleted.TagName

/* Tag  BlobTag ON PARENT DELETE CASCADE */
    delete BlobTag
      from BlobTag,deleted
      where
        /*  BlobTag.TagName = deleted.TagName */
        BlobTag.TagName = deleted.TagName

/* Tag  EnumeratedTag ON PARENT DELETE CASCADE */
    delete EnumeratedTag
      from EnumeratedTag,deleted
      where
        /*  EnumeratedTag.TagName = deleted.TagName */
        EnumeratedTag.TagName = deleted.TagName

/* Tag  EventTag ON PARENT DELETE CASCADE */
    delete EventTag
      from EventTag,deleted
      where
        /*  EventTag.TagName = deleted.TagName */
        EventTag.TagName = deleted.TagName

/* Tag  ComplexTag ON PARENT DELETE CASCADE */
    delete ComplexTag
      from ComplexTag,deleted
      where
        /*  ComplexTag.TagName = deleted.TagName */
        ComplexTag.TagName = deleted.TagName

/* Tag  StringTag ON PARENT DELETE CASCADE */
    delete StringTag
      from StringTag,deleted
      where
        /*  StringTag.TagName = deleted.TagName */
        StringTag.TagName = deleted.TagName

/* Tag  DiscreteTag ON PARENT DELETE CASCADE */
    delete DiscreteTag
      from DiscreteTag,deleted
      where
        /*  DiscreteTag.TagName = deleted.TagName */
        DiscreteTag.TagName = deleted.TagName

/* Tag  AnalogTag ON PARENT DELETE CASCADE */
    delete AnalogTag
      from AnalogTag,deleted
      where
        /*  AnalogTag.TagName = deleted.TagName */
        AnalogTag.TagName = deleted.TagName


/*  Signal handler for system reinitialization */
declare @TagType int
select @TagType = TagType from deleted 
if (@TagType in (1,2,3,4,7,9) )  /* Analog, Discrete, String, Blob or Enum */
begin 
  /* Update InTouch tags tracking */
  update InTouchSpecific set InInSQL = 0 where TagName in (select TagName from deleted) 

  /* List mod in ConfigStatus */
  insert into ConfigStatusPending (Type, ObjectKey, Status)
    select 3, wwTagKey, 3 from deleted

  /* Now remove any insert/update from previous mods  */
  /* Found that it was a better option than a trigger */
  /* on the ConfigStatus pending table                */ 
  delete ConfigStatusPending
     from ConfigStatusPending c, deleted t
     where t.wwTagKey = c.ObjectKey
     and   c.Type = 3
     and   c.Status in (1,2)  -- insert / mod
end

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'Tag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TagName', old.TagName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'IOServerKey', old.IOServerKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'wwTagKey', old.wwTagKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TopicKey', old.TopicKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Description', old.Description
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'AcquisitionType', old.AcquisitionType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageType', old.StorageType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'AcquisitionRate', old.AcquisitionRate
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageRate', old.StorageRate
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ItemName', old.ItemName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TagType', old.TagType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TimeDeadband', old.TimeDeadband
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'DateCreated', old.DateCreated
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'CreatedBy', old.CreatedBy
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'CurrentEditor', old.CurrentEditor
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'SamplesInActiveImage', old.SamplesInActiveImage
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'AIRetrievalMode', old.AIRetrievalMode
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'CalculatedAISamples', old.CalculatedAISamples
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ServerTimeStamp', old.ServerTimeStamp
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'DeadbandType', old.DeadbandType
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'CEVersion', old.CEVersion
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
   
end
/* end of mod tracking */ 

/* Check if there were tags in License Violation */
/* May be some can now be enabled.               */
declare @licensecheck int
declare @allowedtags  int

/* Get the License count */
set @allowedtags = (select convert(int, Value) from SystemParameter
                     where [Name] = 'LicenseTagCount')

/* Get what is there after the delete */
set @licensecheck = (select dbo.faaLicensedTagTotal(0))
/* Add the delete tags */
set @licensecheck = @licensecheck +
         (select count(TagName) from deleted where TagType <> 5
                      and IOServerKey <> 1)

/* How many tags were in violation */
set @licensecheck = @licensecheck - @allowedtags

if (@licensecheck > 0) -- System was in license Violation
begin
  /* We can enable as many tags which were not loaded */
  /* because of the license violation                 */
  declare @tagkey int
  declare @rowcount int
  set @rowcount = 1

  declare tags scroll cursor for
      select wwTagKey from Tag
         where IOServerKey <> 1 and TagType <> 5
      union
      select wwTagKey from deleted
         where IOServerKey <> 1 and TagType <> 5
      order by wwTagKey
    for read only

  open tags
  set @allowedtags = @allowedtags + 1 -- next tag to enable

  fetch absolute @allowedtags from tags into @tagkey

  while (@rowcount <= @licensecheck and @rowcount <= @numrows)  
            and @@FETCH_STATUS = 0 
  begin
      if not exists (select wwTagKey from deleted where wwTagKey = @tagkey)
      begin
         update Tag set Status = 1 where wwTagKey = @tagkey
         insert ConfigStatusPending (Type, ObjectKey, Status)
           values (3, @tagkey, 1)
         set @rowcount = @rowcount + 1
      end
 
      fetch next from tags into @tagkey
  end 
  close tags
  deallocate tags
end
/* End of License Checking */

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_Tag on Tag
  for INSERT
  as
/* INSERT trigger on Tag */
/* default body for tI_Tag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255),
           @IOServerKey int,
           @TopicKey int

  select @numrows = @@rowcount

select @IOServerKey = IOServerKey, @TopicKey = TopicKey from inserted
if @IOServerKey IS NULL and @TopicKey IS NULL
goto skipri


/* Topic contains Tag ON CHILD INSERT RESTRICT */
  if
    /* update(TopicKey) or
       update(IOServerKey) or
       update(StorageNodeKey) */
    update(TopicKey) or
    update(IOServerKey) or
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Topic
        where
          /* inserted.TopicKey = Topic.TopicKey and
             inserted.IOServerKey = Topic.IOServerKey and
             inserted.StorageNodeKey = Topic.StorageNodeKey */
          inserted.TopicKey = Topic.TopicKey and
          inserted.IOServerKey = Topic.IOServerKey and
          inserted.StorageNodeKey = Topic.StorageNodeKey
    /* select @nullcnt = count(*) from inserted where
         inserted.TopicKey is null and
         inserted.IOServerKey is null and
         inserted.StorageNodeKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.TopicKey is null and
      inserted.IOServerKey is null and
      inserted.StorageNodeKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT Tag because Topic does not exist.'
      goto error
    end
  end




skipri:


/* Various checks and validations */
DECLARE @TagName nvarchar(256)
DECLARE @wwTagKey int
DECLARE @TagType int, @AcqType int
DECLARE @StorRate int, @StorType int
if @numrows = 1   -- Single Insert
BEGIN
   /* When a Tag is created, place an entry in the TagRef table */ 
   SELECT @TagName = (SELECT TagName FROM inserted)

   /* Check for unsupported / reserved characters */
   IF (SELECT CHARINDEX('|', @TagName)) > 0
     OR (SELECT CHARINDEX('[', @TagName)) > 0
     OR (SELECT CHARINDEX(']', @TagName)) > 0
   BEGIN
      goto illegalchar
   END
 
   IF not exists (SELECT TagRef.TagName FROM TagRef, inserted 
                    WHERE TagRef.TagName = inserted.TagName) 
   BEGIN
      INSERT TagRef (wwTagKey,ServerKey,TagName,TagType)
        SELECT wwTagKey,1,TagName,TagType 
          FROM inserted
   END
   ELSE   /* If the tag is already there, make sure the key and type are still correct */
   BEGIN 
      UPDATE TagRef SET 
        TagRef.wwTagKey = (SELECT inserted.wwTagKey FROM inserted),
        TagRef.TagType = (SELECT inserted.TagType FROM inserted)
        WHERE TagRef.TagName = @TagName 
   END

   /* Check Analog Storage Rate */
   IF exists (SELECT StorageRate FROM inserted WHERE TagType = 1 AND StorageRate < 1000
                 AND TagName = @TagName) 
   BEGIN
      UPDATE Tag SET StorageRate = 1000 WHERE TagName = @TagName AND StorageType in (1,17)
   END
   ELSE
   /* Check StorageType for Discrete, Strings */
   IF exists (SELECT StorageType FROM inserted WHERE TagType IN (2, 3) AND StorageType = 1
                AND TagName = @TagName)
   BEGIN
      UPDATE Tag SET StorageType = 2 WHERE TagName = @TagName 
   END
END
ELSE
BEGIN   -- Multiple Insert
   DECLARE taglist CURSOR FOR
        SELECT wwTagKey,TagName,TagType,StorageRate,StorageType,AcquisitionType  FROM inserted 
   OPEN taglist
   FETCH NEXT FROM taglist INTO @wwTagKey, @TagName, @TagType, @StorRate, @StorType, @AcqType
   WHILE @@FETCH_STATUS = 0
   BEGIN
      IF (SELECT CHARINDEX('|', @TagName)) > 0
        OR (SELECT CHARINDEX('[', @TagName)) > 0
        OR (SELECT CHARINDEX(']', @TagName)) > 0
      BEGIN
         CLOSE taglist
         DEALLOCATE taglist
         goto illegalchar
      END

      IF not exists (SELECT TagRef.TagName FROM TagRef 
                       WHERE TagRef.TagName = @TagName) 
      BEGIN
         INSERT TagRef (wwTagKey,ServerKey,TagName,TagType)
           VALUES (@wwTagKey,1,@TagName,@TagType) 
      END
      ELSE   /* If the tag is already there, make sure the key and type are still correct */
      BEGIN 
         UPDATE TagRef SET 
           TagRef.wwTagKey = @wwTagKey,
           TagRef.TagType = @TagType
           WHERE TagRef.TagName = @TagName 
      END
      /* Check Analog Storage Rate */
      IF @TagType = 1 AND @StorRate < 1000 AND @AcqType <> 2
      BEGIN
         UPDATE Tag SET StorageRate = 1000 where wwTagKey = @wwTagKey AND StorageType in (1,17)
      END
      ELSE
      IF (@TagType IN (2,3) AND @StorType = 1)
      BEGIN
         UPDATE Tag SET StorageType = 2 WHERE wwTagKey = @wwTagKey
      END

      FETCH NEXT FROM taglist  INTO @wwTagKey, @TagName, @TagType, @StorRate, @StorType, @AcqType
   END

   CLOSE taglist
   DEALLOCATE taglist
  
END

-- If tag belongs to a topic marked for late data, storage type is forced to delta storage
update Tag set StorageType = 2
  from Tag ta, Topic tp, inserted i
  where ta.TopicKey = tp.TopicKey
  and tp.TopicKey = i.TopicKey
  and tp.LateData = 1
  and i.StorageType = 1

-- Modify any MDAS tags entered with NULL IOServerKey or TopicKey
update Tag set IOServerKey = 2, TopicKey = 2
  from Tag ta, inserted i
  where ta.wwTagKey = i.wwTagKey
  and ta.TagType in (1,2,3)
  and (ta.IOServerKey is NULL or ta.TopicKey is NULL)

/*  Signal handler for system reinitialization */

select @TagType = TagType from inserted 
if (@TagType in (1,2,3,4,7,9) )  /* Analog, Discrete, String, Blob or Enum */
begin 
  update Tag set Status = 1 where TagName in (select TagName from inserted)
  /* ConfigStatus table */
  insert into ConfigStatusPending (Type, ObjectKey, Status)
    select 3, wwTagKey, 1 from inserted
end

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'Tag' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TagName', new.TagName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'IOServerKey', new.IOServerKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageNodeKey', new.StorageNodeKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'wwTagKey', new.wwTagKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TopicKey', new.TopicKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Description', new.Description
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'AcquisitionType', new.AcquisitionType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageType', new.StorageType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'AcquisitionRate', new.AcquisitionRate
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageRate', new.StorageRate
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ItemName', new.ItemName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TagType', new.TagType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TimeDeadband', new.TimeDeadband
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'DateCreated', new.DateCreated
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'CreatedBy', new.CreatedBy
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'CurrentEditor', new.CurrentEditor
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'SamplesInActiveImage', new.SamplesInActiveImage
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'AIRetrievalMode', new.AIRetrievalMode
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'CalculatedAISamples', new.CalculatedAISamples
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ServerTimeStamp', new.ServerTimeStamp
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'DeadbandType', new.DeadbandType
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'CEVersion', new.CEVersion
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModType = 'I'
           and   mlt.ModTableKey = @mltkey
   
   
end
/* end of mod tracking */ 

  return

illegalchar:
    set @errno = 17045
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
    if @errmsg  is NULL
    begin
       set @errmsg = 'Error msg not found - Invalid TagName. (TagName cannot contain |, [ or ])'
    end
    goto error

error:
    raiserror @errno @errmsg
    rollback transaction
end

go


create trigger tU_Tag on Tag
  for UPDATE
  as
/* Historian custom trigger on update for Tag */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255),
           @IOServerKey int,
           @TopicKey int

  select @numrows = @@rowcount

select @IOServerKey = IOServerKey, @TopicKey = TopicKey from inserted
if @IOServerKey IS NULL and @TopicKey IS NULL
goto skipri


/* Topic contains Tag ON CHILD UPDATE RESTRICT */
  if
    /* update(TopicKey) or
       update(IOServerKey) or
       update(StorageNodeKey) */
    update(TopicKey) or
    update(IOServerKey) or
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Topic
        where
          /* inserted.TopicKey = Topic.TopicKey and
             inserted.IOServerKey = Topic.IOServerKey and
             inserted.StorageNodeKey = Topic.StorageNodeKey */
          inserted.TopicKey = Topic.TopicKey and
          inserted.IOServerKey = Topic.IOServerKey and
          inserted.StorageNodeKey = Topic.StorageNodeKey
    /* select @nullcnt = count(*) from inserted where
         inserted.TopicKey is null and
         inserted.IOServerKey is null and
         inserted.StorageNodeKey is null */
    select @nullcnt = count(*) from inserted where
      inserted.TopicKey is null and
      inserted.IOServerKey is null and
      inserted.StorageNodeKey is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Tag because Topic does not exist.'
      goto error
    end
  end


/* Tag seen_in WideTableDictionary ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update WideTableDictionary
      set
        /*  WideTableDictionary.TagName = @insTagName */
        WideTableDictionary.TagName = @insTagName
      from WideTableDictionary,inserted,deleted
      where
        /*  WideTableDictionary.TagName = deleted.TagName */
        WideTableDictionary.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag has Annotation ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update Annotation
      set
        /*  Annotation.TagName = @insTagName */
        Annotation.TagName = @insTagName
      from Annotation,inserted,deleted
      where
        /*  Annotation.TagName = deleted.TagName */
        Annotation.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag R/161 InTouchSpecific ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update InTouchSpecific
      set
        /*  InTouchSpecific.TagName = @insTagName */
        InTouchSpecific.TagName = @insTagName
      from InTouchSpecific,inserted,deleted
      where
        /*  InTouchSpecific.TagName = deleted.TagName */
        InTouchSpecific.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag equivalent to TagRef ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update TagRef
      set
        /*  TagRef.TagName = @insTagName */
        TagRef.TagName = @insTagName
      from TagRef,inserted,deleted
      where
        /*  TagRef.TagName = deleted.TagName */
        TagRef.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag to be summarized  listed in SummaryTagList ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update SummaryTagList
      set
        /*  SummaryTagList.TagName = @insTagName */
        SummaryTagList.TagName = @insTagName
      from SummaryTagList,inserted,deleted
      where
        /*  SummaryTagList.TagName = deleted.TagName */
        SummaryTagList.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag linked to SnapshotTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update SnapshotTag
      set
        /*  SnapshotTag.TagName = @insTagName */
        SnapshotTag.TagName = @insTagName
      from SnapshotTag,inserted,deleted
      where
        /*  SnapshotTag.TagName = deleted.TagName */
        SnapshotTag.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag  BlobTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update BlobTag
      set
        /*  BlobTag.TagName = @insTagName */
        BlobTag.TagName = @insTagName
      from BlobTag,inserted,deleted
      where
        /*  BlobTag.TagName = deleted.TagName */
        BlobTag.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag  EnumeratedTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update EnumeratedTag
      set
        /*  EnumeratedTag.TagName = @insTagName */
        EnumeratedTag.TagName = @insTagName
      from EnumeratedTag,inserted,deleted
      where
        /*  EnumeratedTag.TagName = deleted.TagName */
        EnumeratedTag.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag  EventTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update EventTag
      set
        /*  EventTag.TagName = @insTagName */
        EventTag.TagName = @insTagName
      from EventTag,inserted,deleted
      where
        /*  EventTag.TagName = deleted.TagName */
        EventTag.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag  ComplexTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update ComplexTag
      set
        /*  ComplexTag.TagName = @insTagName */
        ComplexTag.TagName = @insTagName
      from ComplexTag,inserted,deleted
      where
        /*  ComplexTag.TagName = deleted.TagName */
        ComplexTag.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag  StringTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update StringTag
      set
        /*  StringTag.TagName = @insTagName */
        StringTag.TagName = @insTagName
      from StringTag,inserted,deleted
      where
        /*  StringTag.TagName = deleted.TagName */
        StringTag.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag  DiscreteTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update DiscreteTag
      set
        /*  DiscreteTag.TagName = @insTagName */
        DiscreteTag.TagName = @insTagName
      from DiscreteTag,inserted,deleted
      where
        /*  DiscreteTag.TagName = deleted.TagName */
        DiscreteTag.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end

/* Tag  AnalogTag ON PARENT UPDATE CASCADE */
  if
    /* update(TagName) */
    update(TagName)
  begin
    if @numrows = 1
    begin
      select @insTagName = inserted.TagName
        from inserted
      update AnalogTag
      set
        /*  AnalogTag.TagName = @insTagName */
        AnalogTag.TagName = @insTagName
      from AnalogTag,inserted,deleted
      where
        /*  AnalogTag.TagName = deleted.TagName */
        AnalogTag.TagName = deleted.TagName
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Tag UPDATE because more than one row has been affected.'
      goto error
    end
  end


skipri:

/* Validate the TagName */
IF @numrows = 1 and update(TagName)
-- Multiple update of the PK would have been already rejected
BEGIN
   declare @TagName nvarchar(256)
   SELECT @TagName = (SELECT TagName FROM inserted) 

   IF (SELECT CHARINDEX('|', @TagName)) > 0
     OR (SELECT CHARINDEX('[', @TagName)) > 0
     OR (SELECT CHARINDEX(']', @TagName)) > 0
   BEGIN
      goto illegalchar
   END
END

-- If tag belongs to a topic marked for late data, storage type is forced to delta storage
update Tag set StorageType = 2
  from Tag ta, Topic tp, inserted i, deleted d
  where ta.TopicKey = tp.TopicKey
  and tp.TopicKey = i.TopicKey
  and tp.TopicKey = d.TopicKey
  and tp.LateData = 1
  and i.StorageType = 1

/* Start Dynamic Reconfig and Validation */
/*  we cannot use the if update(xxxx) as the config editor sends an update for ALL columns */
/*  but Status */

if not update(Status) 
begin
   insert into ConfigStatusPending (Type, ObjectKey, Status)
   select 3, i.wwTagKey, 6
      from inserted i, deleted d
         where i.wwTagKey = d.wwTagKey
         and i.TagType in (1, 2, 3, 4, 7, 9)
         and d.Status not in (1, 2)
         and (ISNULL(d.IOServerKey, 999999) <> ISNULL(i.IOServerKey, 999999)
          or  ISNULL(d.TopicKey, 999999) <> ISNULL(i.TopicKey, 999999))

   insert into ConfigStatusPending (Type, ObjectKey, Status)
   select 3, i.wwTagKey, 2
      from inserted i, deleted d
         where i.wwTagKey = d.wwTagKey
         and i.TagType in (1, 2, 3, 4, 7, 9)
         and d.Status not in (1, 2)
         and (d.AcquisitionType <> i.AcquisitionType
          or  ISNULL(d.ItemName, 'wasnull') <> ISNULL(i.ItemName, 'wasnull')
          or  d.StorageType <> i.StorageType
          or  d.StorageRate <> i.StorageRate
          or  ISNULL(d.TimeDeadband, 999999) <> ISNULL(i.TimeDeadband, 999999)
          or  d.TagType <> i.TagType
          or  ISNULL(d.SamplesInActiveImage, 999999) <> ISNULL(i.SamplesInActiveImage, 999999)
          or  ISNULL(d.AIRetrievalMode, 9) <> ISNULL(i.AIRetrievalMode, 9)
          or  d.ServerTimeStamp <> i.ServerTimeStamp
          or  d.DeadbandType <> i.DeadbandType)

   update Tag set Status = 2 
      from Tag t, inserted i, deleted d
         where i.wwTagKey = t.wwTagKey
         and i.wwTagKey = d.wwTagKey
         and i.TagType in (1, 2, 3, 4, 7, 9)
         and d.Status not in (1, 2)
         and (d.AcquisitionType <> i.AcquisitionType
          or  ISNULL(d.ItemName, 'wasnull') <> ISNULL(i.ItemName, 'wasnull')
          or  d.StorageType <> i.StorageType
          or  d.StorageRate <> i.StorageRate
          or  ISNULL(d.TimeDeadband, 999999) <> ISNULL(i.TimeDeadband, 999999)
          or  d.TagType <> i.TagType
          or  ISNULL(d.SamplesInActiveImage, 999999) <> ISNULL(i.SamplesInActiveImage, 999999)
          or  ISNULL(d.AIRetrievalMode, 9) <> ISNULL(i.AIRetrievalMode, 9)
          or  d.ServerTimeStamp <> i.ServerTimeStamp
          or  d.DeadbandType <> i.DeadbandType
          or  ISNULL(d.IOServerKey, 999999) <> ISNULL(i.IOServerKey, 999999)
          or  ISNULL(d.TopicKey, 999999) <> ISNULL(i.TopicKey, 999999))

   /* Various Validation and Updates */

   /* When changing storage type to 0 or back from not stored need to adjust to proper value */ 
   if exists (select StorageType from inserted where StorageType = 0 and TagType in (1,2,3,4,7,9))
   begin
      update Tag set StorageType = 
               CASE d.StorageType
                  when 1 then 17 -- was cyclic
                  when 2 then 18 -- was delta
                  when 3 then 19 -- was forced
                  when 17 then 17 -- already not stored
                  when 18 then 18 -- already not stored
                  when 19 then 19 -- already not stored
               end
      from Tag t, inserted i, deleted d
         where t.wwTagKey = i.wwTagKey
         and i.wwTagKey = d.wwTagKey
         and i.StorageType <> d.StorageType
         and i.StorageType = 0
         and t.TagType in (1,2,3,4,7,9)
   end

   /* Check Analog Storage Rate */
   IF exists (SELECT StorageRate FROM inserted WHERE TagType = 1 AND StorageRate < 1000
                 AND StorageType in (1, 17) )
   BEGIN
      UPDATE Tag SET StorageRate = 1000 WHERE TagType = 1 AND StorageRate < 1000
                 AND StorageType in (1, 17)
   END
   ELSE
   /* Check StorageType for Discrete, Strings */
   IF exists (SELECT StorageType FROM inserted WHERE TagType IN (2, 3) AND StorageType IN (1, 17))
   BEGIN
      UPDATE Tag SET StorageType = 2 WHERE TagType IN (2, 3) AND StorageType IN (1, 17) 
   END

   /* Re-sync Samples in AI */
   update Tag set CalculatedAISamples  = i.SamplesInActiveImage
      from Tag t, inserted i, deleted d
         where t.wwTagKey = i.wwTagKey
         and i.wwTagKey = d.wwTagKey
         and ISNULL(d.SamplesInActiveImage, 999999) <> ISNULL(t.SamplesInActiveImage, 999999)
         and t.TagType in (1, 2, 3, 4, 7, 9)

   /* Bump the CEVersion value */
   update Tag set CEVersion = (i.CEVersion + 1) % 256
      from Tag t, inserted i, deleted d
         where t.wwTagKey = i.wwTagKey
         and i.wwTagKey = d.wwTagKey
end
/* end of Dynamic Reconfiguration and Validation */


/* start of mod tracking */ 
if not update(Status)
begin
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'Tag' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      if update(TagName)
      begin
         if @numrows = 1
         begin
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TagName <> old.TagName
                          or (new.TagName is NULL and  old.TagName is not NULL)
                          or (old.TagName is NULL and  new.TagName is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'IOServerKey', old.IOServerKey, new.IOServerKey
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.IOServerKey <> old.IOServerKey
                          or (new.IOServerKey is NULL and  old.IOServerKey is not NULL)
                          or (old.IOServerKey is NULL and  new.IOServerKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey, new.StorageNodeKey
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.StorageNodeKey <> old.StorageNodeKey
                          or (new.StorageNodeKey is NULL and  old.StorageNodeKey is not NULL)
                          or (old.StorageNodeKey is NULL and  new.StorageNodeKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'wwTagKey', old.wwTagKey, new.wwTagKey
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.wwTagKey <> old.wwTagKey
                          or (new.wwTagKey is NULL and  old.wwTagKey is not NULL)
                          or (old.wwTagKey is NULL and  new.wwTagKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TopicKey', old.TopicKey, new.TopicKey
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TopicKey <> old.TopicKey
                          or (new.TopicKey is NULL and  old.TopicKey is not NULL)
                          or (old.TopicKey is NULL and  new.TopicKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Description', old.Description, new.Description
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Description <> old.Description
                          or (new.Description is NULL and  old.Description is not NULL)
                          or (old.Description is NULL and  new.Description is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'AcquisitionType', old.AcquisitionType, new.AcquisitionType
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.AcquisitionType <> old.AcquisitionType
                          or (new.AcquisitionType is NULL and  old.AcquisitionType is not NULL)
                          or (old.AcquisitionType is NULL and  new.AcquisitionType is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'StorageType', old.StorageType, new.StorageType
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.StorageType <> old.StorageType
                          or (new.StorageType is NULL and  old.StorageType is not NULL)
                          or (old.StorageType is NULL and  new.StorageType is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'AcquisitionRate', old.AcquisitionRate, new.AcquisitionRate
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.AcquisitionRate <> old.AcquisitionRate
                          or (new.AcquisitionRate is NULL and  old.AcquisitionRate is not NULL)
                          or (old.AcquisitionRate is NULL and  new.AcquisitionRate is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'StorageRate', old.StorageRate, new.StorageRate
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.StorageRate <> old.StorageRate
                          or (new.StorageRate is NULL and  old.StorageRate is not NULL)
                          or (old.StorageRate is NULL and  new.StorageRate is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ItemName', old.ItemName, new.ItemName
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ItemName <> old.ItemName
                          or (new.ItemName is NULL and  old.ItemName is not NULL)
                          or (old.ItemName is NULL and  new.ItemName is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TagType', old.TagType, new.TagType
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TagType <> old.TagType
                          or (new.TagType is NULL and  old.TagType is not NULL)
                          or (old.TagType is NULL and  new.TagType is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TimeDeadband', old.TimeDeadband, new.TimeDeadband
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TimeDeadband <> old.TimeDeadband
                          or (new.TimeDeadband is NULL and  old.TimeDeadband is not NULL)
                          or (old.TimeDeadband is NULL and  new.TimeDeadband is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'DateCreated', old.DateCreated, new.DateCreated
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.DateCreated <> old.DateCreated
                          or (new.DateCreated is NULL and  old.DateCreated is not NULL)
                          or (old.DateCreated is NULL and  new.DateCreated is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'CreatedBy', old.CreatedBy, new.CreatedBy
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.CreatedBy <> old.CreatedBy
                          or (new.CreatedBy is NULL and  old.CreatedBy is not NULL)
                          or (old.CreatedBy is NULL and  new.CreatedBy is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'CurrentEditor', old.CurrentEditor, new.CurrentEditor
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.CurrentEditor <> old.CurrentEditor
                          or (new.CurrentEditor is NULL and  old.CurrentEditor is not NULL)
                          or (old.CurrentEditor is NULL and  new.CurrentEditor is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'SamplesInActiveImage', old.SamplesInActiveImage, new.SamplesInActiveImage
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.SamplesInActiveImage <> old.SamplesInActiveImage
                          or (new.SamplesInActiveImage is NULL and  old.SamplesInActiveImage is not NULL)
                          or (old.SamplesInActiveImage is NULL and  new.SamplesInActiveImage is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'AIRetrievalMode', old.AIRetrievalMode, new.AIRetrievalMode
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.AIRetrievalMode <> old.AIRetrievalMode
                          or (new.AIRetrievalMode is NULL and  old.AIRetrievalMode is not NULL)
                          or (old.AIRetrievalMode is NULL and  new.AIRetrievalMode is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Status', old.Status, new.Status
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Status <> old.Status
                          or (new.Status is NULL and  old.Status is not NULL)
                          or (old.Status is NULL and  new.Status is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'CalculatedAISamples', old.CalculatedAISamples, new.CalculatedAISamples
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.CalculatedAISamples <> old.CalculatedAISamples
                          or (new.CalculatedAISamples is NULL and  old.CalculatedAISamples is not NULL)
                          or (old.CalculatedAISamples is NULL and  new.CalculatedAISamples is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ServerTimeStamp', old.ServerTimeStamp, new.ServerTimeStamp
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ServerTimeStamp <> old.ServerTimeStamp
                          or (new.ServerTimeStamp is NULL and  old.ServerTimeStamp is not NULL)
                          or (old.ServerTimeStamp is NULL and  new.ServerTimeStamp is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'DeadbandType', old.DeadbandType, new.DeadbandType
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.DeadbandType <> old.DeadbandType
                          or (new.DeadbandType is NULL and  old.DeadbandType is not NULL)
                          or (old.DeadbandType is NULL and  new.DeadbandType is not NULL))
                  and   mlt.ModTableKey = @mltkey
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'CEVersion', old.CEVersion, new.CEVersion
               from inserted new, deleted old, ModLogTable mlt
                  where mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.CEVersion <> old.CEVersion
                          or (new.CEVersion is NULL and  old.CEVersion is not NULL)
                          or (old.CEVersion is NULL and  new.CEVersion is not NULL))
                  and   mlt.ModTableKey = @mltkey
         
         end      
      end
      else
      begin
         -- PK columns are in there because the code is generated from a template
         insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TagName <> old.TagName
                          or (new.TagName is NULL and  old.TagName is not NULL)
                          or (old.TagName is NULL and  new.TagName is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'IOServerKey', old.IOServerKey, new.IOServerKey
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.IOServerKey <> old.IOServerKey
                          or (new.IOServerKey is NULL and  old.IOServerKey is not NULL)
                          or (old.IOServerKey is NULL and  new.IOServerKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey, new.StorageNodeKey
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.StorageNodeKey <> old.StorageNodeKey
                          or (new.StorageNodeKey is NULL and  old.StorageNodeKey is not NULL)
                          or (old.StorageNodeKey is NULL and  new.StorageNodeKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'wwTagKey', old.wwTagKey, new.wwTagKey
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.wwTagKey <> old.wwTagKey
                          or (new.wwTagKey is NULL and  old.wwTagKey is not NULL)
                          or (old.wwTagKey is NULL and  new.wwTagKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TopicKey', old.TopicKey, new.TopicKey
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TopicKey <> old.TopicKey
                          or (new.TopicKey is NULL and  old.TopicKey is not NULL)
                          or (old.TopicKey is NULL and  new.TopicKey is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Description', old.Description, new.Description
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Description <> old.Description
                          or (new.Description is NULL and  old.Description is not NULL)
                          or (old.Description is NULL and  new.Description is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'AcquisitionType', old.AcquisitionType, new.AcquisitionType
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.AcquisitionType <> old.AcquisitionType
                          or (new.AcquisitionType is NULL and  old.AcquisitionType is not NULL)
                          or (old.AcquisitionType is NULL and  new.AcquisitionType is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'StorageType', old.StorageType, new.StorageType
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.StorageType <> old.StorageType
                          or (new.StorageType is NULL and  old.StorageType is not NULL)
                          or (old.StorageType is NULL and  new.StorageType is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'AcquisitionRate', old.AcquisitionRate, new.AcquisitionRate
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.AcquisitionRate <> old.AcquisitionRate
                          or (new.AcquisitionRate is NULL and  old.AcquisitionRate is not NULL)
                          or (old.AcquisitionRate is NULL and  new.AcquisitionRate is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'StorageRate', old.StorageRate, new.StorageRate
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.StorageRate <> old.StorageRate
                          or (new.StorageRate is NULL and  old.StorageRate is not NULL)
                          or (old.StorageRate is NULL and  new.StorageRate is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ItemName', old.ItemName, new.ItemName
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ItemName <> old.ItemName
                          or (new.ItemName is NULL and  old.ItemName is not NULL)
                          or (old.ItemName is NULL and  new.ItemName is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TagType', old.TagType, new.TagType
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TagType <> old.TagType
                          or (new.TagType is NULL and  old.TagType is not NULL)
                          or (old.TagType is NULL and  new.TagType is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'TimeDeadband', old.TimeDeadband, new.TimeDeadband
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.TimeDeadband <> old.TimeDeadband
                          or (new.TimeDeadband is NULL and  old.TimeDeadband is not NULL)
                          or (old.TimeDeadband is NULL and  new.TimeDeadband is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'DateCreated', old.DateCreated, new.DateCreated
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.DateCreated <> old.DateCreated
                          or (new.DateCreated is NULL and  old.DateCreated is not NULL)
                          or (old.DateCreated is NULL and  new.DateCreated is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'CreatedBy', old.CreatedBy, new.CreatedBy
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.CreatedBy <> old.CreatedBy
                          or (new.CreatedBy is NULL and  old.CreatedBy is not NULL)
                          or (old.CreatedBy is NULL and  new.CreatedBy is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'CurrentEditor', old.CurrentEditor, new.CurrentEditor
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.CurrentEditor <> old.CurrentEditor
                          or (new.CurrentEditor is NULL and  old.CurrentEditor is not NULL)
                          or (old.CurrentEditor is NULL and  new.CurrentEditor is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'SamplesInActiveImage', old.SamplesInActiveImage, new.SamplesInActiveImage
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.SamplesInActiveImage <> old.SamplesInActiveImage
                          or (new.SamplesInActiveImage is NULL and  old.SamplesInActiveImage is not NULL)
                          or (old.SamplesInActiveImage is NULL and  new.SamplesInActiveImage is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'AIRetrievalMode', old.AIRetrievalMode, new.AIRetrievalMode
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.AIRetrievalMode <> old.AIRetrievalMode
                          or (new.AIRetrievalMode is NULL and  old.AIRetrievalMode is not NULL)
                          or (old.AIRetrievalMode is NULL and  new.AIRetrievalMode is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'Status', old.Status, new.Status
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.Status <> old.Status
                          or (new.Status is NULL and  old.Status is not NULL)
                          or (old.Status is NULL and  new.Status is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'CalculatedAISamples', old.CalculatedAISamples, new.CalculatedAISamples
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.CalculatedAISamples <> old.CalculatedAISamples
                          or (new.CalculatedAISamples is NULL and  old.CalculatedAISamples is not NULL)
                          or (old.CalculatedAISamples is NULL and  new.CalculatedAISamples is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'ServerTimeStamp', old.ServerTimeStamp, new.ServerTimeStamp
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.ServerTimeStamp <> old.ServerTimeStamp
                          or (new.ServerTimeStamp is NULL and  old.ServerTimeStamp is not NULL)
                          or (old.ServerTimeStamp is NULL and  new.ServerTimeStamp is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'DeadbandType', old.DeadbandType, new.DeadbandType
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.DeadbandType <> old.DeadbandType
                          or (new.DeadbandType is NULL and  old.DeadbandType is not NULL)
                          or (old.DeadbandType is NULL and  new.DeadbandType is not NULL))
                  and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
             select mlt.ModTableKey, 'CEVersion', old.CEVersion, new.CEVersion
               from inserted new, deleted old, ModLogTable mlt
                  where new.TagName = old.TagName
                  and   mlt.RowKey = new.TagName
                  and   mlt.DateTime = @thetime
                  and   mlt.id = @thetable
                  and   (new.CEVersion <> old.CEVersion
                          or (new.CEVersion is NULL and  old.CEVersion is not NULL)
                          or (old.CEVersion is NULL and  new.CEVersion is not NULL))
                  and   mlt.ModTableKey = @mltkey
      
      end
   end
end
/* end of mod tracking */ 

  return

illegalchar:
    set @errno = 17045
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
    if @errmsg  is NULL
    begin
       set @errmsg = 'Error msg not found - Invalid TagName. (TagName cannot contain |, [ or ])'
    end
    goto error

error:
    raiserror @errno @errmsg
    rollback transaction

end
go


create trigger tD_TagGroup on TagGroup for DELETE as
/* Historian DELETE trigger on TagGroup */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* TagGroup contains GroupTagList ON PARENT DELETE CASCADE */
    delete GroupTagList
      from GroupTagList,deleted
      where
        /*  GroupTagList.GroupID = deleted.GroupID */
        GroupTagList.GroupID = deleted.GroupID


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_TagRef on TagRef
  for INSERT
  as
/* Historian INSERT trigger on TagRef */
/* default body for tI_TagRef */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @inswwDomainTagKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* ServerList contains TagRef ON CHILD INSERT RESTRICT */
  if
    /* update(ServerKey) */
    update(ServerKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,ServerList
        where
          /* inserted.ServerKey = ServerList.ServerKey */
          inserted.ServerKey = ServerList.ServerKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT TagRef because ServerList does not exist.'
      goto error
    end
  end

/* Tag equivalent to TagRef ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT TagRef because Tag does not exist.'
      goto error
    end
  end



/*  This trigger populates the public name space so that every Tag */
/*  added to the system is in appropriate group for all tags of */
/*  that type.  It assumes that the groups have previously been defined*/
/*  in PublicNameSpace and that PublicNameSpace.NameKey for these groups */
/*  matches TagType.   It also relies on a similar insert trigger on Tag */
/*  to populate TagRef  */ 
INSERT PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT TagType+1, wwDomainTagKey FROM inserted

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tD_TagRef on TagRef for DELETE as
/* Historian DELETE trigger on TagRef */
begin
  declare  @errno   int,
           @errmsg  varchar(255)


     /* TagRef member of GroupTagList ON PARENT DELETE CASCADE */
    delete GroupTagList
      from GroupTagList,deleted
      where
        /*  GroupTagList.wwDomainTagKey = deleted.wwDomainTagKey */
        GroupTagList.wwDomainTagKey = deleted.wwDomainTagKey

     /* TagRef member of PublicGroupTag ON PARENT DELETE CASCADE */
    delete PublicGroupTag
      from PublicGroupTag,deleted
      where
        /*  PublicGroupTag.wwDomainTagKey = deleted.wwDomainTagKey */
        PublicGroupTag.wwDomainTagKey = deleted.wwDomainTagKey

     /* TagRef member of PrivateGroupTag ON PARENT DELETE CASCADE */
    delete PrivateGroupTag
      from PrivateGroupTag,deleted
      where
        /*  PrivateGroupTag.wwDomainTagKey = deleted.wwDomainTagKey */
        PrivateGroupTag.wwDomainTagKey = deleted.wwDomainTagKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_TagRef on TagRef for UPDATE as
/* Historian UPDATE trigger on TagRef */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @inswwDomainTagKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* TagRef member of PublicGroupTag ON PARENT UPDATE CASCADE */
  if
    /* update(wwDomainTagKey) */
    update(wwDomainTagKey)
  begin
    if @numrows = 1
    begin
      select @inswwDomainTagKey = inserted.wwDomainTagKey
        from inserted
      update PublicGroupTag
      set
        /*  PublicGroupTag.wwDomainTagKey = @inswwDomainTagKey */
        PublicGroupTag.wwDomainTagKey = @inswwDomainTagKey
      from PublicGroupTag,inserted,deleted
      where
        /*  PublicGroupTag.wwDomainTagKey = deleted.wwDomainTagKey */
        PublicGroupTag.wwDomainTagKey = deleted.wwDomainTagKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade TagRef UPDATE because more than one row has been affected.'
      goto error
    end
  end

  /* ServerList contains TagRef ON CHILD UPDATE RESTRICT */
  if
    /* update(ServerKey) */
    update(ServerKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,ServerList
        where
          /* inserted.ServerKey = ServerList.ServerKey */
          inserted.ServerKey = ServerList.ServerKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE TagRef because ServerList does not exist.'
      goto error
    end
  end

  /* Tag equivalent to TagRef ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE TagRef because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_TimeDetectorDetail on TimeDetectorDetail
  for DELETE
  as
/* DELETE trigger on TimeDetectorDetail */
/* default body for tD_TimeDetectorDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTimeDetectorDetailKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



  /* Business rule for event system to see that a tag has been deleted */
  /* Place the deleted row into the DeletePending table */

if not exists (select t.TagName from TimeDetectorDetailPendingDelete t, deleted d
                where t.TagName = d.TagName)
begin
   insert into TimeDetectorDetailPendingDelete
   (TagName, FrequencyID, Periodicity, RunTimeDay, RunTimeHour, RunTimeMin)
   select TagName, FrequencyID, Periodicity, RunTimeDay, RunTimeHour, RunTimeMin
   from deleted d
end

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'TimeDetectorDetail' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TimeDetectorDetailKey', old.TimeDetectorDetailKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'FrequencyID', old.FrequencyID
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TagName', old.TagName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Periodicity', old.Periodicity
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StartDateTime', old.StartDateTime
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'RunTimeDay', old.RunTimeDay
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'RunTimeHour', old.RunTimeHour
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'RunTimeMin', old.RunTimeMin
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_TimeDetectorDetail on TimeDetectorDetail
  for INSERT
  as
/* INSERT trigger on TimeDetectorDetail */
/* default body for tI_TimeDetectorDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTimeDetectorDetailKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* Frequency R/228 TimeDetectorDetail ON CHILD INSERT RESTRICT */
  if
    /* update(FrequencyID) */
    update(FrequencyID)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Frequency
        where
          /* inserted.FrequencyID = Frequency.FrequencyID */
          inserted.FrequencyID = Frequency.FrequencyID
    /* select @nullcnt = count(*) from inserted where
         inserted.FrequencyID is null */
    select @nullcnt = count(*) from inserted where
      inserted.FrequencyID is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT TimeDetectorDetail because Frequency does not exist.'
      goto error
    end
  end

/* EventTag R/227 TimeDetectorDetail ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTag
        where
          /* inserted.TagName = EventTag.TagName */
          inserted.TagName = EventTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT TimeDetectorDetail because EventTag does not exist.'
      goto error
    end
  end




/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'TimeDetectorDetail' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TimeDetectorDetailKey', new.TimeDetectorDetailKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'FrequencyID', new.FrequencyID
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TagName', new.TagName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Periodicity', new.Periodicity
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StartDateTime', new.StartDateTime
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'RunTimeDay', new.RunTimeDay
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'RunTimeHour', new.RunTimeHour
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'RunTimeMin', new.RunTimeMin
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TagName
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_TimeDetectorDetail on TimeDetectorDetail
  for UPDATE
  as
/* UPDATE trigger on TimeDetectorDetail */
/* default body for tU_TimeDetectorDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTimeDetectorDetailKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* Frequency R/228 TimeDetectorDetail ON CHILD UPDATE RESTRICT */
  if
    /* update(FrequencyID) */
    update(FrequencyID)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Frequency
        where
          /* inserted.FrequencyID = Frequency.FrequencyID */
          inserted.FrequencyID = Frequency.FrequencyID
    /* select @nullcnt = count(*) from inserted where
         inserted.FrequencyID is null */
    select @nullcnt = count(*) from inserted where
      inserted.FrequencyID is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE TimeDetectorDetail because Frequency does not exist.'
      goto error
    end
  end

/* EventTag R/227 TimeDetectorDetail ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTag
        where
          /* inserted.TagName = EventTag.TagName */
          inserted.TagName = EventTag.TagName
    /* select @nullcnt = count(*) from inserted where
         inserted.TagName is null */
    select @nullcnt = count(*) from inserted where
      inserted.TagName is null
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE TimeDetectorDetail because EventTag does not exist.'
      goto error
    end
  end




update EventTag
set Status = 2  /* event updated */
from EventTag e,inserted i
where e.TagName = i.TagName and e.Status != 99 

/* IndustrialWorkbook 7.0 Support */

DECLARE @TagName nvarchar(256)

if @@ROWCOUNT = 1   -- Single Insert
BEGIN
   if exists (select so.TagName from SummaryOperation so, inserted i where so.TagName = i.TagName)
   BEGIN
      update SummaryOperation set Frequency = f.Frequency, SourceType = 'DYN' 
         from TimeDetectorDetail tdd, Frequency f, inserted i  
            where i.TagName = tdd.TagName
            and   tdd.FrequencyID = f.FrequencyID
            and SummaryOperation.TagName = i.TagName
   END
END
ELSE   -- Multiple Insert
BEGIN
   DECLARE thetaglist CURSOR FOR
        SELECT DISTINCT TagName FROM inserted 
   OPEN thetaglist
   FETCH NEXT FROM thetaglist INTO @TagName
   WHILE @@FETCH_STATUS = 0
   BEGIN
      if exists (select so.TagName from SummaryOperation so where so.TagName = @TagName)
      BEGIN
         update SummaryOperation set Frequency = f.Frequency, SourceType = 'DYN' 
            from TimeDetectorDetail tdd, Frequency f, inserted i  
               where @TagName = tdd.TagName
               and   tdd.FrequencyID = f.FrequencyID
               and   SummaryOperation.TagName = i.TagName
      END
      FETCH NEXT FROM thetaglist  INTO @TagName
   END
   CLOSE thetaglist
   DEALLOCATE thetaglist
END

/* start of mod tracking */ 
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'TimeDetectorDetail' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.TagName, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'TimeDetectorDetailKey', old.TimeDetectorDetailKey, new.TimeDetectorDetailKey
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.TimeDetectorDetailKey <> old.TimeDetectorDetailKey
                       or (new.TimeDetectorDetailKey is NULL and  old.TimeDetectorDetailKey is not NULL)
                       or (old.TimeDetectorDetailKey is NULL and  new.TimeDetectorDetailKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'FrequencyID', old.FrequencyID, new.FrequencyID
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.FrequencyID <> old.FrequencyID
                       or (new.FrequencyID is NULL and  old.FrequencyID is not NULL)
                       or (old.FrequencyID is NULL and  new.FrequencyID is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'TagName', old.TagName, new.TagName
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.TagName <> old.TagName
                       or (new.TagName is NULL and  old.TagName is not NULL)
                       or (old.TagName is NULL and  new.TagName is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Periodicity', old.Periodicity, new.Periodicity
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Periodicity <> old.Periodicity
                       or (new.Periodicity is NULL and  old.Periodicity is not NULL)
                       or (old.Periodicity is NULL and  new.Periodicity is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StartDateTime', old.StartDateTime, new.StartDateTime
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StartDateTime <> old.StartDateTime
                       or (new.StartDateTime is NULL and  old.StartDateTime is not NULL)
                       or (old.StartDateTime is NULL and  new.StartDateTime is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'RunTimeDay', old.RunTimeDay, new.RunTimeDay
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.RunTimeDay <> old.RunTimeDay
                       or (new.RunTimeDay is NULL and  old.RunTimeDay is not NULL)
                       or (old.RunTimeDay is NULL and  new.RunTimeDay is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'RunTimeHour', old.RunTimeHour, new.RunTimeHour
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.RunTimeHour <> old.RunTimeHour
                       or (new.RunTimeHour is NULL and  old.RunTimeHour is not NULL)
                       or (old.RunTimeHour is NULL and  new.RunTimeHour is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'RunTimeMin', old.RunTimeMin, new.RunTimeMin
            from inserted new, deleted old, ModLogTable mlt
               where new.TagName = old.TagName
               and   mlt.RowKey = new.TagName
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.RunTimeMin <> old.RunTimeMin
                       or (new.RunTimeMin is NULL and  old.RunTimeMin is not NULL)
                       or (old.RunTimeMin is NULL and  new.RunTimeMin is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_TimeDetectorDetailPendingDelete on TimeDetectorDetailPendingDelete for UPDATE as
/* Historian UPDATE trigger on TimeDetectorDetailPendingDelete */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* EventTagPendingDelete R/237 TimeDetectorDetailPendingDelete ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,EventTagPendingDelete
        where
          /* inserted.TagName = EventTagPendingDelete.TagName */
          inserted.TagName = EventTagPendingDelete.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE TimeDetectorDetailPendingDelete because EventTagPendingDelete does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_Topic on Topic
  for DELETE
  as
/* Custom delete trigger on Topic */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTopicKey int, 
           @insIOServerKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* Topic contains Tag ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,Tag
      where
        /*  Tag.TopicKey = deleted.TopicKey and
            Tag.IOServerKey = deleted.IOServerKey and
            Tag.StorageNodeKey = deleted.StorageNodeKey */
        Tag.TopicKey = deleted.TopicKey and
        Tag.IOServerKey = deleted.IOServerKey and
        Tag.StorageNodeKey = deleted.StorageNodeKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE Topic because Tag exists.'
      goto error
    end



/* Cannot allow deletion of TopicKeys <= 2 */
if (select count(TopicKey) from deleted where TopicKey <= 2) > 0
begin
  set @errno = 17022
  set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
  if @errmsg  is NULL
  begin
     set @errmsg = 'Error msg not found - Invalid Topic delete'
  end   
   goto error
end

/* Signal handler for system reinitialization */

insert into ConfigStatusPending (Type, ObjectKey, Status)
     select 2, TopicKey, 3 from deleted 

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'Topic' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.TopicKey, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TopicKey', old.TopicKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'IOServerKey', old.IOServerKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Name', old.Name
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'TimeOut', old.TimeOut
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'Status', old.Status
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'LateData', old.LateData
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'IdleDuration', old.IdleDuration
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'ProcessingInterval', old.ProcessingInterval
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_Topic on Topic
  for INSERT
  as
/* Historian INSERT trigger on Topic */
/* default body for tI_Topic */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTopicKey int, 
           @insIOServerKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* IOServer Reads data from Topic ON CHILD INSERT RESTRICT */
  if
    /* update(IOServerKey) or
       update(StorageNodeKey) */
    update(IOServerKey) or
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,IOServer
        where
          /* inserted.IOServerKey = IOServer.IOServerKey and
             inserted.StorageNodeKey = IOServer.StorageNodeKey */
          inserted.IOServerKey = IOServer.IOServerKey and
          inserted.StorageNodeKey = IOServer.StorageNodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT Topic because IOServer does not exist.'
      goto error
    end
  end




/* case sensitive server validation */
/* Duplication validation for case sensitive servers */
if ( select count(UPPER(RTRIM(tp.Name))) from Topic tp, inserted i
     where UPPER(RTRIM(tp.Name)) = UPPER(RTRIM(i.Name))
     and   tp.IOServerKey = i.IOServerKey ) > @numrows
begin
   set @errno = 17029
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg  is NULL
   begin
      set @errmsg = 'Error msg not found - Invalid Topic insert or update, combination IOServerKey + Name already exists'
   end      
   goto error
end


if update(IdleDuration) or update(ProcessingInterval)
begin
-- one or more of the time columns was changed
  declare @TopicKey int
  declare @newIdle int, @newProc int

  declare topic_ins_cursor cursor for
    select TopicKey, IdleDuration, ProcessingInterval from inserted

  open topic_ins_cursor

  fetch next from topic_ins_cursor into @TopicKey, @newIdle, @newProc

  while @@fetch_status = 0
  begin
    if @newProc = 0
      update Topic set ProcessingInterval = 2*IdleDuration
        where Topic.TopicKey = @TopicKey
    else
    if @newProc < @newIdle
    begin
      close topic_ins_cursor
      deallocate topic_ins_cursor
      set @errno = 17064
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
        set @errmsg = 'Error msg not found - ProcessingInterval must be equal to or greater than IdleDuration'
      end      
      goto error
    end

    fetch next from topic_ins_cursor into @TopicKey, @newIdle, @newProc
  end

  close topic_ins_cursor
  deallocate topic_ins_cursor
end

-- All topics marked for late data: set topic timeout to 0
update Topic set TimeOut = 0
  where LateData = 1

/*  Signal handler for system reinitialization */
 
  insert into ConfigStatusPending (Type, ObjectKey, Status)
    select 2, TopicKey, 1 from inserted 

  update Topic set Status = 1 where TopicKey in (select TopicKey from inserted)

/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'Topic' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.TopicKey, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TopicKey', new.TopicKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'IOServerKey', new.IOServerKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'StorageNodeKey', new.StorageNodeKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Name', new.Name
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'TimeOut', new.TimeOut
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'Status', new.Status
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'LateData', new.LateData
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'IdleDuration', new.IdleDuration
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'ProcessingInterval', new.ProcessingInterval
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.TopicKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

   return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_Topic on Topic
  for UPDATE
  as
/* Historian UPDATE trigger on Topic */
/* default body for tU_Topic */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insTopicKey int, 
           @insIOServerKey int, 
           @insStorageNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
/* IOServer Reads data from Topic ON CHILD UPDATE RESTRICT */
  if
    /* update(IOServerKey) or
       update(StorageNodeKey) */
    update(IOServerKey) or
    update(StorageNodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,IOServer
        where
          /* inserted.IOServerKey = IOServer.IOServerKey and
             inserted.StorageNodeKey = IOServer.StorageNodeKey */
          inserted.IOServerKey = IOServer.IOServerKey and
          inserted.StorageNodeKey = IOServer.StorageNodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE Topic because IOServer does not exist.'
      goto error
    end
  end


/* Topic contains Tag ON PARENT UPDATE CASCADE */
  if
    /* update(TopicKey) or
       update(IOServerKey) or
       update(StorageNodeKey) */
    update(TopicKey) or
    update(IOServerKey) or
    update(StorageNodeKey)
  begin
    if @numrows = 1
    begin
      select @insTopicKey = inserted.TopicKey, 
             @insIOServerKey = inserted.IOServerKey, 
             @insStorageNodeKey = inserted.StorageNodeKey
        from inserted
      update Tag
      set
        /*  Tag.TopicKey = @insTopicKey,
            Tag.IOServerKey = @insIOServerKey,
            Tag.StorageNodeKey = @insStorageNodeKey */
        Tag.TopicKey = @insTopicKey,
        Tag.IOServerKey = @insIOServerKey,
        Tag.StorageNodeKey = @insStorageNodeKey
      from Tag,inserted,deleted
      where
        /*  Tag.TopicKey = deleted.TopicKey and
            Tag.IOServerKey = deleted.IOServerKey and
            Tag.StorageNodeKey = deleted.StorageNodeKey */
        Tag.TopicKey = deleted.TopicKey and
        Tag.IOServerKey = deleted.IOServerKey and
        Tag.StorageNodeKey = deleted.StorageNodeKey
    end
    else
    if @numrows > 1
    begin
      select @errno = 30006,
             @errmsg = 'Cannot cascade Topic UPDATE because more than one row has been affected.'
      goto error
    end
  end



/* case sensitive server validation */
/* Duplication validation for case sensitive servers */
if not update(Status) and ( select count(UPPER(RTRIM(tp.Name))) from Topic tp, inserted i
     where UPPER(RTRIM(tp.Name)) = UPPER(RTRIM(i.Name))
     and   tp.IOServerKey = i.IOServerKey ) > @numrows
begin
   set @errno = 17029
   set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
   if @errmsg  is NULL
   begin
      set @errmsg = 'Error msg not found - Invalid Topic insert or update, combination IOServerKey + Name already exists'
   end      
   goto error
end

if update(IdleDuration) or update(ProcessingInterval)
begin
-- one or more of the time columns was changed
  declare @TopicKey int
  declare @newIdle int, @newProc int

  declare topic_upd_cursor cursor for
    select i.TopicKey, i.IdleDuration, i.ProcessingInterval from inserted i, deleted d
      where i.TopicKey = d.TopicKey

  open topic_upd_cursor

  fetch next from topic_upd_cursor into @TopicKey, @newIdle, @newProc

  while @@fetch_status = 0
  begin
    if @newProc = 0
      update Topic set ProcessingInterval = 2*IdleDuration
        where Topic.TopicKey = @TopicKey
    else
    if @newProc < @newIdle
    begin
      close topic_upd_cursor
      deallocate topic_upd_cursor
      set @errno = 17064
      set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
      if @errmsg  is NULL
      begin
        set @errmsg = 'Error msg not found - ProcessingInterval must be equal to or greater than IdleDuration'
      end      
      goto error
    end

    fetch next from topic_upd_cursor into @TopicKey, @newIdle, @newProc
  end

  close topic_upd_cursor
  deallocate topic_upd_cursor
end

-- All topics marked for late data: set topic timeout to 0
update Topic set TimeOut = 0
  where LateData = 1

-- All tags marked for late data are forced to delta storage
update Tag set StorageType = 2
  from Tag ta, Topic tp, inserted i, deleted d
  where ta.TopicKey = tp.TopicKey
  and tp.TopicKey = i.TopicKey
  and tp.TopicKey = d.TopicKey
  and tp.LateData = 1
  and ta.StorageType = 1

/*  Dynamic Reconfiguration          */
/*  All columns mods require re-init */

if not update(Status)
begin
   insert into ConfigStatusPending (Type, ObjectKey, Status)
      select 2, i.TopicKey, 2
         from inserted i, deleted d
            where i.TopicKey = d.TopicKey
            and d.Status not in (1, 2)
            and (i.IOServerKey <> d.IOServerKey or  i.[Name] <> d.[Name]
            or   ISNULL(i.TimeOut, 99999) <> ISNULL(d.TimeOut, 99999)
            or   i.LateData <> d.LateData or i.IdleDuration <> d.IdleDuration
            or   i.ProcessingInterval <> d.ProcessingInterval)

   update Topic set Status = 2 from Topic t, inserted i, deleted d
      where t.TopicKey = i.TopicKey
      and i.TopicKey = d.TopicKey
            and d.Status not in (1, 2)
            and (i.IOServerKey <> d.IOServerKey or  i.[Name] <> d.[Name]
            or   ISNULL(i.TimeOut, 99999) <> ISNULL(d.TimeOut, 99999)
            or   i.LateData <> d.LateData or i.IdleDuration <> d.IdleDuration
            or   i.ProcessingInterval <> d.ProcessingInterval)
end

/* start of mod tracking */ 
if not update(Status)
begin
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'Topic' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.TopicKey, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      /* PK columns are still there because of the script template, not an issue */
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'TopicKey', old.TopicKey, new.TopicKey
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.TopicKey <> old.TopicKey
                       or (new.TopicKey is NULL and  old.TopicKey is not NULL)
                       or (old.TopicKey is NULL and  new.TopicKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'IOServerKey', old.IOServerKey, new.IOServerKey
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.IOServerKey <> old.IOServerKey
                       or (new.IOServerKey is NULL and  old.IOServerKey is not NULL)
                       or (old.IOServerKey is NULL and  new.IOServerKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'StorageNodeKey', old.StorageNodeKey, new.StorageNodeKey
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.StorageNodeKey <> old.StorageNodeKey
                       or (new.StorageNodeKey is NULL and  old.StorageNodeKey is not NULL)
                       or (old.StorageNodeKey is NULL and  new.StorageNodeKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Name', old.Name, new.Name
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Name <> old.Name
                       or (new.Name is NULL and  old.Name is not NULL)
                       or (old.Name is NULL and  new.Name is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'TimeOut', old.TimeOut, new.TimeOut
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.TimeOut <> old.TimeOut
                       or (new.TimeOut is NULL and  old.TimeOut is not NULL)
                       or (old.TimeOut is NULL and  new.TimeOut is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'Status', old.Status, new.Status
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.Status <> old.Status
                       or (new.Status is NULL and  old.Status is not NULL)
                       or (old.Status is NULL and  new.Status is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'LateData', old.LateData, new.LateData
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.LateData <> old.LateData
                       or (new.LateData is NULL and  old.LateData is not NULL)
                       or (old.LateData is NULL and  new.LateData is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'IdleDuration', old.IdleDuration, new.IdleDuration
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.IdleDuration <> old.IdleDuration
                       or (new.IdleDuration is NULL and  old.IdleDuration is not NULL)
                       or (old.IdleDuration is NULL and  new.IdleDuration is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'ProcessingInterval', old.ProcessingInterval, new.ProcessingInterval
            from inserted new, deleted old, ModLogTable mlt
               where new.TopicKey = old.TopicKey
               and   mlt.RowKey = new.TopicKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.ProcessingInterval <> old.ProcessingInterval
                       or (new.ProcessingInterval is NULL and  old.ProcessingInterval is not NULL)
                       or (old.ProcessingInterval is NULL and  new.ProcessingInterval is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_TopicImportInfo on TopicImportInfo for INSERT as
/* Historian INSERT trigger on TopicImportInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* InTouchNode has TopicImportInfo ON CHILD INSERT RESTRICT */
  if
    /* update(NodeKey) */
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchNode
        where
          /* inserted.NodeKey = InTouchNode.NodeKey */
          inserted.NodeKey = InTouchNode.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT TopicImportInfo because InTouchNode does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_TopicImportInfo on TopicImportInfo for UPDATE as
/* Historian UPDATE trigger on TopicImportInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insNodeKey int, 
           @insDdeSourceKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* InTouchNode has TopicImportInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(NodeKey) */
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchNode
        where
          /* inserted.NodeKey = InTouchNode.NodeKey */
          inserted.NodeKey = InTouchNode.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE TopicImportInfo because InTouchNode does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_UserDetail on UserDetail
  for DELETE
  as
/* DELETE trigger on UserDetail */
/* default body for tD_UserDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insUserKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* UserDetail owns PrivateNameSpace ON PARENT DELETE CASCADE */
    delete PrivateNameSpace
      from PrivateNameSpace,deleted
      where
        /*  PrivateNameSpace.UserKey = deleted.UserKey */
        PrivateNameSpace.UserKey = deleted.UserKey

/* UserDetail R/158 WideTableDictionary ON PARENT DELETE CASCADE */
    delete WideTableDictionary
      from WideTableDictionary,deleted
      where
        /*  WideTableDictionary.UserKey = deleted.UserKey */
        WideTableDictionary.UserKey = deleted.UserKey



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (4,5,6,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'UserDetail' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'D', i.UserKey, USER_ID(), @thetime, SUSER_SNAME()
         from deleted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'UserKey', old.UserKey
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'UserName', old.UserName
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'AccessLevel', old.AccessLevel
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'uid', old.uid
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, OldValue)
      select mlt.ModTableKey, 'gid', old.gid
        from deleted old, ModLogTable mlt
           where mlt.RowKey = old.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 
  return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_UserDetail on UserDetail
  for INSERT
  as
/* INSERT trigger on UserDetail */
/* default body for tI_UserDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insUserKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount



/* start of mod tracking */ 
declare @res int
exec @res = aaModLogStatus
if (@res in (1,3,5,7))
begin
   declare @thetime datetime
   declare @thetable int
   declare @mltkey int

   set @thetime = getdate()
   set @thetable = (select id from HistorianSysObjects 
           where Name =  'UserDetail' and Type = 'U')

   insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
      select @thetable, 'I', i.UserKey, USER_ID(), @thetime, SUSER_SNAME()
         from inserted i

   set @mltkey = SCOPE_IDENTITY()

   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'UserKey', new.UserKey
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'UserName', new.UserName
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'AccessLevel', new.AccessLevel
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'uid', new.uid
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   insert ModLogColumn (ModTableKey, ColumnName, NewValue)
      select mlt.ModTableKey, 'gid', new.gid
        from inserted new, ModLogTable mlt
           where mlt.RowKey = new.UserKey
           and   mlt.DateTime = @thetime
           and   mlt.id = @thetable
           and   mlt.ModTableKey = @mltkey
   
end
/* end of mod tracking */ 

  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tU_UserDetail on UserDetail
  for UPDATE
  as
/* UPDATE trigger on UserDetail */
/* default body for tU_UserDetail */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insUserKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

/* UserDetail owns PrivateNameSpace ON PARENT UPDATE RESTRICT */
  if
    /* update(UserKey) */
    update(UserKey)
  begin
    if exists (
      select * from deleted,PrivateNameSpace
      where
        /*  PrivateNameSpace.UserKey = deleted.UserKey */
        PrivateNameSpace.UserKey = deleted.UserKey
    )
    begin
      select @errno  = 30005,
             @errmsg = 'Cannot UPDATE UserDetail because PrivateNameSpace exists.'
      goto error
    end
  end



/* handles only Single updates */
if @@ROWCOUNT = 1   -- Single Insert
begin
   if (select uid from inserted) > 16400
   begin
      update UserDetail set AccessLevel =
         (select inserted.AccessLevel from inserted)
         from inserted, UserDetail
         where UserDetail.gid = inserted.uid
   end 
end

/* start of mod tracking */ 
   declare @res int
   exec @res = aaModLogStatus
   if (@res in (2,3,6,7))
   begin 
      declare @thetime datetime
      declare @thetable int
      declare @mltkey int

      set @thetime = getdate()
      set @thetable = (select id from HistorianSysObjects 
              where Name =  'UserDetail' and Type = 'U')

      insert into ModLogTable (id, ModType, RowKey, UserKey, DateTime, UserName)
         select @thetable, 'U', i.UserKey, USER_ID(), @thetime, SUSER_SNAME()
            from inserted i

      set @mltkey = SCOPE_IDENTITY()

      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'UserKey', old.UserKey, new.UserKey
            from inserted new, deleted old, ModLogTable mlt
               where new.UserKey = old.UserKey
               and   mlt.RowKey = new.UserKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.UserKey <> old.UserKey
                       or (new.UserKey is NULL and  old.UserKey is not NULL)
                       or (old.UserKey is NULL and  new.UserKey is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'UserName', old.UserName, new.UserName
            from inserted new, deleted old, ModLogTable mlt
               where new.UserKey = old.UserKey
               and   mlt.RowKey = new.UserKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.UserName <> old.UserName
                       or (new.UserName is NULL and  old.UserName is not NULL)
                       or (old.UserName is NULL and  new.UserName is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'AccessLevel', old.AccessLevel, new.AccessLevel
            from inserted new, deleted old, ModLogTable mlt
               where new.UserKey = old.UserKey
               and   mlt.RowKey = new.UserKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.AccessLevel <> old.AccessLevel
                       or (new.AccessLevel is NULL and  old.AccessLevel is not NULL)
                       or (old.AccessLevel is NULL and  new.AccessLevel is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'uid', old.uid, new.uid
            from inserted new, deleted old, ModLogTable mlt
               where new.UserKey = old.UserKey
               and   mlt.RowKey = new.UserKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.uid <> old.uid
                       or (new.uid is NULL and  old.uid is not NULL)
                       or (old.uid is NULL and  new.uid is not NULL))
               and   mlt.ModTableKey = @mltkey
      insert ModLogColumn (ModTableKey, ColumnName, OldValue, NewValue)
          select mlt.ModTableKey, 'gid', old.gid, new.gid
            from inserted new, deleted old, ModLogTable mlt
               where new.UserKey = old.UserKey
               and   mlt.RowKey = new.UserKey
               and   mlt.DateTime = @thetime
               and   mlt.id = @thetable
               and   (new.gid <> old.gid
                       or (new.gid is NULL and  old.gid is not NULL)
                       or (old.gid is NULL and  new.gid is not NULL))
               and   mlt.ModTableKey = @mltkey
      
   end
/* end of mod tracking */ 

return

error:
    raiserror @errno @errmsg
    rollback transaction
end
go


create trigger tI_WideTableDictionary on WideTableDictionary for INSERT as
/* Historian INSERT trigger on WideTableDictionary */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Tag seen_in WideTableDictionary ON CHILD INSERT RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT WideTableDictionary because Tag does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_WideTableDictionary on WideTableDictionary for UPDATE as
/* Historian UPDATE trigger on WideTableDictionary */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insUserKey int, 
           @insTagName nvarchar(256),
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount

  /* Tag seen_in WideTableDictionary ON CHILD UPDATE RESTRICT */
  if
    /* update(TagName) */
    update(TagName)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,Tag
        where
          /* inserted.TagName = Tag.TagName */
          inserted.TagName = Tag.TagName
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE WideTableDictionary because Tag does not exist.'
      goto error
    end
  end

  /* UserDetail R/158 WideTableDictionary ON CHILD UPDATE RESTRICT */
  if
    /* update(UserKey) */
    update(UserKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,UserDetail
        where
          /* inserted.UserKey = UserDetail.UserKey */
          inserted.UserKey = UserDetail.UserKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE WideTableDictionary because UserDetail does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go


/* Run at the end of the creation script  */

use Runtime
go

INSERT UserDetail (UserKey, UserName, AccessLevel, uid, gid) VALUES (1,N'dbo',9999,1,0)
go
INSERT UserDetail (UserKey, UserName, AccessLevel, uid, gid) VALUES (0,N'public',1,0,0)
go

EXEC aaUserDetailUpdate
go

UPDATE UserDetail
SET    AccessLevel = 9999
WHERE  UserName = N'dbo'
go

UPDATE UserDetail
SET    AccessLevel = 2
WHERE  UserName IN (N'aaUser', N'aaUsers')
go

UPDATE UserDetail
SET    AccessLevel = 3
WHERE  UserName IN (N'aaPower', N'aaPowerUsers')
go

UPDATE UserDetail
SET    AccessLevel = 4
WHERE  UserName IN (N'aaAdmin', N'aaAdministrators')
go

use master
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_ProcList'))
        begin   
           DROP procedure dbo.xp_ProcList
        end
go
exec sp_addextendedproc 'xp_ProcList', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_DiskCopy'))
        begin   
           DROP procedure dbo.xp_DiskCopy
        end
go
exec sp_addextendedproc 'xp_DiskCopy', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_AnalogHistory'))
        begin   
           DROP procedure dbo.xp_AnalogHistory
        end
go
exec sp_addextendedproc 'xp_AnalogHistory', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_DiscreteHistory'))
        begin   
           DROP procedure dbo.xp_DiscreteHistory
        end
go
exec sp_addextendedproc 'xp_DiscreteHistory', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_AnalogWideHistory'))
        begin   
           DROP procedure dbo.xp_AnalogWideHistory
        end
go
exec sp_addextendedproc 'xp_AnalogWideHistory', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_DiscreteWideHistory'))
        begin   
           DROP procedure dbo.xp_DiscreteWideHistory
        end
go
exec sp_addextendedproc 'xp_DiscreteWideHistory', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_SetStorageTimeDeadband'))
        begin   
           DROP procedure dbo.xp_SetStorageTimeDeadband
        end
go
sp_addextendedproc 'xp_SetStorageTimeDeadband', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_SetStorageValueDeadband'))
        begin   
           DROP procedure dbo.xp_SetStorageValueDeadband
        end
go
sp_addextendedproc 'xp_SetStorageValueDeadband', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_AnalogHistoryDelta'))
        begin   
           DROP procedure dbo.xp_AnalogHistoryDelta
        end
go
sp_addextendedproc 'xp_AnalogHistoryDelta', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_DiscreteHistoryDelta'))
        begin   
           DROP procedure dbo.xp_DiscreteHistoryDelta
        end
go
sp_addextendedproc 'xp_DiscreteHistoryDelta', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_AnalogWideHistoryDelta'))
        begin   
           DROP procedure dbo.xp_AnalogWideHistoryDelta
        end
go
sp_addextendedproc 'xp_AnalogWideHistoryDelta', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_DiscreteWideHistoryDelta'))
        begin   
           DROP procedure dbo.xp_DiscreteWideHistoryDelta
        end
go
sp_addextendedproc 'xp_DiscreteWideHistoryDelta', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_NewHistoryBlock'))
        begin   
           DROP procedure dbo.xp_NewHistoryBlock
        end
go
sp_addextendedproc 'xp_NewHistoryBlock', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_TZgetdate'))
        begin   
           DROP procedure dbo.xp_TZgetdate
        end
go
sp_addextendedproc 'xp_TZgetdate', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_AllowCommit'))
        begin   
           DROP procedure dbo.xp_AllowCommit
        end
go
sp_addextendedproc 'xp_AllowCommit', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_SetAutoStart'))
        begin   
           DROP procedure dbo.xp_SetAutoStart
        end
go
sp_addextendedproc 'xp_SetAutoStart', 'aahSQLXP.dll'
go

--IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_CalculateEnumCRC'))
--        begin   
--           DROP procedure dbo.xp_CalculateEnumCRC
--        end
--go
--sp_addextendedproc 'xp_CalculateEnumCRC', 'aahSQLXP.dll'
--go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_RescanHistoryBlocks'))
        begin   
           DROP procedure dbo.xp_RescanHistoryBlocks
        end
go
sp_addextendedproc 'xp_RescanHistoryBlocks', 'aahSQLXP.dll'
go

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('dbo.xp_SetStoreForwardEvent'))
        begin   
           DROP procedure dbo.xp_SetStoreForwardEvent
        end
go
sp_addextendedproc 'xp_SetStoreForwardEvent', 'aahSQLXP.dll'
go

grant exec on xp_ProcList to Public
go
grant exec on xp_DiskCopy to aaAdministrators
go
grant exec on xp_AnalogHistory to Public
go
grant exec on xp_DiscreteHistory to Public
go
grant exec on xp_AnalogWideHistory to Public
go
grant exec on xp_DiscreteWideHistory to Public
go
grant exec on xp_SetStorageTimeDeadband to aaAdministrators
go
grant exec on xp_SetStorageValueDeadband to aaAdministrators
go
grant exec on xp_sendmail to aaAdministrators
go
grant exec on xp_AnalogHistoryDelta to Public
go
grant exec on xp_DiscreteHistoryDelta to Public
go
grant exec on xp_AnalogWideHistoryDelta to Public
go
grant exec on xp_DiscreteWideHistoryDelta to Public
go
grant exec on xp_NewHistoryBlock to aaAdministrators
go
grant exec on xp_TZgetdate to Public
go
grant exec on xp_AllowCommit to Public
go
grant exec on xp_SetAutoStart to aaAdministrators
go
--grant exec on xp_CalculateEnumCRC to Public
--go
grant exec on xp_RescanHistoryBlocks to Public
go
grant exec on xp_SetStoreForwardEvent to aaAdministrators
go
use Runtime
go

 
 /*
Insert IOServerType basic list as a good starting point
=======================================================
*/

DELETE IOServerType

set NoCount ON

/* IOServerType
*/
INSERT IOServerType (Description,ExeName, ApplicationName) VALUES (N'IndustrialSQL System Driver', 'sysdrv.exe', 'SysDrv')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Allen-Bradley 1784-KT','ab1784kt','ab1784kt')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Allen-Bradley Ethernet Direct','abtcp','abtcp')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Allen-Bradley Interchange','abintchg','abintchg')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Allen-Bradley Serial','abkf2','abkf2')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Aquatrol 1500 Modbus','aq1500mb','aq1500mb')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'R-Net Direct Link','amrnet','amrnet')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Bristol Babcock Open BSI','bsap','bsap')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Fisher ROC','theroc','theroc')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'GE Fanuc CCM2','geccm','geccm')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'GE Fanuc Genius','genius','genius')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'GE Fanuc Host Communications (HCS)','gehcs','gehcs')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'GE Fanuc Series 90 Protocol (SNP)','gesnp','gesnp')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'JBUS','jbus','jbus')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Mitsubishi A-Series','melseca','melseca')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'MMux','mmux','mmux')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Modicon Modbus','modbus','modbus')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Modicon Modbus Plus','mbplus','mbplus')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'OMRON Host Link','omronhl','omronhl')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Reliance Automate Serial','automate','automate')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Reliance Automax PC Link','automax','automax')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens 3964R','s3964r','s3964r')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SINEC H1','h1server','h1server')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SINEC H1 CP 1413','h1cp1413','h1cp1413')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SINEC L2 FDL','l2server','l2server')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SINEC L2 FDL A2','l2fdla2','l2fdla2')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SINEC S7','s7','s7')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens / Texas Instruments 305/405 CCM','ti405','ti405')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens / Texas Instruments 405 Modbus','ti405mbs','ti405mbs')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SIMATIC TI CVU TIWAY','ticvu','ticvu')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SIMATIC TI Direct','tidir','tidir')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SIMATIC TI TIWAY','tiway','tiway')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Square D SY/ENET','syenet','syenet')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Square D SY/LINK','synet','synet')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Square D SY/MAX Point-to-Point','symax','symax')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'S-S Technologies 5136-SD','ss5136sd','ss5136sd')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Télémécanique Xway','telemech','telemech')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Wonderware InTouch','VIEW','VIEW')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Wonderware InControl','rtengine','rtengine')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Wonderware TestProt','testprot','testprot')

/* Added in FS2000 7.1 release */
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Wonderware InSQL Server (legacy)','InSQLIOS','InSQLIOS')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Modicon Ethernet','mbenet','mbenet')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'OMRON SYSMAC NET','omronfo','omronfo')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'OPC Link/OPC Browser','opclink','opclink')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Wonderware WWRSLinx','wwrslinx','wwrslinx')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Siemens SIMATIC Net','Profibus FMS','profibus')

/* Added for InSQL80 release */
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Wonderware InSQL MDAS','InSQL_MDAS','InSQL_MDAS')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Wonderware InSQL Manual Data','InSQL_Manual_Data','InSQL_Manual_Data')

/* Added for InSQL80 SP1 release */
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'DAServer for Allen Bradley PCCC Protocol','DASABTCP','DASABTCP')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'DAServer for Allen Bradley CIP Protocol','DASABCIP','DASABCIP')

/* Added for InSQL90 release */
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'Wonderware InSQL Server','aahIOSvrSvc','aahIOSvrSvc')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'DAServer for Allen Bradley DH Plus Protocol','DASABDHPLUS','DASABDHPlus')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'DAServer for Siemens S7 Protocol','DASSIDirect','DASSIDirect')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'DAServer for Siemens SIMATIC Net Protocol','DASS7','DASS7')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'DAServer for Modicon Ethernet Protocol','DASMBTCP','DASMBTCP')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'DAServer for Modicon Modbus Protocol','DASMBSerial','DASMBSerial')
INSERT IOServerType (Description,ApplicationName,ExeName) VALUES (N'FactorySuite Gateway to DDE, OPC DA and ArchestrA','FSGateway','FSGateway')
go

 
 /*
Populate summary support tables
===============================
*/

set nocount on
go

delete SummaryOperation
go

delete Frequency
go
INSERT Frequency (Frequency) values (N'Hour')
INSERT Frequency (Frequency) values (N'Day')
INSERT Frequency (Frequency) values (N'Week')
INSERT Frequency (Frequency) values (N'Month')
INSERT Frequency (Frequency) values (N'Periodic')
go

delete CalcType
go
INSERT CalcType (CalcType, Description) values ('AVG',N'Average of values of the tag')
INSERT CalcType (CalcType, Description) values ('MIN',N'Minimum value of the tag')
INSERT CalcType (CalcType, Description) values ('MAX',N'Maximum value of the tag')
INSERT CalcType (CalcType, Description) values ('SUM',N'Sum of the values of the tag')
go

 
 /*
Populate the SystemParameter table
==================================
*/

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'DatabaseVersion')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('DatabaseVersion', N'9,0,015,055', 0, N'Runtime database version')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'SystemVersion')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('SystemVersion', '8,0,000,000', 0, N'For backward compatibility only')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HistorianVersion')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HistorianVersion', '9,0,000,000', 0, N'Historian system version')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'ConfigEditorVersion')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('ConfigEditorVersion', N'9,0,000,000', 0, N'Minimum required Configuration Editor version')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'EventStorageDuration')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('EventStorageDuration', 168, 1, N'Max Event History Storage Duration (hours)')   /* 7 days */
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'SummaryStorageDuration')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('SummaryStorageDuration', 336, 1, N'Max Summary History Storage Duration (hours)')    /* 14 days */
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'ModLogTrackingStatus')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('ModLogTrackingStatus', 0, 1, N'Configures modification logging')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HoursPerBlock')
   BEGIN
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HoursPerBlock', 24, 1, N'History block duration (hours)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'AIAutoResize')
   BEGIN
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('AIAutoResize', 1, 1, N'Active image auto resize option. (1=Enabled - 0=Disabled)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'AIResizeInterval')
   BEGIN
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('AIResizeInterval', 5, 1, N'Active image resize interval (minutes)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'DataImportPath')
   BEGIN
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('DataImportPath', '', 1, N'File path for CSV files containing old data')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'TimeSyncMaster')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('TimeSyncMaster', '', 1, N'Server Time Synchronization source. (Must contain the machine name from which this Historian should time sync.) ')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'TimeSyncIODrivers')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('TimeSyncIODrivers', 1, 1, N'When set to 1, this Historian will send time synchronization commands to all its remote IDASs')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'SysPerfTags')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('SysPerfTags', 1, 1, N'System Performance Tags acquisition (0 = Off, 1 = On)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HeadroomAnalog2')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HeadroomAnalog2', 100, 1, N'Number of 2-byte delta analog tags to pre-allocate')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HeadroomAnalog4')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HeadroomAnalog4', 100, 1, N'Number of 4-byte delta analog tags to pre-allocate')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HeadroomAnalog8')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HeadroomAnalog8', 0, 1, N'Number of 8-byte delta analog tags to pre-allocate')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HeadroomDiscrete')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HeadroomDiscrete', 100, 1, N'Number of discrete tags to pre-allocate')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HeadroomString')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HeadroomString', 20, 1, N'Number of string tags to pre-allocate')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'AutoStart')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('AutoStart', 0, 1, N'When set to 1 the system starts automatically')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'SuiteLinkTimeSyncInterval')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('SuiteLinkTimeSyncInterval', 60, 1, N'Number of minutes between SuiteLink time synchronizations (0 = no time sync)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'LicenseTagCount')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('LicenseTagCount', 0, 0, N'Number of allowed tags, read from License')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'LicenseRemoteIDASCount')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('LicenseRemoteIDASCount', 'None (unlicensed)', 0, N'Number of allowed remote IDAS, read from License')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'AllowOriginals')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('AllowOriginals', 0, 1, N'Allow/Disallow manual original data insert for IO Server tags')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'QualityRule')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('QualityRule', 0, 1, N'Use Good and Uncertain points (0), or Good points only (1)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'TimeStampRule')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('TimeStampRule', 1, 1, N'Time stamp at start (0), or end (1) of time interval')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'InterpolationTypeInteger')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('InterpolationTypeInteger', 0, 1, N'Interpolation type for integers (0=Stair, 1=Linear)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'InterpolationTypeReal')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('InterpolationTypeReal', 1, 1, N'Interpolation type for reals (0=Stair, 1=Linear)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HistoryCacheSize')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HistoryCacheSize', 0, 1, N'Allocated memory for history block information (MB)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'HistoryDaysAlwaysCached')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('HistoryDaysAlwaysCached', 0, 1, N'Duration for which history block information is always loaded (days)')
   END
GO

IF not exists (SELECT Name FROM SystemParameter WHERE Name = 'RealTimeWindow')
   BEGIN 
      INSERT SystemParameter (Name, Value, Editable, Description)
         VALUES ('RealTimeWindow', 60, 1, N'Maximum delay, relative to current time, for which data will be considered real-time, when processing swinging door and late data (seconds)')
   END
GO

/* Populate HistorianSysObjects with the details of all User Tables */
INSERT HistorianSysObjects (id,Type,Name) 
  SELECT id, type,name from sysobjects 
  WHERE type = 'U'
GO


/* Populate SnapshotDetail table */

INSERT SnapshotDetail values(-1, default, default, default, default)
INSERT SnapshotDetail values(0, default, default, default, default)
INSERT SnapshotDetail values(1, default, default, default, default)
INSERT SnapshotDetail values(2, default, default, default, default)
INSERT SnapshotDetail values(4, default, default, default, default)
INSERT SnapshotDetail values(8, default, default, default, default) 


/* Populate Detector and Action Type */
INSERT INTO DetectorType (Name, Description, EditorClassName, DetectorClassName)
VALUES (N'System', N'System Detector', NULL, NULL)

INSERT INTO DetectorType (Name, Description, EditorClassName, DetectorClassName)
VALUES (N'External', N'External Detector', NULL, NULL)

INSERT INTO DetectorType (Name, Description, EditorClassName, DetectorClassName)
VALUES (N'Generic SQL', N'Generic SQL Detector', N'GenericDetectorEditor.GenericDetectorEditor', N'Invensys.EventDetector.1')

INSERT INTO DetectorType (Name, Description, EditorClassName, DetectorClassName)
VALUES (N'Analog Specific Value', N'Analog Specific Value SQL Detector',  N'SVAnalogDetectorEditor.SVAnalogDetectorEditor', N'Invensys.EventDetector.1')

INSERT INTO DetectorType (Name, Description, EditorClassName, DetectorClassName)
VALUES (N'Discrete Specific Value', N'Discrete Specific Value SQL Detector',  N'SVDiscreteDetectorEditor.SVDiscreteDetectorEditor', N'Invensys.EventDetector.1')

INSERT INTO DetectorType (Name, Description, EditorClassName, DetectorClassName)
VALUES (N'Schedule', N'Schedule Detector', N'ScheduleDetectorEditor.ScheduleDetectorEditor', N'Invensys.EventDetector.1')


INSERT INTO ActionType (Name, Description, EditorClassName, ActionClassName)
VALUES (N'None', N'No defined Action', NULL, NULL)

INSERT INTO ActionType (Name, Description, EditorClassName, ActionClassName)
VALUES (N'Generic SQL', N'Generic SQL Action', N'GenericActionEditor.GenericActionEditor', N'Invensys.EventAction.1')

INSERT INTO ActionType (Name, Description, EditorClassName, ActionClassName)
VALUES (N'Snapshot', N'Snapshot Action', N'SnapShotActionEditor.SnapShotActionEditor', N'Invensys.EventAction.1')

INSERT INTO ActionType (Name, Description, EditorClassName, ActionClassName)
VALUES (N'E-mail', N'E-mail Action', N'EMailActionEditor.EMailActionEditor', N'Invensys.EventAction.1')

INSERT INTO ActionType (Name, Description, EditorClassName, ActionClassName)
VALUES (N'Deadband', N'Deadband Action', N'DeadbandActionEditor.DeadbandActionEditor', N'Invensys.EventAction.1')

INSERT INTO ActionType (Name, Description, EditorClassName, ActionClassName)
VALUES (N'Summary', N'Summary Calculation Action', N'SummaryActionEditor.SummaryActionEditor', N'Invensys.EventAction.1')

INSERT INTO ActionType (Name, Description, EditorClassName, ActionClassName)
VALUES (N'Stop/Start Storage', N'Stop/Start Storage Action', N'', N'')

GO

 
 /*******************************************************************/
/* Namespace Population Script                                     */
/*******************************************************************/

DELETE NameSpaceIcons
go

-- System Leaf Icons ------------------------------------------------
INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1, N'IDC_L_ANALOG_TAG', N'Analog Tag')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (2, N'IDC_L_DISCRETE_TAG', N'Discrete Tag')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (3, N'IDC_L_STRING_TAG', N'String Tag')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (4, N'IDC_L_COMPLEX_TAG', N'Complex Tag')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (5, N'IDC_L_EVENT_TAG', N'Event Tag')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (6, N'IDC_L_USER', N'User')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (7, N'IDC_L_SERVER', N'Server')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (8, N'IDC_L_STORAGE_LOCATION', N'Storage Location')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (9, N'IDC_L_STORAGE_NODE', N'Storage Node')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (10, N'IDC_L_IO_SERVER_TYPE', N'IO Server Type')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (11, N'IDC_L_IO_SERVER', N'IO Server')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (12, N'IDC_L_MESSAGE', N'Message')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (13, N'IDC_L_ENGINEERING_UNIT', N'Engineering Unit')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (14, N'IDC_L_INTOUCH_NODE', N'Imported InTouch Node')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (15, N'IDC_L_TOPIC', N'Topic')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (16, N'IDC_L_TAG', N'Tag')
go

-- Generic Folder ---------------------------------------------------
INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000000, N'IDC_G_FOLDER', N'Folder')
go

-- Root -------------------------------------------------------------
INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000001, N'IDC_G_WONDERWORLD', N'WonderWorld')
go

-- Namespace Roots --------------------------------------------------
INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000002, N'IDC_G_SYSTEM', N'System')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000003, N'IDC_G_PRIVATE', N'Private')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000004, N'IDC_G_PUBLIC', N'Public')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000005, N'IDC_G_USER', N'Users')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000006, N'IDC_G_SERVER', N'Servers')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000007, N'IDC_G_STORAGE_LOCATION', N'Storage Locations')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000008, N'IDC_G_STORAGE_NODE', N'Storage Nodes')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000009, N'IDC_G_IO_SERVER_TYPE', N'I/O Server Types')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000010, N'IDC_G_IO_SERVER', N'IO Servers')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000011, N'IDC_G_MESSAGE', N'Messages')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000012, N'IDC_G_ENGINEERING_UNIT', N'Engineering Units')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000013, N'IDC_G_INTOUCH_NODE', N'Imported InTouch Nodes')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000014, N'IDC_G_TOPIC', N'Topics')
go

INSERT INTO NameSpaceIcons
  (Type, Name, Description)
VALUES
  (1000015, N'IDC_G_TAG', N'Tags')
go

INSERT INTO NameSpaceIcons
( Type, Name, Description)
VALUES
 (1000016, N'IDC_G_EVENT', N'Events')
go

/*******************************************************************/
/* Private Namespace                                               */
/*******************************************************************/

DELETE PrivateNameSpace
go

-- IDENTITY 1 -------------------------------------------------------
INSERT INTO PrivateNameSpace
  (UserKey, Type, ParentKey, Name)
VALUES
  (0, 1000003, 0, N'Private Groups')
go

/*******************************************************************/
/* Public Namespace                                                */
/*******************************************************************/

DELETE PublicNameSpace
go

-- IDENTITY 1 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000004, 0, N'Public Groups')
go

/*******************************************************************/
/* System Variable Groups                                          */
/*******************************************************************/

-- IDENTITY 2 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 1, N'All Analog Tags')
go

-- IDENTITY 3 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 1, N'All Discrete Tags')
go

-- IDENTITY 4 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 1, N'All String Tags')
go

-- IDENTITY 5 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, -1, N'All Complex Tags')

-- IDENTITY 6 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 1, N'All Event Tags')
go

-- IDENTITY 7 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 1, N'InTouch Nodes')
go

-- IDENTITY 8 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 1, N'System Status Tags')
go

-- IDENTITY 9 -------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'Error')
go

-- IDENTITY 10 ------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'Date')
go

-- IDENTITY 11 ------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'Time')
go

-- IDENTITY 12 ------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'Space')
go

-- IDENTITY 13 ------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'I/O Stats')
go

-- IDENTITY 14 ------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'Event System')
go

-- IDENTITY 15 ------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'System Monitoring')
go

-- IDENTITY 16 ------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'Performance Monitoring')
go

-- IDENTITY 17 ------------------------------------------------------
INSERT INTO PublicNameSpace
  (Type, ParentKey, Name)
VALUES
  (1000000, 8, N'Others')
go

DELETE PublicGroupTag
go


 
 /*
Insert the data for the Historian System
========================================
*/

INSERT ServerList
  (ComputerName, Description)
VALUES 
  (ISNULL(@@ServerName, 'UnNamed'), N'Historian')
GO

SET NoCount ON

DECLARE @NodeKey     int
DECLARE @IOServerKey int
DECLARE @NoUnit      int
DECLARE @SecUnit     int
DECLARE @MinUnit     int
DECLARE @HourUnit    int
DECLARE @DayUnit     int
DECLARE @MonthUnit   int
DECLARE @YearUnit    int
DECLARE @SpaceUnit   int
DECLARE @PerCentUnit int
DECLARE @wwTagKey    int
DECLARE @BytesUnit   int

/* Storage */

INSERT StorageNode (ComputerName)
   VALUES (ISNULL(@@ServerName,'UnNamed'))

SELECT @NodeKey = @@IDENTITY

/* Storage Loc */
INSERT StorageLocation
  (StorageType, SortOrder, StorageNodeKey, Path, MaxMBSize, MinMBThreshold, MaxAgeThreshold)
VALUES 
  (1, 1, @NodeKey, 'rr:\CircularData', 0, 125, 0)
   
INSERT StorageLocation 
  (StorageType, SortOrder, StorageNodeKey, Path, MaxMBSize, MinMBThreshold, MaxAgeThreshold)
VALUES
  (2, 1, @NodeKey, 'rr:\OverflowData', 0, 125, 0)

INSERT StorageLocation
  (StorageType, SortOrder, StorageNodeKey, Path, MaxMBSize, MinMBThreshold, MaxAgeThreshold)
VALUES
  (3, 1, @NodeKey, 'rr:\BufferData', 0, 125, 0)

INSERT StorageLocation
  (StorageType, SortOrder, StorageNodeKey, Path, MaxMBSize, MinMBThreshold, MaxAgeThreshold)
VALUES
  (4, 1, @NodeKey, 'rr:\PermanentData', 0, 125, 0)

/* System & MDAS IODrivers (place holders) */
SET IDENTITY_INSERT IODriver ON

insert IODriver (IODriverKey, StorageNodeKey, ComputerName, StoreForwardMode, MinMBThreshold)
values (1, 1, 'Historian System', 0, 0)

insert IODriver (IODriverKey, StorageNodeKey, ComputerName, StoreForwardMode, MinMBThreshold)
values (0, 1, 'Historian MDAS', 0, 0)

SET IDENTITY_INSERT IODriver OFF


/* IOServer for sys tags */
EXEC  aaIOServerInsert
  @StorageNodeKey       = @NodeKey,
  @ApplicationName      = 'SysDrv',
  @Description          = 'System Status I/O Server', 
  @AutoStart            = 0,
  @ExeType              = 1,
  @InitializationStatus = 0,
  @ProtocolType         = 2,
  @ComputerName         = @@ServerName,
  @IODriverKey          = 1

SELECT @IOServerKey = (SELECT IOServerKey FROM IOServer WHERE ApplicationName = 'SysDrv')

-- Insert Topics for SysTags -- 
EXEC aaTopicInsert
  @IOServerKey    = @IOServerKey, 
  @StorageNodeKey = @NodeKey,
  @Name           = 'System'

/* IOServer for MDAS */
EXEC  aaIOServerInsert
  @StorageNodeKey       = @NodeKey,
  @ApplicationName      = 'InSQL_MDAS',
  @Description          = 'InSQL MDAS', 
  @AutoStart            = 0,
  @ExeType              = 1,
  @InitializationStatus = 0,
  @ProtocolType         = 2,
  @ComputerName         = @@ServerName,
  @IODriverKey          = 0

SELECT @IOServerKey = (SELECT IOServerKey FROM IOServer WHERE ApplicationName = 'InSQL_MDAS')

-- Insert Topics for MDAS -- 
EXEC aaTopicInsert
  @IOServerKey    = @IOServerKey, 
  @StorageNodeKey = @NodeKey,
  @Name           = 'MDAS'

/* End of Default IOServer Definition */

/* Start insertion of System Tags     */

/* Legacy Engineering Units */
/* These units were present, in this order, in previous versions of InSQL including 8.0. */
EXEC @PerCentUnit = aaEngineeringUnitInsert '%'
EXEC @NoUnit      = aaEngineeringUnitInsert 'None'
EXEC @SecUnit     = aaEngineeringUnitInsert 'Second'
EXEC @MinUnit     = aaEngineeringUnitInsert 'Minute'
EXEC @HourUnit    = aaEngineeringUnitInsert 'Hour'
EXEC @DayUnit     = aaEngineeringUnitInsert 'Day'
EXEC @MonthUnit   = aaEngineeringUnitInsert 'Month'
EXEC @YearUnit    = aaEngineeringUnitInsert 'Year'
EXEC @SpaceUnit   = aaEngineeringUnitInsert 'Mb'
EXEC @BytesUnit   = aaEngineeringUnitInsert 'Bytes'

/* Additional engineering units */
EXEC aaEngineeringUnitInsert @Unit='ft' 
EXEC aaEngineeringUnitInsert @Unit='in' 
EXEC aaEngineeringUnitInsert @Unit='cm' 
EXEC aaEngineeringUnitInsert @Unit='m' 
EXEC aaEngineeringUnitInsert @Unit='ft/s', @IntegralDivisor=1
EXEC aaEngineeringUnitInsert @Unit='ft/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='m/s', @IntegralDivisor=1
EXEC aaEngineeringUnitInsert @Unit='m/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='gal' 
EXEC aaEngineeringUnitInsert @Unit='m3' 
EXEC aaEngineeringUnitInsert @Unit='l' 
EXEC aaEngineeringUnitInsert @Unit='hl' 
EXEC aaEngineeringUnitInsert @Unit='gal/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='gal/h', @IntegralDivisor=3600
EXEC aaEngineeringUnitInsert @Unit='gal/d', @IntegralDivisor=86400
EXEC aaEngineeringUnitInsert @Unit='m3/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='l/s', @IntegralDivisor=1
EXEC aaEngineeringUnitInsert @Unit='l/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='hl/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='l/h', @IntegralDivisor=3600
EXEC aaEngineeringUnitInsert @Unit='hl/h', @IntegralDivisor=3600
EXEC aaEngineeringUnitInsert @Unit='l/d', @IntegralDivisor=86400
EXEC aaEngineeringUnitInsert @Unit='hl/d', @IntegralDivisor=86400
EXEC aaEngineeringUnitInsert @Unit='kg' 
EXEC aaEngineeringUnitInsert @Unit='t' 
EXEC aaEngineeringUnitInsert @Unit='kg/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='t/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='t/h', @IntegralDivisor=3600
EXEC aaEngineeringUnitInsert @Unit='t/d', @IntegralDivisor=86400
EXEC aaEngineeringUnitInsert @Unit='lb' 
EXEC aaEngineeringUnitInsert @Unit='lb/s', @IntegralDivisor=1
EXEC aaEngineeringUnitInsert @Unit='lb/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='psi' 
EXEC aaEngineeringUnitInsert @Unit='Pa' 
EXEC aaEngineeringUnitInsert @Unit='hPa' 
EXEC aaEngineeringUnitInsert @Unit='kW' 
EXEC aaEngineeringUnitInsert @Unit='MW' 
EXEC aaEngineeringUnitInsert @Unit='A' 
EXEC aaEngineeringUnitInsert @Unit='V' 
EXEC aaEngineeringUnitInsert @Unit='kV' 
declare @degF nchar(2)
set @degF = nchar(176) + N'F'
EXEC aaEngineeringUnitInsert @Unit=@degF
declare @degC nchar(2)
set @degC = nchar(176) + N'C'
EXEC aaEngineeringUnitInsert @Unit=@degC 
EXEC aaEngineeringUnitInsert @Unit='K' 
EXEC aaEngineeringUnitInsert @Unit='units' 
EXEC aaEngineeringUnitInsert @Unit='rpm', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='units/s', @IntegralDivisor=1
EXEC aaEngineeringUnitInsert @Unit='units/min', @IntegralDivisor=60
EXEC aaEngineeringUnitInsert @Unit='units/h', @IntegralDivisor=3600
EXEC aaEngineeringUnitInsert @Unit='units/d', @IntegralDivisor=86400

EXEC aaAnalogTagInsert
  @TagName         = 'SysCritErrCnt',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Total Critical errors since startup',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 60000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysCritErrCnt',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysFatalErrCnt',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Total Fatal errors since startup',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 60000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysFatalErrCnt',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysErrErrCnt',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Total non-fatal errors since startup',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 60000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysErrErrCnt',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 10000,
  @MinRaw          = 0,
  @MaxRaw          = 10000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysWarnErrCnt',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Total warnings since startup',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 60000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysWarnErrCnt',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 10000,
  @MinRaw          = 0,
  @MaxRaw          = 10000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysStatusRxTotalItems',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Total items received from SysDrv since startup',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 10000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysStatusRxTotalItems',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 2000000000,
  @MinRaw          = 0,
  @MaxRaw          = 2000000000,
  @Scaling         = 0,
  @RawType         = 2,
  @IntegerSize     = 0,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysStatusRxItemsPerSec',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Items per second received from SysDrv',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 1000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysStatusRxItemsPerSec',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 10000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 2,
  @IntegerSize     = 0,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysSpaceMain',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Space left on Circular Data Path',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 300000,
  @TimeDeadband    = 300000,
  @ItemName        = 'SysSpaceMain',
  @EUKey           = @SpaceUnit,
  @MinEU           = 0,
  @MaxEU           = 100000,
  @MinRaw          = 0,
  @MaxRaw          = 100000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysSpaceAlt',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Space left on Alternative Data Path',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 300000,
  @TimeDeadband    = 300000,
  @ItemName        = 'SysSpaceAlt',
  @EUKey           = @SpaceUnit,
  @MinEU           = 0,
  @MaxEU           = 100000,
  @MinRaw          = 0,
  @MaxRaw          = 100000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysSpaceBuffer',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Space left on Buffer Data Path',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 300000,
  @TimeDeadband    = 300000,
  @ItemName        = 'SysSpaceBuffer',
  @EUKey           = @SpaceUnit,
  @MinEU           = 0,
  @MaxEU           = 100000,
  @MinRaw          = 0,
  @MaxRaw          = 100000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysSpacePerm',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Space left on Permanent Data Path',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 300000,
  @TimeDeadband    = 300000,
  @ItemName        = 'SysSpacePerm',
  @EUKey           = @SpaceUnit,
  @MinEU           = 0,
  @MaxEU           = 100000,
  @MinRaw          = 0,
  @MaxRaw          = 100000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysMinutesRun',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Minutes since the last startup',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 60000,
  @ItemName        = 'SysMinutesRun',
  @EUKey           = @MinUnit,
  @MinEU           = 0,
  @MaxEU           = 500000,
  @MinRaw          = 0,
  @MaxRaw          = 500000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysTimeSec',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'System Time : Seconds',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 1000,
  @ItemName        = 'SysTimeSec',
  @EUKey           = @SecUnit,
  @MinEU           = 0,
  @MaxEU           = 59,
  @MinRaw          = 0,
  @MaxRaw          = 59,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0,
  @RolloverValue   = 60

EXEC  aaAnalogTagInsert
  @TagName         = 'SysTimeMin',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'System Time : Minutes',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 60000,
  @ItemName        = 'SysTimeMin',
  @EUKey           = @MinUnit,
  @MinEU           = 0,
  @MaxEU           = 59,
  @MinRaw          = 0,
  @MaxRaw          = 59,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0,
  @RolloverValue   = 60

EXEC  aaAnalogTagInsert
  @TagName         = 'SysTimeHour',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'System Time : Hours',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 300000,
  @ItemName        = 'SysTimeHour',
  @EUKey           = @HourUnit,
  @MinEU           = 0,
  @MaxEU           = 23,
  @MinRaw          = 0,
  @MaxRaw          = 23,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0,
  @RolloverValue   = 24

EXEC  aaAnalogTagInsert
  @TagName         = 'SysDateDay',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'System Date : Day',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 300000,
  @ItemName        = 'SysDateDay',
  @EUKey           = @DayUnit,
  @MinEU           = 1,
  @MaxEU           = 31,
  @MinRaw          = 1,
  @MaxRaw          = 31,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysDateMonth',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'System Date : Month',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 300000,
  @ItemName        = 'SysDateMonth',
  @EUKey           = @MonthUnit,
  @MinEU           = 1,
  @MaxEU           = 12,
  @MinRaw          = 1,
  @MaxRaw          = 12,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC  aaAnalogTagInsert
  @TagName         = 'SysDateYear',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'System Date : Year',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 300000,
  @ItemName        = 'SysDateYear',
  @EUKey           = @YearUnit,
  @MinEU           = 0,
  @MaxEU           = 2050,
  @MinRaw          = 0,
  @MaxRaw          = 2050,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysConfigStatus',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'System Configuration Status (Re-init tracking)',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 10000,
  @ItemName        = 'SysConfigStatus',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 200,
  @MinRaw          = 0,
  @MaxRaw          = 200,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfCPUTotal',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU total processor load',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfCPUTotal',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfCPU0',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load on processor 0',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfCPU0',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfCPU1',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load on processor 1',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfCPU1',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfCPU2',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load on processor 2',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfCPU2',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfCPU3',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load on processor 3',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfCPU3',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0


EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfConfigCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for Historian Config Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfConfigCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfEventSysCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for Historian Event System',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfEventSysCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfStorageCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for Historian Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfStorageCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfManualStorageCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for Historian Manual Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfManualStorageCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfInSQLIOSCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for InSQLIOS',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfInSQLIOSCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSysDrvCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for Historian System Driver',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfSysDrvCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSQLServerCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for MS-SQL Server',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfSQLServerCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfRetrievalCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for Retrieval Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfRetrievalCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfConfigPrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for Historian Config Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfConfigPrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfConfigVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for Historian Config Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfConfigVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfEventSysPrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for Historian Event System',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfEventSysPrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfEventSysVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for Historian Event System',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfEventSysVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfStoragePrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for Historian Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfStoragePrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfStorageVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for Historian Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfStorageVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfManualStoragePrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for Historian Manual Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfManualStoragePrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfManualStorageVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for Historian Manual Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfManualStorageVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0


 
 EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfInSQLIOSPrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for InSQLIOS',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfInSQLIOSPrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfInSQLIOSVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for InSQLIOS',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfInSQLIOSVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSysDrvPrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for Historian System Driver',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfSysDrvPrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSysDrvVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for Historian System Driver',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfSysDrvVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSQLServerPrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for MS-SQL Server',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfSQLServerPrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSQLServerVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for MS-SQL Server',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfSQLServerVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfRetrievalPrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for Retrieval Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfRetrievalPrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfRetrievalVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for Retrieval Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfRetrievalVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfConfigThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for Historian Config Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfConfigThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfEventSysThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for Historian Event System',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfEventSysThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfStorageThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for Historian Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfStorageThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfManualStorageThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for Historian Manual Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfManualStorageThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfInSQLIOSThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for InSQLIOS',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfInSQLIOSThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSysDrvThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for Historian System Driver',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfSysDrvThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSQLServerThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for MS-SQL Server',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfSQLServerThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfRetrievalThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for Retrieval Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfRetrievalThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfConfigHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for Historian Config Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfConfigHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfEventSysHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for Historian Event System',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfEventSysHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfStorageHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for Historian Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfStorageHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfManualStorageHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for Historian Manual Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfManualStorageHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfInSQLIOSHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for InSQLIOS',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfInSQLIOSHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSysDrvHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for Historian System Driver',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfSysDrvHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSQLServerHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for MS-SQL Server',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfSQLServerHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfRetrievalHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for Retrieval Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfRetrievalHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfConfigPageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for Historian Config Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfConfigPageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfEventSysPageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for Historian Event System',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfEventSysPageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfStoragePageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for Historian Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfStoragePageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfManualStoragePageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for Historian Manual Storage',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfManualStoragePageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfInSQLIOSPageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for InSQLIOS',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfInSQLIOSPageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSysDrvPageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for Historian System Driver',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfSysDrvPageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfSQLServerPageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for MS-SQL Server',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfSQLServerPageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfRetrievalPageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for Retrieval Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfRetrievalPageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysHeadroomAnalog2',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Available headroom for Analog Tags (2 bytes)',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysHeadroomAnalog2',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysHeadroomAnalog4',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Available headroom for Analog Tags (4 bytes)',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysHeadroomAnalog4',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysHeadroomAnalog8',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Available headroom for Analog Tags (8 bytes)',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysHeadroomAnalog8',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysHeadroomDiscrete',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Available headroom for Discrete Tags',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysHeadroomDiscrete',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysHeadroomString',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Available headroom for String Tags',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysHeadroomString',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysEventNormActionQSize',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Event System Normal Action Queue Size',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 10000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysEventNormActionQSize',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysEventCritActionQSize',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Event System Critical Action Queue Size',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 10000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysEventCritActionQSize',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysEventDelayedActionQSize',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Event System Delayed Action Queue Size',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 10000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysEventDelayedActionQSize',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

GO
 
 EXEC aaMessageInsert 'OFF', 'ON'

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysPulse',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System Pulse', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysPulse',
  @MessageKey      = 1

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysStorage',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System Storage Status', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysStorage',
  @MessageKey      = 1

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysEventSystem',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'Event System Status', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysEventSystem',
  @MessageKey      = 1

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysRetrieval',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System Lower Retrieval Status', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysRetrieval',
  @MessageKey      = 1

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysInSQLIOS',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System InSQL I/O Server Status', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysInSQLIOS',
  @MessageKey      = 1

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysConfiguration',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System Configuration Status (1 = Configuration changes pending or in progress)', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysConfiguration',
  @MessageKey      = 1

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysManualStorage',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System Manual (Late) Storage Service Status', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysManualStorage',
  @MessageKey      = 1

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysSystemDriver',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System Driver Service Status', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysSystemDriver',
  @MessageKey      = 1

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysOLEDB',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System OLE-DB Provider Status', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysOLEDB',
  @MessageKey      = 1

EXEC aaStringTagInsert
  @TagName         = 'SysString',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System Hourly String', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysString', 
  @MaxLength       = 131,
  @InitialValue    = '',
  @DoubleByte      = 1

GO
EXEC aaEventTagInsert 
  @TagName         = 'SysStatusEvent',
  @Description     = N'Status Tag snapshot event',
  @ScanRate        = 60000,
  @TimeDeadband    = 0,
  @Logged          = 1,
  @DetectorTypeKey = 4,
  @DetectorString  = N'exec aaEventDetection N''SysTimeMin'', ''='', 0, N''Leading'', 0,  ''@StartTime'',  ''@EndTime''',
  @ActionTypeKey   =  3,
  @ActionString    = N'exec aaEventSnapshotInsert @EventLogKey, ''@EventTime'', ''@EventTagName''',
  @Status = 0,
  @Priority = 0,
  @Edge = 1

INSERT SnapshotTag (TagName, EventTagName)
   VALUES (N'SysSpaceMain', N'SysStatusEvent')

INSERT SnapshotTag (TagName, EventTagName)
   VALUES (N'SysPerfCPUTotal', N'SysStatusEvent')
GO

INSERT TagGroup (GroupID, Description, Type)
   VALUES (1, 'System Tags', 42)
GO

/***********************************************************/
/* System Variables in Dedicated PublicGroupTag            */
/***********************************************************/

-- Other Variables ---------------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 17, wwDomainTagKey
  FROM   TagRef 
  WHERE  TagName = 'SysMinutesRun'

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 17, wwDomainTagKey 
  FROM   TagRef 
  WHERE  TagName = 'SysString'

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 17, wwDomainTagKey 
  FROM   TagRef 
  WHERE  TagName = 'SysConfigStatus'

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 17, wwDomainTagKey 
  FROM   TagRef 
  WHERE  TagName like 'SysHead%'

-- Error Variables --------------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 9, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName LIKE 'Sys%ErrCnt'

-- Date Variables ---------------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 10, wwDomainTagKey
  FROM   TagRef 
  WHERE  TagName LIKE 'SysDate%'

-- Time Variables ---------------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 11, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName LIKE 'SysTime%'

-- Space Variables --------------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 12, wwDomainTagKey 
  FROM   TagRef
  WHERE  TagName LIKE 'SysSpace%'

-- I/O Stats Variables -----------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 13, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName LIKE 'SysStatus%Rx%'
GO

-- Event Variables --------------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 14, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName LIKE 'SysEvent%'

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 14, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = 'SysStatusEvent'

-- System Monitoring --------------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 15, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName IN ( 'SysEventSystem', 'SysRetrieval', 'SysInSQLIOS', 
                                         'SysPulse', 'SysConfiguration', 'SysStorage',
                                         'SysManualStorage', 'SysSystemDriver', 'SysOLEDB')
GO

-- Performance Monitoring --------------------------------------------------
INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName LIKE 'SysPerf%'
GO

/* Add the Local IO Driver */
insert IODriver (StorageNodeKey, ComputerName, StoreForwardMode)
   select 1, @@SERVERNAME, 0 
GO

-- InSQL 9.0 System Tags --------------------------------------------------
-- Added after the other tags in order to preserve the same wwTagKeys as InSQL 8.0

DECLARE @NoUnit int
DECLARE @PerCentUnit int
DECLARE @BytesUnit int
select @NoUnit = EUKey from EngineeringUnit where Unit = 'None'
select @PerCentUnit = EUKey from EngineeringUnit where Unit = '%'
select @BytesUnit = EUKey from EngineeringUnit where Unit = 'Bytes'

-- Indexing Service --------------------------------------------------
EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfIndexingCPU',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = '%CPU load for Historian Indexing Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfIndexingCPU',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfIndexingPrivateBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Private Bytes for Historian Indexing Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfIndexingPrivateBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfIndexingVirtualBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Virtual Bytes for Historian Indexing Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysPerfIndexingVirtualBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 600000000,
  @MinRaw          = 0,
  @MaxRaw          = 600000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfIndexingThreadCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Thread count for Historian Indexing Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfIndexingThreadCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 128,
  @MinRaw          = 0,
  @MaxRaw          = 128,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfIndexingHandleCount',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Handle count for Historian Indexing Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfIndexingHandleCount',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 20000,
  @MinRaw          = 0,
  @MaxRaw          = 20000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfIndexingPageFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Page faults per second for Historian Indexing Service',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfIndexingPageFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 256,
  @MinRaw          = 0,
  @MaxRaw          = 256,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName LIKE 'SysPerfIndexing%'

EXEC aaDiscreteTagInsert 
  @TagName         = 'SysIndexing',
  @TopicKey        = 1, 
  @IOServerKey     = 1, 
  @Description     = N'System Indexing Service Status', 
  @AcquisitionType = 3, 
  @StorageType     = 2, 
  @StorageRate     = 0, 
  @ItemName        = N'SysIndexing',
  @MessageKey      = 1

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 15, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName = 'SysIndexing'

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfAvailableBytes',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Available physical memory',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfAvailableBytes',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 4000000000,
  @MinRaw          = 0,
  @MaxRaw          = 4000000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfMemoryPages',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Pages per second read from or written to disk to resolve hard page faults',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfMemoryPages',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 10000,
  @MinRaw          = 0,
  @MaxRaw          = 10000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysPerfDiskTime',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'% of elapsed time that system disk drives are busy servicing read or write requests',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysPerfDiskTime',
  @EUKey           = @PerCentUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 16, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName IN ('SysPerfAvailableBytes', 'SysPerfMemoryPages', 'SysPerfDiskTime')

EXEC aaAnalogTagInsert
  @TagName         = 'SysHistoryCacheUsed',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Bytes used for history block cache',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 0,
  @TimeDeadband    = 0,
  @ItemName        = N'SysHistoryCacheUsed',
  @EUKey           = @BytesUnit,
  @MinEU           = 0,
  @MaxEU           = 3000000000,
  @MinRaw          = 0,
  @MaxRaw          = 3000000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysHistoryCacheFaults',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'History blocks loaded from disk per minute',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 0,
  @TimeDeadband    = 0,
  @ItemName        = N'SysHistoryCacheFaults',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysHistoryClients',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Number of clients connected to the Indexing Service',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 0,
  @TimeDeadband    = 0,
  @ItemName        = N'SysHistoryClients',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 100,
  @MinRaw          = 0,
  @MaxRaw          = 100,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 17, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName IN ( 'SysHistoryCacheUsed', 'SysHistoryCacheFaults', 'SysHistoryClients')

EXEC aaAnalogTagInsert
  @TagName         = 'SysDataAcq0BadValues',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Bad quality points per second for MDAS Data Acquisition',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysDataAcq0BadValues',
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 1000000,
  @MinRaw          = 0,
  @MaxRaw          = 1000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysDataAcq0OutsideRealtime',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = 'Discarded points per second for MDAS Data Acquisition',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 5000,
  @TimeDeadband    = 0,
  @ItemName        = 'SysDataAcq0OutsideRealtime',
  @EUKey           = 2,
  @MinEU           = 0,
  @MaxEU           = 1000000,
  @MinRaw          = 0,
  @MaxRaw          = 1000000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 32,
  @SignedInteger   = 0

EXEC aaAnalogTagInsert
  @TagName         = 'SysDataAcqOverallItemsPerSec',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Items per second received from all sources',
  @AcquisitionType = 3,
  @StorageType     = 1,
  @StorageRate     = 10000,
  @TimeDeadband    = 0,
  @ItemName        = N'SysDataAcqOverallItemsPerSec',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 100000,
  @MinRaw          = 0,
  @MaxRaw          = 100000,
  @Scaling         = 0,
  @RawType         = 2,
  @IntegerSize     = 0,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 13, wwDomainTagKey
  FROM   TagRef
  WHERE  TagName IN ('SysDataAcq0BadValues', 'SysDataAcq0OutsideRealtime', 'SysDataAcqOverallItemsPerSec')

EXEC aaAnalogTagInsert
  @TagName         = 'SysRateDeadbandForcedValues',
  @TopicKey        = 1,
  @IOServerKey     = 1,
  @Description     = N'Total forced values for all tags configured for rate-deadband filtering, since startup',
  @AcquisitionType = 3,
  @StorageType     = 2,
  @StorageRate     = 0,
  @TimeDeadband    = 0,
  @ItemName        = N'SysRateDeadbandForcedValues',
  @EUKey           = @NoUnit,
  @MinEU           = 0,
  @MaxEU           = 1000,
  @MinRaw          = 0,
  @MaxRaw          = 1000,
  @Scaling         = 0,
  @RawType         = 3,
  @IntegerSize     = 16,
  @SignedInteger   = 0

INSERT INTO PublicGroupTag (NameKey, wwDomainTagKey)
  SELECT 17, wwDomainTagKey 
  FROM   TagRef 
  WHERE  TagName = 'SysRateDeadbandForcedValues'


INSERT SQLTemplate (Description, Type, Script) VALUES
  (N'Invoke an external application',1,N'exec master..xp_cmdshell <Your Command>, no_output')
go
INSERT SQLTemplate (Description,Type,Script) VALUES
  (N'Change delta storage time deadband',1,N'exec master..xp_SetStorageTimeDeadband <NewVal in mS> <YourTagName> ')
go
INSERT SQLTemplate (Description,Type,Script) VALUES
  (N'Change delta storage value deadband',1,N'exec master..xp_SetStorageValueDeadband <NewVal in EU> <YourTagName> ')
go
INSERT SQLTemplate (Description,Type,Script) VALUES
  (N'Send an Email message, fixed text',1,
N'Set Quoted_Identifier OFF 
exec master..xp_sendmail
    @recipients = <ToWhom>,
    @message = "The event @EventTagName occurred at @EventTime",
    @no_output = "true" ')
go
INSERT SQLTemplate (Description,Type,Script) VALUES
  (N'Send an Email message, with query',1,
N'Set Quoted_Identifier OFF 
exec master..xp_sendmail
    @recipients = <ToWhom>,
    @subject = "Data for @EventTagName at @EventTime",
    @query = <"Your query">,
    @no_output = "true" ')
go

INSERT SQLTemplate (Description,Type,Script) VALUES
(N'Value below LowLow limit',0,
N'Set Quoted_Identifier OFF 
SELECT DateTime
FROM AnalogHistory, Limit 
WHERE AnalogHistory.TagName = <"YourTag"> 
AND AnalogHistory.DateTime >= "@StartTime" 
AND AnalogHistory.DateTime < "@EndTime" 
AND AnalogHistory.TagName = Limit.TagName 
AND AnalogHistory.Value IS NOT NULL 
AND AnalogHistory.Value < Limit.Value 
AND ContextKey = 1 
AND LimitNameKey = 1 
AND wwRetrievalMode = "Delta" ')
go
INSERT SQLTemplate (Description,Type,Script) VALUES
(N'Value below Low limit',0,
N'Set Quoted_Identifier OFF 
SELECT DateTime
FROM AnalogHistory, Limit 
WHERE AnalogHistory.TagName = <"YourTag"> 
AND AnalogHistory.DateTime >= "@StartTime" 
AND AnalogHistory.DateTime < "@EndTime" 
AND AnalogHistory.TagName = Limit.TagName 
AND AnalogHistory.Value IS NOT NULL 
AND AnalogHistory.Value < Limit.Value 
AND ContextKey = 1 
AND LimitNameKey = 2 
AND wwRetrievalMode = "Delta" ')
go
INSERT SQLTemplate (Description,Type,Script) VALUES
(N'Value above High limit',0,
N'Set Quoted_Identifier OFF 
SELECT DateTime
FROM AnalogHistory, Limit 
WHERE AnalogHistory.TagName = <"YourTag"> 
AND AnalogHistory.DateTime >= "@StartTime" 
AND AnalogHistory.DateTime < "@EndTime" 
AND AnalogHistory.TagName = Limit.TagName 
AND AnalogHistory.Value IS NOT NULL 
AND AnalogHistory.Value > Limit.Value 
AND ContextKey = 1 
AND LimitNameKey = 3 
AND wwRetrievalMode = "Delta" ')
go
INSERT SQLTemplate (Description,Type,Script) VALUES
(N'Value above HighHigh limit',0,
N'Set Quoted_Identifier OFF 
SELECT DateTime
FROM AnalogHistory, Limit 
WHERE AnalogHistory.TagName = <"YourTag"> 
AND AnalogHistory.DateTime >= "@StartTime" 
AND AnalogHistory.DateTime < "@EndTime" 
AND AnalogHistory.TagName = Limit.TagName 
AND AnalogHistory.Value IS NOT NULL 
AND AnalogHistory.Value > Limit.Value 
AND ContextKey = 1 
AND LimitNameKey = 4 
AND wwRetrievalMode = "Delta" ')
go
insert SQLTemplate (Description,Type,Script) VALUES
(N'Create a New Data Block', 1,
N'exec master..xp_NewHistoryBlock')
go

UPDATE StorageNode SET DbStatus = 0
go

/* Reset Status Flags */
update Tag set Status = 0
go
update Topic set Status = 0
go
update IOServer set Status = 0 
go
update IODriver set Status = 0
go
update StorageLocation set Status = 0
go
update SnapshotDetail set Status = 0
go
update EngineeringUnit set Status = 0
go
truncate table ConfigStatusPending
go


 
 /* Populate QualityMap table */
insert QualityMap (QualityDetail, QualityString) values (0, N'Bad Quality of undetermined state')
insert QualityMap (QualityDetail, QualityString) values (1, N'No data available, tag did not exist at the time')
insert QualityMap (QualityDetail, QualityString) values (2, N'Running insert')
insert QualityMap (QualityDetail, QualityString) values (10, N'Communication loss')
insert QualityMap (QualityDetail, QualityString) values (16, N'Good value, received out of time sync (cyclic tag)')
insert QualityMap (QualityDetail, QualityString) values (17, N'Duplicate time stamp; infinite slope')
insert QualityMap (QualityDetail, QualityString) values (20, N'IDAS overflow recovery')
insert QualityMap (QualityDetail, QualityString) values (24, N'IOServer communication failed')
insert QualityMap (QualityDetail, QualityString) values (33, N'Violation of History Duration license feature')
insert QualityMap (QualityDetail, QualityString) values (44, N'Pipe reconnect')
insert QualityMap (QualityDetail, QualityString) values (64, N'Cannot convert')
insert QualityMap (QualityDetail, QualityString) values (150, N'Storage startup')
insert QualityMap (QualityDetail, QualityString) values (151, N'Store forward storage startup')
insert QualityMap (QualityDetail, QualityString) values (192, N'Good')
insert QualityMap (QualityDetail, QualityString) values (202, N'Good point of version Latest')
insert QualityMap (QualityDetail, QualityString) values (212, N'Counter rollover has occurred')
insert QualityMap (QualityDetail, QualityString) values (248, N'First value received in store forward mode')
insert QualityMap (QualityDetail, QualityString) values (249, N'Not a number')
insert QualityMap (QualityDetail, QualityString) values (252, N'First value received from IOServer')
insert QualityMap (QualityDetail, QualityString) values (256, N'Bad Quality of undetermined state, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (257, N'No data available, tag did not exist at the time, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (258, N'Running insert, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (266, N'Communication loss, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (272, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (273, N'Duplicate time stamp; infinite slope, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (276, N'IDAS overflow recovery, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (280, N'IOServer communication failed, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (300, N'Pipe reconnect, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (320, N'Cannot convert, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (406, N'Storage startup, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (407, N'Store forward storage startup, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (448, N'Good, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (458, N'Good point of version Latest, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (468, N'Counter rollover has occurred, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (504, N'First value received in store forward mode, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (505, N'Not a number, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (508, N'First value received from IOServer, timestamp overwritten; values in future')
insert QualityMap (QualityDetail, QualityString) values (512, N'Bad Quality of undetermined state, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (513, N'No data available, tag did not exist at the time, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (514, N'Running insert, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (522, N'Communication loss, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (528, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (529, N'Duplicate time stamp; infinite slope, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (532, N'IDAS overflow recovery, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (536, N'IOServer communication failed, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (556, N'Pipe reconnect, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (576, N'Cannot convert, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (662, N'Storage startup, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (663, N'Store forward storage startup, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (704, N'Good, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (714, N'Good point of version Latest, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (724, N'Counter rollover has occurred, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (760, N'First value received in store forward mode, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (761, N'Not a number, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (764, N'First value received from IOServer, timestamp overwritten; values out of time sequence')
insert QualityMap (QualityDetail, QualityString) values (1024, N'Bad Quality of undetermined state, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1025, N'No data available, tag did not exist at the time, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1026, N'Running insert, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1034, N'Communication loss, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1040, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1041, N'Duplicate time stamp; infinite slope, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1044, N'IDAS overflow recovery, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1048, N'IOServer communication failed, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1068, N'Pipe reconnect, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1088, N'Cannot convert, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1174, N'Storage startup, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1175, N'Store forward storage startup, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1216, N'Good, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1226, N'Good point of version Latest, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1236, N'Counter rollover has occurred, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1272, N'First value received in store forward mode, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1273, N'Not a number, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (1276, N'First value received from IOServer, timestamp overwritten; server timestamping selected')
insert QualityMap (QualityDetail, QualityString) values (2048, N'Bad Quality of undetermined state, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2049, N'No data available, tag did not exist at the time, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2050, N'Running insert, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2058, N'Communication loss, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2064, N'Good value, received out of time sync (cyclic tag), intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2065, N'Duplicate time stamp; infinite slope, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2068, N'IDAS overflow recovery, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2072, N'IOServer communication failed, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2092, N'Pipe reconnect, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2112, N'Cannot convert, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2198, N'Storage startup, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2199, N'Store forward storage startup, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2240, N'Good, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2250, N'Good point of version Latest, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2260, N'Counter rollover has occurred, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2296, N'First value received in store forward mode, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2297, N'Not a number, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2300, N'First value received from IOServer, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2304, N'Bad Quality of undetermined state, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2305, N'No data available, tag did not exist at the time, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2306, N'Running insert, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2314, N'Communication loss, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2320, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2321, N'Duplicate time stamp; infinite slope, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2324, N'IDAS overflow recovery, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2328, N'IOServer communication failed, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2348, N'Pipe reconnect, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2368, N'Cannot convert, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2454, N'Storage startup, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2455, N'Store forward storage startup, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2496, N'Good, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2506, N'Good point of version Latest, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2516, N'Counter rollover has occurred, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2552, N'First value received in store forward mode, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2553, N'Not a number, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2556, N'First value received from IOServer, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2560, N'Bad Quality of undetermined state, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2561, N'No data available, tag did not exist at the time, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2562, N'Running insert, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2570, N'Communication loss, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2576, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2577, N'Duplicate time stamp; infinite slope, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2580, N'IDAS overflow recovery, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2584, N'IOServer communication failed, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2604, N'Pipe reconnect, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2624, N'Cannot convert, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2710, N'Storage startup, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2711, N'Store forward storage startup, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2752, N'Good, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2762, N'Good point of version Latest, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2772, N'Counter rollover has occurred, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2808, N'First value received in store forward mode, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2809, N'Not a number, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (2812, N'First value received from IOServer, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm')
 
 insert QualityMap (QualityDetail, QualityString) values (3072, N'Bad Quality of undetermined state, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3073, N'No data available, tag did not exist at the time, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3074, N'Running insert, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3082, N'Communication loss, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3088, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3089, N'Duplicate time stamp; infinite slope, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3092, N'IDAS overflow recovery, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3096, N'IOServer communication failed, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3116, N'Pipe reconnect, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3136, N'Cannot convert, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3222, N'Storage startup, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3223, N'Store forward storage startup, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3264, N'Good, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3274, N'Good point of version Latest, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3284, N'Counter rollover has occurred, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3320, N'First value received in store forward mode, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3321, N'Not a number, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (3324, N'First value received from IOServer, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm')
insert QualityMap (QualityDetail, QualityString) values (4096, N'Bad Quality of undetermined state, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4097, N'No data available, tag did not exist at the time, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4098, N'Running insert, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4106, N'Communication loss, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4112, N'Good value, received out of time sync (cyclic tag), partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4113, N'Duplicate time stamp; infinite slope, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4116, N'IDAS overflow recovery, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4120, N'IOServer communication failed, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4140, N'Pipe reconnect, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4160, N'Cannot convert, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4246, N'Storage startup, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4247, N'Store forward storage startup, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4288, N'Good, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4298, N'Good point of version Latest, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4308, N'Counter rollover has occurred, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4344, N'First value received in store forward mode, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4345, N'Not a number, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4348, N'First value received from IOServer, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4352, N'Bad Quality of undetermined state, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4353, N'No data available, tag did not exist at the time, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4354, N'Running insert, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4362, N'Communication loss, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4368, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4369, N'Duplicate time stamp; infinite slope, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4372, N'IDAS overflow recovery, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4376, N'IOServer communication failed, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4396, N'Pipe reconnect, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4416, N'Cannot convert, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4502, N'Storage startup, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4503, N'Store forward storage startup, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4544, N'Good, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4554, N'Good point of version Latest, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4564, N'Counter rollover has occurred, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4600, N'First value received in store forward mode, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4601, N'Not a number, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4604, N'First value received from IOServer, timestamp overwritten; values in future, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4608, N'Bad Quality of undetermined state, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4609, N'No data available, tag did not exist at the time, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4610, N'Running insert, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4618, N'Communication loss, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4624, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4625, N'Duplicate time stamp; infinite slope, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4628, N'IDAS overflow recovery, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4632, N'IOServer communication failed, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4652, N'Pipe reconnect, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4672, N'Cannot convert, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4758, N'Storage startup, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4759, N'Store forward storage startup, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4800, N'Good, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4810, N'Good point of version Latest, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4820, N'Counter rollover has occurred, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4856, N'First value received in store forward mode, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4857, N'Not a number, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (4860, N'First value received from IOServer, timestamp overwritten; values out of time sequence, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5120, N'Bad Quality of undetermined state, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5121, N'No data available, tag did not exist at the time, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5122, N'Running insert, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5130, N'Communication loss, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5136, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5137, N'Duplicate time stamp; infinite slope, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5140, N'IDAS overflow recovery, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5144, N'IOServer communication failed, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5164, N'Pipe reconnect, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5184, N'Cannot convert, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5270, N'Storage startup, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5271, N'Store forward storage startup, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5312, N'Good, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5322, N'Good point of version Latest, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5332, N'Counter rollover has occurred, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5368, N'First value received in store forward mode, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5369, N'Not a number, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (5372, N'First value received from IOServer, timestamp overwritten; server timestamping selected, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6144, N'Bad Quality of undetermined state, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6145, N'No data available, tag did not exist at the time, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6146, N'Running insert, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6154, N'Communication loss, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6160, N'Good value, received out of time sync (cyclic tag), intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6161, N'Duplicate time stamp; infinite slope, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6164, N'IDAS overflow recovery, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6168, N'IOServer communication failed, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6188, N'Pipe reconnect, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6208, N'Cannot convert, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6294, N'Storage startup, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6295, N'Store forward storage startup, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6336, N'Good, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6346, N'Good point of version Latest, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6356, N'Counter rollover has occurred, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6392, N'First value received in store forward mode, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6393, N'Not a number, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6396, N'First value received from IOServer, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6400, N'Bad Quality of undetermined state, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6401, N'No data available, tag did not exist at the time, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6402, N'Running insert, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6410, N'Communication loss, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6416, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6417, N'Duplicate time stamp; infinite slope, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6420, N'IDAS overflow recovery, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6424, N'IOServer communication failed, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6444, N'Pipe reconnect, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6464, N'Cannot convert, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6550, N'Storage startup, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6551, N'Store forward storage startup, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6592, N'Good, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6602, N'Good point of version Latest, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6612, N'Counter rollover has occurred, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6648, N'First value received in store forward mode, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6649, N'Not a number, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6652, N'First value received from IOServer, timestamp overwritten; values in future, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6656, N'Bad Quality of undetermined state, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6657, N'No data available, tag did not exist at the time, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6658, N'Running insert, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6666, N'Communication loss, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6672, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6673, N'Duplicate time stamp; infinite slope, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6676, N'IDAS overflow recovery, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6680, N'IOServer communication failed, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6700, N'Pipe reconnect, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6720, N'Cannot convert, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6806, N'Storage startup, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6807, N'Store forward storage startup, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6848, N'Good, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6858, N'Good point of version Latest, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6868, N'Counter rollover has occurred, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6904, N'First value received in store forward mode, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6905, N'Not a number, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (6908, N'First value received from IOServer, timestamp overwritten; values out of time sequence, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7168, N'Bad Quality of undetermined state, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7169, N'No data available, tag did not exist at the time, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7170, N'Running insert, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7178, N'Communication loss, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7184, N'Good value, received out of time sync (cyclic tag), timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7185, N'Duplicate time stamp; infinite slope, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7188, N'IDAS overflow recovery, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7192, N'IOServer communication failed, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7212, N'Pipe reconnect, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7232, N'Cannot convert, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7318, N'Storage startup, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7319, N'Store forward storage startup, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7360, N'Good, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7370, N'Good point of version Latest, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7380, N'Counter rollover has occurred, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7416, N'First value received in store forward mode, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7417, N'Not a number, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (7420, N'First value received from IOServer, timestamp overwritten; server timestamping selected, intermediate point stored by deadband storage algorithm, partial cycle')
insert QualityMap (QualityDetail, QualityString) values (65536, N'No data stored in history')

GO

 
 /* Populate OPCQualityMap table */
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (0, 'Bad')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (1, 'Bad, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (2, 'Bad, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (3, 'Bad, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (4, 'Bad, Configuration Error')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (5, 'Bad, Configuration Error, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (6, 'Bad, Configuration Error, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (7, 'Bad, Configuration Error, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (8, 'Bad, Not Connected')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (9, 'Bad, Not Connected, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (10, 'Bad, Not Connected, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (11, 'Bad, Not Connected, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (12, 'Bad, Device Failure')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (13, 'Bad, Device Failure, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (14, 'Bad, Device Failure, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (15, 'Bad, Device Failure, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (16, 'Bad, Sensor Failure')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (17, 'Bad, Sensor Failure, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (18, 'Bad, Sensor Failure, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (19, 'Bad, Sensor Failure, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (20, 'Bad, Last Known Value')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (21, 'Bad, Last Known Value, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (22, 'Bad, Last Known Value, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (23, 'Bad, Last Known Value, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (24, 'Bad, Comm Failure')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (25, 'Bad, Comm Failure, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (26, 'Bad, Comm Failure, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (27, 'Bad, Comm Failure, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (28, 'Bad, Out of Service')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (29, 'Bad, Out of Service, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (30, 'Bad, Out of Service, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (31, 'Bad, Out of Service, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (32, 'Bad, Waiting for Initial Data')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (33, 'Bad, Waiting for Initial Data, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (34, 'Bad, Waiting for Initial Data, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (35, 'Bad, Waiting for Initial Data, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (64, 'Uncertain')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (65, 'Uncertain, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (66, 'Uncertain, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (67, 'Uncertain, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (68, 'Uncertain, Last Usable Value')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (69, 'Uncertain, Last Usable Value, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (70, 'Uncertain, Last Usable Value, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (71, 'Uncertain, Last Usable Value, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (80, 'Uncertain, Sensor Not Accurate')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (81, 'Uncertain, Sensor Not Accurate, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (82, 'Uncertain, Sensor Not Accurate, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (83, 'Uncertain, Sensor Not Accurate, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (84, 'Uncertain, Engineering Units Exceeded')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (85, 'Uncertain, Engineering Units Exceeded, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (86, 'Uncertain, Engineering Units Exceeded, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (87, 'Uncertain, Engineering Units Exceeded, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (88, 'Uncertain, Sub-Normal')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (89, 'Uncertain, Sub-Normal, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (90, 'Uncertain, Sub-Normal, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (91, 'Uncertain, Sub-Normal, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (192, 'Good')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (193, 'Good, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (194, 'Good, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (195, 'Good, Constant')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (216, 'Good, Local Override')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (217, 'Good, Local Override, Low Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (218, 'Good, Local Override, High Limited')
INSERT INTO OPCQualityMap (OPCQuality, Description) VALUES (219, 'Good, Local Override, Constant')

GO

 
 /*
Set up SQL Agent
================
*/

use msdb
go
if exists (select name from msdb..sysjobs where name = 'Update_User_Detail')
begin
   exec sp_delete_job @job_name = 'Update_User_Detail'
end
go
exec sp_add_job @job_name = 'Update_User_Detail'
    ,@enabled = 1 
    ,@description = 'Periodically update Historian user information'
    ,@start_step_id = 1 
    ,@category_name = NULL
    ,@category_id = NULL 
    ,@owner_login_name = 'aadbo'
go
exec sp_add_jobserver @job_name = 'Update_User_Detail'
go
exec sp_add_jobstep @job_name = 'Update_User_Detail'
    ,@step_id = 1 
    ,@step_name = 'Run Historian stored procedure'
    ,@subsystem = 'TSQL' 
    ,@command = 'exec aaUserDetailUpdate'
    ,@additional_parameters =NULL
    ,@cmdexec_success_code = 0
    ,@on_success_action = 1
    ,@on_success_step_id = 0
    ,@on_fail_action = 2
    ,@on_fail_step_id = 0
    ,@server = NULL
    ,@database_name = 'Runtime'
go
exec sp_add_jobschedule @job_name = 'Update_User_Detail'
    ,@name = 'Hourly'
    ,@enabled = 1
    ,@freq_type = 4 /*daily*/
    ,@freq_interval = 1 /*every day*/
    ,@freq_subday_type = 8 /*hours*/
    ,@freq_subday_interval = 1 /*every 1 hour*/
go

use Runtime
go

 
 /*
Set up views
============
*/

 /**********  v_EventSnapshot  **********/
if exists (select name from sysobjects where name = 'v_EventSnapshot')
   BEGIN
      drop view v_EventSnapshot
   END
GO

CREATE VIEW v_EventSnapshot
AS
 SELECT eh.TagName as Event, eh.DateTime as EventTime, eh.DetectDateTime as DetectionTime,
          Edge =  
             CASE eh.Edge
                WHEN 1 THEN 'Leading'
                WHEN 0 THEN 'Trailing'
                WHEN 2 THEN 'Both'
                WHEN 3 THEN 'None'
                WHEN 4 THEN 'Time'
                WHEN 5 THEN 'External'
                ELSE '-'
             END,
          sst.TagName as TagName, ass.Value as Value, ass.Quality as Quality,
          ass.QualityDetail as QualityDetail 
    FROM EventHistory eh LEFT OUTER JOIN AnalogSnapshot ass on eh.EventLogKey = ass.EventLogKey
           INNER JOIN SnapshotTag sst on sst.SnapshotTagKey = ass.SnapshotTagKey

 UNION

 SELECT eh.TagName as Event, eh.DateTime as EventTime, eh.DetectDateTime as DetectionTime,
          Edge =  
             CASE eh.Edge
                WHEN 1 THEN 'Leading'
                WHEN 0 THEN 'Trailing'
                WHEN 2 THEN 'Both'
                WHEN 3 THEN 'None'
                WHEN 4 THEN 'Time'
                WHEN 5 THEN 'External'
                ELSE '-'
             END,
          sst.TagName as TagName, ass.Value as Value, ass.Quality as Quality,
          ass.QualityDetail as QualityDetail
    FROM EventHistory eh LEFT OUTER JOIN DiscreteSnapshot ass on eh.EventLogKey = ass.EventLogKey
           INNER JOIN SnapshotTag sst on sst.SnapshotTagKey = ass.SnapshotTagKey

 UNION

 SELECT eh.TagName as Event, eh.DateTime as EventTime, eh.DetectDateTime as DetectionTime,
          Edge =  
             CASE eh.Edge
                WHEN 1 THEN 'Leading'
                WHEN 0 THEN 'Trailing'
                WHEN 2 THEN 'Both'
                WHEN 3 THEN 'None'
                WHEN 4 THEN 'Time'
                WHEN 5 THEN 'External'
                ELSE '-'
             END,
          '-' as TagName, NULL as Value, NULL as Quality,
          NULL as QualityDetail 
    FROM EventHistory eh, EventTag et 
       WHERE eh.TagName = et.TagName
       AND et.ActionTypeKey <> 3

GO
GRANT select on v_EventSnapshot to Public
GO

 /**********  v_EventStringSnapshot  **********/
if exists (select name from sysobjects where name = 'v_EventStringSnapshot')
   BEGIN
      drop view v_EventStringSnapshot
   END
GO

CREATE VIEW v_EventStringSnapshot
AS
 SELECT eh.TagName as Event, eh.DateTime as EventTime, eh.DetectDateTime as DetectionTime,
          Edge =  
             CASE eh.Edge
                WHEN 1 THEN 'Leading'
                WHEN 0 THEN 'Trailing'
                WHEN 2 THEN 'Both'
                WHEN 3 THEN 'None'
                WHEN 4 THEN 'Time'
                WHEN 5 THEN 'External'
                ELSE '-'
             END,
          sst.TagName as TagName, ass.Value as Value, ass.Quality as Quality,
          ass.QualityDetail as QualityDetail 
    FROM EventHistory eh LEFT OUTER JOIN StringSnapshot ass on eh.EventLogKey = ass.EventLogKey
           INNER JOIN SnapshotTag sst on sst.SnapshotTagKey = ass.SnapshotTagKey

GO
GRANT select on v_EventStringSnapshot to Public
GO

 /**********  v_SnapshotData  **********/
if exists (select name from sysobjects where name = 'v_SnapshotData')
   BEGIN
      drop view v_SnapshotData
   END
GO

CREATE VIEW v_SnapshotData
AS
 SELECT eh.TagName as Event, eh.DateTime as EventTime, eh.DetectDateTime as DetectionTime,
          Edge =  
             CASE eh.Edge
                WHEN 1 THEN 'Leading'
                WHEN 0 THEN 'Trailing'
                WHEN 2 THEN 'Both'
                WHEN 3 THEN 'None'
                WHEN 4 THEN 'Time'
                WHEN 5 THEN 'External'
                ELSE '-'
             END,
          sst.TagName as TagName, convert(varchar,ass.Value) as Value, ass.Quality as Quality,
          ass.QualityDetail as QualityDetail 
    FROM EventHistory eh LEFT OUTER JOIN AnalogSnapshot ass on eh.EventLogKey = ass.EventLogKey
           INNER JOIN SnapshotTag sst on sst.SnapshotTagKey = ass.SnapshotTagKey

 UNION

 SELECT eh.TagName as Event, eh.DateTime as EventTime, eh.DetectDateTime as DetectionTime,
          Edge =  
             CASE eh.Edge
                WHEN 1 THEN 'Leading'
                WHEN 0 THEN 'Trailing'
                WHEN 2 THEN 'Both'
                WHEN 3 THEN 'None'
                WHEN 4 THEN 'Time'
                WHEN 5 THEN 'External'
                ELSE '-'
             END,
          sst.TagName as TagName, convert(varchar,ass.Value) as Value, ass.Quality as Quality,
          ass.QualityDetail as QualityDetail
    FROM EventHistory eh LEFT OUTER JOIN DiscreteSnapshot ass on eh.EventLogKey = ass.EventLogKey
           INNER JOIN SnapshotTag sst on sst.SnapshotTagKey = ass.SnapshotTagKey

 UNION

 SELECT eh.TagName as Event, eh.DateTime as EventTime, eh.DetectDateTime as DetectionTime,
          Edge =  
             CASE eh.Edge
                WHEN 1 THEN 'Leading'
                WHEN 0 THEN 'Trailing'
                WHEN 2 THEN 'Both'
                WHEN 3 THEN 'None'
                WHEN 4 THEN 'Time'
                WHEN 5 THEN 'External'
                ELSE '-'
             END,
          sst.TagName as TagName, RTRIM(ass.Value) as Value, ass.Quality as Quality,
          ass.QualityDetail as QualityDetail
    FROM EventHistory eh LEFT OUTER JOIN StringSnapshot ass on eh.EventLogKey = ass.EventLogKey
           INNER JOIN SnapshotTag sst on sst.SnapshotTagKey = ass.SnapshotTagKey

 UNION

 SELECT eh.TagName as Event, eh.DateTime as EventTime, eh.DetectDateTime as DetectionTime,
          Edge =  
             CASE eh.Edge
                WHEN 1 THEN 'Leading'
                WHEN 0 THEN 'Trailing'
                WHEN 2 THEN 'Both'
                WHEN 3 THEN 'None'
                WHEN 4 THEN 'Time'
                WHEN 5 THEN 'External'
                ELSE '-'
             END,
          '-' as TagName, '-' as Value, NULL as Quality,
          NULL as QualityDetail 
    FROM EventHistory eh, EventTag et 
       WHERE eh.TagName = et.TagName
       AND et.ActionTypeKey <> 3

GO
GRANT select on v_SnapshotData to Public
GO

 /**********  v_SummaryData  **********/
if exists (select name from sysobjects where name = 'v_SummaryData')
   BEGIN
      drop view v_SummaryData
   END
GO

CREATE VIEW v_SummaryData
AS
   SELECT stl.TagName, sh.SumDateCalcType as CalcType, sh.SummaryDate, sd.Value, sd.Quality,
            sh.SumDateDuration as Duration, sh.SumDateResolution as Resolution,
            sh.SumDateTimeStamp as TimeStamp, so.TagName as EventTag
      FROM SummaryTagList stl INNER JOIN SummaryData sd on stl.SumVarKey = sd.SumVarKey 
           INNER JOIN SummaryHistory sh on sd.LogKey = sh.LogKey
              INNER JOIN SummaryOperation so on sh.OperationKey = so.OperationKey
                 INNER JOIN EventTag et on so.TagName = et.TagName
GO

GRANT select on v_SummaryData to Public
GO

 /**********  v_ModTracking  **********/
if exists (select name from sysobjects where name = 'v_ModTracking')
   BEGIN
      drop view v_ModTracking
   END
GO

CREATE VIEW v_ModTracking 
AS
   select [DateTime] = mlt.DateTime, [Table] = obj.Name, [Column] = mlc.ColumnName,
          [ModType] = mlt.ModType, [RowKey] = mlt.RowKey, [New Value] = mlc.NewValue,
          [Old Value] = mlc.OldValue, [User] = mlt.UserName  
      from ModLogTable mlt, HistorianSysObjects obj, ModLogColumn mlc
           where obj.id = mlt.id 
           and mlc.ModTableKey = mlt.ModTableKey
GO

GRANT select on v_ModTracking to Public
GO

 /**********  SystemNameSpace  **********/
if exists (select name from sysobjects where name = 'SystemNameSpace')
   BEGIN
      drop view SystemNameSpace
   END
GO

create view SystemNameSpace
as 
select NameKey = 1, Type = 1000002, ParentKey = 0, [Name] = 'System Objects', PKey = NULL
UNION
select NameKey = 2, Type = 1000005, ParentKey = 1, [Name] = 'Group/Users', PKey = NULL
UNION
select NameKey = 3, Type = 1000007, ParentKey = 1, [Name] = 'Storage Locations', PKey = NULL
UNION
select NameKey = 4, Type = 1000013, ParentKey = 1, [Name] = 'Imported Nodes', PKey = NULL
UNION
select NameKey = 5, Type = 1000010, ParentKey = 1, [Name] = 'I/O Servers', PKey = NULL
UNION
select NameKey = 6, Type = 1000016, ParentKey = 1, [Name] = 'Events', PKey = NULL
UNION
select NameKey = 7, Type = 1000011, ParentKey = 1, [Name] = 'Messages', PKey = NULL
UNION
select NameKey = 8, Type = 1000012, ParentKey = 1, [Name] = 'Engineering Units', PKey = NULL
UNION
-- NameKey should be an IDENTIFIER so an artificial offset safeguard is created
select NameKey = IOServerKey + 100, Type = 11,
    ParentKey = 5, [Name] = '\\' + RTRIM(ComputerName) + '\' + ApplicationName, PKey = IOServerKey
      from IOServer
UNION
-- NameKey should be an IDENTIFIER so an artificial offset safeguard is created
select NameKey = TopicKey + 2000000, Type = 15,
    ParentKey = IOServerKey + 100, [Name] = 'Topic : ' + RTRIM([Name]), PKey = TopicKey
      from Topic
GO

GRANT select on SystemNameSpace to Public
GO

 /**********  v_ErrorLog  **********/
if exists (select name from sysobjects where name = 'v_ErrorLog')
   BEGIN
      drop view v_ErrorLog
   END
GO

create view v_ErrorLog 
as
select ErrorLog.DateTime, ErrorLog.Type, LocalizedText.LocalizedText, ErrorLog.Parameter, ErrorLog.TotalCount, 
         ErrorLog.ModuleID, ErrorLog.Host, ErrorLog.FileName, ErrorLog.Line
   from ErrorLog, LocalizedText 
      where LocalizedText.TextKey = ErrorLog.ErrorCode
      and LanguageID = 1033
GO

GRANT select on v_ErrorLog to Public
GO

 
 /*
Set up system functions
=======================
*/

/**********  faaLicensedTagTotal  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaLicensedTagTotal'))
  DROP function dbo.faaLicensedTagTotal
GO

create function faaLicensedTagTotal(@TagType int = 0)
returns int
as
begin
   declare @result int
   if @TagType = 0
   begin
      set @result = (select COUNT(TagName) from Tag where IOServerKey <> 1 and TagType in (1,2,3,4,7,9))
   end
   else
   if @TagType in (1,2,3,4,7,9)
   begin
      set @result = (select COUNT(TagName) from Tag where IOServerKey <> 1 and TagType = @TagType)
   end
   else
   begin
      set @result = 0
   end
   return @result
end
go
grant exec on faaLicensedTagTotal to public
go

/**********  faaLicensedTagDetails  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaLicensedTagDetails'))
  DROP function dbo.faaLicensedTagDetails
GO

create function faaLicensedTagDetails()
returns table
as
return (
   select 'Tag Type' =
      CASE 
         WHEN (GROUPING(TagType) = 1) THEN 'Total'
         WHEN TagType = 1 THEN 'Analog'
         WHEN TagType = 2 THEN 'Discrete'
         WHEN TagType = 3 THEN 'String'
         WHEN TagType = 4 THEN 'Complex'
         WHEN TagType = 5 THEN 'Event'
         WHEN TagType = 7 THEN 'Blob'
         WHEN TagType = 9 THEN 'Enumerated'
      END,
      Count(TagName) as 'Tag Count',
      CASE WHEN (GROUPING(TagType) = 1) THEN Runtime.dbo.faaLicensedTagTotal(0)
         ELSE Runtime.dbo.faaLicensedTagTotal(TagType) END as 'Licensed Tags' 
from Tag
group by TagType with CUBE
)
go
grant select on Runtime.dbo.faaLicensedTagDetails to public
go

/**********  faaTagsInLicenseViolation  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaTagsInLicenseViolation'))
  DROP function dbo.faaTagsInLicenseViolation
GO

create function faaTagsInLicenseViolation()
   RETURNS @taglist TABLE (TagName nvarchar(256) NOT NULL, wwTagKey int,
                           [Description] nvarchar(512), Address nvarchar(512))
AS
BEGIN
   declare @tags table (TagCount int IDENTITY, TagName nvarchar(256), wwTagKey int, 
                        Description nvarchar(512), Address nvarchar(512))
   declare @allowedtags int

   set @allowedtags = (select convert(int, Value) from SystemParameter
                         where [Name] = 'LicenseTagCount')

   insert into @tags (TagName, wwTagKey, [Description], Address)
     select TagName, wwTagKey, t.[Description],
          '\\' + RTRIM(ios.ComputerName) + '\' + RTRIM(ios.ApplicationName)
                 + '!' + tp.[Name] + ':' + t.ItemName 
         from Tag t, Topic tp, IOServer ios
           where t.IOServerKey <> 1 and TagType <> 5
           and   t.TopicKey = tp.TopicKey
           and   tp.IOServerKey = ios.IOServerKey
     order by wwTagKey

   /* return the result */
   insert @taglist (TagName, wwTagKey, [Description], Address)
    select TagName, wwTagKey, [Description], Address from @tags
      where TagCount > @allowedtags 
      order by wwTagKey

   return
END
go
grant select on Runtime.dbo.faaTagsInLicenseViolation to public
go

/**********  faaCheckLicenseViolation  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaCheckLicenseViolation'))
   drop function dbo.faaCheckLicenseViolation
go

create function faaCheckLicenseViolation()
returns int
as
begin
   declare @result int
   declare @allowedtags int
   declare @tagcount int

   set @allowedtags = (select convert(int, Value) from SystemParameter
                         where [Name] = 'LicenseTagCount')

   set @tagcount = (select dbo.faaLicensedTagTotal(0))

   if @tagcount > @allowedtags
     set @result = @tagcount - @allowedtags
   else
     set @result = 0      

   return @result   
end
go
grant exec on Runtime.dbo.faaCheckLicenseViolation to public
go

/**********  faaTZgetdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaTZgetdate'))
   drop function dbo.faaTZgetdate
go

create function faaTZgetdate(@TimeZone nvarchar(100))
returns datetime
as
begin
  declare @TZDateTime datetime
  exec @TZDateTime = master..xp_TZgetdate @TimeZone, @TZDateTime OUTPUT
  return @TZDateTime
end
go
grant exec on dbo.faaTZgetdate to public
go

/**********  faaGetLocalizedText  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaGetLocalizedText'))
   drop function dbo.faaGetLocalizedText
go

create function faaGetLocalizedText (@LangID int)
returns table 
as
return 
(
/* This function returns the string from the LocalizedText table         */
/* for the requested language or english if the translation is not found */
   select TextKey, LanguageID, LocalizedText from LocalizedText 
      where LanguageID = @LangID
   UNION
   select TextKey, LanguageID, LocalizedText from LocalizedText
      where LanguageID = 1033
      GROUP BY TextKey, LanguageID, LocalizedText
         HAVING TextKey <> ALL
            (select TextKey from LocalizedText 
                where LanguageID = @LangID)
)
go
grant select on Runtime.dbo.faaGetLocalizedText to public 
go
 
/**********  faaUser_ID  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaUser_ID'))
   drop function dbo.faaUser_ID
go

create function faaUser_ID() 
  returns int 
AS
BEGIN
  declare @User int
  declare @UID int
  declare @UName sysname 

  set @User = user_id()

  if not exists (select uid from sysusers
    where uid = @User and (isntuser = 1 or issqluser = 1))
  begin
    declare GroupsCursor cursor for 
      select uid, name from sysusers where isntgroup = 1 order by name
    for read only

    open GroupsCursor
    fetch next from GroupsCursor into @UID, @UName

    while (@@FETCH_STATUS <> -1)
    begin 
      if IS_MEMBER(@UName) = 1 
        set @User = @UID
      fetch next from GroupsCursor into @UID, @UName
    end

    close GroupsCursor
    deallocate GroupsCursor
  end

  return @User

END
GO

grant exec on Runtime.dbo.faaUser_ID to public
go

/**********  faaObjectTagName  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaObjectTagName'))
   drop function dbo.faaObjectTagName
go

create function faaObjectTagName(@DisplayName nvarchar(255))
  returns nvarchar(255)
AS
BEGIN
  declare @BaseName nvarchar(255)

  select @BaseName = case when @DisplayName like '%[ ][[]%'
      then left(@DisplayName, charindex(' [', @DisplayName)-1)
      else @DisplayName
      end

  return @BaseName
END
go

grant exec on dbo.faaObjectTagName to public
go

/**********  faaContainedName  **********/
if exists (select * from sysobjects where id = object_id('dbo.faaContainedName'))
   drop function dbo.faaContainedName
go

create function faaContainedName(@DisplayName nvarchar(255))
  returns nvarchar(255)
AS
BEGIN
  declare @ContainedName nvarchar(255)
  declare @start int
  declare @end int

  set @start = charindex(' [ ', @DisplayName)
  set @end = charindex(' ]', @DisplayName)

  if (@start > 0 and @end > 0)
  begin
    set @ContainedName = substring(@DisplayName, @start + 3, @end-@start-3)
  end
  else
  begin
    set @ContainedName = ''
  end

  return @ContainedName
END
go

grant exec on dbo.faaContainedName to public
go

 
 