/*-------------------------------------------------------------------------*/
/*  Invensys Systems - InSQL 9.0                                           */
/*  Holding database build script for InSQL 9.0                            */
/*  Tue Jul 12 19:24:30 2005                                               */
/*-------------------------------------------------------------------------*/
/* IMPORTANT NOTE!                                                         */
/* This script should be run after Runtime.sql                             */
/*-------------------------------------------------------------------------*/


set QUOTED_IDENTIFIER OFF
set NOCOUNT ON
go

/* Configuration of roles and logins */

/* Create the database roles in the current database */
use Holding
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 current 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)

  /* Add the logins to the relevant database roles */
  use Holding

  declare @loginame sysname
  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

  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 */
/* Assume that Runtime.sql has been run already, and that the aa* SQL Server logins exist on the SQL server. */
/* Grant access to the SQL Server logins */

use Holding
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 */
sp_changedbowner aadbo, true
go

/* Legacy support: compatibility with InSQL 8.0 and previous.   */
/* ************************************************************ */
if (not exists (select name from sysusers where name = 'wwUsers'))
begin
  exec sp_addrole wwUsers
end
go
exec sp_addrolemember aaUsers, wwUsers
go

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

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

/* Check that the legacy SQL Server logins exist on the SQL server, add if needed */
/* (This is also done in InSQLLegacySupport.sql). */
use master
go

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

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

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

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

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

/* Grant access to the legacy SQL Server logins */
use Holding
go

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

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

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

/* Add wwdbo as a member of the db_owner role in Holding */
if (not exists (select name from sysusers where name = 'wwdbo'))
begin
  exec sp_adduser wwdbo, wwdbo, db_owner
end
go

/* End: Legacy support */
/* ******************* */
 
 
 
 CREATE TABLE almGrpInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        ag_level             int NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on almGrpInfo to aaAdministrators
 
 
 CREATE TABLE DdeCfg (
        DdeSourceKey         int NOT NULL,
        NodeKey              int NOT NULL,
        SourceName           nchar(50) NULL,
        ApplicationName      nchar(50) NULL,
        TopicName            nchar(50) NULL,
        RequestInitialData   bit NULL DEFAULT 0,
        AlwaysAdvise         bit NULL DEFAULT 0,
        StorageType          smallint NOT NULL DEFAULT 1
                                    CHECK (StorageType BETWEEN 0 and 3),
        StorageRate          int NOT NULL DEFAULT 10000,
        TimeDeadband         int NOT NULL DEFAULT 0
                                    CHECK (TimeDeadband >= 0),
        ValueDeadband        float(25) NOT NULL DEFAULT 0
                                    CHECK (ValueDeadband BETWEEN 0 and 100),
        RateDeadband         float(25) NOT NULL DEFAULT 0
                                    CHECK (RateDeadband >= 0),
        DeadbandType         tinyint NULL DEFAULT 1,
        Edited               char(1) NOT NULL DEFAULT "",
        ToInSQL              bit NOT NULL DEFAULT 0,
        ProtocolType         int NULL DEFAULT 2,
        IODriverKey          int NULL,
        R_IOServerKey        int NULL,
        R_TopicKey           int NULL,
        PRIMARY KEY (DdeSourceKey, NodeKey)
 )
go
 
 CREATE INDEX XIF16DdeCfg ON DdeCfg
 (
        NodeKey
 )
go
 
 Grant Select, Insert, Delete, Update on DdeCfg to aaAdministrators
 
 
 CREATE TABLE discConstInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        dc_initValue         bit NULL DEFAULT 0,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on discConstInfo to aaAdministrators
 
 
 CREATE TABLE discDDEIOInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        d_initValue          bit NULL DEFAULT 0,
        d_onMsg              nchar(15) NULL,
        d_offMsg             nchar(15) NULL,
        d_almPri             int NULL,
        ddio_source          int NULL,
        ddio_itemName        nvarchar(80) NULL,
        ddio_inputConv       int NULL,
        R_MessageKey         int NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on discDDEIOInfo to aaAdministrators
 
 
 CREATE TABLE discVarInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        d_initValue          bit NULL DEFAULT 0,
        d_onMsg              nchar(15) NULL,
        d_offMsg             nchar(15) NULL,
        d_almPri             int NULL,
        R_MessageKey         int NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on discVarInfo to aaAdministrators
 
 
 CREATE TABLE histInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        dbhst_dbHnd_1        int NULL,
        dbhst_dbHnd_2        int NULL,
        dbhst_dbHnd_3        int NULL,
        dbhst_dbHnd_4        int NULL,
        dbhst_dbHnd_5        int NULL,
        dbhst_dbHnd_6        int NULL,
        dbhst_dbHnd_7        int NULL,
        dbhst_dbHnd_8        int NULL,
        dbhst_minVal         real NULL,
        dbhst_maxVal         real NULL,
        dbhst_alternateTags  int NULL,
        dbhst_displayMode    int NULL,
        dbhst_chartStart     int NULL,
        dbhst_chartLength    int NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on histInfo to aaAdministrators
 
 
 CREATE TABLE intgConstInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        ic_initValue         int NULL,
        ic_EGU               nchar(32) NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on intgConstInfo to aaAdministrators
 
 
 CREATE TABLE intgDDEIOInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        i_hihiChecked        bit NULL DEFAULT 0,
        i_hiChecked          bit NULL DEFAULT 0,
        i_loChecked          bit NULL DEFAULT 0,
        i_loloChecked        bit NULL DEFAULT 0,
        i_minorDevChecked    bit NULL DEFAULT 0,
        i_majorDevChecked    bit NULL DEFAULT 0,
        i_rocChecked         bit NULL DEFAULT 0,
        i_almPriHiHi         int NULL DEFAULT 0,
        i_almPriHi           int NULL DEFAULT 0,
        i_almPriLo           int NULL DEFAULT 0,
        i_almPriLoLo         int NULL DEFAULT 0,
        i_almPriMinorDev     int NULL,
        i_almPriMajorDev     int NULL,
        i_almPriROC          int NULL DEFAULT 0,
        i_roc                int NULL DEFAULT 0,
        i_rocUnits           int NULL DEFAULT 0,
        i_EGU                nchar(32) NULL,
        i_initValue          int NULL,
        i_minValue           int NULL,
        i_maxValue           int NULL,
        i_valueDeadband      real NULL,
        i_hihi               int NULL DEFAULT 0,
        i_hi                 int NULL DEFAULT 0,
        i_lo                 int NULL DEFAULT 0,
        i_lolo               int NULL DEFAULT 0,
        i_devTarget          int NULL,
        diio_source          int NULL,
        diio_itemName        nvarchar(81) NULL,
        diio_minRaw          int NULL,
        diio_maxRaw          int NULL,
        diio_inputConv       int NULL,
        R_EUKey              int NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on intgDDEIOInfo to aaAdministrators
 
 
 CREATE TABLE intgVarInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        i_hihiChecked        bit NULL DEFAULT 0,
        i_hiChecked          bit NULL DEFAULT 0,
        i_loChecked          bit NULL DEFAULT 0,
        i_loloChecked        bit NULL DEFAULT 0,
        i_minorDevChecked    bit NULL DEFAULT 0,
        i_majorDevChecked    bit NULL DEFAULT 0,
        i_rocChecked         bit NULL DEFAULT 0,
        i_almPriHiHi         int NULL DEFAULT 0,
        i_almPriHi           int NULL DEFAULT 0,
        i_almPriLo           int NULL DEFAULT 0,
        i_almPriLoLo         int NULL DEFAULT 0,
        i_almPriMinorDev     int NULL,
        i_almPriMajorDev     int NULL,
        i_almPriROC          int NULL DEFAULT 0,
        i_roc                int NULL DEFAULT 0,
        i_rocUnits           int NULL DEFAULT 0,
        i_EGU                nchar(32) NULL,
        i_initValue          int NULL,
        i_minValue           int NULL,
        i_maxValue           int NULL,
        i_valueDeadband      real NULL,
        i_hihi               int NULL DEFAULT 0,
        i_hi                 int NULL DEFAULT 0,
        i_lo                 int NULL DEFAULT 0,
        i_lolo               int NULL DEFAULT 0,
        i_devTarget          int NULL DEFAULT 0,
        R_EUKey              int NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on intgVarInfo to aaAdministrators
 
 
 CREATE TABLE InTouchDB (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        db_tagname           nchar(32) NOT NULL,
        db_description       nchar(512) NULL,
        db_type              int NULL,
        db_io_type           int NULL,
        db_group             int NULL,
        db_valid             bit NULL DEFAULT 0,
        db_modified          bit NULL DEFAULT 0,
        db_useCountRead      bit NULL DEFAULT 0,
        db_useCountWrite     bit NULL DEFAULT 0,
        db_useCountAlmInfo   bit NULL DEFAULT 0,
        db_version           int NULL,
        typeinfo             int NULL,
        db_logged            bit NULL DEFAULT 0,
        db_useTagAsItem      bit NULL DEFAULT 0,
        db_eventlogged       bit NULL DEFAULT 0,
        db_alarmParmsSaved   bit NULL DEFAULT 0,
        db_currentValueSaved bit NULL DEFAULT 0,
        db_intgLogDeadband   int NULL,
        db_realLogDeadband   real NULL,
        db_eventLoggingPriority int NULL,
        db_intgAlmDeadband   int NULL,
        db_realAlmDeadband   real NULL,
        db_almDevDeadband    real NULL,
        db_minorDev          real NULL,
        db_majorDev          real NULL,
        Edited               char(1) NOT NULL DEFAULT "",
        ToInSQL              bit NOT NULL DEFAULT 0,
        InSQLName            nvarchar(256) NOT NULL,
        CurrentEditor        int NULL DEFAULT 0,
        UDT                  bit NULL DEFAULT 0,
        UDTChild             bit NULL DEFAULT 0,
        HasUDTChild          bit NULL DEFAULT 0,
        InSQLDeadband        float(25) NOT NULL DEFAULT 0,
        ParentdbHnd          int NULL,
        ParentNodeKey        int NULL,
        PRIMARY KEY NONCLUSTERED (dbHnd, NodeKey)
 )
go
 
 CREATE UNIQUE INDEX XPKInTouchDBTagName ON InTouchDB
 (
        InSQLName
 )
go
 
 CREATE INDEX XIF15InTouchDB ON InTouchDB
 (
        NodeKey
 )
go
 
 CREATE INDEX XIF17InTouchDB ON InTouchDB
 (
        ParentdbHnd,
        ParentNodeKey
 )
go
 
 CREATE INDEX XIE19InTouchDB ON InTouchDB
 (
        ToInSQL,
        Edited,
        typeinfo
 )
go
 
 CREATE INDEX XIE21InTouchDB ON InTouchDB
 (
        db_tagname
 )
go
 
 CREATE INDEX XIE23InTouchDB ON InTouchDB
 (
        db_realLogDeadband
 )
go
 
 CREATE INDEX XIE25InTouchDB ON InTouchDB
 (
        Edited,
        NodeKey
 )
go
 
 Grant Select, Insert, Delete, Update on InTouchDB to aaAdministrators
 
 
 CREATE TABLE InTouchNode (
        NodeKey              int NOT NULL,
        MachineName          nvarchar(255) NOT NULL,
        Description          nvarchar(50) NULL,
        ApplicationPath      nvarchar(255) NULL,
        PrefixOrSuffix       bit NOT NULL DEFAULT 0,
        DuplicateChar        nvarchar(12) NOT NULL DEFAULT "",
        AlwaysModifyName     bit NOT NULL DEFAULT 0,
        Edited               char(1) NOT NULL DEFAULT "",
        ImportPlantTags      tinyint NOT NULL DEFAULT 0,
        ImportSystemTags     tinyint NOT NULL DEFAULT 0,
        ImportMemoryTags     tinyint NOT NULL DEFAULT 0,
        ImportAllTags        int NOT NULL DEFAULT 0,
        PRIMARY KEY (NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on InTouchNode to aaAdministrators
 
 
 CREATE TABLE realConstInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        rc_initValue         real NULL,
        rc_EGU               nchar(32) NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on realConstInfo to aaAdministrators
 
 
 CREATE TABLE realDDEIOInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        r_hihiChecked        bit NULL DEFAULT 0,
        r_hiChecked          bit NULL DEFAULT 0,
        r_loChecked          bit NULL DEFAULT 0,
        r_loloChecked        bit NULL DEFAULT 0,
        r_minorDevChecked    bit NULL DEFAULT 0,
        r_majorDevChecked    bit NULL DEFAULT 0,
        r_rocChecked         bit NULL DEFAULT 0,
        r_almPriHiHi         int NULL DEFAULT 0,
        r_almPriHi           int NULL DEFAULT 0,
        r_almPriLo           int NULL DEFAULT 0,
        r_almPriLoLo         int NULL DEFAULT 0,
        r_almPriMinorDev     int NULL,
        r_almPriMajorDev     int NULL,
        r_almPriROC          int NULL DEFAULT 0,
        r_roc                int NULL DEFAULT 0,
        r_rocUnits           int NULL DEFAULT 0,
        r_EGU                nchar(32) NULL,
        r_initValue          real NULL,
        r_minValue           real NULL,
        r_maxValue           real NULL,
        r_valueDeadband      real NULL,
        r_hihi               real NULL DEFAULT 0,
        r_hi                 real NULL DEFAULT 0,
        r_lo                 real NULL DEFAULT 0,
        r_lolo               real NULL DEFAULT 0,
        r_devTarget          real NULL,
        drio_source          int NULL,
        drio_itemName        nvarchar(81) NULL,
        drio_minRaw          real NULL,
        drio_maxRaw          real NULL,
        drio_inputConv       int NULL,
        R_EUKey              int NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on realDDEIOInfo to aaAdministrators
 
 
 CREATE TABLE realVarInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        r_hihiChecked        bit NULL DEFAULT 0,
        r_hiChecked          bit NULL DEFAULT 0,
        r_loChecked          bit NULL DEFAULT 0,
        r_loloChecked        bit NULL DEFAULT 0,
        r_minorDevChecked    bit NULL DEFAULT 0,
        r_majorDevChecked    bit NULL DEFAULT 0,
        r_rocChecked         bit NULL DEFAULT 0,
        r_almPriHiHi         int NULL DEFAULT 0,
        r_almPriHi           int NULL DEFAULT 0,
        r_almPriLo           int NULL DEFAULT 0,
        r_almPriLoLo         int NULL DEFAULT 0,
        r_almPriMinorDev     int NULL,
        r_almPriMajorDev     int NULL,
        r_almPriROC          int NULL DEFAULT 0,
        r_roc                int NULL DEFAULT 0,
        r_rocUnits           int NULL DEFAULT 0,
        r_EGU                nchar(32) NULL,
        r_initValue          real NULL,
        r_minValue           real NULL,
        r_maxValue           real NULL,
        r_valueDeadband      real NULL,
        r_hihi               real NULL DEFAULT 0,
        r_hi                 real NULL DEFAULT 0,
        r_lo                 real NULL DEFAULT 0,
        r_lolo               real NULL DEFAULT 0,
        r_devTarget          real NULL,
        R_EUKey              int NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on realVarInfo to aaAdministrators
 
 
 CREATE TABLE strgDDEIOInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        dmio_nMaxString      int NULL,
        dmio_initValue       nvarchar(131) NULL,
        dmio_source          int NULL,
        dmio_itemName        nvarchar(80) NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on strgDDEIOInfo to aaAdministrators
 
 
 CREATE TABLE strgInfo (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        sv_nMaxString        int NULL,
        sv_initValue         nvarchar(131) NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on strgInfo to aaAdministrators
 
 
 CREATE TABLE UDTChildren (
        dbHnd                int NOT NULL,
        NodeKey              int NOT NULL,
        ParentdbHnd          int NOT NULL,
        PRIMARY KEY (dbHnd, NodeKey)
 )
go
 
 Grant Select, Insert, Delete, Update on UDTChildren to aaAdministrators
 
 
 if exists (select * from sysobjects where id = object_id('dbo.ww_Clean_Limits_ROCs'))
  DROP PROCEDURE dbo.ww_Clean_Limits_ROCs
GO

CREATE procedure ww_Clean_Limits_ROCs 

as

BEGIN TRAN
/******************************************************************************/
-- Check Limit (Delete any tags which might have been deleted in a re-import)
DELETE Runtime.dbo.Limit WHERE TagName NOT IN (SELECT TagName FROM Runtime.dbo.AnalogTag)

/******************************************************************************/
-- Check ROC (Delete any tags which might have been deleted in a re-import)
DELETE Runtime.dbo.RateOfChange WHERE TagName NOT IN
       (SELECT TagName FROM Runtime.dbo.AnalogTag)

/******************************************************************************/
-- Check Deviation (Delete any tags which might have been deleted in a re-import)
DELETE Runtime.dbo.Deviation WHERE TagName NOT IN
       (SELECT TagName FROM Runtime.dbo.AnalogTag)

/******************************************************************************/
-- Cleanup the Limit Table for unchecked limits
DELETE Runtime.dbo.Limit FROM Runtime.dbo.Limit WHERE Checked = 0 

/******************************************************************************/
-- InTouch can have range values and have unchecked
DELETE Runtime.dbo.RateOfChange WHERE Checked = 0

/******************************************************************************/
-- Clean Deviation if both Checked are set to 0
DELETE Runtime.dbo.Deviation  WHERE MinorChecked = 0 AND MajorChecked = 0

/******************************************************************************/

COMMIT TRAN

GO

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

CREATE procedure ww_Cleanup_AfterImport 

as

begin tran
/******************************************************************************/
-- The script runs on all InTouchNode entries..
/******************************************************************************/
-- Validation of Tag.ItemName
-- Rule : Node priority in Nodekey order i.e. Node 1 is master,
--        Node 2 as priority on Node 3 etc...
--        If a Node with lower priority has a duplicate topickey + itemname
--        the tag is deleted.

SET NOCOUNT ON

declare @NodeCount   int
declare @CurNode     int
declare @TagName     nvarchar(256)
declare @TopicKey    int
declare @ItemName    nvarchar(256)
declare @rowcount    int
declare @currow      int

select @NodeCount = 1
select @CurNode   = 0
select @currow    = 1              
select @rowcount  = 0

select @NodeCount = (select max(NodeKey) from Runtime.dbo.InTouchNode)

while @CurNode < @NodeCount
begin
   if exists (select NodeKey FROM Runtime.dbo.InTouchNode
             where NodeKey = @CurNode) 
      begin
         Declare TagList SCROLL CURSOR
            for select Tag.TagName, Tag.TopicKey, Tag.ItemName
               from Runtime.dbo.Tag Tag, 
                    Runtime.dbo.InTouchSpecific ITS
                   where Tag.TagName = ITS.TagName
                   and   ITS.NodeKey = @CurNode
                      order by Tag.TopicKey, Tag.ItemName
             
         open TagList

         select @rowcount = @@cursor_rows

         while @currow <= @rowcount
         begin
            fetch next from TagList INTO @TagName, @TopicKey, @ItemName
            if exists (select Tag.TagName from Runtime.dbo.Tag Tag,
                                               Runtime.dbo.InTouchSpecific ITS
                      where Tag.TopicKey =  @TopicKey
                      and   Tag.ItemName =  @ItemName
                      and   Tag.TagName  = ITS.TagName
                      and   ITS.NodeKey  > @CurNode) 
            begin
               delete Tag from Runtime.dbo.Tag Tag,
                               Runtime.dbo.InTouchSpecific ITS
                  where Tag.TopicKey = @TopicKey
                  and   Tag.ItemName = @ItemName
                  and   Tag.TagName  = ITS.TagName
                  and   ITS.NodeKey  > @CurNode
            end
            select @currow = @currow + 1
         end

         deallocate TagList
         select @CurNode = @CurNode + 1
      end
   else
   begin
      select @CurNode = @CurNode + 1
   end
end

/******************************************************************************/
-- Clean Topic items if not used
delete Runtime.dbo.Topic
  where TopicKey not in
    (select DISTINCT TopicKey from Runtime.dbo.Tag where TagType < 5)
  and TopicKey > 2  -- Need to keep MDAS topic

/******************************************************************************/
-- Clean IOServer if not used
delete Runtime.dbo.IOServer
   where IOServerKey not in
     (select DISTINCT IOServerKey from Runtime.dbo.Topic)
   and IOServerKey > 2 -- Just a safeguard to avoid deletion of MDAS IOServer

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end
go

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

CREATE procedure ww_DeltaReImportInit 
  @NodeNo          int

as

-- Get the InTouchNode stuff

INSERT InTouchNode (NodeKey, MachineName, ApplicationPath, Description,
                    PrefixOrSuffix, DuplicateChar, AlwaysModifyName, Edited,
                    ImportPlantTags, ImportSystemTags, ImportMemoryTags)
   SELECT NodeKey, MachineName, Path, Description, PrefixOrSuffix, 
          DuplicateChar, AlwaysModifyName, 'M',
          ImportPlantTags, ImportSystemTags, ImportMemoryTags
      FROM Runtime.dbo.InTouchNode
         WHERE NodeKey = @NodeNo
      
/******************************************************************************/

-- Get the DdeCfg from TopicImportInfo
INSERT DdeCfg (DdeSourceKey, NodeKey, SourceName, ApplicationName, TopicName,
               RequestInitialData, AlwaysAdvise, StorageType, StorageRate,
               TimeDeadband, ValueDeadband, RateDeadband, DeadbandType, ToInSQL, ProtocolType, Edited)
   SELECT DdeSourceKey, NodeKey, SourceName, ApplicationName, TopicName,
          RequestInitialData, AlwaysAdvise, DefaultStorageType,
          DefaultStorageRate, TimeDeadband, ValueDeadband, RateDeadband, DeadbandType, Import, ProtocolType, 'M'
      FROM Runtime.dbo.TopicImportInfo                 
         WHERE NodeKey = @NodeNo

GO

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

CREATE procedure ww_DeltaReImportTagExist 
AS

if exists (select TagName from Runtime.dbo.InTouchSpecific its,
                               Holding.dbo.InTouchDB itdb
              where itdb.NodeKey = its.NodeKey
              and   itdb.db_tagname = its.OriginalName)

begin
   -- InTouchTag existed and is still "InInSQL"
   update Holding.dbo.InTouchDB
     set Edited = 'M', InSQLName = its.TagName
         from Holding.dbo.InTouchDB itdb, Runtime.dbo.InTouchSpecific its
            where (itdb.NodeKey = its.NodeKey
                and itdb.db_tagname = its.OriginalName
                and itdb.Edited = 'I'
                and its.InInSQL = 1)

   -- InTouchTag existed and is not anymore "InInSQL"   
   -- Needs to be seen as a complete new insert
   delete from Runtime.dbo.InTouchSpecific 
      where TagName IN ( Select TagName
                 from Holding.dbo.InTouchDB itdb, Runtime.dbo.InTouchSpecific its
                    where itdb.NodeKey = its.NodeKey
                    and itdb.db_tagname = its.OriginalName
                    and itdb.Edited = 'I'
                    and its.InInSQL = 0)

   -- InTouch Tag has been deleted
   update Holding.dbo.InTouchDB
     set InSQLName = its.TagName
         from Holding.dbo.InTouchDB itdb, Runtime.dbo.InTouchSpecific its
            where (itdb.NodeKey = its.NodeKey
                and itdb.db_tagname = its.OriginalName
                and itdb.Edited = 'D')

end
GO

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

CREATE procedure ww_DumpLogs 

AS

Dump tran Holding with no_log

Dump tran Runtime with no_log

GO

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

CREATE PROCEDURE ww_DupTags_ResetToInSQL  

AS

UPDATE InTouchDB
  SET ToInSQL = 0
  WHERE InSQLName IN ( SELECT TagName FROM Runtime.dbo.Tag, InTouchDB
                            WHERE ( Runtime.dbo.Tag.TagName = InTouchDB.InSQLName )
                            AND ( InTouchDB.Edited = "I" ))

GO

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

CREATE procedure ww_InTouchNodeDelete 
@NodeKey int

AS

Dump tran Runtime with no_log

DELETE Runtime.dbo.AnalogTag
   WHERE TagName IN
      (SELECT TagName FROM Runtime.dbo.InTouchSpecific
         WHERE NodeKey = @NodeKey AND InInSQL=1)

Dump tran Runtime with no_log

DELETE Runtime.dbo.DiscreteTag
   WHERE TagName IN
      (SELECT TagName FROM Runtime.dbo.InTouchSpecific
         WHERE NodeKey = @NodeKey AND InInSQL=1)

Dump tran Runtime with no_log

DELETE Runtime.dbo.StringTag
   WHERE TagName IN
      (SELECT TagName FROM Runtime.dbo.InTouchSpecific
         WHERE NodeKey = @NodeKey AND InInSQL=1)

Dump tran Runtime with no_log

DELETE Runtime.dbo.EventTag
   WHERE TagName IN
      (SELECT TagName FROM Runtime.dbo.InTouchSpecific
         WHERE NodeKey = @NodeKey AND InInSQL=1)

Dump tran Runtime with no_log

DELETE Runtime.dbo.ComplexTag
   WHERE TagName IN
      (SELECT TagName FROM Runtime.dbo.InTouchSpecific
         WHERE NodeKey = @NodeKey AND InInSQL=1)

Dump tran Runtime with no_log

DELETE Runtime.dbo.Tag 
   WHERE TagName IN
      (SELECT TagName FROM Runtime.dbo.InTouchSpecific
         WHERE NodeKey = @NodeKey AND InInSQL=1)

Dump tran Runtime with no_log

DELETE Runtime.dbo.TopicImportInfo
   WHERE NodeKey = @NodeKey

Dump tran Runtime with no_log

DELETE Runtime.dbo.InTouchSpecific
   WHERE NodeKey = @NodeKey

/* delete corresponding PNS entry for this node before actually deleting the node itself */

DECLARE @MachineName nvarchar(255) 
SELECT  @MachineName = RTRIM(( SELECT MachineName from Runtime.dbo.InTouchNode WHERE NodeKey = @NodeKey ))

-- delete current node's related Public Name Space entries 
DECLARE @NameKey int 
SELECT @NameKey = NULL

SELECT @NameKey = A.NameKey FROM Runtime.dbo.PublicNameSpace A, Runtime.dbo.PublicNameSpace B
WHERE  A.Name = @MachineName
AND    A.ParentKey = B.NameKey
AND    B.Name = 'InTouch Nodes'

-- only delete if parent is InTouch Nodes as there might be other entries
-- with this machine name which we do not wish to delete 
IF ( @NameKey IS NOT NULL )
BEGIN
  EXECUTE Runtime.dbo.ww_PublicNSDeleteGroup @NameKey
END

DELETE Runtime.dbo.InTouchNode
   WHERE NodeKey = @NodeKey

/******************************************************************************/
-- Clean Topic items if not used
delete Runtime.dbo.Topic
  where TopicKey not in
    (select DISTINCT TopicKey from Runtime.dbo.Tag where TagType < 5)
  and TopicKey > 2  -- Need to keep MDAS topic

/******************************************************************************/
-- Clean IOServer if not used
delete Runtime.dbo.IOServer
   where IOServerKey not in
     (select DISTINCT IOServerKey from Runtime.dbo.Topic)
   and IOServerKey > 2 -- Just a safeguard to avoid deletion of MDAS IOServer

/******************************************************************************/
-- CR L00032129 - NiravT
-- Remove IOServertype - 'NA' created by Galaxy Name source
delete Runtime.dbo.IOServerType
   where ApplicationName = 'NA' AND 
 ((select count(*) from Runtime.dbo.IOServer where ApplicationName = 'NA') = 0)
Dump tran Runtime with no_log

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

CREATE procedure ww_Init_EngUnit_Msg_Limit 

as

BEGIN TRAN

/******************************************************************************/
-- EngineeringUnit Table
-- First look for <NULL> or <Empty> units and replace by 'None' 
UPDATE Holding.dbo.intgDDEIOInfo SET i_EGU = 'None'
   WHERE i_EGU IS NULL OR i_EGU = ''

UPDATE Holding.dbo.realDDEIOInfo SET r_EGU = 'None'
   WHERE r_EGU IS NULL OR r_EGU = ''

UPDATE Holding.dbo.intgVarInfo SET i_EGU = 'None'
   WHERE i_EGU IS NULL OR i_EGU = ''

UPDATE Holding.dbo.realVarInfo SET r_EGU = 'None'
   WHERE r_EGU IS NULL OR r_EGU = ''

-- Now Insert in Runtime.EngineeringUnit
INSERT Runtime.dbo.EngineeringUnit (Unit)
   (SELECT DISTINCT RTRIM(i_EGU) 
      FROM Holding.dbo.intgDDEIOInfo
            GROUP BY RTRIM(i_EGU)
               HAVING RTRIM(i_EGU) <> ALL 
                  (SELECT Unit FROM Runtime.dbo.EngineeringUnit))

INSERT Runtime.dbo.EngineeringUnit (Unit)
   (SELECT DISTINCT RTRIM(r_EGU)
      FROM Holding.dbo.realDDEIOInfo
         GROUP BY RTRIM(r_EGU)
            HAVING RTRIM(r_EGU) <> ALL 
               (SELECT Unit FROM Runtime.dbo.EngineeringUnit))

INSERT Runtime.dbo.EngineeringUnit (Unit)
   (SELECT DISTINCT RTRIM(i_EGU)
      FROM Holding.dbo.intgVarInfo
            GROUP BY RTRIM(i_EGU)
               HAVING RTRIM(i_EGU) <> ALL 
                  (SELECT Unit FROM Runtime.dbo.EngineeringUnit))

INSERT Runtime.dbo.EngineeringUnit (Unit)
   (SELECT DISTINCT RTRIM(r_EGU)
      FROM Holding.dbo.realVarInfo
            GROUP BY RTRIM(r_EGU)
               HAVING RTRIM(r_EGU) <> ALL 
                  (SELECT Unit FROM Runtime.dbo.EngineeringUnit))

--/************************************************************************/
-- Message Table
-- First look for <NULL> or <Empty> messages and replace by 0 or 1

UPDATE Holding.dbo.discVarInfo SET d_offMsg = '0'
   WHERE d_offMsg IS NULL OR d_offMsg = ''

UPDATE Holding.dbo.discVarInfo SET d_onMsg = '1'
   WHERE d_onMsg IS NULL OR d_onMsg = ''

UPDATE Holding.dbo.discDDEIOInfo SET d_offMsg = '0'
   WHERE d_offMsg IS NULL OR d_offMsg = ''

UPDATE Holding.dbo.discDDEIOInfo SET d_onMsg = '1'
   WHERE d_onMsg IS NULL OR d_onMsg = ''

-- Now Insert in Runtime.Message
INSERT Runtime.dbo.Message (Message0, Message1)
   (SELECT DISTINCT RTRIM(d_offMsg), RTRIM(d_onMsg)
      FROM Holding.dbo.discVarInfo
            GROUP BY d_offMsg, d_onMsg
               HAVING RTRIM(d_offMsg) + RTRIM(d_onMsg) <> ALL
                  (SELECT Message0+Message1 FROM Runtime.dbo.Message))

INSERT Runtime.dbo.Message (Message0, Message1)
   (SELECT DISTINCT RTRIM(d_offMsg), RTRIM(d_onMsg)
      FROM Holding.dbo.discDDEIOInfo
            GROUP BY d_offMsg, d_onMsg
               HAVING RTRIM(d_offMsg) + RTRIM(d_onMsg) <> ALL
                  (SELECT Message0+Message1 FROM Runtime.dbo.Message))


-- /******************************************************************************/
-- "Limit" Definition Tables
DECLARE @contextkey      int      -- The InTouch context identifier
DECLARE @lolokey         int      -- The InTouch context lolo limit identifier
DECLARE @lokey           int      -- The InTouch context lo   limit identifier
DECLARE @hikey           int      -- The InTouch context hi   limit identifier
DECLARE @hihikey         int      -- The InTouch context hihi limit identifier

-- Context Table : InTouch defined as a context.
IF not exists (SELECT Description FROM Runtime.dbo.Context WHERE Description = 'InTouch')
BEGIN 
   INSERT Runtime.dbo.Context (Description) VALUES ('InTouch')
   SELECT @contextkey = @@Identity
END
ELSE 
BEGIN
   SELECT @contextkey = (SELECT ContextKey FROM Runtime.dbo.Context
                           WHERE Description = 'InTouch')
END

-- LimitName Table : LoLo, Lo, Hi, HiHi
IF not exists (SELECT Name FROM Runtime.dbo.LimitName WHERE Name = 'LoLo')
BEGIN 
   INSERT Runtime.dbo.LimitName (Name) VALUES ('LoLo')
   SELECT @lolokey = @@Identity
END
ELSE 
BEGIN
   SELECT @lolokey = (SELECT LimitNameKey FROM Runtime.dbo.LimitName WHERE Name = 'LoLo')
END

IF not exists (SELECT Name FROM Runtime.dbo.LimitName WHERE Name = 'Lo')
BEGIN 
   INSERT Runtime.dbo.LimitName (Name) VALUES ('Lo')
   SELECT @lokey = @@Identity
END
ELSE 


BEGIN
   SELECT @lokey = (SELECT LimitNameKey FROM Runtime.dbo.LimitName WHERE Name = 'Lo')
END

IF not exists (SELECT Name FROM Runtime.dbo.LimitName WHERE Name = 'Hi')
BEGIN 
   INSERT Runtime.dbo.LimitName (Name) VALUES ('Hi')
   SELECT @hikey = @@Identity
END
ELSE 
BEGIN
   SELECT @hikey = (SELECT LimitNameKey FROM Runtime.dbo.LimitName WHERE Name = 'Hi')
END

IF not exists (SELECT Name FROM Runtime.dbo.LimitName WHERE Name = 'HiHi')
BEGIN 
   INSERT Runtime.dbo.LimitName (Name) VALUES ('HiHi')
   SELECT @hihikey = @@Identity
END
ELSE 
BEGIN
   SELECT @hihikey = (SELECT LimitNameKey FROM Runtime.dbo.LimitName WHERE Name = 'HiHi')
END

IF @@ERROR <> 0
BEGIN
   ROLLBACK TRAN
   RETURN -1
END
ELSE
BEGIN
   COMMIT TRAN
   RETURN 0
END
GO

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

CREATE procedure ww_Insert_DDEDisc 
as

begin tran

/******************************************************************************/
-- IO Disc to Tag and DiscreteTag
/******************************************************************************/

declare @StorageNodeKey int
set @StorageNodeKey =  (select min(StorageNodeKey) from Runtime..StorageNode)

/* Insert in Tag Table */
insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
           case dcfg.StorageType when 1 then 2 when 2 then 2 when 3 then 3 end,
 0, rtrim(iodisc.ddio_itemName), itdb.CurrentEditor, 2, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.discDDEIOInfo iodisc,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = iodisc.dbHnd
         and dcfg.DdeSourceKey = iodisc.ddio_source
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert into DiscreteTag Table */
insert into Runtime.dbo.DiscreteTag (TagName, MessageKey, InitialValue)  
   select rtrim(itdb.InSQLName), iodisc.R_MessageKey, iodisc.d_initValue
      from Holding.dbo.InTouchDB      itdb, 
           Holding.dbo.discDDEIOInfo  iodisc
         where itdb.dbHnd = iodisc.dbHnd
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Keep track of what was imported in InTouchSpecific */
insert into Runtime.dbo.InTouchSpecific (TagName, NodeKey, OriginalName, TypeInfo,  InInSQL)
   select rtrim(InSQLName), NodeKey, rtrim(db_tagname), typeinfo, ToInSQL
      from Holding.dbo.InTouchDB
      where typeinfo = 5 and Edited  = 'I'
      and rtrim(InSQLName) not in (select TagName from Runtime.dbo.InTouchSpecific) 

/* Populate the Public Name Space InTouchNode Tree */
declare @namekey int
set @namekey =  (select TOP 1 NameKey from Runtime.dbo.PublicNameSpace
                                 where [Name] = (select RTRIM(MachineName) from InTouchNode)
                                 and ParentKey = 7)

if @namekey is not null
begin
   insert into Runtime.dbo.PublicGroupTag (NameKey, wwDomainTagKey)
      select @namekey, wwDomainTagKey
         from  Runtime.dbo.TagRef tr, Holding.dbo.InTouchDB itdb
            where itdb.typeinfo = 5 and itdb.Edited = 'I'
            and tr.TagName = itdb.InSQLName
            and itdb.ToInSQL = 1
end

/* if needed update the InInSQL Flag */
update Runtime.dbo.InTouchSpecific set InInSQL =  itdb.ToInSQL
   from Runtime.dbo.InTouchSpecific its, InTouchDB itdb
      where its.TagName = itdb.InSQLName
      and its.InInSQL <> itdb.ToInSQL
      and itdb.typeinfo = 5 and itdb.Edited = 'I'

/* Flag InTouchDB as imported */
update Holding.dbo.InTouchDB set Edited = ''
         where ToInSQL = 1
         and   Edited     = 'I'
         and   typeinfo    = 5

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end
GO 
GRANT exec on ww_Insert_DDEDisc to  aaAdministrators
go
go
 
 if exists (select * from sysobjects where id = object_id('dbo.ww_Insert_DDEInt'))
  DROP PROCEDURE dbo.ww_Insert_DDEInt
GO

CREATE procedure ww_Insert_DDEInt 
as

begin tran

/******************************************************************************/
-- IOint to Tag and AnalogTag
/******************************************************************************/

declare @StorageNodeKey int
set @StorageNodeKey =  (select min(StorageNodeKey) from Runtime..StorageNode)

/* Insert in Tag Table */
insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
          dcfg.StorageType, dcfg.StorageRate, rtrim(ioint.diio_itemName), itdb.CurrentEditor, 1, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end,
case dcfg.DeadbandType when 3 then 2 else 1
end
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.intgDDEIOInfo ioint,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = ioint.dbHnd
         and dcfg.DdeSourceKey = ioint.diio_source
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert into AnalogTag Table */
insert into Runtime.dbo.AnalogTag (TagName, EUKey, MinEU, MaxEU, MinRaw, MaxRaw, Scaling,
                                   RawType,  IntegerSize, SignedInteger, InitialValue, ValueDeadband, RateDeadband)
   select rtrim(itdb.InSQLName), ioint.R_EUKey, ioint.i_minValue, ioint.i_maxValue,
          ioint.diio_minRaw, ioint.diio_maxRaw, ioint.diio_inputConv, 3, 32, 1, ioint.i_initValue,
          case dcfg.DeadbandType
                   when 0 then 0
                   when 1 then itdb.InSQLDeadband
                   when 2 then dcfg.ValueDeadband
                   when 3 then dcfg.ValueDeadband
           end,
           dcfg.RateDeadband
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.intgDDEIOInfo ioint,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = ioint.dbHnd
         and dcfg.DdeSourceKey = ioint.diio_source
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Limits */
-- Get the limit Information
declare @contextkey int  -- The InTouch context identifier
declare @limitkey     int  -- The InTouch context limit identifier

set @contextkey = (select ContextKey from Runtime.dbo.Context
                         where [Description] = 'InTouch')
set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'HiHi')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, ioint.i_hihi, @limitkey,
            ioint.i_almPriHiHi, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.intgDDEIOInfo ioint
         where itdb.dbHnd = ioint.dbHnd
         and ioint.i_hihiChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'Hi')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, ioint.i_hi, @limitkey,
            ioint.i_almPriHi, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.intgDDEIOInfo ioint
         where itdb.dbHnd = ioint.dbHnd
         and ioint.i_hiChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'Lo')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, ioint.i_lo, @limitkey,
            ioint.i_almPriLo, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.intgDDEIOInfo ioint
         where itdb.dbHnd = ioint.dbHnd
         and ioint.i_loChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'LoLo')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, ioint.i_lolo, @limitkey,
            ioint.i_almPriLoLo, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.intgDDEIOInfo ioint
         where itdb.dbHnd = ioint.dbHnd
         and ioint.i_loloChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Rate Of Change */
insert into Runtime.dbo.RateOfChange (TagName, ContextKey, Value, 
                                      TimeBase, Priority, Checked) 
   select rtrim(itdb.InSQLName), @contextkey, ioint.i_roc, ioint.i_rocUnits, 
              ioint.i_almPriROC, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgDDEIOInfo  ioint
         where itdb.dbHnd = ioint.dbHnd
         and ioint.i_rocChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Deviation */
insert into Runtime.dbo.Deviation (TagName, ContextKey, MinorDeviation, MinorChecked,
                                   MinorPriority, MajorDeviation, MajorChecked,
                                   MajorPriority, Target, Deadband)
   select rtrim(itdb.InSQLName), @contextkey, itdb.db_minorDev, ioint.i_minorDevChecked,
            ioint.i_almPriMinorDev, itdb.db_majorDev, ioint.i_majorDevChecked,
            ioint.i_almPriMajorDev, ioint.i_devTarget, itdb.db_almDevDeadband 
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgDDEIOInfo  ioint
         where itdb.dbHnd = ioint.dbHnd
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
         and (ioint.i_minorDevChecked = 1
                  or ioint.i_majorDevChecked = 1)
            order by itdb.db_tagname

/* Keep track of what was imported in InTouchSpecific */
insert into Runtime.dbo.InTouchSpecific (TagName, NodeKey, OriginalName, TypeInfo,  InInSQL)
   select rtrim(InSQLName), NodeKey, rtrim(db_tagname), typeinfo, ToInSQL
      from Holding.dbo.InTouchDB
      where typeinfo = 1 and Edited  = 'I'
      and rtrim(InSQLName) not in (select TagName from Runtime.dbo.InTouchSpecific) 

/* Populate the Public Name Space InTouchNode Tree */
declare @namekey int
set @namekey =  (select TOP 1 NameKey from Runtime.dbo.PublicNameSpace
                                 where [Name] = (select RTRIM(MachineName) from InTouchNode)
                                 and ParentKey = 7)

if @namekey is not null
begin
   insert into Runtime.dbo.PublicGroupTag (NameKey, wwDomainTagKey)
      select @namekey, wwDomainTagKey
         from  Runtime.dbo.TagRef tr, Holding.dbo.InTouchDB itdb
            where itdb.typeinfo = 1 and itdb.Edited = 'I'
            and tr.TagName = itdb.InSQLName
            and itdb.ToInSQL = 1
end

/* if needed update the InInSQL Flag */
update Runtime.dbo.InTouchSpecific set InInSQL =  itdb.ToInSQL
   from Runtime.dbo.InTouchSpecific its, InTouchDB itdb
      where its.TagName = itdb.InSQLName
      and its.InInSQL <> itdb.ToInSQL
      and itdb.typeinfo = 1 and itdb.Edited = 'I'

/* Flag InTouchDB as imported */
update Holding.dbo.InTouchDB set Edited = ''
         where ToInSQL = 1
         and   Edited     = 'I'
         and   typeinfo    = 1

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end
GO

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

CREATE procedure ww_Insert_DDEReal 
as

begin tran

/******************************************************************************/
-- IOreal to Tag and AnalogTag
/******************************************************************************/

declare @StorageNodeKey int
set @StorageNodeKey =  (select min(StorageNodeKey) from Runtime..StorageNode)

/* Insert in Tag Table */
insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
          dcfg.StorageType, dcfg.StorageRate, rtrim(ioreal.drio_itemName), itdb.CurrentEditor, 1, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end,
case dcfg.DeadbandType when 3 then 2 else 1
end
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.realDDEIOInfo ioreal,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = ioreal.dbHnd
         and dcfg.DdeSourceKey = ioreal.drio_source
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert into AnalogTag Table */
insert into Runtime.dbo.AnalogTag (TagName, EUKey, MinEU, MaxEU, MinRaw, MaxRaw, Scaling, RawType,  IntegerSize, SignedInteger, InitialValue, ValueDeadband, RateDeadband)  
   select rtrim(itdb.InSQLName), ioreal.R_EUKey, ioreal.r_minValue, ioreal.r_maxValue,
          ioreal.drio_minRaw, ioreal.drio_maxRaw, ioreal.drio_inputConv, 2, 0, 0, ioreal.r_initValue,
          case dcfg.DeadbandType
                   when 0 then 0
                   when 1 then itdb.InSQLDeadband
                   when 2 then dcfg.ValueDeadband
     when 3 then dcfg.ValueDeadband
           end,
     dcfg.RateDeadband
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.realDDEIOInfo ioreal,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = ioreal.dbHnd
         and dcfg.DdeSourceKey = ioreal.drio_source
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Limits */
-- Get the limit Information
declare @contextkey int  -- The InTouch context identifier
declare @limitkey     int  -- The InTouch context limit identifier

set @contextkey = (select ContextKey from Runtime.dbo.Context
                         where [Description] = 'InTouch')
set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'HiHi')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, ioreal.r_hihi, @limitkey,
            ioreal.r_almPriHiHi, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.realDDEIOInfo ioreal
         where itdb.dbHnd = ioreal.dbHnd
         and ioreal.r_hihiChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'Hi')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, ioreal.r_hi, @limitkey,
            ioreal.r_almPriHi, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.realDDEIOInfo ioreal
         where itdb.dbHnd = ioreal.dbHnd
         and ioreal.r_hiChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'Lo')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, ioreal.r_lo, @limitkey,
            ioreal.r_almPriLo, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.realDDEIOInfo ioreal
         where itdb.dbHnd = ioreal.dbHnd
         and ioreal.r_loChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'LoLo')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, ioreal.r_lolo, @limitkey,
            ioreal.r_almPriLoLo, 1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.realDDEIOInfo ioreal
         where itdb.dbHnd = ioreal.dbHnd
         and ioreal.r_loloChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Rate Of Change */
insert into Runtime.dbo.RateOfChange (TagName, ContextKey, Value, 
                                      TimeBase, Priority, Checked) 
   select rtrim(itdb.InSQLName), @contextkey, ioreal.r_roc, ioreal.r_rocUnits, 
              ioreal.r_almPriROC, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realDDEIOInfo  ioreal
         where itdb.dbHnd = ioreal.dbHnd
         and ioreal.r_rocChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Deviation */
insert into Runtime.dbo.Deviation (TagName, ContextKey, MinorDeviation, MinorChecked,
                                   MinorPriority, MajorDeviation, MajorChecked,
                                   MajorPriority, Target, Deadband)
   select rtrim(itdb.InSQLName), @contextkey, itdb.db_minorDev, ioreal.r_minorDevChecked,
            ioreal.r_almPriMinorDev, itdb.db_majorDev, ioreal.r_majorDevChecked,
            ioreal.r_almPriMajorDev, ioreal.r_devTarget, itdb.db_almDevDeadband 
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realDDEIOInfo  ioreal
         where itdb.dbHnd = ioreal.dbHnd
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
         and (ioreal.r_minorDevChecked = 1
                  or ioreal.r_majorDevChecked = 1)
            order by itdb.db_tagname

/* Keep track of what was imported in InTouchSpecific */
insert into Runtime.dbo.InTouchSpecific (TagName, NodeKey, OriginalName, TypeInfo,  InInSQL)
   select rtrim(InSQLName), NodeKey, rtrim(db_tagname), typeinfo, ToInSQL
      from Holding.dbo.InTouchDB
      where typeinfo = 2 and Edited  = 'I'
      and rtrim(InSQLName) not in (select TagName from Runtime.dbo.InTouchSpecific) 

/* Populate the Public Name Space InTouchNode Tree */
declare @namekey int
set @namekey =  (select TOP 1 NameKey from Runtime.dbo.PublicNameSpace
                                 where [Name] = (select RTRIM(MachineName) from InTouchNode)
                                 and ParentKey = 7)

if @namekey is not null
begin
   insert into Runtime.dbo.PublicGroupTag (NameKey, wwDomainTagKey)
      select @namekey, wwDomainTagKey
         from  Runtime.dbo.TagRef tr, Holding.dbo.InTouchDB itdb
            where itdb.typeinfo = 2 and itdb.Edited = 'I'
            and tr.TagName = itdb.InSQLName
            and itdb.ToInSQL = 1
end

/* if needed update the InInSQL Flag */
update Runtime.dbo.InTouchSpecific set InInSQL =  itdb.ToInSQL
   from Runtime.dbo.InTouchSpecific its, InTouchDB itdb
      where its.TagName = itdb.InSQLName
      and its.InInSQL <> itdb.ToInSQL
      and itdb.typeinfo = 2 and itdb.Edited = 'I'

/* Flag InTouchDB as imported */
update Holding.dbo.InTouchDB set Edited = ''
         where ToInSQL = 1
         and   Edited     = 'I'
         and   typeinfo    = 2

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end
GO

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

CREATE procedure ww_Insert_DDEString 
as
begin tran

/******************************************************************************/
-- IOString to Tag and StringTag
/******************************************************************************/

declare @StorageNodeKey int
set @StorageNodeKey =  (select min(StorageNodeKey) from Runtime..StorageNode)

/* Insert in Tag Table */
insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
case dcfg.StorageType when 1 then 2 when 2 then 2 when 3 then 3 end,
0, rtrim(iostr.dmio_itemName), itdb.CurrentEditor, 3, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end,1
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.strgDDEIOInfo iostr,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = iostr.dbHnd
         and dcfg.DdeSourceKey = iostr.dmio_source
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert into StringTag Table */
insert into Runtime.dbo.StringTag (TagName, InitialValue, MaxLength)  
   select rtrim(itdb.InSQLName), rtrim(iostr.dmio_initValue), 
       case 
           when  iostr.dmio_nMaxString = 0 then 131
           when  iostr.dmio_nMaxString between 1 and 8 then 8
           when  iostr.dmio_nMaxString between 9 and 16 then 16
           when  iostr.dmio_nMaxString between 17 and 24 then 24
           when  iostr.dmio_nMaxString between 25 and 32 then 32
           when  iostr.dmio_nMaxString between 33 and 48 then 48
           when  iostr.dmio_nMaxString between 49 and 64 then 64
           when  iostr.dmio_nMaxString between 65 and 128 then 128
           when  iostr.dmio_nMaxString between 129 and 131 then 131  -- InTouch Legacy
           when  iostr.dmio_nMaxString between 132 and 256 then 256
           when  iostr.dmio_nMaxString between 257 and 512 then 512
          else 512
       end
      from Holding.dbo.InTouchDB     itdb, 
           Holding.dbo.strgDDEIOInfo iostr
         where itdb.dbHnd = iostr.dbHnd
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Keep track of what was imported in InTouchSpecific */
insert into Runtime.dbo.InTouchSpecific (TagName, NodeKey, OriginalName, TypeInfo,  InInSQL)
   select rtrim(InSQLName), NodeKey, rtrim(db_tagname), typeinfo, ToInSQL
      from Holding.dbo.InTouchDB
      where typeinfo = 7 and Edited  = 'I'
      and rtrim(InSQLName) not in (select TagName from Runtime.dbo.InTouchSpecific) 

/* Populate the Public Name Space InTouchNode Tree */
declare @namekey int
set @namekey =  (select TOP 1 NameKey from Runtime.dbo.PublicNameSpace
                                 where [Name] = (select RTRIM(MachineName) from InTouchNode)
                                 and ParentKey = 7)

if @namekey is not null
begin
   insert into Runtime.dbo.PublicGroupTag (NameKey, wwDomainTagKey)
      select @namekey, wwDomainTagKey
         from  Runtime.dbo.TagRef tr, Holding.dbo.InTouchDB itdb
            where itdb.typeinfo = 7 and itdb.Edited = 'I'
            and tr.TagName = itdb.InSQLName
            and itdb.ToInSQL = 1
end

/* if needed update the InInSQL Flag */
update Runtime.dbo.InTouchSpecific set InInSQL =  itdb.ToInSQL
   from Runtime.dbo.InTouchSpecific its, InTouchDB itdb
      where its.TagName = itdb.InSQLName
      and its.InInSQL <> itdb.ToInSQL
      and itdb.typeinfo = 7 and itdb.Edited = 'I'

/* Flag InTouchDB as imported */
update Holding.dbo.InTouchDB set Edited = ''
         where ToInSQL = 1
         and  Edited        = 'I'
         and   typeinfo    = 7

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end

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

CREATE PROCEDURE ww_Insert_InTouchDB
(  @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32), 
   @db_description           nchar(512) , 
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit
 )
 
AS

INSERT InTouchDB(
   NodeKey,
   dbHnd,
   db_tagname, 
   db_description,
   db_type,
   db_io_type,
   db_group,
   db_valid,
   db_modified,
   db_useCountRead,
   db_useCountWrite,
   db_useCountAlmInfo,
   db_version,
   typeinfo,
   db_logged,
   db_useTagAsItem,
   db_eventlogged,
   db_alarmParmsSaved,
   db_currentValueSaved,
   db_intgLogDeadband,
   db_realLogDeadband,
   db_eventLoggingPriority,
   db_intgAlmDeadband,
   db_realAlmDeadband,
   db_almDevDeadband,
   db_minorDev,
   db_majorDev,
   Edited,
   ToInSQL,
   InSQLName,
   CurrentEditor, 
   UDT,
   UDTChild,
   HasUDTChild )     

VALUES(     
   @NodeKey,                
   @dbHnd,
   RTRIM(@db_tagname),             
   RTRIM(@db_description),         
   @db_type,                
   @db_io_type,             
   @db_group,               
   @db_valid,               
   @db_modified,            
   @db_useCountRead,        
   @db_useCountWrite,       
   @db_useCountAlmInfo,     
   @db_version,             
   @typeinfo,               
   @db_logged,              
   @db_useTagAsItem,        
   @db_eventlogged,         
   @db_alarmParmsSaved,     
   @db_currentValueSaved,   
   @db_intgLogDeadband,     
   @db_realLogDeadband,     
   @db_eventLoggingPriority,
   @db_intgAlmDeadband,     
   @db_realAlmDeadband,     
   @db_almDevDeadband,      
   @db_minorDev,            
   @db_majorDev,            
   @Edited,                 
   @ToInSQL,
   @InSQLName,
   @CurrentEditor,
   @UDT,
   @UDTChild,
   @HasUDTChild )

GO

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

CREATE procedure ww_Insert_MemDisc 
as

begin tran

/******************************************************************************/
-- memDisc to Tag and DiscreteTag
/******************************************************************************/

declare @StorageNodeKey int
set @StorageNodeKey =  (select min(StorageNodeKey) from Runtime..StorageNode)

/* Insert in Tag Table */
insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
case dcfg.StorageType when 1 then 2 when 2 then 2 when 3 then 3 end,
          0, rtrim(itdb.db_tagname), itdb.CurrentEditor, 2, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end,1
      from Holding.dbo.InTouchDB   itdb, 
           Holding.dbo.discVarInfo memdisc,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memdisc.dbHnd
         and itdb.db_tagname not like '$%'  -- exclude InTouch system tags
         and dcfg.DdeSourceKey = -1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
case dcfg.StorageType when 1 then 2 when 2 then 2 when 3 then 3 end,
 0, rtrim(itdb.db_tagname), itdb.CurrentEditor, 2, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 when 2 then dcfg.TimeDeadband  when 3 then 0 end,1
      from Holding.dbo.InTouchDB   itdb, 
           Holding.dbo.discVarInfo memdisc,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memdisc.dbHnd
         and itdb.db_tagname like '$%'  -- InTouch system tags
         and dcfg.DdeSourceKey = -2
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert into DiscreteTag Table */
insert into Runtime.dbo.DiscreteTag (TagName, MessageKey, InitialValue)  
   select rtrim(itdb.InSQLName), memdisc.R_MessageKey, memdisc.d_initValue
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.discVarInfo  memdisc
         where itdb.dbHnd = memdisc.dbHnd
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Keep track of what was imported in InTouchSpecific */
insert into Runtime.dbo.InTouchSpecific (TagName, NodeKey, OriginalName, TypeInfo,  InInSQL)
   select rtrim(InSQLName), NodeKey, rtrim(db_tagname), typeinfo, ToInSQL
      from Holding.dbo.InTouchDB
      where typeinfo = 6 and Edited  = 'I'
      and rtrim(InSQLName) not in (select TagName from Runtime.dbo.InTouchSpecific) 

/* Populate the Public Name Space InTouchNode Tree */
declare @namekey int
set @namekey =  (select TOP 1 NameKey from Runtime.dbo.PublicNameSpace
                                 where [Name] = (select RTRIM(MachineName) from InTouchNode)
                                 and ParentKey = 7)

if @namekey is not null
begin
   insert into Runtime.dbo.PublicGroupTag (NameKey, wwDomainTagKey)
      select @namekey, wwDomainTagKey
         from  Runtime.dbo.TagRef tr, Holding.dbo.InTouchDB itdb
            where itdb.typeinfo = 6 and itdb.Edited = 'I'
            and tr.TagName = itdb.InSQLName
            and itdb.ToInSQL = 1
end

/* if needed update the InInSQL Flag */
update Runtime.dbo.InTouchSpecific set InInSQL =  itdb.ToInSQL
   from Runtime.dbo.InTouchSpecific its, InTouchDB itdb
      where its.TagName = itdb.InSQLName
      and its.InInSQL <> itdb.ToInSQL
      and itdb.typeinfo = 6 and itdb.Edited = 'I'

/* Flag InTouchDB as imported */
update Holding.dbo.InTouchDB set Edited = ''
         where ToInSQL = 1
         and   Edited     = 'I'
         and   typeinfo    = 6

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end

GO

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

CREATE procedure ww_Insert_MemInt 
as

begin tran

/******************************************************************************/
-- memInt to Tag and AnalogTag
/******************************************************************************/

declare @StorageNodeKey int
set @StorageNodeKey =  (select min(StorageNodeKey) from Runtime..StorageNode)

/* Insert in Tag Table */
insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
          dcfg.StorageType, dcfg.StorageRate, rtrim(itdb.db_tagname), itdb.CurrentEditor, 1, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end,
case dcfg.DeadbandType when 3 then 2 else 1
end
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memint.dbHnd
         and dcfg.DdeSourceKey = -1
         and itdb.db_tagname not like '$%'  -- exclude InTouch system tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
          dcfg.StorageType, dcfg.StorageRate, rtrim(itdb.db_tagname), itdb.CurrentEditor, 1, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end,
case dcfg.DeadbandType when 3 then 2 else 1
end 
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memint.dbHnd
         and dcfg.DdeSourceKey = -2
         and itdb.db_tagname like '$%'  -- InTouch system tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert into AnalogTag Table */
insert into Runtime.dbo.AnalogTag (TagName, EUKey, MinEU, MaxEU, MinRaw, MaxRaw, Scaling,
                                   RawType,  IntegerSize, SignedInteger,  InitialValue, ValueDeadband, RateDeadband)  
   select rtrim(itdb.InSQLName), memint.R_EUKey, memint.i_minValue, memint.i_maxValue,
          memint.i_minValue, memint.i_maxValue, 0, 3, 32, 1,  i_initValue, 
          case dcfg.DeadbandType
             when 0 then 0
             when 1 then itdb.InSQLDeadband
             when 2 then dcfg.ValueDeadband
 when 3 then dcfg.ValueDeadband
          end,
     dcfg.RateDeadband
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memint.dbHnd
         and dcfg.DdeSourceKey = -1
         and itdb.db_tagname not like '$%'  -- exclude InTouch system tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

insert into Runtime.dbo.AnalogTag (TagName, EUKey, MinEU, MaxEU, MinRaw, MaxRaw, Scaling,
                                   RawType,  IntegerSize, SignedInteger,  InitialValue, ValueDeadband, RateDeadband)  
   select rtrim(itdb.InSQLName), memint.R_EUKey, memint.i_minValue, memint.i_maxValue,
          memint.i_minValue, memint.i_maxValue, 0, 3, 32, 1,  i_initValue, 
          case dcfg.DeadbandType
             when 0 then 0
             when 1 then itdb.InSQLDeadband
             when 2 then dcfg.ValueDeadband
 when 3 then dcfg.ValueDeadband
          end,
 dcfg.RateDeadband
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memint.dbHnd
         and dcfg.DdeSourceKey = -2
         and itdb.db_tagname like '$%'  -- InTouch system tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Limits */
-- Get the limit Information
declare @contextkey int  -- The InTouch context identifier
declare @limitkey     int  -- The InTouch context limit identifier

set @contextkey = (select ContextKey from Runtime.dbo.Context
                         where [Description] = 'InTouch')
set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'HiHi')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, memint.i_hihi, @limitkey,
            memint.i_almPriHiHi, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint
         where itdb.dbHnd = memint.dbHnd
         and memint.i_hihiChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'Hi')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, memint.i_hi, @limitkey,
            memint.i_almPriHi, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint
         where itdb.dbHnd = memint.dbHnd
         and memint.i_hiChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'Lo')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, memint.i_lo, @limitkey,
            memint.i_almPriLo, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint
         where itdb.dbHnd = memint.dbHnd
         and memint.i_loChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'LoLo')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, memint.i_lolo, @limitkey,
            memint.i_almPriLoLo, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint
         where itdb.dbHnd = memint.dbHnd
         and memint.i_loloChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Rate Of Change */
insert into Runtime.dbo.RateOfChange (TagName, ContextKey, Value, 
                                      TimeBase, Priority, Checked) 
   select rtrim(itdb.InSQLName), @contextkey, memint.i_roc, memint.i_rocUnits, 
              memint.i_almPriROC, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint
         where itdb.dbHnd = memint.dbHnd
         and memint.i_rocChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Deviation */
insert into Runtime.dbo.Deviation (TagName, ContextKey, MinorDeviation, MinorChecked,
                                   MinorPriority, MajorDeviation, MajorChecked,
                                   MajorPriority, Target, Deadband)
   select rtrim(itdb.InSQLName), @contextkey, itdb.db_minorDev, memint.i_minorDevChecked,
            memint.i_almPriMinorDev, itdb.db_majorDev, memint.i_majorDevChecked,
            memint.i_almPriMajorDev, memint.i_devTarget, itdb.db_almDevDeadband 
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.intgVarInfo  memint
         where itdb.dbHnd = memint.dbHnd
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
         and (memint.i_minorDevChecked = 1
                  or memint.i_majorDevChecked = 1)
            order by itdb.db_tagname

/* Keep track of what was imported in InTouchSpecific */
insert into Runtime.dbo.InTouchSpecific (TagName, NodeKey, OriginalName, TypeInfo,  InInSQL)
   select rtrim(InSQLName), NodeKey, rtrim(db_tagname), typeinfo, ToInSQL
      from Holding.dbo.InTouchDB
      where typeinfo = 3 and Edited  = 'I'
      and rtrim(InSQLName) not in (select TagName from Runtime.dbo.InTouchSpecific) 

/* Populate the Public Name Space InTouchNode Tree */
declare @namekey int
set @namekey =  (select TOP 1 NameKey from Runtime.dbo.PublicNameSpace
                                 where [Name] = (select RTRIM(MachineName) from InTouchNode)
                                 and ParentKey = 7)

if @namekey is not null
begin
   insert into Runtime.dbo.PublicGroupTag (NameKey, wwDomainTagKey)
      select @namekey, wwDomainTagKey
         from  Runtime.dbo.TagRef tr, Holding.dbo.InTouchDB itdb
            where itdb.typeinfo = 3 and itdb.Edited = 'I'
            and tr.TagName = itdb.InSQLName
            and itdb.ToInSQL = 1
end

/* if needed update the InInSQL Flag */
update Runtime.dbo.InTouchSpecific set InInSQL =  itdb.ToInSQL
   from Runtime.dbo.InTouchSpecific its, InTouchDB itdb
      where its.TagName = itdb.InSQLName
      and its.InInSQL <> itdb.ToInSQL
      and itdb.typeinfo = 3 and itdb.Edited = 'I'

/* Flag InTouchDB as imported */
update Holding.dbo.InTouchDB set Edited = ''
         where ToInSQL = 1
         and   Edited     = 'I'
         and   typeinfo    = 3

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end
GO

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

CREATE procedure ww_Insert_MemReal 
as

begin tran

/******************************************************************************/
-- memReal to Tag and AnalogTag
/******************************************************************************/

declare @StorageNodeKey int
set @StorageNodeKey =  (select min(StorageNodeKey) from Runtime..StorageNode)

/* Insert in Tag Table */
insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
          dcfg.StorageType, dcfg.StorageRate, rtrim(itdb.db_tagname), itdb.CurrentEditor, 1, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end,
case dcfg.DeadbandType when 3 then 2 else 1
end
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memreal.dbHnd
         and dcfg.DdeSourceKey = -1
         and itdb.db_tagname not like '$%'  -- exclude InTouch system tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
          dcfg.StorageType, dcfg.StorageRate, rtrim(itdb.db_tagname), itdb.CurrentEditor, 1, @StorageNodeKey,
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end,
case dcfg.DeadbandType when 3 then 2 else 1
end
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memreal.dbHnd
         and dcfg.DdeSourceKey = -2
         and itdb.db_tagname like '$%'  -- InTouch system tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert into AnalogTag Table */
insert into Runtime.dbo.AnalogTag (TagName, EUKey, MinEU, MaxEU, MinRaw, MaxRaw, Scaling, RawType,  IntegerSize, SignedInteger, InitialValue, ValueDeadband, RateDeadband)  
   select rtrim(itdb.InSQLName), memreal.R_EUKey, memreal.r_minValue, memreal.r_maxValue,
          memreal.r_minValue, memreal.r_maxValue, 0, 2, 0, 0, memreal.r_initValue, 
          case dcfg.DeadbandType
             when 0 then 0
             when 1 then itdb.InSQLDeadband
             when 2 then dcfg.ValueDeadband
 when 3 then dcfg.ValueDeadband
          end,
     dcfg.RateDeadband
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memreal.dbHnd
         and dcfg.DdeSourceKey = -1
         and itdb.db_tagname not like '$%'  -- exclude InTouch system tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

insert into Runtime.dbo.AnalogTag (TagName, EUKey, MinEU, MaxEU, MinRaw, MaxRaw, Scaling, RawType,  IntegerSize, SignedInteger, InitialValue, ValueDeadband, RateDeadband)  
   select rtrim(itdb.InSQLName), memreal.R_EUKey, memreal.r_minValue, memreal.r_maxValue,
          memreal.r_minValue, memreal.r_maxValue, 0, 2, 0, 0, memreal.r_initValue, 
          case dcfg.DeadbandType
             when 0 then 0
             when 1 then itdb.InSQLDeadband
             when 2 then dcfg.ValueDeadband
 when 3 then dcfg.ValueDeadband
          end,
 dcfg.RateDeadband
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memreal.dbHnd
         and dcfg.DdeSourceKey = -2
         and itdb.db_tagname  like '$%'  --  InTouch system tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Limits */
-- Get the limit Information
declare @contextkey int  -- The InTouch context identifier
declare @limitkey     int  -- The InTouch context limit identifier

set @contextkey = (select ContextKey from Runtime.dbo.Context
                         where [Description] = 'InTouch')
set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'HiHi')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, memreal.r_hihi, @limitkey,
            memreal.r_almPriHiHi, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal
         where itdb.dbHnd = memreal.dbHnd
         and memreal.r_hihiChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'Hi')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, memreal.r_hi, @limitkey,
            memreal.r_almPriHi, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal
         where itdb.dbHnd = memreal.dbHnd
         and memreal.r_hiChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'Lo')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, memreal.r_lo, @limitkey,
            memreal.r_almPriLo, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal
         where itdb.dbHnd = memreal.dbHnd
         and memreal.r_loChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

set @limitkey = (select LimitNameKey from Runtime.dbo.LimitName where [Name] = 'LoLo')
insert into Runtime.dbo.Limit (TagName, ContextKey, LimitType, Value, LimitNameKey,
                               Priority, Checked)  
   select rtrim(itdb.InSQLName), @contextkey, 0, memreal.r_lolo, @limitkey,
            memreal.r_almPriLoLo, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal
         where itdb.dbHnd = memreal.dbHnd
         and memreal.r_loloChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Rate Of Change */
insert into Runtime.dbo.RateOfChange (TagName, ContextKey, Value, 
                                      TimeBase, Priority, Checked) 
   select rtrim(itdb.InSQLName), @contextkey, memreal.r_roc, memreal.r_rocUnits, 
              memreal.r_almPriROC, 1
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal
         where itdb.dbHnd = memreal.dbHnd
         and memreal.r_rocChecked = 1
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert the Checked Deviation */
insert into Runtime.dbo.Deviation (TagName, ContextKey, MinorDeviation, MinorChecked,
                                   MinorPriority, MajorDeviation, MajorChecked,
                                   MajorPriority, Target, Deadband)
   select rtrim(itdb.InSQLName), @contextkey, itdb.db_minorDev, memreal.r_minorDevChecked,
            memreal.r_almPriMinorDev, itdb.db_majorDev, memreal.r_majorDevChecked,
            memreal.r_almPriMajorDev, memreal.r_devTarget, itdb.db_almDevDeadband 
      from Holding.dbo.InTouchDB    itdb, 
           Holding.dbo.realVarInfo  memreal
         where itdb.dbHnd = memreal.dbHnd
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
         and (memreal.r_minorDevChecked = 1
                  or memreal.r_majorDevChecked = 1)
            order by itdb.db_tagname

/* Keep track of what was imported in InTouchSpecific */
insert into Runtime.dbo.InTouchSpecific (TagName, NodeKey, OriginalName, TypeInfo,  InInSQL)
   select rtrim(InSQLName), NodeKey, rtrim(db_tagname), typeinfo, ToInSQL
      from Holding.dbo.InTouchDB
      where typeinfo = 4 and Edited  = 'I'
      and rtrim(InSQLName) not in (select TagName from Runtime.dbo.InTouchSpecific) 

/* Populate the Public Name Space InTouchNode Tree */
declare @namekey int
set @namekey =  (select TOP 1 NameKey from Runtime.dbo.PublicNameSpace
                                 where [Name] = (select RTRIM(MachineName) from InTouchNode)
                                 and ParentKey = 7)

if @namekey is not null
begin
   insert into Runtime.dbo.PublicGroupTag (NameKey, wwDomainTagKey)
      select @namekey, wwDomainTagKey
         from  Runtime.dbo.TagRef tr, Holding.dbo.InTouchDB itdb
            where itdb.typeinfo = 4 and itdb.Edited = 'I'
            and tr.TagName = itdb.InSQLName
            and itdb.ToInSQL = 1
end

/* if needed update the InInSQL Flag */
update Runtime.dbo.InTouchSpecific set InInSQL =  itdb.ToInSQL
   from Runtime.dbo.InTouchSpecific its, InTouchDB itdb
      where its.TagName = itdb.InSQLName
      and its.InInSQL <> itdb.ToInSQL
      and itdb.typeinfo = 4 and itdb.Edited = 'I'

/* Flag InTouchDB as imported */
update Holding.dbo.InTouchDB set Edited = ''
         where ToInSQL = 1
         and   Edited     = 'I'
         and   typeinfo   = 4

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end
GO 
GRANT exec on ww_Insert_MemReal to  aaAdministrators
go
go
 
 if exists (select * from sysobjects where id = object_id('dbo.ww_Insert_MemString'))
  DROP PROCEDURE dbo.ww_Insert_MemString
GO

CREATE procedure ww_Insert_MemString 
as
begin tran

/******************************************************************************/
-- MemString to Tag and StringTag
/******************************************************************************/

declare @StorageNodeKey int
set @StorageNodeKey =  (select min(StorageNodeKey) from Runtime..StorageNode)

/* Insert in Tag Table */
insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
case dcfg.StorageType when 1 then 2 when 2 then 2 when 3 then 3 end,
           0, rtrim(itdb.db_tagname), itdb.CurrentEditor, 3, @StorageNodeKey, 
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end, 1
      from Holding.dbo.InTouchDB  itdb, 
           Holding.dbo.strgInfo   memstr,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memstr.dbHnd
         and dcfg.DdeSourceKey = -1
         and itdb.db_tagname not like '$%' -- exclude InTouch System Tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

insert into Runtime.dbo.Tag (TagName, TopicKey, IOServerKey, [Description], StorageType,
                             StorageRate, ItemName, CurrentEditor, TagType, StorageNodeKey, TimeDeadband, DeadbandType)
   select rtrim(itdb.InSQLName), dcfg.R_TopicKey, dcfg.R_IOServerKey, rtrim(itdb.db_description),  
case dcfg.StorageType when 1 then 2 when 2 then 2 when 3 then 3 end,
           0, rtrim(itdb.db_tagname), itdb.CurrentEditor, 3, @StorageNodeKey, 
case dcfg.DeadbandType when 0 then 0 when 1 then 0 else dcfg.TimeDeadband end, 1
      from Holding.dbo.InTouchDB  itdb, 
           Holding.dbo.strgInfo   memstr,
           Holding.dbo.DdeCfg dcfg
         where itdb.dbHnd = memstr.dbHnd
         and dcfg.DdeSourceKey = -2
         and itdb.db_tagname like '$%' --  InTouch System Tags
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Insert into StringTag Table */
insert into Runtime.dbo.StringTag (TagName, InitialValue, MaxLength)  
   select rtrim(itdb.InSQLName), rtrim(memstr.sv_initValue), 
       case 
           when  memstr.sv_nMaxString = 0 then 131
           when  memstr.sv_nMaxString between 1 and 8 then 8
           when  memstr.sv_nMaxString between 9 and 16 then 16
           when  memstr.sv_nMaxString between 17 and 24 then 24
           when  memstr.sv_nMaxString between 25 and 32 then 32
           when  memstr.sv_nMaxString between 33 and 48 then 48
           when  memstr.sv_nMaxString between 49 and 64 then 64
           when  memstr.sv_nMaxString between 65 and 128 then 128
           when  memstr.sv_nMaxString between 129 and 131 then 131  -- InTouch Legacy
           when  memstr.sv_nMaxString between 132 and 256 then 256
           when  memstr.sv_nMaxString between 257 and 512 then 512
          else 512
       end
      from Holding.dbo.InTouchDB  itdb, 
           Holding.dbo.strgInfo   memstr
         where itdb.dbHnd = memstr.dbHnd
         and itdb.ToInSQL = 1
         and itdb.Edited = 'I'
            order by itdb.db_tagname

/* Keep track of what was imported in InTouchSpecific */
insert into Runtime.dbo.InTouchSpecific (TagName, NodeKey, OriginalName, TypeInfo,  InInSQL)
   select rtrim(InSQLName), NodeKey, rtrim(db_tagname), typeinfo, ToInSQL
      from Holding.dbo.InTouchDB
      where typeinfo = 8 and Edited  = 'I'
      and rtrim(InSQLName) not in (select TagName from Runtime.dbo.InTouchSpecific) 

/* Populate the Public Name Space InTouchNode Tree */
declare @namekey int
set @namekey =  (select TOP 1 NameKey from Runtime.dbo.PublicNameSpace
                                 where [Name] = (select RTRIM(MachineName) from InTouchNode)
                                 and ParentKey = 7)

if @namekey is not null
begin
   insert into Runtime.dbo.PublicGroupTag (NameKey, wwDomainTagKey)
      select @namekey, wwDomainTagKey
         from  Runtime.dbo.TagRef tr, Holding.dbo.InTouchDB itdb
            where itdb.typeinfo = 8 and itdb.Edited = 'I'
            and tr.TagName = itdb.InSQLName
            and itdb.ToInSQL = 1
end

/* if needed update the InInSQL Flag */
update Runtime.dbo.InTouchSpecific set InInSQL =  itdb.ToInSQL
   from Runtime.dbo.InTouchSpecific its, InTouchDB itdb
      where its.TagName = itdb.InSQLName
      and its.InInSQL <> itdb.ToInSQL
      and itdb.typeinfo = 8 and itdb.Edited = 'I'

/* Flag InTouchDB as imported */
update Holding.dbo.InTouchDB set Edited = ''
         where ToInSQL = 1
         and   Edited     = 'I'
         and   typeinfo   = 8

if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end
GO

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

CREATE procedure ww_Insert_Node_IOServer_Topic 

as

BEGIN TRAN
/******************************************************************************/
-- Insert any NEW InTouchNode in Runtime

IF (SELECT Edited FROM Holding.dbo.InTouchNode) = 'I'
BEGIN
   INSERT Runtime.dbo.InTouchNode (NodeKey, MachineName, Description, Path, DuplicateChar,
                       PrefixOrSuffix, AlwaysModifyName, ImportPlantTags, ImportSystemTags, ImportMemoryTags,
                       ImportAllTags)
      (SELECT NodeKey, MachineName, Description, ApplicationPath, DuplicateChar,
              PrefixOrSuffix, AlwaysModifyName, ImportPlantTags, ImportSystemTags, ImportMemoryTags,
                     ImportAllTags
         FROM Holding.dbo.InTouchNode IT)
END
ELSE    -- It is a re-import
BEGIN  -- Update what was imported, it might have change
   UPDATE Runtime.dbo.InTouchNode
        SET ImportPlantTags = hitn.ImportPlantTags,
            ImportSystemTags = hitn.ImportSystemTags,
            ImportMemoryTags = hitn.ImportMemoryTags,
            ImportAllTags = hitn.ImportAllTags
        FROM Holding.dbo.InTouchNode hitn, Runtime.dbo.InTouchNode ritn
        WHERE ritn.NodeKey = hitn.NodeKey
END

-- Add the node in the PublicNameSpace
INSERT Runtime.dbo.PublicNameSpace (Type, ParentKey, [Name], ConfigStor)
   (SELECT 2000000, 7, RTRIM(MachineName), NULL
      FROM Holding.dbo.InTouchNode IT
         WHERE IT.Edited  = 'I')

UPDATE Holding.dbo.InTouchNode SET Edited = ''
   WHERE Edited     = 'I'

/******************************************************************************/
-- IOServer and Topic Tables
-- We define the IOServers and Topics by the content of Holding.ddecfg
-- If a DdeCfg.ApplicatioName does not exists in IOServerType, it needs first to
-- be added there.

DECLARE @rowcount      int      -- number of rows in the cursor
DECLARE @nodekey       int       -- current InTouch Node
DECLARE @ddecfgrow     int       -- current cursor row
DECLARE @appname       nchar(50)  -- ddecfg application name
DECLARE @topicname     nchar(50)  -- ddecfg topic name
DECLARE @protocoltype  int       -- Protocol Type 1=DDE, 2=SuiteLink
DECLARE @computername  nchar(50)  -- deducted computername
DECLARE @ioserverkey   int       -- ioserverkey reference in topic

DECLARE @ViewProtocolType int    -- derived from Holding.DdeCfg's System's ProtocolType: DDE for InT 6, SuiteLink for InT 7

DECLARE @iodriverkey  int        -- IODriver associated to IOServer

SELECT @nodekey = (SELECT NodeKey FROM Holding.dbo.InTouchNode) 



-- Now for the Inserted DdeCfg items
DECLARE thetopics SCROLL CURSOR
      FOR SELECT ApplicationName, TopicName, ProtocolType, IODriverKey 
         FROM Holding.dbo.DdeCfg
            WHERE NodeKey = @nodekey
            AND   Edited  in ('I', 'M')
            AND   ToInSQL = 1
            AND   DdeSourceKey > 0

SELECT  @ddecfgrow = 1

OPEN thetopics
SET @rowcount = @@cursor_rows

WHILE @ddecfgrow <= @rowcount 
BEGIN
   FETCH NEXT FROM thetopics INTO @appname, @topicname, @protocoltype, @iodriverkey

   IF (@iodriverkey is NULL or @iodriverkey < 2 
              or not exists (select IODriverKey from Runtime.dbo.IODriver where IODriverKey = @iodriverkey))
   BEGIN  -- Protection against no IODriverKey or wrong IODriverKey in DdeCfg
      SELECT @iodriverkey = (SELECT min(IODriverKey) from Runtime.dbo.IODriver where IODriverKey > 1)
   END
   -- need to breakup computer name / application name from @appname
   IF ASCII(@appname) = 92 -- we have a computername
   BEGIN
      SELECT @appname = SUBSTRING (@appname, 3, 50) -- get rid of the "\\"
      SELECT @computername = SUBSTRING (@appname, 1, PATINDEX ('%\%', @appname) - 1)
      SELECT @appname = SUBSTRING (@appname, PATINDEX ('%\%', @appname) + 1, 50)
   END
   ELSE
   BEGIN   -- computer name is then the InTouchNode.MachineName
      SELECT @computername = 
         (SELECT MachineName FROM Holding.dbo.InTouchNode              WHERE NodeKey = @nodekey)
   END

   -- verify that we have an IOServerType for @appname
   IF not exists (SELECT UPPER(ApplicationName) FROM Runtime.dbo.IOServerType
                     WHERE UPPER(ApplicationName) = UPPER(RTRIM (@appname)))
   BEGIN
      INSERT Runtime.dbo.IOServerType (ApplicationName, Description, ExeName, Revision, Platform)
         VALUES (RTRIM(@appname), RTRIM(@appname), RTRIM(@appname), '-', '-')
   END
   ELSE -- update @appname to match exact entry in IOServerType (case sensitive server issue)
   BEGIN
      SET @appname = (SELECT RTRIM(ApplicationName) FROM Runtime.dbo.IOServerType
                        WHERE UPPER(ApplicationName) = UPPER(RTRIM (@appname)))
   END

   -- Now we can Insert the IOServer and Topic
   IF not exists (SELECT UPPER(ApplicationName), UPPER(ComputerName) FROM Runtime.dbo.IOServer
                     WHERE UPPER(ApplicationName) = UPPER(RTRIM(@appname))
                     AND   UPPER(ComputerName)    = UPPER(RTRIM(@computername)) )
   BEGIN                     
      INSERT Runtime.dbo.IOServer (StorageNodeKey, ApplicationName, ComputerName, 
                           AutoStart, ExeType, InitializationStatus, ProtocolType,
                           IODriverKey)
         VALUES (1, RTRIM(@appname), RTRIM(@computername), 
                      0, 0, 0, @protocoltype, @iodriverkey)

      SELECT @ioserverkey = (SELECT IOServerKey FROM Runtime.dbo.IOServer
                                WHERE UPPER(ApplicationName) = UPPER(RTRIM(@appname))
                                AND   UPPER(ComputerName)    = UPPER(RTRIM(@computername)))
   END
   ELSE
   BEGIN
      SELECT @ioserverkey = (SELECT IOServerKey FROM Runtime.dbo.IOServer
                                WHERE UPPER(ApplicationName) = UPPER(RTRIM(@appname))
                                AND   UPPER(ComputerName)    = UPPER(RTRIM(@computername)) )

      UPDATE Runtime.dbo.IOServer SET ProtocolType = @protocoltype
      WHERE IOServerKey = @ioserverkey 
   END

   IF not exists (SELECT IOServerKey, StorageNodeKey, Name FROM Runtime.dbo.Topic
                     WHERE IOServerKey = @ioserverkey
                     AND   StorageNodeKey = 1
                     AND   UPPER(Name) = UPPER(RTRIM(@topicname)) )
   BEGIN

      INSERT Runtime.dbo.Topic (IOServerKey, StorageNodeKey, Name)
         VALUES ( @ioserverkey, 1, RTRIM(@topicname) )
   END  

   SELECT @ddecfgrow = @ddecfgrow + 1

END

DEALLOCATE thetopics

-- Topic for the InTouch mem tags
SELECT @computername =  MachineName FROM Holding.dbo.InTouchNode
                           WHERE NodeKey = @nodekey

SELECT @iodriverkey = IODriverKey from DdeCfg where DdeSourceKey = -1
         and NodeKey = @nodekey

IF not exists (SELECT DdeSourceKey FROM Holding.dbo.DdeCfg Dde,
                                        Holding.dbo.InTouchNode IT
               WHERE Dde.NodeKey = IT.NodeKey
               AND   UPPER(ApplicationName) = UPPER( 
                         '\\' + RTRIM(IT.MachineName) + '\View|TagName!')
               AND   IT.NodeKey = @nodekey)
BEGIN
   IF not exists (SELECT TopicKey FROM Runtime.dbo.Topic, Runtime.dbo.IOServer 
                  WHERE Runtime.dbo.Topic.IOServerKey = Runtime.dbo.IOServer.IOServerKey                   AND   Runtime.dbo.Topic.StorageNodeKey = 1
                  AND   UPPER(Runtime.dbo.IOServer.ComputerName) = UPPER(@computername)
                  AND   UPPER(Runtime.dbo.IOServer.ApplicationName) = 'VIEW'
                  AND   UPPER(Runtime.dbo.Topic.Name) = UPPER('TagName')) 
   BEGIN
      -- first check that we have a VIEW IOServerType

      IF not exists (SELECT ApplicationName FROM Runtime.dbo.IOServerType
                        WHERE ApplicationName = 'VIEW')
      BEGIN
         INSERT Runtime.dbo.IOServerType (ApplicationName, Description, ExeName)
            VALUES ('VIEW', 'InTouch Runtime Viewer', 'view.exe')
      END

      -- need an IOServer
      IF not exists (SELECT IOServerKey FROM Runtime.dbo.IOServer
                        WHERE UPPER(ComputerName) = UPPER(@computername)
                        AND   UPPER(ApplicationName) = 'VIEW')
      BEGIN
  SELECT @ViewProtocolType = ( SELECT ProtocolType from Holding.dbo.DdeCfg
            WHERE ( DdeSourceKey = -2 )) -- System 
         INSERT Runtime.dbo.IOServer (StorageNodeKey, ApplicationName, ComputerName, 
                           AutoStart, ExeType, InitializationStatus, ProtocolType,
                           IODriverKey)
            VALUES (1, 'VIEW', RTRIM(@computername), 0, 0, 0, @ViewProtocolType, @iodriverkey)

         SELECT @ioserverkey = (SELECT IOServerKey FROM Runtime.dbo.IOServer
                                WHERE UPPER(ComputerName) = UPPER(@computername)
                                AND   UPPER(ApplicationName) = 'VIEW')
      END
      ELSE
      BEGIN
         SELECT @ioserverkey = (SELECT IOServerKey FROM Runtime.dbo.IOServer
                                WHERE UPPER(ComputerName) = UPPER(@computername)
                                AND   UPPER(ApplicationName) = 'VIEW')
      END

      INSERT Runtime.dbo.Topic (IOServerKey, StorageNodeKey, Name)
         VALUES (@ioserverkey, 1, 'TagName')
   END
END


-- Reset the TopicImportInfo table
DELETE Runtime.dbo.TopicImportInfo WHERE NodeKey = @nodekey

INSERT Runtime.dbo.TopicImportInfo (NodeKey, DdeSourceKey, SourceName,
                        ApplicationName, TopicName, RequestInitialData,
                        AlwaysAdvise, DefaultStorageRate,
                        DefaultStorageType, TimeDeadband, Import, ProtocolType,
                        ValueDeadband, DeadbandType, IODriverKey, RateDeadband)
   (SELECT @nodekey, DdeSourceKey, SourceName, ApplicationName,
           TopicName, RequestInitialData, AlwaysAdvise,
           StorageRate, StorageType, TimeDeadband, ToInSQL, ProtocolType,
           ValueDeadband, DeadbandType, IODriverKey, RateDeadband
       FROM Holding.dbo.DdeCfg
          WHERE NodeKey = @nodekey
          AND   Edited  in ('I', 'M') )

UPDATE Holding.dbo.DdeCfg SET Edited = ''
   WHERE ToInSQL = 1
   AND   Edited     in ('I', 'M')
   AND   NodeKey    = @nodekey

IF @@ERROR <> 0
BEGIN
   ROLLBACK TRAN
   RETURN -1
END
ELSE
BEGIN
   COMMIT TRAN
   RETURN 0
END
GO

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

CREATE PROCEDURE ww_Insert_almGrpInfo  
(  @NodeKey                           int,
   @dbHnd                               int,
-- almGrp -------------------------
   @ag_level int ) 
AS

INSERT almGrpInfo(
   NodeKey,
   dbHnd,
-- almGrp -------------------------
   ag_level )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- almGrp -------------------------
   @ag_level )

GO

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

CREATE PROCEDURE ww_Insert_discConstInfo  
(  @NodeKey                           int,
   @dbHnd                               int,
-- discConst -------------------------
   @dc_initValue   int )
  
AS

INSERT discConstInfo(
   NodeKey,
   dbHnd,
-- discConst -------------------------
   dc_initValue )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- discConst -------------------------
   @dc_initValue )

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

CREATE PROCEDURE ww_Insert_discDDEIOInfo 
(  @NodeKey                           int,
   @dbHnd                               int,
-- disc -------------
   @d_initValue int,
   @d_onMsg nchar(15),
   @d_offMsg nchar(15),
   @d_almPri int,
-- DDEIO ------------
   @ddio_source int,
   @ddio_itemName nvarchar(80),
   @ddio_inputConv int )

AS

INSERT discDDEIOInfo(
   NodeKey,
   dbHnd,
-- disc -------------
   d_initValue,
   d_onMsg,
   d_offMsg,
   d_almPri, 
-- DDEIO ------------
   ddio_source,
   ddio_itemName,
   ddio_inputConv )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- disc -------------
   @d_initValue,
   @d_onMsg,
   @d_offMsg,
   @d_almPri, 
-- DDEIO ------------
   @ddio_source,
   @ddio_itemName,
   @ddio_inputConv )

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

CREATE PROCEDURE ww_Insert_discVarInfo 
(  @NodeKey     int,
   @dbHnd       int,
-- disc -----------
   @d_initValue int,
   @d_onMsg nchar(15),
   @d_offMsg nchar(15),
   @d_almPri int )

AS

INSERT discVarInfo(
   NodeKey,
   dbHnd,
-- disc -------------
   d_initValue,
   d_onMsg,
   d_offMsg,
   d_almPri )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- disc --------------
   @d_initValue,
   @d_onMsg,
   @d_offMsg,
   @d_almPri )

GO


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

CREATE PROCEDURE ww_Insert_histInfo 
(  @NodeKey                           int,
   @dbHnd                               int,
-- HistInfo -------------------------
   @dbhst_dbHnd_1 int,
   @dbhst_dbHnd_2 int,
   @dbhst_dbHnd_3 int,
   @dbhst_dbHnd_4 int,
   @dbhst_dbHnd_5 int,
   @dbhst_dbHnd_6 int,
   @dbhst_dbHnd_7 int,
   @dbhst_dbHnd_8 int,
   @dbhst_minVal float,
   @dbhst_maxVal float,
   @dbhst_alternateTags int,
   @dbhst_displayMode int,
   @dbhst_chartStart int,
   @dbhst_chartLength int )

AS

INSERT histInfo(
   NodeKey,
   dbHnd,
-- HistInfo -------------------------
   dbhst_dbHnd_1,
   dbhst_dbHnd_2,
   dbhst_dbHnd_3,
   dbhst_dbHnd_4,
   dbhst_dbHnd_5,
   dbhst_dbHnd_6,
   dbhst_dbHnd_7,
   dbhst_dbHnd_8,
   dbhst_minVal,
   dbhst_maxVal,
   dbhst_alternateTags,
   dbhst_displayMode,
   dbhst_chartStart,
   dbhst_chartLength )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- HistInfo -------------------------
   @dbhst_dbHnd_1,
   @dbhst_dbHnd_2,
   @dbhst_dbHnd_3,
   @dbhst_dbHnd_4,
   @dbhst_dbHnd_5,
   @dbhst_dbHnd_6,
   @dbhst_dbHnd_7,
   @dbhst_dbHnd_8,
   @dbhst_minVal,
   @dbhst_maxVal,
   @dbhst_alternateTags,
   @dbhst_displayMode,
   @dbhst_chartStart,
   @dbhst_chartLength )

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

CREATE PROCEDURE ww_Insert_intgConstInfo  
(  @NodeKey                           int,
   @dbHnd                               int,
-- intgConst -------------------------
   @ic_initValue   int,
   @ic_EGU       nvarchar(32))
 
AS

INSERT intgConstInfo(
   NodeKey,
   dbHnd,
-- intgConst -------------------------
   ic_initValue,
   ic_EGU )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- intgConst -------------------------
   @ic_initValue,
   @ic_EGU )

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

CREATE PROCEDURE ww_Insert_intgDDEIOInfo 
(  @NodeKey                           int,
   @dbHnd                               int,
-- intg --------------------
   @i_hihiChecked  bit,
   @i_hiChecked  bit,
   @i_loChecked  bit,
   @i_loloChecked  bit,
   @i_minorDevChecked bit,
   @i_majorDevChecked bit,
   @i_rocChecked  bit,
   @i_almPriHiHi  int,
   @i_almPriHi  int,
   @i_almPriLo  int,
   @i_almPriLoLo  int,
   @i_almPriMinorDev int,
   @i_almPriMajorDev int,
   @i_almPriROC  int,
   @i_roc   int,
   @i_rocUnits  int,
   @i_EGU  nchar(32),
   @i_initValue  int,
   @i_minValue  int,
   @i_maxValue  int,
   @i_valueDeadband real,
   @i_hihi   int,
   @i_hi   int,
   @i_lo   int,
   @i_lolo   int,
   @i_devTarget  int,
-- DDEIO --------------------
   @diio_source int,
   @diio_itemName nchar(81),
   @diio_minRaw int,
   @diio_maxRaw int,
   @diio_inputConv int )

AS

INSERT intgDDEIOInfo(
   NodeKey,
   dbHnd,
-- intg --------------------
   i_hihiChecked,
   i_hiChecked,
   i_loChecked,
   i_loloChecked,
   i_minorDevChecked,
   i_majorDevChecked,
   i_rocChecked,
   i_almPriHiHi,
   i_almPriHi,
   i_almPriLo,
   i_almPriLoLo,
   i_almPriMinorDev,
   i_almPriMajorDev,
   i_almPriROC,
   i_roc,
   i_rocUnits,
   i_EGU,
   i_initValue,
   i_minValue,
   i_maxValue,
   i_valueDeadband,
   i_hihi,
   i_hi,
   i_lo,
   i_lolo,
   i_devTarget,
-- DDEIO ----------------
   diio_source,
   diio_itemName,
   diio_minRaw,
   diio_maxRaw,
   diio_inputConv )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- intg --------------------
   @i_hihiChecked,    
   @i_hiChecked,      
   @i_loChecked,      
   @i_loloChecked,    
   @i_minorDevChecked,
   @i_majorDevChecked,
   @i_rocChecked,     
   @i_almPriHiHi,     
   @i_almPriHi,       
   @i_almPriLo,       
   @i_almPriLoLo,     
   @i_almPriMinorDev, 
   @i_almPriMajorDev, 
   @i_almPriROC,      
   @i_roc,            
   @i_rocUnits,       
   @i_EGU,            
   @i_initValue,      
   @i_minValue,       
   @i_maxValue,       
   @i_valueDeadband,  
   @i_hihi,           
   @i_hi,             
   @i_lo,             
   @i_lolo,           
   @i_devTarget,
-- DDEIO -----------------
   @diio_source,
   @diio_itemName,
   @diio_minRaw,
   @diio_maxRaw,
   @diio_inputConv )

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

CREATE PROCEDURE ww_Insert_intgVarInfo 
(  @NodeKey                           int,
   @dbHnd                               int,
-- intg --------------------
   @i_hihiChecked  bit,
   @i_hiChecked  bit,
   @i_loChecked  bit,
   @i_loloChecked  bit,
   @i_minorDevChecked bit,
   @i_majorDevChecked bit,
   @i_rocChecked  bit,
   @i_almPriHiHi  int,
   @i_almPriHi  int,
   @i_almPriLo  int,
   @i_almPriLoLo  int,
   @i_almPriMinorDev int,
   @i_almPriMajorDev int,
   @i_almPriROC  int,
   @i_roc   int,
   @i_rocUnits  int,
   @i_EGU  nchar(32),
   @i_initValue  int,
   @i_minValue  int,
   @i_maxValue  int,
   @i_valueDeadband real,
   @i_hihi   int,
   @i_hi   int,
   @i_lo   int,
   @i_lolo   int,
   @i_devTarget  int )

AS

INSERT intgVarInfo(
   NodeKey,
   dbHnd,
-- intg --------------------
   i_hihiChecked,
   i_hiChecked,
   i_loChecked,
   i_loloChecked,
   i_minorDevChecked,
   i_majorDevChecked,
   i_rocChecked,
   i_almPriHiHi,
   i_almPriHi,
   i_almPriLo,
   i_almPriLoLo,
   i_almPriMinorDev,
   i_almPriMajorDev,
   i_almPriROC,
   i_roc,
   i_rocUnits,
   i_EGU,
   i_initValue,
   i_minValue,
   i_maxValue,
   i_valueDeadband,
   i_hihi,
   i_hi,
   i_lo,
   i_lolo,
   i_devTarget )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- intg --------------------
   @i_hihiChecked,    
   @i_hiChecked,      
   @i_loChecked,      
   @i_loloChecked,    
   @i_minorDevChecked,
   @i_majorDevChecked,
   @i_rocChecked,     
   @i_almPriHiHi,     
   @i_almPriHi,       
   @i_almPriLo,       
   @i_almPriLoLo,     
   @i_almPriMinorDev, 
   @i_almPriMajorDev, 
   @i_almPriROC,      
   @i_roc,            
   @i_rocUnits,       
   @i_EGU,            
   @i_initValue,      
   @i_minValue,       
   @i_maxValue,       
   @i_valueDeadband,  
   @i_hihi,           
   @i_hi,             
   @i_lo,             
   @i_lolo,           
   @i_devTarget )

GO

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


CREATE PROCEDURE ww_Insert_realConstInfo
(  @NodeKey                           int,
   @dbHnd                               int,
-- realConst -------------------------
   @rc_initValue   real,
   @rc_EGU       nvarchar(32))
 
AS

INSERT realConstInfo(
   NodeKey,
   dbHnd,
-- intgConst -------------------------
   rc_initValue,
   rc_EGU )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- realConst -------------------------
   @rc_initValue,
   @rc_EGU )

GO

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

CREATE PROCEDURE ww_Insert_realDDEIOInfo
( 
   @NodeKey                           int,
   @dbHnd                               int,
-- real --------------------
   @r_hihiChecked  bit,
   @r_hiChecked  bit,
   @r_loChecked  bit,
   @r_loloChecked  bit,
   @r_minorDevChecked bit,
   @r_majorDevChecked bit,
   @r_rocChecked  bit,
   @r_almPriHiHi  int,
   @r_almPriHi  int,
   @r_almPriLo  int,
   @r_almPriLoLo  int,
   @r_almPriMinorDev int,
   @r_almPriMajorDev int,
   @r_almPriROC  int,
   @r_roc   int,
   @r_rocUnits  int,
   @r_EGU  nchar(32),
   @r_initValue  real,
   @r_minValue  real,
   @r_maxValue  real,
   @r_valueDeadband real,
   @r_hihi  real,
   @r_hi  real,
   @r_lo  real,
   @r_lolo         real,
   @r_devTarget  real,
-- DDEIO ---------------------------
   @drio_source int,
   @drio_itemName nvarchar(81),
   @drio_minRaw real,
   @drio_maxRaw real,
   @drio_inputConv int )

AS

INSERT realDDEIOInfo(
   NodeKey,
   dbHnd,
-- real --------------------
   r_hihiChecked,
   r_hiChecked,
   r_loChecked,
   r_loloChecked,
   r_minorDevChecked,
   r_majorDevChecked,
   r_rocChecked,
   r_almPriHiHi,
   r_almPriHi,
   r_almPriLo,
   r_almPriLoLo,
   r_almPriMinorDev,
   r_almPriMajorDev,
   r_almPriROC,
   r_roc,
   r_rocUnits,
   r_EGU,
   r_initValue,
   r_minValue,
   r_maxValue,
   r_valueDeadband,
   r_hihi,
   r_hi,
   r_lo,
   r_lolo,
   r_devTarget,
-- DDEIO ---------------------------
   drio_source,
   drio_itemName,
   drio_minRaw,
   drio_maxRaw,
   drio_inputConv )


VALUES( 
   @NodeKey,          
   @dbHnd,           
-- real --------------------
   @r_hihiChecked,    
   @r_hiChecked,      
   @r_loChecked,      
   @r_loloChecked,    
   @r_minorDevChecked,
   @r_majorDevChecked,
   @r_rocChecked,     
   @r_almPriHiHi,     
   @r_almPriHi,       
   @r_almPriLo,       
   @r_almPriLoLo,     
   @r_almPriMinorDev, 
   @r_almPriMajorDev, 
   @r_almPriROC,      
   @r_roc,            
   @r_rocUnits,       
   @r_EGU,
   @r_initValue,      
   @r_minValue,       
   @r_maxValue,       
   @r_valueDeadband,  
   @r_hihi,           
   @r_hi,             
   @r_lo,             
   @r_lolo,           
   @r_devTarget,
-- DDEIO ---------------------------
   @drio_source,
   @drio_itemName,
   @drio_minRaw,
   @drio_maxRaw,
   @drio_inputConv )
GO
GRANT exec on ww_Insert_realDDEIOInfo to aaAdministrators
go
go
 
 if exists (select * from sysobjects where id = object_id('dbo.ww_Insert_realVarInfo'))
  DROP PROCEDURE dbo.ww_Insert_realVarInfo
GO

CREATE PROCEDURE ww_Insert_realVarInfo 
( 
   @NodeKey                           int,
   @dbHnd                               int,
-- real --------------------
   @r_hihiChecked  bit,
   @r_hiChecked  bit,
   @r_loChecked  bit,
   @r_loloChecked  bit,
   @r_minorDevChecked bit,
   @r_majorDevChecked bit,
   @r_rocChecked  bit,
   @r_almPriHiHi  int,
   @r_almPriHi  int,
   @r_almPriLo  int,
   @r_almPriLoLo  int,
   @r_almPriMinorDev int,
   @r_almPriMajorDev int,
   @r_almPriROC  int,
   @r_roc   int,
   @r_rocUnits  int,
   @r_EGU  nchar(32),
   @r_initValue  real,
   @r_minValue  real,
   @r_maxValue  real,
   @r_valueDeadband real,
   @r_hihi  real,
   @r_hi  real,
   @r_lo  real,
   @r_lolo  real,
   @r_devTarget  real )

AS

INSERT realVarInfo(
   NodeKey,
   dbHnd,
-- real --------------------
   r_hihiChecked,
   r_hiChecked,
   r_loChecked,
   r_loloChecked,
   r_minorDevChecked,
   r_majorDevChecked,
   r_rocChecked,
   r_almPriHiHi,
   r_almPriHi,
   r_almPriLo,
   r_almPriLoLo,
   r_almPriMinorDev,
   r_almPriMajorDev,
   r_almPriROC,
   r_roc,
   r_rocUnits,
   r_EGU,
   r_initValue,
   r_minValue,
   r_maxValue,
   r_valueDeadband,
   r_hihi,
   r_hi,
   r_lo,
   r_lolo,
   r_devTarget )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- real --------------------
   @r_hihiChecked,    
   @r_hiChecked,      
   @r_loChecked,      
   @r_loloChecked,    
   @r_minorDevChecked,
   @r_majorDevChecked,
   @r_rocChecked,     
   @r_almPriHiHi,     
   @r_almPriHi,       
   @r_almPriLo,       
   @r_almPriLoLo,     
   @r_almPriMinorDev, 
   @r_almPriMajorDev, 
   @r_almPriROC,      
   @r_roc,            
   @r_rocUnits,       
   @r_EGU,
   @r_initValue,      
   @r_minValue,       
   @r_maxValue,       
   @r_valueDeadband,  
   @r_hihi,           
   @r_hi,             
   @r_lo,             
   @r_lolo,           
   @r_devTarget )

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

CREATE PROCEDURE ww_Insert_strgDDEIOInfo
(  @NodeKey                           int,
   @dbHnd                               int,
-- strg -------------------------
   @dmio_nMaxString int,
   @dmio_initValue  nvarchar(131),
-- DDEIO --------------------
   @dmio_source int,
   @dmio_itemName nvarchar(80))

AS

INSERT strgDDEIOInfo(
   NodeKey,
   dbHnd,
-- strg -------------------------
   dmio_nMaxString,
   dmio_initValue,
-- DDEIO --------------------
   dmio_source,
   dmio_itemName )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- strg -------------------------
   @dmio_nMaxString,
   @dmio_initValue,
-- DDEIO --------------------
   @dmio_source,
   @dmio_itemName )

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

CREATE PROCEDURE ww_Insert_strgInfo 
(  @NodeKey                           int,
   @dbHnd                               int,
-- strgInfo -------------------------
   @sv_nMaxString int,
   @sv_initValue      nvarchar(131))
 
AS

INSERT strgInfo(
   NodeKey,
   dbHnd,
-- strg -------------------------
   sv_nMaxString,
   sv_initValue )

VALUES( 
   @NodeKey,          
   @dbHnd,           
-- strg -------------------------
   @sv_nMaxString,
   @sv_initValue )

GO

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

CREATE PROCEDURE ww_MakeUniqueTagname 

 @db_tagname nchar(32), @NodeKey int, @InSQLName nvarchar(256) output, @ToInSQL tinyint output

AS

DECLARE @DuplicateChar            nchar(12) 
DECLARE @PrefixOrSuffix              bit
DECLARE @AlwaysModifyName    bit

SELECT 
 @DuplicateChar    = DuplicateChar,
 @PrefixOrSuffix   = PrefixOrSuffix,
 @AlwaysModifyName = AlwaysModifyName
FROM InTouchNode 

-- Generate tagname uniqueness if necessary
-- < CR L00025398  - NiravT 
IF RTRIM(@DuplicateChar) = '' AND (( SELECT COUNT(*) FROM Runtime.dbo.Tag WHERE TagName = @db_tagname) = 1) AND NOT EXISTS(SELECT TagName FROM Runtime.dbo.InTouchSpecific WHERE TagName = RTRIM(@InSQLName) AND NodeKey = @NodeKey AND InInSQL = 1)
-- > CR L00025398
BEGIN
   -- InSQL80 - Allows no DuplicateChar but cancel import if TagName already exists
   SET @ToInSQL = 0
   RETURN
END
ELSE
--> CR L00011127
IF ((@AlwaysModifyName = 1) OR ( ((SELECT COUNT(*) FROM Runtime.dbo.Tag WHERE TagName = @db_tagname) = 1) AND 
                                 ((SELECT COUNT(*) FROM Holding.dbo.InTouchDB WHERE db_tagname = @db_tagname) = 0)))
--< CR L00011127
BEGIN
  IF ( @PrefixOrSuffix = 1 )
  BEGIN
    SELECT @InSQLName = rtrim(@DuplicateChar) + rtrim(@db_tagname)
  END
  ELSE
  BEGIN
    SELECT @InSQLName = rtrim( @db_tagname ) + rtrim(@DuplicateChar) 
  END
  -- Final check, that TagName could already exist...
  IF EXISTS (SELECT TagName FROM Runtime.dbo.Tag WHERE TagName = RTRIM(@InSQLName))
  BEGIN
    --> CR L00011182
    IF NOT EXISTS(SELECT TagName FROM Runtime.dbo.InTouchSpecific WHERE TagName = RTRIM(@InSQLName) AND NodeKey = @NodeKey)
      SET @ToInSQL = 0
    --< CR L00011182

     RETURN
  END
END

-- InSQL80: disable Tags with illegal TagName
-- |, [ and ] are not allowed
IF (SELECT CHARINDEX('|', @InSQLName)) > 0
  OR (SELECT CHARINDEX('[', @InSQLName)) > 0
  OR (SELECT CHARINDEX(']', @InSQLName)) > 0
BEGIN
   SET @ToInSQL = 0
   RETURN
END

go

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

CREATE procedure ww_PopulatePublicNS 

AS

DECLARE @ParentKey int
SELECT @ParentKey = NULL

-- top level
DECLARE @topCurrentRow     int
DECLARE @topMaxRows        int
DECLARE @topGroupID        int
DECLARE @topdbHnd          int
DECLARE @topNodeKey        int 
DECLARE @topTagName        nvarchar(256) 
DECLARE @topParentdbHnd    int
DECLARE @topParentKey      int
DECLARE @NameKey           int

-- middle level
DECLARE @middleCurrentRow  int
DECLARE @middleMaxRows     int
DECLARE @middleGroupID     int
DECLARE @middledbHnd       int
DECLARE @middleNodeKey     int 
DECLARE @middleTagName     nvarchar(256) 
DECLARE @middleParentdbHnd int

-- bottom level
DECLARE @bottomCurrentRow  int
DECLARE @bottomMaxRows     int
DECLARE @bottomGroupID     int
DECLARE @bottomdbHnd       int
DECLARE @bottomNodeKey     int 
DECLARE @bottomTagName     nvarchar(256) 
DECLARE @bottomParentdbHnd int
DECLARE @bottomTypeInfo    int
DECLARE @InSQLTypeInfo     int
DECLARE @bottomTagKey      int

/* get current Node under group InTouchNodes */
DECLARE @MachineName nvarchar(255) 
SELECT  @MachineName = ( SELECT MachineName from InTouchNode )
SELECT  @MachineName = RTRIM( @MachineName ) 

/* -- SELECT @ParentKey = ( SELECT NameKey FROM Runtime.dbo.PublicNameSpace WHERE Name = @MachineName ) */
/* -- SELECT @NameKey = A.NameKey FROM Runtime.dbo.PublicNameSpace A, Runtime.dbo.PublicNameSpace B */
SELECT @ParentKey = A.NameKey FROM Runtime.dbo.PublicNameSpace A, Runtime.dbo.PublicNameSpace B
WHERE  A.Name = @MachineName
AND    A.ParentKey = B.NameKey
AND    B.Name = 'InTouch Nodes'

IF ( @ParentKey IS NULL )
BEGIN
  RAISERROR('Public Name Space entry: Missing InTouch Node Entry.',18,2) WITH SETERROR
  RETURN -1
END

/* get the current Node's application */
DECLARE @ApplicationPath nvarchar(255) 
SELECT  @ApplicationPath = ( SELECT ApplicationPath from InTouchNode )
SELECT  @ApplicationPath = RTRIM( @ApplicationPath )

SELECT @topParentKey = ( SELECT NameKey FROM Runtime.dbo.PublicNameSpace 
                           WHERE ( Name      = @ApplicationPath )
                           AND   ( ParentKey = @ParentKey       ))

/* insert the UDT folder under its Node/App combo */
EXECUTE @topParentKey = Runtime.dbo.ww_PublicNSAddGroup 'SuperTags', @topParentKey, 1000000

/* if 'User Defined Tags' does not exist in the PNS abort with error return value and report error message */
IF (@topParentKey = NULL )
BEGIN
  RAISERROR('Missing Public Name Space entry: SuperTags.',18,2) WITH SETERROR
  RETURN -1
END

DECLARE TopLevelParents SCROLL CURSOR 
  -- Get all Top Level Parents (where tag is UDT and not UDTChild)
  FOR SELECT dbHnd, NodeKey, InSQLName, ParentdbHnd FROM InTouchDB
    WHERE ( UDT & ~UDTChild = 1)
    
OPEN TopLevelParents
SELECT @topCurrentRow  = 1
SELECT @topMaxRows = @@cursor_rows

WHILE ( @topCurrentRow <= @topMaxRows )
BEGIN
  /*********************************************/
  -- for each Parent
  FETCH NEXT FROM TopLevelParents INTO @topdbHnd, @topNodeKey, @topTagName, @topParentdbHnd
  BEGIN
    -- ww_PopulatePublicNS_AlmGrps would have already deleted UDTs so don't need to check here
    -- exec PNSAddGroup which returns its group ID
    EXECUTE @topGroupID = Runtime.dbo.ww_PublicNSAddGroup @topTagName, @topParentKey, 1000000
    -- Get all this Parent's middle level child-parents (where tag is UDTChild and has children )
    DECLARE Child_Parents SCROLL CURSOR 
      FOR SELECT dbHnd, NodeKey, InSQLName, ParentdbHnd FROM InTouchDB
        WHERE (( UDTChild & HasUDTChild = 1  ) 
        AND    ( ParentdbHnd   = @topdbHnd   )
        AND    ( ParentNodeKey = @topNodeKey ))

    OPEN Child_Parents
    SELECT @middleCurrentRow  = 1
    SELECT @middleMaxRows = @@cursor_rows

    WHILE ( @middleCurrentRow <= @middleMaxRows )
    BEGIN
      /*********************************************/
      -- for each Child_Parent
      FETCH NEXT FROM Child_Parents INTO @middledbHnd, @middleNodeKey, @middleTagName, @middleParentdbHnd
      BEGIN
        -- exec PNSAddGroup which returns the its group ID
        EXECUTE @middleGroupID = Runtime.dbo.ww_PublicNSAddGroup @middleTagName, @topGroupID, 1000000

        -- Get all this Child_Parent's children (where tag is UDTChild and has no children )
        DECLARE Children SCROLL CURSOR 
          FOR SELECT typeinfo, InSQLName, ParentdbHnd FROM InTouchDB
            WHERE (( UDTChild & ~HasUDTChild = 1    ) 
            AND    ( ParentdbHnd   = @middledbHnd   )
            AND    ( ParentNodeKey = @middleNodeKey ))

        OPEN Children
        SELECT @bottomCurrentRow  = 1
        SELECT @bottomMaxRows = @@cursor_rows

        WHILE ( @bottomCurrentRow <= @bottomMaxRows )
        BEGIN
          /*********************************************/
          -- for each Child
          FETCH NEXT FROM Children INTO @bottomTypeInfo, @bottomTagName, @bottomParentdbHnd
          BEGIN
            SELECT @bottomTagKey = ( SELECT wwTagKey FROM Runtime.dbo.Tag WHERE TagName = @bottomTagName )
            EXECUTE Runtime.dbo.ww_PublicNSAddLeaf @bottomTagKey, @middleGroupID
          END
          SELECT @bottomCurrentRow = @bottomCurrentRow + 1
        END

        DEALLOCATE Children 
      END
      SELECT @middleCurrentRow = @middleCurrentRow + 1
    END
    DEALLOCATE Child_Parents

  END
  SELECT @topCurrentRow = @topCurrentRow + 1
END

DEALLOCATE TopLevelParents
GO

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

CREATE procedure ww_PopulatePublicNS_AlmGrps 

AS 

SET NOCOUNT ON 

-- adding the Node to the PublicNS 
DECLARE @AG            nvarchar(256) 
DECLARE @GroupID       int
DECLARE @ParentGroupID int

SELECT @GroupID = ( SELECT NameKey FROM Runtime.dbo.PublicNameSpace WHERE Name = 'InTouch Nodes' )
SELECT @ParentGroupID = @GroupID

-- if 'InTouch Nodes' does not exist in the PNS abort with error return value and report error message 
IF (@ParentGroupID = NULL )
BEGIN
  RAISERROR('Missing Public Name Space entry: InTouch Nodes.',18,2) WITH SETERROR
  RETURN -1
END

-- delete corresponding PNS entry for this node before actually deleting the node itself 
DECLARE @MachineName nvarchar(255) 
SELECT  @MachineName = RTRIM(( SELECT MachineName from InTouchNode ))
SELECT  @AG = RTRIM( @MachineName ) 

-- delete current node's related Public Name Space entries 
DECLARE @NameKey int 
SELECT @NameKey = NULL

SELECT @NameKey = A.NameKey FROM Runtime.dbo.PublicNameSpace A, Runtime.dbo.PublicNameSpace B
WHERE  A.Name = @MachineName
AND    A.ParentKey = B.NameKey
AND    B.Name = 'InTouch Nodes'

-- only delete if parent is InTouch Nodes as there might be other entries
-- with this machine name which we do not wish to delete 
IF ( @NameKey IS NOT NULL )
BEGIN
  EXECUTE Runtime.dbo.ww_PublicNSDeleteGroup @NameKey
END

EXECUTE @GroupID = Runtime.dbo.ww_PublicNSAddGroup @AG, @ParentGroupID, 1000000
SELECT @ParentGroupID = @GroupID

-- adding the Node's application to the PublicNS 
DECLARE @ApplicationPath nvarchar(255) 
SELECT  @ApplicationPath = ( SELECT ApplicationPath from InTouchNode )
SELECT  @AG = RTRIM( @ApplicationPath )

EXECUTE @GroupID = Runtime.dbo.ww_PublicNSAddGroup @AG, @ParentGroupID, 1000000

/* Alarms Groups disabled - above code needed to create folder for SuperTags

SELECT @ParentGroupID = @GroupID

-- adding the Alarm Group folder to the PublicNS 
SELECT  @AG = 'Alarm Groups'

EXECUTE @GroupID = Runtime.dbo.ww_PublicNSAddGroup @AG, @ParentGroupID, 1000000
SELECT @ParentGroupID = @GroupID

-- Add the top alarm group 
SELECT @AG = '$System'
-- to correct for InTouch bug
UPDATE InTouchDB SET
  db_group = 0
WHERE db_tagname = '$System'

DECLARE @AGLevel       int
DECLARE @LeafTagKey    int
DECLARE @typeinfo      int
CREATE TABLE  #tblAG( CurrentAG nvarchar(32), CurrentAGLevel int, ParentGroupID int )
SELECT  @AGLevel = 1

DECLARE @SystemGroupID int

-- have defined the level at which we start ie where the AG is, to be 1 - so insert 1 into table 
INSERT INTO #tblAG VALUES ( @AG, @AGLevel, @ParentGroupID ) 

WHILE ( @AGLevel > 0 )
BEGIN
  -- if there is a AG at the current level in tblTemp then output it & delete it 
  IF EXISTS ( SELECT * FROM #tblAG WHERE CurrentAGLevel = @AGLevel )   
    BEGIN
      -- get it 
      SELECT @AG = CurrentAG, @ParentGroupID = ParentGroupID  
        FROM #tblAG
        WHERE CurrentAGLevel = @AGLevel

      -- if an alarm group make a folder in the PNS 
      SELECT @typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE db_tagname = @AG ) 
      IF ( @typeinfo = 12 ) 
      BEGIN
        EXECUTE @GroupID = Runtime.dbo.ww_PublicNSAddGroup @AG, @ParentGroupID, 1000000
        IF ( @AG = '$System' )
        BEGIN
          SELECT @SystemGroupID = @GroupID
        END
      END
      ELSE
      -- if not an alarm group must be a leaf-level tag therefore add to PublicGroupTag 
      BEGIN 
        IF ( @SystemGroupID <> @ParentGroupID )
        BEGIN
          SELECT @LeafTagKey = ( SELECT wwTagKey FROM Runtime.dbo.Tag WHERE TagName = @AG )
          EXECUTE Runtime.dbo.ww_PublicNSAddLeaf @LeafTagKey, @ParentGroupID
        END
      END
      -- delete it 
      DELETE FROM #tblAG  
        WHERE (( CurrentAGLevel = @AGLevel )
          AND  ( CurrentAG      = @AG      ))
      -- if true then descend a level to check if this AG has children, if so put child into tblAG 
      IF (@@rowcount > 0) 
        BEGIN
          SELECT @AGLevel = @AGLevel + 1
          -- below gets the children of the current AG 
          -- inserts: Name, @AGLevel ie Names will vary as they are found but @AGLevel will not 
          INSERT #tblAG
            SELECT db_tagname, @AGLevel, @GroupID
              FROM InTouchDB
              -- who in InTouchDB has a db_group equal to the dbHnd of @AG below ? 
              WHERE db_group IN
                ( SELECT dbHnd
                    FROM InTouchDB
                    WHERE db_tagname = @AG ) 
        END
    END
  ELSE
    -- if there is no AG at the current level to output, back up a level and check for more AGs 
    BEGIN
      -- PRINT 'going  up one level in the table to look for unprocessed AGs' 
      SELECT @AGLevel = @AGLevel - 1
    END 
END

DROP TABLE #tblAG

*/

GO

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

CREATE procedure ww_PrepareTagTransfer 
as

/******************************************************************************
-- This sp is used to simplify the transfer from Holding to Runtime by 
-- writng into the holding table some key information needed for the
-- Runtime configuration.  This to avoid expensive sub-select 
-- statements when the transfer is performed
*******************************************************************************/

begin tran
/* Get the TopicKey and IOServerKey */
declare @machname nchar(50)
set @machname = (select MachineName from InTouchNode) 

/* View topics first */
update DdeCfg set R_TopicKey = t.TopicKey, R_IOServerKey = t.IOServerKey 
    from Runtime.dbo.Topic t, Runtime.dbo.IOServer ios 
      where ios.IOServerKey = t.IOServerKey
      and  UPPER(t.Name) = UPPER('TagName')
      and UPPER(ios.ComputerName) = UPPER(@machname)
      and UPPER(ios.ApplicationName) = 'VIEW'
      and DdeSourceKey < 0

/* IO Topics */
update DdeCfg set R_TopicKey = t.TopicKey, R_IOServerKey = t.IOServerKey 
    from Runtime.dbo.Topic t, Runtime.dbo.IOServer ios, DdeCfg d
      where ios.IOServerKey = t.IOServerKey
      and UPPER(t.Name) = UPPER(d.TopicName)
      and ( (UPPER(d.ApplicationName) = UPPER(ios.ApplicationName)
            and UPPER(ios.ComputerName) = UPPER(@machname))
           or UPPER(d.ApplicationName) = UPPER('\\' + RTRIM(ios.ComputerName) +
                         '\'  + RTRIM(ios.ApplicationName)) )      
      and DdeSourceKey > 0

/* Engineering Unit Key for Analog */
update intgDDEIOInfo set R_EUKey = eu.EUKey
   from Runtime.dbo.EngineeringUnit eu, intgDDEIOInfo ana
      where RTRIM(eu.Unit) = RTRIM(ana.i_EGU)

update intgVarInfo set R_EUKey = eu.EUKey
   from Runtime.dbo.EngineeringUnit eu, intgVarInfo ana
      where RTRIM(eu.Unit) = RTRIM(ana.i_EGU)

update realDDEIOInfo set R_EUKey = eu.EUKey
   from Runtime.dbo.EngineeringUnit eu, realDDEIOInfo ana
      where RTRIM(eu.Unit) = RTRIM(ana.r_EGU)

update realVarInfo set R_EUKey = eu.EUKey
   from Runtime.dbo.EngineeringUnit eu, realVarInfo ana
      where RTRIM(eu.Unit) = RTRIM(ana.r_EGU)

/* Message Key for Discrete */
update discDDEIOInfo set R_MessageKey = m.MessageKey
   from Runtime.dbo.Message m, discDDEIOInfo disc
      where RTRIM(m.Message0) + RTRIM(m.Message1)
            = RTRIM(disc.d_offMsg) + RTRIM(disc.d_onMsg)

update discVarInfo set R_MessageKey = m.MessageKey
   from Runtime.dbo.Message m, discVarInfo disc
      where RTRIM(m.Message0) + RTRIM(m.Message1)
            = RTRIM(disc.d_offMsg) + RTRIM(disc.d_onMsg)

/*********************************************************/
-- Need to fix MaxEU for $ system tags  (0 by default)
update Holding.dbo.intgVarInfo set i_maxValue = 1000
   from Holding.dbo.intgVarInfo intg, InTouchDB itdb
      where intg.dbHnd = itdb.dbHnd
      and itdb.db_tagname like '$%'
      and intg.i_maxValue = 0 

update Holding.dbo.realVarInfo set r_maxValue = 1000
   from Holding.dbo.realVarInfo rl, InTouchDB itdb
      where rl.dbHnd = itdb.dbHnd
      and itdb.db_tagname like '$%'
      and rl.r_maxValue = 0  

/*********************************************************/
-- Scaling : Update the Scaling code received from InTouch
-- 201 Linear changes to 1
-- 202 Sqare Root changes to 2
update Holding.dbo.intgDDEIOInfo
   set diio_inputConv = 1 where diio_inputConv = 201
update Holding.dbo.intgDDEIOInfo
   set diio_inputConv = 2 where diio_inputConv = 202
update Holding.dbo.realDDEIOInfo
   set drio_inputConv = 1 where drio_inputConv = 201
update Holding.dbo.realDDEIOInfo
   set drio_inputConv = 2 where drio_inputConv = 202

/*********************************************************/
-- Convert the Log Deadbands to a % of EU value for InSQL
update Holding.dbo.InTouchDB
   set InSQLDeadband = (db_intgLogDeadband * 100) / 
                       (convert(real, i_maxValue) - convert(real, i_minValue))
      from InTouchDB itdb, intgDDEIOInfo idde
         where itdb.dbHnd = idde.dbHnd
         and db_intgLogDeadband <> 0

update Holding.dbo.InTouchDB
   set InSQLDeadband = (db_intgLogDeadband * 100) / 
                       (convert(real, i_maxValue) - convert(real, i_minValue))
      from InTouchDB itdb, intgVarInfo imem
         where itdb.dbHnd = imem.dbHnd
         and db_intgLogDeadband <> 0

-- << CRL00031699 -- NiravT
update Holding.dbo.InTouchDB
   set InSQLDeadband = (db_realLogDeadband * 100) / (convert(float,r_maxValue) - convert (float, r_minValue))
      from InTouchDB itdb, realDDEIOInfo rdde
         where itdb.dbHnd = rdde.dbHnd
         and db_realLogDeadband <> 0

update Holding.dbo.InTouchDB
   set InSQLDeadband = (db_realLogDeadband * 100) / (convert(float,r_maxValue) - convert (float, r_minValue))
      from InTouchDB itdb, realVarInfo rmem
         where itdb.dbHnd = rmem.dbHnd
         and db_realLogDeadband <> 0
-- >> CRL00031699

-- Validate that we do not have anything out of the 0 - 100 range
if exists (select InSQLDeadband from InTouchDB where InSQLDeadband < 0)
begin
   update InTouchDB set InSQLDeadband = 0 where InSQLDeadband < 0
end

if exists (select InSQLDeadband from InTouchDB where InSQLDeadband > 100)
begin
   update InTouchDB set InSQLDeadband = 100 where InSQLDeadband > 100
end


if @@ERROR <> 0
begin
   rollback tran
   return -1
end
else
begin
   commit tran
   return 0
end
go

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

CREATE PROCEDURE ww_SubTypeTableDelete  
  @Existing_typeinfo int,
  @dbHnd    int

AS

IF ( @Existing_typeinfo = 1 )
BEGIN
  DELETE intgDDEIOInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 2 )
BEGIN
  DELETE realDDEIOInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 3 )
BEGIN
  DELETE intgVarInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 4 )
BEGIN
  DELETE realVarInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 5 )
BEGIN
  DELETE discDDEIOInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 6 )
BEGIN
  DELETE discVarInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 7 )
BEGIN
  DELETE strgDDEIOInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 8 )
BEGIN
  DELETE strgInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 9 )
BEGIN
  DELETE intgConstInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 10 )
BEGIN
  DELETE realConstInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 11 )
BEGIN
  DELETE discConstInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 12 )
BEGIN
  DELETE almGrpInfo WHERE ( dbHnd = @dbHnd )
END

IF ( @Existing_typeinfo = 13 )
BEGIN
  DELETE histInfo WHERE ( dbHnd = @dbHnd )
END

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

CREATE PROCEDURE ww_Update_InTouchDB(
   @NodeKey                 int,
   @dbHnd                   int,
   @Existing_dbHnd          int,
   @db_tagname              nchar(32),
   @db_description          nchar(512) ,
   @db_type                 int,
   @db_io_type              int,
   @db_group                int,
   @db_valid                bit,
   @db_modified             bit,
   @db_useCountRead         bit,
   @db_useCountWrite        bit,
   @db_useCountAlmInfo      bit,
   @db_version              int,
   @typeinfo                int,
   @db_logged               bit,
   @db_useTagAsItem         bit,
   @db_eventlogged          bit,
   @db_alarmParmsSaved      bit,
   @db_currentValueSaved    bit,
   @db_intgLogDeadband      int,
   @db_realLogDeadband      real,
   @db_eventLoggingPriority int,
   @db_intgAlmDeadband      int,
   @db_realAlmDeadband      real,
   @db_almDevDeadband       real,
   @db_minorDev             real,
   @db_majorDev             real,
   @Edited                  char(1),
   @ToInSQL              bit,
   @InSQLName            nchar(256),
   @CurrentEditor           int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit )

AS

UPDATE InTouchDB SET
   dbHnd                   = @dbHnd,
-- db_tagname              = @db_tagname, 
   db_description          = @db_description,
   db_type                 = @db_type,
   db_io_type              = @db_io_type,
   db_group                = @db_group,
   db_valid                = @db_valid,
   db_modified             = @db_modified,
   db_useCountRead         = @db_useCountRead,
   db_useCountWrite        = @db_useCountWrite,
   db_useCountAlmInfo      = @db_useCountAlmInfo,
   db_version              = @db_version,
   typeinfo                = @typeinfo,
   db_logged               = @db_logged,
   db_useTagAsItem         = @db_useTagAsItem,
   db_eventlogged          = @db_eventlogged,
   db_alarmParmsSaved      = @db_alarmParmsSaved,
   db_currentValueSaved    = @db_currentValueSaved,
   db_intgLogDeadband      = @db_intgLogDeadband,
   db_realLogDeadband      = @db_realLogDeadband,
   db_eventLoggingPriority = @db_eventLoggingPriority,
   db_intgAlmDeadband      = @db_intgAlmDeadband,
   db_realAlmDeadband      = @db_realAlmDeadband,
   db_almDevDeadband       = @db_almDevDeadband,
   db_minorDev             = @db_minorDev,
   db_majorDev             = @db_majorDev,
   Edited                  = @Edited,
   ToInSQL              = @ToInSQL,
   InSQLName            = @InSQLName,
   CurrentEditor           = @CurrentEditor,
   UDT                       = @UDT,           
   UDTChild          = @UDTChild,
   HasUDTChild    =   @HasUDTChild       

WHERE  dbHnd = @Existing_dbHnd and NodeKey = @NodeKey

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

CREATE PROCEDURE ww_SetIOTags_ToInSQL
  @NodeKey          int,
  @dXio_source     int,
  @ToInSQL          bit = 1 OUTPUT
 
AS

-- this SP is called from the 4 ww_Process_[dde tags] SPs

-- Step1: Don't Import if tag's source (topic) is not being imported
DECLARE @Source_ToInSQL int
SELECT @Source_ToInSQL = (SELECT ToInSQL FROM DdeCfg WHERE ( DdeSourceKey = @dXio_source ))
IF @Source_ToInSQL = 0
BEGIN
  SELECT @ToInSQL = 0
END
GO

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

CREATE PROCEDURE ww_Process_almGrpInfo 
( 
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int, 
   @db_tagname               nvarchar(32),
   @db_description           nvarchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nvarchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- almGrp -------------------------
    @ag_level  int )

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,
    @UDT,
    @UDTChild,
    @HasUDTChild         

   IF ( @Existing_typeinfo <> @typeinfo )
     BEGIN
      -- insert the new subtable entry ie new typeinfo
      EXECUTE ww_Insert_almGrpInfo
       @NodeKey,                      
       @dbHnd,
    -- almGrp -------------------------
       @ag_level
       -- remove the original subtable entry ie old typeinfo
       EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
     END
     ELSE
     BEGIN
       -- have to synch dbHnd with parent InTouchDB and update subtable values
       -- and then remove -dbHnd entry
      EXECUTE ww_Insert_almGrpInfo
       @NodeKey,                      
       @dbHnd,
    -- almGrp -------------------------
       @ag_level
      END
      EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
          
END
ElSE
-- If the tag does not yet exist in InSQL
BEGIN
  
  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,
    @UDT,
    @UDTChild,
    @HasUDTChild         

   EXECUTE ww_Insert_almGrpInfo
      @NodeKey,                      
      @dbHnd,
   -- almGrp -------------------------
      @ag_level
END

GO

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

CREATE PROCEDURE ww_Process_discConstInfo  
( -- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- discConst -------------------------
   @dc_initValue     int )

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,   
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,
    @UDT,
    @UDTChild,
    @HasUDTChild         

     IF ( @Existing_typeinfo <> @typeinfo )
     BEGIN
       -- insert the new subtable entry ie new typeinfo
        EXECUTE ww_Insert_discConstInfo
         @NodeKey,
         @dbHnd,
         @dc_initValue     
        -- remove the original subtable entry ie old typeinfo
       EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
     END
     ELSE
     BEGIN
        -- have to synch dbHnd with parent InTouchDB and update subtable values
        -- and then remove -dbHnd entry
        EXECUTE ww_Insert_discConstInfo
          @NodeKey,
          @dbHnd,
          @dc_initValue     
      END
      EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd

END
ElSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,
    @UDT,
    @UDTChild,
    @HasUDTChild         

  EXECUTE ww_Insert_discConstInfo
    @NodeKey,
    @dbHnd,
    @dc_initValue     

END

GO

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

CREATE PROCEDURE ww_Process_discDDEIOInfo  
(
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- discDDEIO -------------------------
   @d_initValue      int,
   @d_onMsg                 nchar(15),
   @d_offMsg                nchar(15),
   @d_almPri      int,
   @ddio_source             int,
   @ddio_itemName           nvarchar(80),
   @ddio_inputConv          int )

AS

IF (@ToInSQL = 1)
BEGIN
  EXECUTE ww_SetIOTags_ToInSQL @NodeKey, @ddio_source, @ToInSQL OUTPUT
END

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END
  
  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd, 
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild          

   IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
    EXECUTE ww_Insert_discDDEIOInfo
     @NodeKey,                      
     @dbHnd,
     @d_initValue,
     @d_onMsg,
     @d_offMsg,
     @d_almPri,
  -- discDDEIO -------------------------
     @ddio_source,
     @ddio_itemName,
     @ddio_inputConv

      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
    EXECUTE ww_Insert_discDDEIOInfo
     @NodeKey,                      
     @dbHnd,
     @d_initValue,
     @d_onMsg,
     @d_offMsg,
     @d_almPri,
  -- discDDEIO -------------------------
     @ddio_source,
     @ddio_itemName,
     @ddio_inputConv
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ElSE
-- If the tag does not yet exist in InSQL
BEGIN
  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild    

EXECUTE ww_Insert_discDDEIOInfo
   @NodeKey,                      
   @dbHnd,
   @d_initValue,
   @d_onMsg,
   @d_offMsg,
   @d_almPri,
-- discDDEIO -------------------------
   @ddio_source,
   @ddio_itemName,
   @ddio_inputConv

END

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

CREATE PROCEDURE ww_Process_discVarInfo 
( 
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- discVar -------------------------
   @d_initValue       int,
   @d_onMsg                  nchar(15),
   @d_offMsg                nchar(15),
   @d_almPri       int )

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,  
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,
    @UDT,
    @UDTChild,
    @HasUDTChild          

    IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
     EXECUTE ww_Insert_discVarInfo
      @NodeKey,                      
      @dbHnd,
      @d_initValue,
      @d_onMsg,
      @d_offMsg,
      @d_almPri
      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
     EXECUTE ww_Insert_discVarInfo
      @NodeKey,                      
      @dbHnd,
      @d_initValue,
      @d_onMsg,
      @d_offMsg,
      @d_almPri
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ELSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild          

  EXECUTE ww_Insert_discVarInfo
   @NodeKey,                      
   @dbHnd,
   @d_initValue,
   @d_onMsg,
   @d_offMsg,
   @d_almPri
END

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

CREATE PROCEDURE ww_Process_histInfo  
( 
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- HistInfo -------------------------
   @dbhst_dbHnd_1           int,
   @dbhst_dbHnd_2           int,
   @dbhst_dbHnd_3           int,
   @dbhst_dbHnd_4           int,
   @dbhst_dbHnd_5           int,
   @dbhst_dbHnd_6           int,
   @dbhst_dbHnd_7           int,
   @dbhst_dbHnd_8           int,
   @dbhst_minVal            real,
   @dbhst_maxVal            real,
   @dbhst_alternateTags     int,
   @dbhst_displayMode       int,
   @dbhst_chartStart        int,
   @dbhst_chartLength       int )

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,  
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,        
    @UDT,
    @UDTChild,
    @HasUDTChild         

    IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
     EXECUTE ww_Insert_histInfo
       @NodeKey,
       @dbHnd,
       @dbhst_dbHnd_1,
       @dbhst_dbHnd_2,
       @dbhst_dbHnd_3,
       @dbhst_dbHnd_4,
       @dbhst_dbHnd_5,
       @dbhst_dbHnd_6,
       @dbhst_dbHnd_7,
       @dbhst_dbHnd_8,
       @dbhst_minVal,
       @dbhst_maxVal, 
       @dbhst_alternateTags,
       @dbhst_displayMode,
       @dbhst_chartStart,
       @dbhst_chartLength
      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
      EXECUTE ww_Insert_histInfo
       @NodeKey,
       @dbHnd,
       @dbhst_dbHnd_1, 
       @dbhst_dbHnd_2,
       @dbhst_dbHnd_3,
       @dbhst_dbHnd_4,
       @dbhst_dbHnd_5,
       @dbhst_dbHnd_6,
       @dbhst_dbHnd_7,
       @dbhst_dbHnd_8,
       @dbhst_minVal,
       @dbhst_maxVal, 
       @dbhst_alternateTags,
       @dbhst_displayMode,
       @dbhst_chartStart,
       @dbhst_chartLength
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd

END
ElSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild         

  EXECUTE ww_Insert_histInfo
    @NodeKey,
    @dbHnd,
    @dbhst_dbHnd_1,
    @dbhst_dbHnd_2,
    @dbhst_dbHnd_3,
    @dbhst_dbHnd_4,
    @dbhst_dbHnd_5,
    @dbhst_dbHnd_6,
    @dbhst_dbHnd_7,
    @dbhst_dbHnd_8,
    @dbhst_minVal,
    @dbhst_maxVal, 
    @dbhst_alternateTags,
    @dbhst_displayMode,
    @dbhst_chartStart,
    @dbhst_chartLength

END

GO

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

CREATE PROCEDURE ww_Process_intgConstInfo
( 
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- intgConstInfo -------------------------
   @ic_initValue             int,
   @ic_EGU                   nvarchar(32))

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,  
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild      

    IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
     EXECUTE ww_Insert_intgConstInfo
      @NodeKey,                      
      @dbHnd,
    -- intgConstInfo -------------------------
      @ic_initValue,
      @ic_EGU
      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
     EXECUTE ww_Insert_intgConstInfo
      @NodeKey,                      
      @dbHnd,
    -- intgConstInfo -------------------------
      @ic_initValue,
      @ic_EGU
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ELSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,  
    @UDTChild,
    @HasUDTChild         

  EXECUTE ww_Insert_intgConstInfo
   @NodeKey,                      
   @dbHnd,
   -- intgConstInfo -------------------------
   @ic_initValue,
   @ic_EGU

END

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

CREATE PROCEDURE ww_Process_intgDDEIOInfo  
( -- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- intgDDEIO -------------------------
   @i_hihiChecked       bit,
   @i_hiChecked         bit,
   @i_loChecked        bit,
   @i_loloChecked       bit,
   @i_minorDevChecked       bit,
   @i_majorDevChecked       bit,
   @i_rocChecked       bit,
   @i_almPriHiHi       int,
   @i_almPriHi        int,
   @i_almPriLo               int,
   @i_almPriLoLo       int,
   @i_almPriMinorDev       int,
   @i_almPriMajorDev       int,
   @i_almPriROC        int,
   @i_roc        int,
   @i_rocUnits        int,
   @i_EGU        nchar(32),
   @i_initValue        int,
   @i_minValue        int,
   @i_maxValue        int,
   @i_valueDeadband           real,
   @i_hihi        int,
   @i_hi        int,
   @i_lo        int,
   @i_lolo        int,
   @i_devTarget        int,
   @diio_source               int,
   @diio_itemName             nchar(81),
   @diio_minRaw               int,
   @diio_maxRaw               int,
   @diio_inputConv            int )

AS

IF (@ToInSQL = 1)
BEGIN
  EXECUTE ww_SetIOTags_ToInSQL  @NodeKey, @diio_source, @ToInSQL OUTPUT
END

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd    int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,   
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild          

   IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
   EXECUTE ww_Insert_intgDDEIOInfo
    @NodeKey,
    @dbHnd,
    @i_hihiChecked,
    @i_hiChecked,
    @i_loChecked,
    @i_loloChecked,
    @i_minorDevChecked,
    @i_majorDevChecked,
    @i_rocChecked,
    @i_almPriHiHi,
    @i_almPriHi,
    @i_almPriLo,
    @i_almPriLoLo,
    @i_almPriMinorDev,
    @i_almPriMajorDev,
    @i_almPriROC,
    @i_roc,
    @i_rocUnits,
    @i_EGU,
    @i_initValue,
    @i_minValue,
    @i_maxValue,
    @i_valueDeadband,
    @i_hihi,
    @i_hi,
    @i_lo,
    @i_lolo,
    @i_devTarget,
    @diio_source,
    @diio_itemName,
    @diio_minRaw,
    @diio_maxRaw,
    @diio_inputConv
      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
   EXECUTE ww_Insert_intgDDEIOInfo
    @NodeKey,
    @dbHnd,
    @i_hihiChecked,
    @i_hiChecked,
    @i_loChecked,
    @i_loloChecked,
    @i_minorDevChecked,
    @i_majorDevChecked,
    @i_rocChecked,
    @i_almPriHiHi,
    @i_almPriHi,
    @i_almPriLo,
    @i_almPriLoLo,
    @i_almPriMinorDev,
    @i_almPriMajorDev,
    @i_almPriROC,
    @i_roc,
    @i_rocUnits,
    @i_EGU,
    @i_initValue,
    @i_minValue,
    @i_maxValue,
    @i_valueDeadband,
    @i_hihi,
    @i_hi,
    @i_lo,
    @i_lolo,
    @i_devTarget,
    @diio_source,
    @diio_itemName,
    @diio_minRaw,
    @diio_maxRaw,
    @diio_inputConv
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ElSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild         

  EXECUTE ww_Insert_intgDDEIOInfo
    @NodeKey,
    @dbHnd,
    @i_hihiChecked,
    @i_hiChecked,
    @i_loChecked,
    @i_loloChecked,
    @i_minorDevChecked,
    @i_majorDevChecked,
    @i_rocChecked,
    @i_almPriHiHi,
    @i_almPriHi,
    @i_almPriLo,
    @i_almPriLoLo,
    @i_almPriMinorDev,
    @i_almPriMajorDev,
    @i_almPriROC,
    @i_roc,
    @i_rocUnits,
    @i_EGU,
    @i_initValue,
    @i_minValue,
    @i_maxValue,
    @i_valueDeadband,
    @i_hihi,
    @i_hi,
    @i_lo,
    @i_lolo,
    @i_devTarget,
    @diio_source,
    @diio_itemName,
    @diio_minRaw,
    @diio_maxRaw,
    @diio_inputConv

END

GO

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

CREATE PROCEDURE ww_Process_intgVarInfo(
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName            nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- intgVar -------------------------
   @i_hihiChecked            bit,
   @i_hiChecked              bit,
   @i_loChecked              bit,
   @i_loloChecked            bit,
   @i_minorDevChecked        bit,
   @i_majorDevChecked        bit,
   @i_rocChecked             bit,
   @i_almPriHiHi             int,
   @i_almPriHi               int,
   @i_almPriLo               int,
   @i_almPriLoLo             int,
   @i_almPriMinorDev         int,
   @i_almPriMajorDev         int,
   @i_almPriROC              int,
   @i_roc                    int,
   @i_rocUnits               int,
   @i_EGU                    nchar(32),
   @i_initValue              int,
   @i_minValue               int,
   @i_maxValue               int,
   @i_valueDeadband          real,
   @i_hihi                   int,
   @i_hi                     int,
   @i_lo                     int,
   @i_lolo                   int,
   @i_devTarget              int )

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd    int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd, 
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,           
    @UDT,
    @UDTChild,
    @HasUDTChild          

    IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
      -- insert the new subtable entry ie new typeinfo
      EXECUTE ww_Insert_intgVarInfo
       @NodeKey,
       @dbHnd,
       @i_hihiChecked,
       @i_hiChecked,
       @i_loChecked,
       @i_loloChecked,
       @i_minorDevChecked,
       @i_majorDevChecked,
       @i_rocChecked,
       @i_almPriHiHi,
       @i_almPriHi,
       @i_almPriLo,
       @i_almPriLoLo,
       @i_almPriMinorDev,
       @i_almPriMajorDev,
       @i_almPriROC,
       @i_roc,
       @i_rocUnits,
       @i_EGU,
       @i_initValue,
       @i_minValue,
       @i_maxValue,
       @i_valueDeadband,
       @i_hihi,
       @i_hi,
       @i_lo,
       @i_lolo,
       @i_devTarget

      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
      EXECUTE ww_Insert_intgVarInfo
       @NodeKey,
       @dbHnd,
       @i_hihiChecked,
       @i_hiChecked,
       @i_loChecked,
       @i_loloChecked,
       @i_minorDevChecked,
       @i_majorDevChecked,
       @i_rocChecked,
       @i_almPriHiHi,
       @i_almPriHi,
       @i_almPriLo,
       @i_almPriLoLo,
       @i_almPriMinorDev,
       @i_almPriMajorDev,
       @i_almPriROC,
       @i_roc,
       @i_rocUnits,
       @i_EGU,
       @i_initValue,
       @i_minValue,
       @i_maxValue,
       @i_valueDeadband,
       @i_hihi,
       @i_hi,
       @i_lo,
       @i_lolo,
       @i_devTarget
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ELSE
-- If the tag does not yet exist in InSQL
BEGIN

    EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild         

  EXECUTE ww_Insert_intgVarInfo
    @NodeKey,
    @dbHnd,
    @i_hihiChecked,
    @i_hiChecked,
    @i_loChecked,
    @i_loloChecked,
    @i_minorDevChecked,
    @i_majorDevChecked,
    @i_rocChecked,
    @i_almPriHiHi,
    @i_almPriHi,
    @i_almPriLo,
    @i_almPriLoLo,
    @i_almPriMinorDev,
    @i_almPriMajorDev,
    @i_almPriROC,
    @i_roc,
    @i_rocUnits,
    @i_EGU,
    @i_initValue,
    @i_minValue,
    @i_maxValue,
    @i_valueDeadband,
    @i_hihi,
    @i_hi,
    @i_lo,
    @i_lolo,
    @i_devTarget

END

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

CREATE PROCEDURE ww_Process_realConstInfo 
( 
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- realConst -------------------------
   @rc_initValue     real,
   @rc_EGU                  nvarchar(32))

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd, 
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild         

    IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
      EXECUTE ww_Insert_realConstInfo
       @NodeKey,                      
       @dbHnd,
       -- realConst -------------------------
       @rc_initValue,
       @rc_EGU
      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
      EXECUTE ww_Insert_realConstInfo
       @NodeKey,                      
       @dbHnd,
       -- realConst -------------------------
       @rc_initValue,
       @rc_EGU
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ELSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild         

EXECUTE ww_Insert_realConstInfo
   @NodeKey,                      
   @dbHnd,
-- realConst -------------------------
   @rc_initValue,
   @rc_EGU

END


GO

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

CREATE PROCEDURE ww_Process_realDDEIOInfo  
( 
-- InTouchDB ---------------
   @NodeKey                    int,
   @dbHnd                      int,
   @db_tagname                 nchar(32), 
   @db_description             nchar(512) , 
   @db_type                    int,
   @db_io_type                 int,
   @db_group                   int,
   @db_valid                   bit,
   @db_modified                bit,
   @db_useCountRead            bit,
   @db_useCountWrite           bit,
   @db_useCountAlmInfo         bit,
   @db_version                 int,
   @typeinfo                   int,
   @db_logged                  bit,
   @db_useTagAsItem            bit,
   @db_eventlogged             bit,
   @db_alarmParmsSaved         bit,
   @db_currentValueSaved       bit,
   @db_intgLogDeadband         int,
   @db_realLogDeadband         real,
   @db_eventLoggingPriority    int,
   @db_intgAlmDeadband         int,
   @db_realAlmDeadband         real,
   @db_almDevDeadband          real,
   @db_minorDev                real,
   @db_majorDev                real,
   @Edited                     char(1),
   @ToInSQL                 bit,
   @InSQLName               nchar(256),
   @CurrentEditor           int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- realDDEIO -------------------------
   @r_hihiChecked        bit,
   @r_hiChecked         bit,
   @r_loChecked         bit,
   @r_loloChecked        bit,
   @r_minorDevChecked        bit,
   @r_majorDevChecked        bit,
   @r_rocChecked        bit,
   @r_almPriHiHi        int,
   @r_almPriHi         int,
   @r_almPriLo         int,
   @r_almPriLoLo        int,
   @r_almPriMinorDev        int,
   @r_almPriMajorDev        int,
   @r_almPriROC         int,
   @r_roc         int,
   @r_rocUnits         int,
   @r_EGU         nchar(32),
   @r_initValue         real,
   @r_minValue         real,
   @r_maxValue         real,
   @r_valueDeadband        real,
   @r_hihi         real,
   @r_hi         real,
   @r_lo         real,
   @r_lolo         real,
   @r_devTarget         real,
   @drio_source                int,
   @drio_itemName              nchar(81),
   @drio_minRaw                real,
   @drio_maxRaw                real,
   @drio_inputConv             int )
 
AS

IF (@ToInSQL = 1)
BEGIN
  EXECUTE ww_SetIOTags_ToInSQL  @NodeKey, @drio_source, @ToInSQL OUTPUT
END

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd    int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,   
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild         

   IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
     EXECUTE ww_Insert_realDDEIOInfo
       @NodeKey,                      
       @dbHnd,
       @r_hihiChecked,
       @r_hiChecked,
       @r_loChecked,
       @r_loloChecked,
       @r_minorDevChecked,
       @r_majorDevChecked,
       @r_rocChecked,
       @r_almPriHiHi,
       @r_almPriHi,
       @r_almPriLo,
       @r_almPriLoLo,
       @r_almPriMinorDev,
       @r_almPriMajorDev,
       @r_almPriROC,
       @r_roc,
       @r_rocUnits,
       @r_EGU,
       @r_initValue,
       @r_minValue,
       @r_maxValue,
       @r_valueDeadband,
       @r_hihi,
       @r_hi,
       @r_lo,
       @r_lolo,
       @r_devTarget,
       @drio_source,
       @drio_itemName,
       @drio_minRaw,
       @drio_maxRaw,
       @drio_inputConv

      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
     EXECUTE ww_Insert_realDDEIOInfo
       @NodeKey,                      
       @dbHnd,
       @r_hihiChecked,
       @r_hiChecked,
       @r_loChecked,
       @r_loloChecked,
       @r_minorDevChecked,
       @r_majorDevChecked,
       @r_rocChecked,
       @r_almPriHiHi,
       @r_almPriHi,
       @r_almPriLo,
       @r_almPriLoLo,
       @r_almPriMinorDev,
       @r_almPriMajorDev,
       @r_almPriROC,
       @r_roc,
       @r_rocUnits,
       @r_EGU,
       @r_initValue,
       @r_minValue,
       @r_maxValue,
       @r_valueDeadband,
       @r_hihi,
       @r_hi,
       @r_lo,
       @r_lolo,
       @r_devTarget,
       @drio_source,
       @drio_itemName,
       @drio_minRaw,
       @drio_maxRaw,
       @drio_inputConv

    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ElSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild         

  EXECUTE ww_Insert_realDDEIOInfo
   @NodeKey,                      
   @dbHnd,
   @r_hihiChecked,
   @r_hiChecked,
   @r_loChecked,
   @r_loloChecked,
   @r_minorDevChecked,
   @r_majorDevChecked,
   @r_rocChecked,
   @r_almPriHiHi,
   @r_almPriHi,
   @r_almPriLo,
   @r_almPriLoLo,
   @r_almPriMinorDev,
   @r_almPriMajorDev,
   @r_almPriROC,
   @r_roc,
   @r_rocUnits,
   @r_EGU,
   @r_initValue,
   @r_minValue,
   @r_maxValue,
   @r_valueDeadband,
   @r_hihi,
   @r_hi,
   @r_lo,
   @r_lolo,
   @r_devTarget,
   @drio_source,
   @drio_itemName,
   @drio_minRaw,
   @drio_maxRaw,
   @drio_inputConv
END

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

CREATE PROCEDURE ww_Process_realVarInfo 
( 
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- realVar -------------------------
   @r_hihiChecked       bit,
   @r_hiChecked        bit,
   @r_loChecked               bit,
   @r_loloChecked       bit,
   @r_minorDevChecked       bit,
   @r_majorDevChecked       bit,
   @r_rocChecked       bit,
   @r_almPriHiHi       int,
   @r_almPriHi        int,
   @r_almPriLo        int,
   @r_almPriLoLo       int,
   @r_almPriMinorDev       int,
   @r_almPriMajorDev       int,
   @r_almPriROC        int,
   @r_roc        int,
   @r_rocUnits        int,
   @r_EGU        nchar(32),
   @r_initValue        real,
   @r_minValue        real,
   @r_maxValue        real,
   @r_valueDeadband       real,
   @r_hihi        real,
   @r_hi        real,
   @r_lo        real,
   @r_lolo        real,
   @r_devTarget               real )

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,  
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT, 
    @UDTChild,
    @HasUDTChild         

   IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
      EXECUTE ww_Insert_realVarInfo
       @NodeKey,                      
       @dbHnd,
       @r_hihiChecked,
       @r_hiChecked,
       @r_loChecked,
       @r_loloChecked,
       @r_minorDevChecked,
       @r_majorDevChecked,
       @r_rocChecked,
       @r_almPriHiHi,
       @r_almPriHi,
       @r_almPriLo,
       @r_almPriLoLo,
       @r_almPriMinorDev,
       @r_almPriMajorDev,
       @r_almPriROC,
       @r_roc,
       @r_rocUnits,
       @r_EGU,
       @r_initValue,
       @r_minValue,
       @r_maxValue,
       @r_valueDeadband,
       @r_hihi,
       @r_hi,
       @r_lo,
       @r_lolo,
       @r_devTarget
      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
      EXECUTE ww_Insert_realVarInfo
       @NodeKey,                      
       @dbHnd,
       @r_hihiChecked,
       @r_hiChecked,
       @r_loChecked,
       @r_loloChecked,
       @r_minorDevChecked,
       @r_majorDevChecked,
       @r_rocChecked,
       @r_almPriHiHi,
       @r_almPriHi,
       @r_almPriLo,
       @r_almPriLoLo,
       @r_almPriMinorDev,
       @r_almPriMajorDev,
       @r_almPriROC,
       @r_roc,
       @r_rocUnits,
       @r_EGU,
       @r_initValue,
       @r_minValue,
       @r_maxValue,
       @r_valueDeadband,
       @r_hihi,
       @r_hi,
       @r_lo,
       @r_lolo,
       @r_devTarget
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ElSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,    
    @UDTChild,
    @HasUDTChild          

EXECUTE ww_Insert_realVarInfo
   @NodeKey,                      
   @dbHnd,
   @r_hihiChecked,
   @r_hiChecked,
   @r_loChecked,
   @r_loloChecked,
   @r_minorDevChecked,
   @r_majorDevChecked,
   @r_rocChecked,
   @r_almPriHiHi,
   @r_almPriHi,
   @r_almPriLo,
   @r_almPriLoLo,
   @r_almPriMinorDev,
   @r_almPriMajorDev,
   @r_almPriROC,
   @r_roc,
   @r_rocUnits,
   @r_EGU,
   @r_initValue,
   @r_minValue,
   @r_maxValue,
   @r_valueDeadband,
   @r_hihi,
   @r_hi,
   @r_lo,
   @r_lolo,
   @r_devTarget
END

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

CREATE PROCEDURE ww_Process_strgDDEIOInfo  
( 
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                    int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- strgDDEIO -------------------------
   @dmio_nMaxString           int,
   @dmio_initValue       nvarchar(131),
   @dmio_source               int,
   @dmio_itemName             nvarchar(80))

AS

IF (@ToInSQL = 1)
BEGIN
  EXECUTE ww_SetIOTags_ToInSQL @NodeKey, @dmio_source, @ToInSQL OUTPUT
END

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,   
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT, 
    @UDTChild,
    @HasUDTChild         

 IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
      EXECUTE ww_Insert_strgDDEIOInfo
        @NodeKey,                      
        @dbHnd,
     -- strgDDEIO -------------------------
        @dmio_nMaxString,
        @dmio_initValue,
        @dmio_source,
        @dmio_itemName
      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
      EXECUTE ww_Insert_strgDDEIOInfo
        @NodeKey,                      
        @dbHnd,
     -- strgDDEIO -------------------------
        @dmio_nMaxString,
        @dmio_initValue,
        @dmio_source,
        @dmio_itemName
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ElSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild        

EXECUTE ww_Insert_strgDDEIOInfo
   @NodeKey,                      
   @dbHnd,
-- strgDDEIO -------------------------
   @dmio_nMaxString,
   @dmio_initValue,
   @dmio_source,
   @dmio_itemName

END

GO

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

CREATE PROCEDURE ww_Process_strgInfo  
(
-- InTouchDB ---------------
   @NodeKey                  int,
   @dbHnd                   int,
   @db_tagname               nchar(32),
   @db_description           nchar(512),
   @db_type                  int,
   @db_io_type               int,
   @db_group                 int,
   @db_valid                 bit,
   @db_modified              bit,
   @db_useCountRead          bit,
   @db_useCountWrite         bit,
   @db_useCountAlmInfo       bit,
   @db_version               int,
   @typeinfo                 int,
   @db_logged                bit,
   @db_useTagAsItem          bit,
   @db_eventlogged           bit,
   @db_alarmParmsSaved       bit,
   @db_currentValueSaved     bit,
   @db_intgLogDeadband       int,
   @db_realLogDeadband       real,
   @db_eventLoggingPriority  int,
   @db_intgAlmDeadband       int,
   @db_realAlmDeadband       real,
   @db_almDevDeadband        real,
   @db_minorDev              real,
   @db_majorDev              real,
   @Edited                   char(1),
   @ToInSQL               bit,
   @InSQLName             nchar(256),
   @CurrentEditor            int,
   @UDT            bit,
   @UDTChild          bit,
   @HasUDTChild          bit,
-- strgInfo -------------------------
   @sv_nMaxString       int,
   @sv_initValue              nvarchar(131))

AS

SELECT @db_tagname = RTRIM( @db_tagname )

DECLARE @Existing_dbHnd int
DECLARE @Existing_typeinfo int

SELECT @Existing_dbHnd = ( SELECT dbHnd FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))
SELECT @Existing_typeinfo = ( SELECT typeinfo FROM InTouchDB WHERE ( NodeKey = @NodeKey AND db_tagname = @db_tagname ))

--> CR L00011121, CR L00011182
DECLARE @PrevToInSQL bit
SET  @PrevToInSQL = @ToInSQL
EXECUTE ww_MakeUniqueTagname @db_tagname, @NodeKey, @InSQLName OUTPUT, @ToInSQL OUTPUT
--< CR L00011121, CR L00011182

IF @Existing_typeinfo > 0
BEGIN
   --> CR L00011121
   SET  @ToInSQL = @PrevToInSQL
   --< CR L00011121

   -- If InTouch/Importer is the current editor ALLOW UPDATING of tag in/to InSQL
  IF (( SELECT CurrentEditor FROM InTouchDB WHERE dbHnd = @Existing_dbHnd ) & 1 ) = 1 
  BEGIN
    --> CR L00011127
    IF(@ToInSQL = 0 )
      SELECT @Edited = 'D'
    ELSE
      SELECT @Edited = 'M'
    --< CR L00011127
  END
  ELSE
  BEGIN
    SELECT @Edited = 'X'
  END

  EXECUTE ww_Update_InTouchDB
    @NodeKey,
    @dbHnd,  
    @Existing_dbHnd,
    @db_tagname,
    @db_description,
    @db_type,
    @db_io_type,    
    @db_group,
    @db_valid,
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,
    @db_eventlogged,
    @db_alarmParmsSaved,
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,
    @UDTChild,
    @HasUDTChild          

    IF ( @Existing_typeinfo <> @typeinfo )
    BEGIN
     -- insert the new subtable entry ie new typeinfo
     EXECUTE ww_Insert_strgInfo
      @NodeKey,                      
      @dbHnd,
      -- strgInfo -------------------------
      @sv_nMaxString,
      @sv_initValue
      -- remove the original subtable entry ie old typeinfo
      EXECUTE ww_SubTypeTableDelete @Existing_typeinfo, @Existing_dbHnd
    END
    ELSE
    BEGIN
      -- have to synch dbHnd with parent InTouchDB and update subtable values
      -- and then remove -dbHnd entry
     EXECUTE ww_Insert_strgInfo
      @NodeKey,                      
      @dbHnd,
      -- strgInfo -------------------------
      @sv_nMaxString,
      @sv_initValue
    END
    EXECUTE ww_SubTypeTableDelete @typeinfo, @Existing_dbHnd
END
ELSE
-- If the tag does not yet exist in InSQL
BEGIN

  EXECUTE ww_Insert_InTouchDB
    @NodeKey,
    @dbHnd,
    @db_tagname,
    @db_description,    
    @db_type,
    @db_io_type,
    @db_group,
    @db_valid,    
    @db_modified,
    @db_useCountRead,
    @db_useCountWrite,
    @db_useCountAlmInfo,
    @db_version,
    @typeinfo,
    @db_logged,
    @db_useTagAsItem,    
    @db_eventlogged,
    @db_alarmParmsSaved,    
    @db_currentValueSaved,
    @db_intgLogDeadband,
    @db_realLogDeadband,
    @db_eventLoggingPriority,
    @db_intgAlmDeadband,
    @db_realAlmDeadband,
    @db_almDevDeadband,
    @db_minorDev,
    @db_majorDev,
    @Edited,
    @ToInSQL,
    @InSQLName,
    @CurrentEditor,            
    @UDT,   
    @UDTChild,
    @HasUDTChild          

  EXECUTE ww_Insert_strgInfo
   @NodeKey,                      
   @dbHnd,
-- strgInfo -------------------------
   @sv_nMaxString,
   @sv_initValue

END

GO

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

CREATE PROCEDURE ww_RunToHold_LimitsROCS
  @NodeNo          int
as

-- Limits ---------------------------------------------------------------------
-- 1 intgDDEIOInfo
UPDATE intgDDEIOInfo SET
  i_lolo        = L.Value, 
  i_almPriLoLo  = L.Priority,
  i_loloChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, intgDDEIOInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 1
UPDATE intgDDEIOInfo SET
  i_lo        = L.Value, 
  i_almPriLo  = L.Priority,
  i_loChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, intgDDEIOInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 2
UPDATE intgDDEIOInfo SET
  i_hi        = L.Value, 
  i_almPriHi  = L.Priority,
  i_hiChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, intgDDEIOInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 3
UPDATE intgDDEIOInfo SET
  i_lolo        = L.Value, 
  i_almPriLoLo  = L.Priority,
  i_loloChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, intgDDEIOInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 4

-- 2 realDDEIOInfo
UPDATE realDDEIOInfo SET
  r_lolo        = L.Value, 
  r_almPriLoLo  = L.Priority,
  r_loloChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, realDDEIOInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 1
UPDATE realDDEIOInfo SET
  r_lo        = L.Value, 
  r_almPriLo  = L.Priority,
  r_loChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, realDDEIOInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 2
UPDATE realDDEIOInfo SET
  r_hi        = L.Value, 
  r_almPriHi  = L.Priority,
  r_hiChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, realDDEIOInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 3
UPDATE realDDEIOInfo SET
  r_lolo        = L.Value, 
  r_almPriLoLo  = L.Priority,
  r_loloChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, realDDEIOInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 4


-- 3 intgVarInfo
UPDATE intgVarInfo SET
  i_lolo        = L.Value, 
  i_almPriLoLo  = L.Priority,
  i_loloChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, intgVarInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 1
UPDATE intgVarInfo SET
  i_lo        = L.Value, 
  i_almPriLo  = L.Priority,  i_loChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, intgVarInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 2
UPDATE intgVarInfo SET
  i_hi        = L.Value, 
  i_almPriHi  = L.Priority,
  i_hiChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, intgVarInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 3
UPDATE intgVarInfo SET
  i_lolo        = L.Value, 
  i_almPriLoLo  = L.Priority,
  i_loloChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, intgVarInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 4


-- 4 realVarInfo
UPDATE realVarInfo SET
  r_lolo        = L.Value, 
  r_almPriLoLo  = L.Priority,
  r_loloChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, realVarInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 1
UPDATE realVarInfo SET
  r_lo        = L.Value, 
  r_almPriLo  = L.Priority,
  r_loChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, realVarInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 2
UPDATE realVarInfo SET
  r_hi        = L.Value, 
  r_almPriHi  = L.Priority,
  r_hiChecked = L.Checked     FROM Runtime.dbo.Limit L, InTouchDB ITDB, realVarInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 3
UPDATE realVarInfo SET
  r_lolo        = L.Value, 
  r_almPriLoLo  = L.Priority,
  r_loloChecked = L.Checked 
    FROM Runtime.dbo.Limit L, InTouchDB ITDB, realVarInfo INFO
      WHERE ITDB.InSQLName = L.TagName
        AND ITDB.dbHnd     = INFO.dbHnd
        AND L.LimitNameKey = 4

-- ROCs -----------------------------------------------------------------------

-- 1 intgDDEIOInfo
UPDATE intgDDEIOInfo 
  SET i_roc        = r.Value,
      i_rocUnits   = r.TimeBase,
      i_almPriROC  = r.Priority,
      i_rocChecked = r.Checked
    FROM InTouchDB itdb, intgDDEIOInfo i, Runtime.dbo.InTouchSpecific its,
         Runtime.dbo.Context c, Runtime.dbo.RateOfChange r
      WHERE itdb.dbHnd      = i.dbHnd
      AND   itdb.db_tagname = its.OriginalName
      AND   itdb.NodeKey    = @NodeNo
      AND   c.[Description] = 'InTouch'
      AND   r.ContextKey    = c.ContextKey
      AND   r.TagName       = its.TagName
      AND   its.InInSQL     = 1

-- 2 realDDEIOInfo
UPDATE realDDEIOInfo 
  SET r_roc        = r.Value,
      r_rocUnits   = r.TimeBase,
      r_almPriROC  = r.Priority,
      r_rocChecked = r.Checked
    FROM InTouchDB itdb, realDDEIOInfo i, Runtime.dbo.InTouchSpecific its,
         Runtime.dbo.Context c, Runtime.dbo.RateOfChange r
      WHERE itdb.dbHnd      = i.dbHnd
      AND   itdb.db_tagname = its.OriginalName
      AND   itdb.NodeKey    = @NodeNo
      AND   c.[Description] = 'InTouch'
      AND   r.ContextKey    = c.ContextKey
      AND   r.TagName       = its.TagName
      AND   its.InInSQL     = 1

-- 3 intgVarInfo
UPDATE intgVarInfo 
  SET i_roc        = r.Value,
      i_rocUnits   = r.TimeBase,
      i_almPriROC  = r.Priority,
      i_rocChecked = r.Checked
    FROM InTouchDB itdb, intgVarInfo i, Runtime.dbo.InTouchSpecific its,
         Runtime.dbo.Context c, Runtime.dbo.RateOfChange r
      WHERE itdb.dbHnd      = i.dbHnd
      AND   itdb.db_tagname = its.OriginalName
      AND   itdb.NodeKey    = @NodeNo
      AND   c.[Description] = 'InTouch'
      AND   r.ContextKey    = c.ContextKey
      AND   r.TagName       = its.TagName
      AND   its.InInSQL = 1

-- 4 realVarInfo
UPDATE realVarInfo 
  SET r_roc        = r.Value,
      r_rocUnits   = r.TimeBase,
      r_almPriROC  = r.Priority,
      r_rocChecked = r.Checked
    FROM InTouchDB itdb, realVarInfo i, Runtime.dbo.InTouchSpecific its,
         Runtime.dbo.Context c, Runtime.dbo.RateOfChange r
      WHERE itdb.dbHnd      = i.dbHnd
      AND   itdb.db_tagname = its.OriginalName
      AND   itdb.NodeKey    = @NodeNo
      AND   c.[Description] = 'InTouch'
      AND   r.ContextKey    = c.ContextKey
      AND   r.TagName       = its.TagName
      AND   its.InInSQL     = 1
GO

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

CREATE PROCEDURE ww_RunToHold
   @NodeNo  int

as

-- Get the InTouchNode stuff

INSERT InTouchNode (NodeKey, MachineName, ApplicationPath, Description,
                    PrefixOrSuffix, DuplicateChar, AlwaysModifyName, Edited,
                    ImportPlantTags, ImportSystemTags, ImportMemoryTags, ImportAllTags)
   SELECT NodeKey, MachineName, Path, Description, PrefixOrSuffix, 
          DuplicateChar, AlwaysModifyName, 'D',
          ImportPlantTags, ImportSystemTags, ImportMemoryTags, ImportAllTags
      FROM Runtime.dbo.InTouchNode
         WHERE NodeKey = @NodeNo
      
/******************************************************************************/

-- Get the DdeCfg from TopicImportInfo
INSERT DdeCfg (DdeSourceKey, NodeKey, SourceName, ApplicationName, TopicName,
               RequestInitialData, AlwaysAdvise, StorageType, StorageRate,
               TimeDeadband, ToInSQL, ProtocolType, Edited, ValueDeadband, DeadbandType,
               IODriverKey, RateDeadband)
   SELECT DdeSourceKey, NodeKey, SourceName, ApplicationName, TopicName,
          RequestInitialData, AlwaysAdvise, DefaultStorageType,
          DefaultStorageRate, TimeDeadband, Import, ProtocolType, 'D', ValueDeadband, DeadbandType,
          IODriverKey, RateDeadband
      FROM Runtime.dbo.TopicImportInfo                 
         WHERE NodeKey = @NodeNo

/******************************************************************************/
-- Get the Tag info from InTouchSpecific & Tag, Populate InTouchDB

INSERT InTouchDB
       ( dbHnd, NodeKey, db_tagname, typeinfo, InSQLName,ToInSQL,  
         db_description, Edited, CurrentEditor )
SELECT (wwTagKey * -1), NodeKey, OriginalName, TypeInfo, i.TagName, InInSQL, 
                    Description, 'D', CurrentEditor 
      FROM Runtime.dbo.InTouchSpecific i, Runtime.dbo.Tag t
         WHERE i.TagName = t.TagName
         AND   i.NodeKey = @NodeNo

/******************************************************************************/
-- Depending on TypeInfo, populate the relevant sub-table

INSERT intgDDEIOInfo (dbHnd, NodeKey, i_EGU, i_initValue, i_minValue,
                      i_maxValue, diio_source, diio_itemName,
                      diio_minRaw, diio_maxRaw, diio_inputConv, i_valueDeadband)
   SELECT ITDB.dbHnd, ITS.NodeKey, EU.Unit, ATAG.InitialValue,
          ATAG.MinEU, ATAG.MaxEU, TII.DdeSourceKey, TAG.ItemName,
          ATAG.MinRaw,ATAG.MaxRaw, ATAG.Scaling, ATAG.ValueDeadband
      FROM Runtime.dbo.InTouchSpecific       ITS,
                 Runtime.dbo.Tag             TAG,
                 Runtime.dbo.AnalogTag       ATAG,
                 Runtime.dbo.EngineeringUnit EU,
                 Runtime.dbo.TopicImportInfo TII,
                 Runtime.dbo.Topic           TP,
                 Runtime.dbo.IOServer        IOS, 
                 Runtime.dbo.InTouchNode     ITN,
                 InTouchDB                   ITDB
         WHERE  ITS.TypeInfo      = 1
          AND    ITS.NodeKey      = @NodeNo
          AND    ITS.NodeKey      = ITN.NodeKey
          AND    TII.NodeKey      = ITN.NodeKey         
          AND    ITS.TagName      = ITDB.InSQLName
          AND    ITS.TagName      = TAG.TagName
          AND    TAG.TagName      = ATAG.TagName
          AND    TAG.TopicKey     = TP.TopicKey
          AND    TP.IOServerKey   = IOS.IOServerKey
          AND    ATAG.EUKey       = EU.EUKey
          AND    TP.Name          = TII.TopicName
          AND    ( (TII.ApplicationName = IOS.ApplicationName
                 AND IOS.ComputerName = ITN.MachineName)
                 OR TII.ApplicationName = '\\' + IOS.ComputerName + '\' + IOS.ApplicationName)

-- InSQL80 Push back the Value Deadband into the InTouchDB table
-- This avoid to do the InTouchDB insert in multiple queries
UPDATE InTouchDB set db_intgLogDeadband = i_valueDeadband
   from InTouchDB itdb, intgDDEIOInfo idde
      where itdb.dbHnd = idde.dbHnd

INSERT realDDEIOInfo (dbHnd, NodeKey, r_EGU, r_initValue, r_minValue,
                      r_maxValue, drio_source, drio_itemName,
                      drio_minRaw, drio_maxRaw, drio_inputConv, r_valueDeadband)
   SELECT ITDB.dbHnd, ITS.NodeKey, EU.Unit, ATAG.InitialValue,
          ATAG.MinEU, ATAG.MaxEU, TII.DdeSourceKey, TAG.ItemName,
          ATAG.MinRaw,ATAG.MaxRaw, ATAG.Scaling, ATAG.ValueDeadband
      FROM Runtime.dbo.InTouchSpecific        ITS,
                  Runtime.dbo.Tag             TAG,
                  Runtime.dbo.AnalogTag       ATAG,
                  Runtime.dbo.EngineeringUnit EU,
                  Runtime.dbo.TopicImportInfo TII,
                  Runtime.dbo.Topic           TP,
                  Runtime.dbo.IOServer        IOS, 
                  Runtime.dbo.InTouchNode     ITN,
                  InTouchDB                   ITDB
         WHERE  ITS.TypeInfo     = 2
         AND    ITS.NodeKey      = @NodeNo
         AND    ITS.NodeKey      = ITN.NodeKey         
         AND    TII.NodeKey      = ITN.NodeKey 
         AND    ITS.TagName      = ITDB.InSQLName
         AND    ITS.TagName      = TAG.TagName
         AND    TAG.TagName      = ATAG.TagName
         AND    TAG.TopicKey     = TP.TopicKey
         AND    TP.IOServerKey   = IOS.IOServerKey
         AND    ATAG.EUKey       = EU.EUKey
         AND    TP.Name          = TII.TopicName
         AND    ( (TII.ApplicationName = IOS.ApplicationName
                      AND IOS.ComputerName = ITN.MachineName)
                   OR TII.ApplicationName = '\\' + IOS.ComputerName + '\' + IOS.ApplicationName)

-- InSQL80 Push back the Value Deadband into the InTouchDB table
-- This avoid to do the InTouchDB insert in multiple queries
UPDATE InTouchDB set db_realLogDeadband = r_valueDeadband
   from InTouchDB itdb, realDDEIOInfo rdde
      where itdb.dbHnd = rdde.dbHnd

INSERT intgVarInfo (dbHnd, NodeKey, i_EGU, i_initValue, i_minValue, i_maxValue, i_valueDeadband)
   SELECT ITDB.dbHnd, ITS.NodeKey, EU.Unit, ATAG.InitialValue,
           ATAG.MinEU, ATAG.MaxEU, ATAG.ValueDeadband
       FROM Runtime.dbo.InTouchSpecific       ITS,
                  Runtime.dbo.Tag             TAG,
                  Runtime.dbo.AnalogTag       ATAG,
                  Runtime.dbo.EngineeringUnit EU,
                  InTouchDB                   ITDB
         WHERE  ITS.TypeInfo = 3
         AND    ITS.NodeKey  = @NodeNo
         AND    ITS.TagName  = ITDB.InSQLName
         AND    TAG.TagName  = ITDB.db_tagname
         AND    ITS.TagName  = TAG.TagName
         AND    TAG.TagName  = ATAG.TagName
         AND    ATAG.EUKey   = EU.EUKey

-- InSQL80 Push back the Value Deadband into the InTouchDB table
-- This avoid to do the InTouchDB insert in multiple queries
UPDATE InTouchDB set db_realLogDeadband = i_valueDeadband
   from InTouchDB itdb, intgVarInfo imem
      where itdb.dbHnd = imem.dbHnd

INSERT realVarInfo (dbHnd, NodeKey, r_EGU, r_initValue, r_minValue,
                      r_maxValue, r_valueDeadband)
   SELECT ITDB.dbHnd, ITS.NodeKey, EU.Unit, ATAG.InitialValue,
          ATAG.MinEU, ATAG.MaxEU, ATAG.ValueDeadband
      FROM Runtime.dbo.InTouchSpecific       ITS,
                 Runtime.dbo.Tag             TAG,
                 Runtime.dbo.AnalogTag       ATAG,
                 Runtime.dbo.EngineeringUnit EU,
                 InTouchDB                   ITDB
         WHERE  ITDB.typeinfo    = 4
         AND    ITS.NodeKey      = @NodeNo
         AND    ITS.TagName      = ITDB.InSQLName
         AND    ITS.TagName      = TAG.TagName
         AND    TAG.TagName      = ITDB.db_tagname
         AND    TAG.TagName      = ATAG.TagName
         AND    ATAG.EUKey       = EU.EUKey

-- InSQL80 Push back the Value Deadband into the InTouchDB table
-- This avoid to do the InTouchDB insert in multiple queries
UPDATE InTouchDB set db_realLogDeadband = r_valueDeadband
   from InTouchDB itdb, realVarInfo rmem
      where itdb.dbHnd = rmem.dbHnd

INSERT discDDEIOInfo (dbHnd, NodeKey, d_onMsg, d_offMsg, d_initValue,
                      ddio_source, ddio_itemName)
   SELECT ITDB.dbHnd, ITS.NodeKey, MS.Message1, MS.Message0,
          DTAG.InitialValue, TII.DdeSourceKey, TAG.ItemName
      FROM Runtime.dbo.InTouchSpecific       ITS,
                 Runtime.dbo.Tag             TAG,
                 Runtime.dbo.DiscreteTag     DTAG,
                 Runtime.dbo.Message         MS,
                 Runtime.dbo.TopicImportInfo TII,
                 Runtime.dbo.Topic           TP,
                 Runtime.dbo.InTouchNode     ITN,
                 Runtime.dbo.IOServer        IOS,
                 InTouchDB                   ITDB
         WHERE  ITS.TypeInfo     = 5
         AND    ITS.NodeKey      = @NodeNo
         AND    ITS.NodeKey      = ITN.NodeKey
         AND    TII.NodeKey      = ITN.NodeKey          
         AND    ITS.TagName      = ITDB.InSQLName
         AND    ITS.TagName      = TAG.TagName
         AND    TAG.TagName      = DTAG.TagName
         AND    TAG.TopicKey     = TP.TopicKey
         AND    IOS.IOServerKey  = TP.IOServerKey
         AND    DTAG.MessageKey  = MS.MessageKey
         AND    TP.Name          = TII.TopicName
         AND    ( (TII.ApplicationName = IOS.ApplicationName
                      AND IOS.ComputerName = ITN.MachineName)
                 OR TII.ApplicationName = '\\' + IOS.ComputerName + '\' + IOS.ApplicationName)

INSERT discVarInfo (dbHnd, NodeKey, d_onMsg, d_offMsg, d_initValue)
   SELECT ITDB.dbHnd, ITS.NodeKey, MS.Message1, MS.Message0, DTAG.InitialValue
       FROM Runtime.dbo.InTouchSpecific        ITS,
                   Runtime.dbo.Tag             TAG,
                   Runtime.dbo.DiscreteTag     DTAG,
                   Runtime.dbo.Message         MS,
                   InTouchDB                   ITDB
         WHERE  ITS.TypeInfo      = 6
          AND    ITS.NodeKey      = @NodeNo
          AND    ITS.TagName      = ITDB.InSQLName
          AND    ITS.TagName      = TAG.TagName
          AND    TAG.TagName      = DTAG.TagName
          AND    DTAG.MessageKey  = MS.MessageKey


INSERT strgDDEIOInfo (dbHnd, NodeKey, dmio_nMaxString, dmio_initValue,
                      dmio_source, dmio_itemName)
   SELECT ITDB.dbHnd, ITS.NodeKey, STAG.MaxLength, STAG.InitialValue,
          TII.DdeSourceKey, TAG.ItemName
      FROM Runtime.dbo.InTouchSpecific       ITS,
                 Runtime.dbo.Tag             TAG,
                 Runtime.dbo.StringTag       STAG,
                 Runtime.dbo.TopicImportInfo TII,
                 Runtime.dbo.Topic           TP,
                 Runtime.dbo.IOServer        IOS,
                 Runtime.dbo.InTouchNode     ITN,
                 InTouchDB                   ITDB
         WHERE  ITS.TypeInfo     = 7
         AND    ITS.NodeKey      = @NodeNo
         AND    ITS.NodeKey      = ITN.NodeKey         
         AND    TII.NodeKey      = ITN.NodeKey 
         AND    ITS.TagName      = ITDB.InSQLName
         AND    ITS.TagName      = TAG.TagName
         AND    TAG.TagName      = STAG.TagName
         AND    TAG.TopicKey     = TP.TopicKey
         AND    IOS.IOServerKey  = TP.IOServerKey
         AND    TP.Name          = TII.TopicName
         AND    ( (TII.ApplicationName = IOS.ApplicationName
                     AND IOS.ComputerName = ITN.MachineName)
             OR TII.ApplicationName = '\\' + IOS.ComputerName + '\' + IOS.ApplicationName)


INSERT strgInfo (dbHnd, NodeKey, sv_nMaxString, sv_initValue)
    SELECT ITDB.dbHnd, ITS.NodeKey, STAG.MaxLength, STAG.InitialValue
       FROM Runtime.dbo.InTouchSpecific       ITS,
                  Runtime.dbo.Tag             TAG,
                  Runtime.dbo.StringTag       STAG,
                  InTouchDB                   ITDB
         WHERE  ITS.TypeInfo     = 8
         AND    ITS.NodeKey      = @NodeNo
         AND    ITS.TagName      = ITDB.InSQLName
         AND    ITS.TagName      = TAG.TagName
         AND    TAG.TagName      = STAG.TagName


EXECUTE ww_RunToHold_LimitsROCS @NodeNo

/******************************************************************************/
-- UPDATE inputConv fields  (linear 201 / square root 202)

UPDATE intgDDEIOInfo SET diio_inputConv = 201 WHERE diio_inputConv = 1
UPDATE intgDDEIOInfo SET diio_inputConv = 202 WHERE diio_inputConv = 2
UPDATE realDDEIOInfo SET drio_inputConv = 201 WHERE drio_inputConv = 1
UPDATE realDDEIOInfo SET drio_inputConv = 202 WHERE drio_inputConv = 2

/******************************************************************************/
-- UPDATE r_EGU, i_EGU fields (empty strings where replace by '-' by H2RSP.SQL)

UPDATE intgDDEIOInfo SET i_EGU = '' WHERE i_EGU = 'None'
UPDATE realDDEIOInfo SET r_EGU = '' WHERE r_EGU = 'None'
UPDATE intgVarInfo   SET i_EGU = '' WHERE i_EGU = 'None'
UPDATE realVarInfo   SET r_EGU = '' WHERE r_EGU = 'None'

/******************************************************************************/
-- UPDATE Messages fields (empty strings where replace by '-' by H2RSP.SQL)

UPDATE discDDEIOInfo SET d_onMsg  = '' WHERE d_onMsg  = 'None'
UPDATE discDDEIOInfo SET d_offMsg = '' WHERE d_offMsg = 'None'
UPDATE discVarInfo   SET d_onMsg  = '' WHERE d_onMsg  = 'None'
UPDATE discVarInfo   SET d_offMsg = '' WHERE d_offMsg = 'None'

GO

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

CREATE procedure ww_UpdateUDTChildren 

AS

DECLARE @currentrow     int
DECLARE @maxrows        int

DECLARE @dbHnd          int
DECLARE @NodeKey        int
DECLARE @ParentdbHnd    int

DECLARE taglist SCROLL CURSOR 
   FOR SELECT InTDB.dbHnd, InTDB.NodeKey, UDTCh.ParentdbHnd
      FROM Holding.dbo.InTouchDB InTDB, Holding.dbo.UDTChildren UDTCh
         WHERE (( InTDB.UDTChild = 1 )
         AND    ( InTDB.NodeKey = UDTCh.NodeKey )
         AND    ( InTDB.dbHnd   = UDTCh.dbHnd   ))

OPEN taglist

SELECT @currentrow  = 1
SELECT @maxrows = @@cursor_rows

WHILE @currentrow <= @maxrows
   BEGIN
      FETCH NEXT FROM taglist INTO @dbHnd, @NodeKey, @ParentdbHnd
        BEGIN
          UPDATE InTouchDB
          SET
            ParentdbHnd   = @ParentdbHnd,
            ParentNodeKey = @NodeKey
          WHERE (( dbHnd = @dbHnd ) AND ( NodeKey = @NodeKey ))
        END

      SELECT @currentrow = @currentrow + 1
   END

DEALLOCATE taglist
GO

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

CREATE procedure ww_Update_AllTagTypes
AS
BEGIN TRAN
/*********************/
-- UPDATED TAGS

-- An existing tag could have been changed to anything.....
-- (ana to disv. , DDE to Mem, Int to Real...)
-- Build a list of modified tags and handle them one by one

DECLARE @nodekey     int      -- InTouch node being updated
DECLARE @machname    nvarchar(50) -- InTouch Node machine Name
DECLARE @contextkey  int
DECLARE @lolokey     int     -- InTouch context lolo limit identifier
DECLARE @lokey       int      -- InTouch context lo   limit identifier
DECLARE @hikey       int      -- InTouch context hi   limit identifier
DECLARE @hihikey     int     -- InTouch context hihi limit identifier

DECLARE @currow      int      -- current cursor row (Update)
DECLARE @modrows     int    -- number of modified tags (Update)
DECLARE @thetag      nvarchar(256)  -- current Holding tagname
DECLARE @dbhnd       int      -- Holding tag identifier
DECLARE @ITvartype   int     -- What Holding table is it in
DECLARE @ToInSQL  bit       -- for updating InTouchSpecific

DECLARE @runvartype  int       -- What Holding table was is it last time
DECLARE @runtagname  nvarchar(256)  -- Tag.TagName from @thetag
DECLARE @charconvert nvarchar(80)  -- To convert int to char for update sp's
DECLARE @tagrows      int      -- Cursor rows (Insert)
DECLARE @tagcurrow    int     -- Current cursor row (Insert)

-- Var definitions for Tag Tables Update
DECLARE @iDescription nvarchar(512)  -- InTouch tag desc
DECLARE @iEU          nvarchar(32)     -- Cursor Eng. Unit
DECLARE @iinitval     int          -- Cursor Initial value INTEGER
DECLARE @rinitval     real        -- Cursor Initial value REAL
DECLARE @binitval     bit         -- Cursor Initial value BIT
DECLARE @sinitval     nvarchar(131)    -- Cursor Initial value STRING
DECLARE @iminval      int        -- Cursor minval value INTEGER
DECLARE @rminval      real      -- Cursor minval value REAL
DECLARE @imaxval      int       -- Cursor maxval value INTEGER
DECLARE @rmaxval      real     -- Cursor maxval value REAL
DECLARE @iddesource   int     -- Cursor dde source (topic)
DECLARE @iitemname    nvarchar(81)     -- Cursor item name (address)
DECLARE @iminraw      int       -- Cursor min raw value INTEGER
DECLARE @rminraw      real     -- Cursor min raw value REAL
DECLARE @imaxraw      int      -- Cursor max raw value INTEGER
DECLARE @rmaxraw      real    -- Cursor max raw value REAL
DECLARE @iconvert     int       -- Cursor conversion factor
DECLARE @donmsg       nvarchar(15)    -- Cursor ON message
DECLARE @doffmsg      nvarchar(15)     -- Cursor OFF message
DECLARE @istrglen     int          -- Cursor Maxlenght for String
DECLARE @itopickey    int        -- runtime topic for dde source
DECLARE @iscanrate    int        -- topic scanrate
DECLARE @iEUkey       int        -- runtime EU key for eng unit
DECLARE @imeskey      int        -- runtime Message key

DECLARE @nalmhihi     real      -- for Alarm HIHI value INTEGER/REAL
DECLARE @nalmhi       real       -- for Alarm HI value INTEGER/REAL
DECLARE @nalmlo       real       -- for Alarm LO value INTEGER/REAL
DECLARE @nalmlolo     real      -- for Alarm LOLO value INTEGER/REAL
DECLARE @ndevtarget   real    -- for Deviation value INTEGER / REAL

DECLARE @ialmhihi     int       -- Alarm HIHI value INTEGER
DECLARE @ialmhi       int        -- Alarm HI value INTEGER
DECLARE @ialmlo       int        -- Alarm LO value INTEGER
DECLARE @ialmlolo     int       -- Alarm LOLO value INTEGER
DECLARE @ralmhihi     real     -- Alarm HIHI value REAL
DECLARE @ralmhi       real      -- Alarm HI value REAL
DECLARE @ralmlo       real      -- Alarm LO value REAL
DECLARE @ralmlolo     real     -- Alarm LOLO value REAL
DECLARE @ialmphihi    int      -- Alarm HIHI priority
DECLARE @ialmphi      int       -- Alarm HI priority
DECLARE @ialmplo      int       -- Alarm LO priority
DECLARE @ialmplolo    int      -- Alarm LOLO priority
DECLARE @ialmchkhihi  bit    -- Alarm HIHI Checked bit 
DECLARE @ialmchkhi    bit     -- Alarm HI Checked bit 
DECLARE @ialmchklo    bit     -- Alarm LO Checked bit 
DECLARE @ialmchklolo  bit    -- Alarm LOLO Checked bit 

DECLARE @iroc         int          -- ROC Value INTEGER  
DECLARE @iproc        int         -- ROC Priority  
DECLARE @irocchk      bit       -- ROC Chcked bit
DECLARE @irocunit     int        -- ROC Time Base  

DECLARE @ioserverkey  int    -- IOServer key to be updated in TAG

DECLARE @minordevchk  bit      -- Minor Deviation Checked bit 
DECLARE @majordevchk  bit      -- Major Deviation Checked bit
DECLARE @minordevalmp int      -- Minor Deviation Alarm Priority
DECLARE @majordevalmp int      -- Major Deviation Alarm Priority
DECLARE @minordev     real       -- Minor Deviation
DECLARE @majordev     real       -- Major Deviation
DECLARE @devalmdbd    real     -- Deviation Alarm Deadband
DECLARE @idevtarget   int          -- Deviation Target INTEGER
DECLARE @rdevtarget   real       -- Deviation Target REAL

DECLARE @MemSysSourceKey int       -- for updating Mem and Sys tags' storage rates

DECLARE @insqldeadband float(25)  -- History InSQL value deadband in % of EU
DECLARE @deadbandtype tinyint   -- Deadband type selected (0 = none, 1 = InTouch,  2 = Time and/or Value, 3 = Swinging Door)
DECLARE @topicvaluedeadband float(25)   -- InSQL specific value deadband
DECLARE @topicratedeadband float(25)   -- InSQL specific rate deadband
DECLARE @topictimedeadband int   -- InSQL specific time deadband
DECLARE @storetype int  -- Topic Storage Type

SET @nodekey = (SELECT NodeKey FROM Holding.dbo.InTouchNode) 
SET @machname = (SELECT MachineName FROM InTouchNode WHERE NodeKey = @nodekey)
SET @contextkey = (SELECT ContextKey FROM Runtime.dbo.Context WHERE Description = 'InTouch')

SET @lolokey = (SELECT LimitNameKey FROM Runtime.dbo.LimitName WHERE Name = 'LoLo')
SET @lokey   = (SELECT LimitNameKey FROM Runtime.dbo.LimitName WHERE Name = 'Lo')
SET @hikey   = (SELECT LimitNameKey FROM Runtime.dbo.LimitName WHERE Name = 'Hi')
SET @hihikey = (SELECT LimitNameKey FROM Runtime.dbo.LimitName WHERE Name = 'HiHi')

-- Get Modified Tags (M) from Holding.InTouchDB
DECLARE mycursor CURSOR FAST_FORWARD
 FOR SELECT db_tagname, db_description, dbHnd, typeinfo, ToInSQL, db_almDevDeadband, db_minorDev, db_majorDev, InSQLDeadband
  FROM Holding.dbo.InTouchDB
  WHERE Edited  = 'M' AND   NodeKey = @nodekey
  ORDER BY db_tagname

OPEN mycursor
SELECT @modrows = @@cursor_rows
SELECT @ITvartype = 0
SELECT @currow = 1

IF @@cursor_rows > 0
BEGIN
 WHILE @currow <= @modrows
 BEGIN
  --> CR L00011125
  SET @iconvert = 0
  --< CR L00011125

  FETCH NEXT FROM mycursor
   INTO @thetag, @iDescription, @dbhnd, @ITvartype, @ToInSQL,
   @devalmdbd, @minordev, @majordev, @insqldeadband
 
  -- Find the vartype within InTouch and what it was in InSQL
  -- Find the InSQL TagName
 
  -- get the typeinfo of the tag from the previous import
  SELECT @runvartype = (SELECT TypeInfo FROM Runtime.dbo.InTouchSpecific
   WHERE OriginalName = @thetag AND   NodeKey      = @nodekey)
 
  -- get the name of the tag from the previous import
  SELECT @runtagname = (SELECT TagName FROM Runtime.dbo.InTouchSpecific
   WHERE OriginalName = @thetag AND   NodeKey      = @nodekey)
 
  -- switch on Holding typeinfo
  IF @ITvartype = 1   -- DDE Integer
  BEGIN
   -- get typeinfo specific data from Holding subtable
   DECLARE intgdde CURSOR FAST_FORWARD
    FOR SELECT i_hihiChecked, i_hiChecked, i_loChecked,
     i_loloChecked, i_rocChecked, i_almPriHiHi, i_almPriHi,
     i_almPriLo, i_almPriLoLo, i_almPriROC, i_roc,
     i_rocUnits, i_EGU, i_initValue, i_minValue, i_maxValue,
     i_hihi, i_hi, i_lo, i_lolo,
     diio_source, diio_itemName, diio_minRaw, diio_maxRaw,
     diio_inputConv, i_minorDevChecked, i_majorDevChecked,
     i_almPriMinorDev, i_almPriMajorDev, i_devTarget
    FROM Holding.dbo.intgDDEIOInfo
    WHERE dbHnd   = @dbhnd
    AND   NodeKey = @nodekey
 
   OPEN intgdde
    
   FETCH NEXT FROM intgdde INTO @ialmchkhihi, @ialmchkhi,
    @ialmchklo, @ialmchklolo, @irocchk, @ialmphihi,
    @ialmphi, @ialmplo, @ialmplolo, @iproc, @iroc,
    @irocunit, @iEU, @iinitval, @iminval, @imaxval,
    @ialmhihi, @ialmhi, @ialmlo,
    @ialmlolo, @iddesource, @iitemname, @iminraw,
    @imaxraw, @iconvert, @minordevchk, @majordevchk,
    @minordevalmp, @majordevalmp, @idevtarget
   
   DEALLOCATE intgdde
  END
  ELSE IF @ITvartype = 2  -- DDE Real
  BEGIN
   DECLARE realdde CURSOR FAST_FORWARD
    FOR SELECT r_hihiChecked, r_hiChecked, r_loChecked,
     r_loloChecked, r_rocChecked, r_almPriHiHi, r_almPriHi,
     r_almPriLo, r_almPriLoLo, r_almPriROC, r_roc,
     r_rocUnits, r_EGU, r_initValue, r_minValue, r_maxValue,
     r_hihi, r_hi, r_lo, r_lolo,
     drio_source, drio_itemName, drio_minRaw, drio_maxRaw, 
     drio_inputConv, r_minorDevChecked, r_majorDevChecked,
     r_almPriMinorDev, r_almPriMajorDev, r_devTarget
    FROM Holding.dbo.realDDEIOInfo
    WHERE dbHnd   = @dbhnd
    AND   NodeKey = @nodekey
 
   OPEN realdde
 
   FETCH NEXT FROM realdde INTO @ialmchkhihi, @ialmchkhi,
    @ialmchklo, @ialmchklolo, @irocchk, @ialmphihi,
    @ialmphi, @ialmplo, @ialmplolo, @iproc, @iroc,
    @irocunit, @iEU, @rinitval, @rminval, @rmaxval,
    @ralmhihi, @ralmhi, @ralmlo,
    @ralmlolo, @iddesource, @iitemname, @rminraw,
    @rmaxraw, @iconvert, @minordevchk, @majordevchk,
    @minordevalmp, @majordevalmp, @rdevtarget
   
   DEALLOCATE realdde
  END
  ELSE IF @ITvartype = 3  -- Mem Integer
  BEGIN
   DECLARE intgmem CURSOR FAST_FORWARD
    FOR SELECT i_hihiChecked, i_hiChecked, i_loChecked,
     i_loloChecked, i_rocChecked, i_almPriHiHi, i_almPriHi,
     i_almPriLo, i_almPriLoLo, i_almPriROC, i_roc,
     i_rocUnits, i_EGU, i_initValue, i_minValue, i_maxValue,
     i_hihi, i_hi, i_lo, i_lolo,
     i_minorDevChecked, i_majorDevChecked,
     i_almPriMinorDev, i_almPriMajorDev, i_devTarget
    FROM Holding.dbo.intgVarInfo
    WHERE dbHnd   = @dbhnd
    AND   NodeKey = @nodekey
 
   OPEN intgmem
 
   FETCH NEXT FROM intgmem INTO @ialmchkhihi, @ialmchkhi,
    @ialmchklo, @ialmchklolo, @irocchk, @ialmphihi,
    @ialmphi, @ialmplo, @ialmplolo, @iproc, @iroc,
    @irocunit, @iEU, @iinitval, @iminval, @imaxval,
    @ialmhihi, @ialmhi, @ialmlo,
    @ialmlolo, @minordevchk, @majordevchk,
    @minordevalmp, @majordevalmp, @idevtarget
 
   DEALLOCATE intgmem
  END
  ELSE IF @ITvartype = 4  -- Mem Real
  BEGIN
   DECLARE realmem CURSOR FAST_FORWARD
    FOR SELECT r_hihiChecked, r_hiChecked, r_loChecked, 
     r_loloChecked, r_rocChecked, r_almPriHiHi, r_almPriHi, 
     r_almPriLo, r_almPriLoLo, r_almPriROC, r_roc, 
     r_rocUnits, r_EGU, r_initValue, r_minValue, r_maxValue,
     r_hihi, r_hi, r_lo, r_lolo,
     r_minorDevChecked, r_majorDevChecked,
     r_almPriMinorDev, r_almPriMajorDev, r_devTarget
    FROM Holding.dbo.realVarInfo
    WHERE dbHnd   = @dbhnd
    AND   NodeKey = @nodekey
 
   OPEN realmem
 
   FETCH NEXT FROM realmem INTO @ialmchkhihi, @ialmchkhi,
    @ialmchklo, @ialmchklolo, @irocchk, @ialmphihi,
    @ialmphi, @ialmplo, @ialmplolo, @iproc, @iroc,
    @irocunit, @iEU, @rinitval, @rminval, @rmaxval,
    @ralmhihi, @ralmhi, @ralmlo,
    @ralmlolo, @minordevchk, @majordevchk,
    @minordevalmp, @majordevalmp, @rdevtarget
 
   DEALLOCATE realmem
  END
  ELSE IF @ITvartype = 5  -- DDE Discrete
  BEGIN
   DECLARE discdde CURSOR FAST_FORWARD
    FOR SELECT d_initValue, d_onMsg, d_offMsg, ddio_source, ddio_itemName
    FROM Holding.dbo.discDDEIOInfo
    WHERE dbHnd   = @dbhnd
    AND   NodeKey = @nodekey
 
   OPEN discdde
 
   FETCH NEXT FROM discdde INTO @binitval, @donmsg, @doffmsg, @iddesource, @iitemname 
 
   DEALLOCATE discdde
  END
  ELSE IF @ITvartype = 6  -- Mem Discrete
  BEGIN
   DECLARE discmem CURSOR FAST_FORWARD
    FOR SELECT d_initValue, d_onMsg, d_offMsg
    FROM Holding.dbo.discVarInfo
    WHERE dbHnd   = @dbhnd
    AND   NodeKey = @nodekey
 
   OPEN discmem
 
   FETCH NEXT FROM discmem INTO @binitval, @donmsg, @doffmsg
 
   DEALLOCATE discmem
  END
  ELSE IF @ITvartype = 7  -- DDE String
  BEGIN
   DECLARE strgdde CURSOR FAST_FORWARD
    FOR SELECT dmio_nMaxString, dmio_initValue, dmio_source, dmio_itemName
    FROM Holding.dbo.strgDDEIOInfo
    WHERE dbHnd   = @dbhnd
    AND   NodeKey = @nodekey
 
   OPEN strgdde
 
   FETCH NEXT FROM strgdde INTO @istrglen, @sinitval, @iddesource, @iitemname
 
   DEALLOCATE strgdde
  END
  ELSE IF @ITvartype = 8  -- Mem String
  BEGIN
   DECLARE strgmem CURSOR FAST_FORWARD
    FOR SELECT sv_nMaxString, sv_initValue
    FROM Holding.dbo.strgInfo
    WHERE dbHnd   = @dbhnd
    AND   NodeKey = @nodekey
 
   OPEN strgmem
 
   FETCH NEXT FROM strgmem INTO @istrglen, @sinitval
 
   DEALLOCATE strgmem
  END
 
  -- Need to get the runtime Eng. unit key for Analogs
  IF @ITvartype in (1, 2, 3, 4)
  BEGIN
   SELECT @iEUkey = (SELECT EUKey FROM Runtime.dbo.EngineeringUnit
    WHERE RTRIM(Unit) = RTRIM(@iEU))
 
   IF @iEUkey = NULL
   BEGIN 
    SELECT @iEUkey = 1 -- means %
   END 
  END
 
  -- Need to get the runtime message key for discretes
  IF @ITvartype in (5, 6)
  BEGIN
   SELECT @imeskey = (SELECT MessageKey FROM Runtime.dbo.Message
    WHERE RTRIM(Message0) = RTRIM(@doffmsg)
    AND   RTRIM(Message1) = RTRIM(@donmsg))
  END
 
  /*********************/
 
  -- Now we start to look at what was modified.. and update the InSQL side accordingly
 
  IF ((@ITvartype = @runvartype)
   OR (@ITvartype in (1,2,3,4) AND @runvartype in (1,2,3,4))
   OR (@ITvartype in (5,6)     AND @runvartype in (5,6))
   OR (@ITvartype in (7,8)     AND @runvartype in (7,8)))
  -- Fine it is still the same vartype group, just need to update
  -- the IT related fields
  BEGIN
   -- Ready to Update the columns
   -- For Char columns, we need to patch the var content
   -- (because of the stored procedure syntax)
 
   -- For int/real vars we need to convert to a Char
   -- for this, @charconvert is set before each update
 
   IF @ITvartype in (1, 2, 5, 7) -- DDE tags
   BEGIN
    -- need to get the Topic.Key, the ScanRate and the IOServerKey
    SET @itopickey = (SELECT R_TopicKey FROM Holding.dbo.DdeCfg
       WHERE DdeSourceKey = @iddesource
       AND NodeKey = @nodekey)
 
    SET @iscanrate = (SELECT StorageRate FROM Holding.dbo.DdeCfg
       WHERE DdeSourceKey = @iddesource
       AND NodeKey = @nodekey)
 
    SET @ioserverkey  = (SELECT R_IOServerKey FROM Holding.dbo.DdeCfg
       WHERE DdeSourceKey = @iddesource
       AND   NodeKey = @nodekey)
 
    SET @deadbandtype = (SELECT DeadbandType FROM Holding.dbo.DdeCfg
       WHERE DdeSourceKey = @iddesource
       AND NodeKey = @nodekey)
 
    SET @topicvaluedeadband = (SELECT ValueDeadband FROM Holding.dbo.DdeCfg
        WHERE DdeSourceKey = @iddesource
        AND NodeKey = @nodekey)
 
    SET @topictimedeadband = (SELECT TimeDeadband FROM Holding.dbo.DdeCfg
        WHERE DdeSourceKey = @iddesource
        AND NodeKey = @nodekey)
    SET @topicratedeadband = (SELECT RateDeadband FROM Holding.dbo.DdeCfg
        WHERE DdeSourceKey = @iddesource
        AND NodeKey = @nodekey)
 
    SET @storetype = (SELECT StorageType FROM Holding.dbo.DdeCfg
       WHERE DdeSourceKey = @iddesource
       AND NodeKey = @nodekey)
 
    IF @iscanrate IS NULL 
    BEGIN
     SELECT @iscanrate = 0
    END          
 
    UPDATE Runtime.dbo.Tag 
    SET
     IOServerKey = @ioserverkey,
     TopicKey = @itopickey,
     ItemName = RTRIM(@iitemname),
     -- < CR L00012847
     -- StorageRate = @iscanrate,
     StorageRate = CASE @ITvartype 
       WHEN 5 THEN 0
       WHEN 7 THEN 0
       ELSE @iscanrate
       END,
     -- > CR L00012847
     Description = RTRIM(@iDescription),
     TimeDeadband = CASE @deadbandtype
       WHEN 0 then 0
       WHEN 1 then 0
       ELSE  @topictimedeadband
       END,
     StorageType = CASE @storetype
       WHEN 3 then 3
       WHEN 2 THEN 2
       ELSE CASE TagType
               WHEN 1 then @storetype
               ELSE StorageType
         END
                  END,
     DeadbandType = CASE @deadbandtype  
          WHEN 0 THEN 1
          WHEN 1 THEN 1
          WHEN 2 THEN 1
          ELSE CASE TagType 
        WHEN 1 THEN 2
        ELSE 1
        END
       END
   WHERE TagName = RTRIM(@runtagname)
   END
   ELSE -- MEM tags                  
   BEGIN
    -- need to get the Topic.Key
 
    --> CR L00011098
    SELECT @ioserverkey = Topic.IOServerKey, @itopickey = Topic.TopicKey 
     FROM Runtime.dbo.Topic Topic, Runtime.dbo.IOServer IOS
     WHERE Topic.IOServerKey = IOS.IOServerKey
      AND Topic.Name = 'TagName'
      AND IOS.ComputerName = @machname
      AND   IOS.ApplicationName = 'VIEW'
    --< CR L00011098
 
    IF ( @thetag like '$%')
    BEGIN
     SELECT @MemSysSourceKey = -2 -- system
    END
    ELSE
    BEGIN
     SELECT @MemSysSourceKey = -1 -- memory
    END
 
      SELECT @iscanrate = (SELECT StorageRate FROM Holding.dbo.DdeCfg
       WHERE DdeSourceKey = @MemSysSourceKey
       AND   NodeKey = @nodekey)
 
    IF @iscanrate IS NULL 
    BEGIN
     SELECT @iscanrate = 0
    END          
 
    SET @deadbandtype = (SELECT DeadbandType FROM Holding.dbo.DdeCfg
       WHERE DdeSourceKey = @MemSysSourceKey
       AND NodeKey = @nodekey)
 
    SET @topicvaluedeadband = (SELECT ValueDeadband FROM Holding.dbo.DdeCfg
        WHERE DdeSourceKey = @MemSysSourceKey
        AND NodeKey = @nodekey)
 
    SET @topictimedeadband = (SELECT TimeDeadband FROM Holding.dbo.DdeCfg
        WHERE DdeSourceKey = @MemSysSourceKey
        AND NodeKey = @nodekey)

    SET @topicratedeadband = (SELECT RateDeadband FROM Holding.dbo.DdeCfg
        WHERE DdeSourceKey = @MemSysSourceKey
        AND NodeKey = @nodekey)
 
    SET @storetype = (SELECT StorageType FROM Holding.dbo.DdeCfg
       WHERE DdeSourceKey = @MemSysSourceKey
       AND NodeKey = @nodekey)
 
    --> CR L00011098  
    UPDATE Runtime.dbo.Tag 
    SET
    IOServerKey      = @ioserverkey,
    TopicKey           = @itopickey,
    ItemName          = RTRIM(@thetag),
    -- < CR L00012847
    -- StorageRate = @iscanrate,
    StorageRate = CASE @ITvartype 
     WHEN 6 THEN 0
     WHEN 8 THEN 0
     ELSE @iscanrate
     END,
    -- > CR L00012847
    Description        = RTRIM(@iDescription),
    TimeDeadband = CASE @deadbandtype
      WHEN 0 then 0
      WHEN 1 then 0
      ELSE @topictimedeadband
      END,
     StorageType = CASE @storetype
       WHEN 3 then 3
       WHEN 2 then 2
       ELSE CASE TagType
               WHEN 1 then @storetype
               ELSE StorageType
         END
                  END,
     DeadbandType = CASE @deadbandtype  
          WHEN 0 THEN 1
          WHEN 1 THEN 1
          WHEN 2 THEN 1
          ELSE CASE TagType 
        WHEN 1 THEN 2
        ELSE 1
        END
       END
    WHERE TagName   = @runtagname
    --< CR L00011098  
   END
 
   -- AnalogTag Table
   IF @ITvartype in (1, 3) -- Ana Integer
   BEGIN
    UPDATE Runtime.dbo.AnalogTag 
    SET
     EUKey = @iEUkey,
     MinEU = @iminval,
     MaxEU = @imaxval,
     ValueDeadband  =  CASE @deadbandtype
       WHEN 0 THEN 0
       WHEN 1 THEN @insqldeadband
       ELSE @topicvaluedeadband
       END,
     InitialValue   =  @iinitval,
     MinRaw =  CASE @ITvartype
      WHEN 1 THEN @iminraw  -- I/O tag
      WHEN 3 THEN @iminval  -- Mem tag
      END,
     MaxRaw =  CASE @ITvartype
      WHEN 1 THEN @imaxraw  -- I/O tag
      WHEN 3 THEN @imaxval  -- Mem tag
      END,
     -- <CR L00030636
     Scaling            = CASE @iconvert
      WHEN 0 THEN 0
                 WHEN 1 THEN 1
                 WHEN 2 THEN 0
     END,
     -- > CR L00030636
     RateDeadband = @topicratedeadband
    WHERE TagName = @runtagname
 
    IF @runvartype in (2, 4) -- It was a Real, now an Int
    BEGIN
     --> CR L00011125
     UPDATE Runtime.dbo.AnalogTag  
     SET
      RawType        = 3,
      IntegerSize     = 32,
      SignedInteger = 1
     WHERE TagName = @runtagname
     --< CR L00011125
    END
   END
   ELSE IF @ITvartype in (2, 4) -- Ana Real
   BEGIN
    UPDATE Runtime.dbo.AnalogTag  
    SET
     EUKey  = @iEUkey,
     MinEU  = @rminval,
     MaxEU  = @rmaxval,
     ValueDeadband  =  CASE @deadbandtype
       WHEN 0 THEN 0
       WHEN 1 THEN @insqldeadband
       ELSE @topicvaluedeadband
       END,
     InitialValue   = @rinitval,
     MinRaw =  CASE @ITvartype
      WHEN 2 THEN @rminraw  -- I/O tag
      WHEN 4 THEN @rminval   -- Mem tag 
      END,
     MaxRaw =  CASE @ITvartype
      WHEN 2 THEN @rmaxraw  -- I/O tag
      WHEN 4 THEN @rmaxval   -- Mem tag
      END,
     -- <CR L00030636
     Scaling            = CASE @iconvert
      WHEN 0 THEN 0
                 WHEN 1 THEN 1
                 WHEN 2 THEN 0
     END,
     -- > CR L00030636
     RateDeadband = @topicratedeadband
    WHERE TagName = @runtagname
 
    IF @runvartype in (1, 3) -- It was an Int, now a Real
    BEGIN
     --> CR L00011125
     UPDATE Runtime.dbo.AnalogTag  
     SET
      RawType        = 2
     WHERE TagName = @runtagname
     --< CR L00011125
    END
   END
   ELSE IF @ITvartype in (5, 6) -- Discrete
   BEGIN
    UPDATE Runtime.dbo.DiscreteTag 
    SET
     MessageKey     = @imeskey,
     InitialValue   = @binitval
    WHERE TagName = @runtagname
   END
   ELSE IF @ITvartype in (7, 8) -- String
   BEGIN
    -- InSQL80 map String length to an acceptable value
    SET @istrglen =  
     CASE 
     WHEN @istrglen = 0 then 131
     WHEN @istrglen between 1 and 8 then 8
     WHEN @istrglen between 9 and 16 then 16
     WHEN @istrglen between 17 and 24 then 24
     WHEN @istrglen between 25 and 32 then 32
     WHEN @istrglen between 33 and 48 then 48
     WHEN @istrglen between 49 and 64 then 64
     WHEN @istrglen between 65 and 128 then 128
     WHEN @istrglen between 129 and 131 then 131  -- InTouch Legacy
     WHEN @istrglen between 132 and 256 then 256
     WHEN @istrglen between 257 and 512 then 512
     ELSE 512
     END
 
    UPDATE Runtime.dbo.StringTag 
    SET
     MaxLength   = @istrglen,
     InitialValue   = RTRIM(@sinitval)
    WHERE TagName = @runtagname
   END
 
   -- If Analog we need to process the Alarms, ROC and Deviation
   -- We systematically delete the previous runtime rows
   -- and re-insert...
   IF @ITvartype in (1,2,3,4)
   BEGIN
    DELETE Runtime.dbo.Limit WHERE TagName = @runtagname
    DELETE Runtime.dbo.RateOfChange WHERE TagName = @runtagname
    DELETE Runtime.dbo.Deviation    WHERE TagName = @runtagname
 
    IF @ITvartype in (1,3)
    BEGIN
     SELECT @nalmhihi = @ialmhihi
     SELECT @nalmhi   = @ialmhi
     SELECT @nalmlo   = @ialmlo
     SELECT @nalmlolo = @ialmlolo
     SELECT @ndevtarget = @idevtarget
    END
    ELSE IF @ITvartype in (2,4)
    BEGIN
     SELECT @nalmhihi = @ralmhihi
     SELECT @nalmhi   = @ralmhi
     SELECT @nalmlo   = @ralmlo
     SELECT @nalmlolo = @ralmlolo
     SELECT @ndevtarget = @rdevtarget
    END
 
    INSERT Runtime.dbo.Limit
     VALUES (@runtagname, @contextkey, 0, @nalmhihi, @hihikey, @ialmphihi, @ialmchkhihi, '')
 
    INSERT Runtime.dbo.Limit
     VALUES (@runtagname, @contextkey, 0, @nalmhi, @hikey, @ialmphi, @ialmchkhi, '')
 
    INSERT Runtime.dbo.Limit
     VALUES (@runtagname, @contextkey, 0, @nalmlo, @lokey, @ialmplo, @ialmchklo, '')
 
    INSERT Runtime.dbo.Limit
     VALUES (@runtagname, @contextkey, 0, @nalmlolo, @lolokey, @ialmplolo, @ialmchklolo, '')
 
    INSERT Runtime.dbo.RateOfChange
     VALUES (@runtagname, @contextkey, @iroc, @irocunit, @iproc, @irocchk)
 
    INSERT Runtime.dbo.Deviation
     VALUES (@runtagname, @contextkey, @minordev, @minordevchk, @minordevalmp, 
      @majordev, @majordevchk, @majordevalmp, @ndevtarget, @devalmdbd)
 
   END
 
   -- Reset the Edited flag
   UPDATE Holding.dbo.InTouchDB SET Edited = ''
    WHERE db_tagname = @thetag AND   NodeKey    = @nodekey
 
   --> CR L00011106
   UPDATE Runtime.dbo.InTouchSpecific 
   SET 
    TypeInfo   = @ITvartype,
    InInSQL = @ToInSQL
   WHERE OriginalName = RTRIM(@thetag) AND   NodeKey = @nodekey
   --< CR L00011106
  END
  ELSE
  BEGIN
   -- The vartype group has changed : was ana now disc etc...
   -- We delete the tag in InSQL
   -- and reset the flag in Holding to "I" (Insert) 
   DELETE Runtime.dbo.Tag WHERE TagName = RTRIM(@runtagname)
   DELETE Runtime.dbo.InTouchSpecific 
    WHERE (( TagName = @runtagname ) AND ( NodeKey = @nodekey ))
 
   --> CR L00011121
   UPDATE Holding.dbo.InTouchDB 
   SET 
    Edited     = 'I', 
    ToInSQL = 1
   WHERE db_tagname = @thetag AND   NodeKey    = @nodekey
   --< CR L00011121
  END
 
  SELECT @currow = @currow + 1
 END 
END      

DEALLOCATE mycursor

COMMIT TRAN

BEGIN TRAN

/*********************************/
-- DELETED TAGS  Only if Tag.CurrentEditor is set to InTouch (1)

DELETE Runtime.dbo.Tag 
 WHERE TagName IN ( SELECT TagName FROM Runtime.dbo.Tag, Holding.dbo.InTouchDB 
    WHERE ( Runtime.dbo.Tag.TagName = InSQLName ) 
    AND   ( Edited = 'D' ) 
    AND   ( NodeKey    = @nodekey )
    AND   ( Runtime.dbo.Tag.CurrentEditor = 1))

UPDATE Holding.dbo.InTouchDB 
SET 
 Edited = ' '
WHERE NodeKey = @nodekey 
AND   Edited     = 'D'

COMMIT TRAN
GO

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

CREATE procedure ww_Holding_To_Runtime 
as
/******************************************************************************
-- This sp is used as the container for all sp activity to be performed 
-- during the transfer from the Holding Database to Runtime
*******************************************************************************/
BEGIN TRAN
declare @result int
set @result = 0

-- InTouch Node / IOServers / Topic
exec @result = ww_Insert_Node_IOServer_Topic
if @result <> 0 goto abortimport

exec @result = ww_Init_EngUnit_Msg_Limit
if @result <> 0 goto abortimport

exec @result = ww_PrepareTagTransfer
if @result <> 0 goto abortimport

exec @result = ww_Update_AllTagTypes
if @result <> 0 goto abortimport

exec @result = ww_Insert_DDEReal
if @result <> 0 goto abortimport

exec @result = ww_Insert_DDEInt
if @result <> 0 goto abortimport

exec @result = ww_Insert_DDEDisc
if @result <> 0 goto abortimport

exec @result = ww_Insert_DDEString
if @result <> 0 goto abortimport

exec @result = ww_Insert_MemReal
if @result <> 0 goto abortimport

exec @result = ww_Insert_MemInt
if @result <> 0 goto abortimport

exec @result = ww_Insert_MemDisc
if @result <> 0 goto abortimport

exec @result = ww_Insert_MemString
if @result <> 0 goto abortimport

exec @result = ww_Clean_Limits_ROCs
if @result <> 0 goto abortimport

exec @result = ww_Cleanup_AfterImport
if @result <> 0 goto abortimport

COMMIT TRAN
return 0

abortimport:
  ROLLBACK TRAN
  return -1
go

GRANT exec on ww_Holding_To_Runtime to aaAdministrators
go
go
 
 
 
 create trigger tI_almGrpInfo on almGrpInfo for INSERT as
/* Wonderware INSERT trigger on almGrpInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  almGrpInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT almGrpInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_almGrpInfo on almGrpInfo for UPDATE as
/* Wonderware UPDATE trigger on almGrpInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  almGrpInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE almGrpInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_DdeCfg on DdeCfg for INSERT as
/* Wonderware INSERT trigger on DdeCfg */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchNode  DdeCfg 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 DdeCfg because InTouchNode does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_DdeCfg on DdeCfg for UPDATE as
/* Wonderware UPDATE trigger on DdeCfg */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insDdeSourceKey int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchNode  DdeCfg 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 DdeCfg because InTouchNode does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_discConstInfo on discConstInfo for INSERT as
/* Wonderware INSERT trigger on discConstInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  discConstInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT discConstInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_discConstInfo on discConstInfo for UPDATE as
/* Wonderware UPDATE trigger on discConstInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  discConstInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE discConstInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_discDDEIOInfo on discDDEIOInfo for INSERT as
/* Wonderware INSERT trigger on discDDEIOInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  discDDEIOInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT discDDEIOInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_discDDEIOInfo on discDDEIOInfo for UPDATE as
/* Wonderware UPDATE trigger on discDDEIOInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  discDDEIOInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE discDDEIOInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_discVarInfo on discVarInfo for INSERT as
/* Wonderware INSERT trigger on discVarInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  discVarInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT discVarInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_discVarInfo on discVarInfo for UPDATE as
/* Wonderware UPDATE trigger on discVarInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  discVarInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE discVarInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_histInfo on histInfo for INSERT as
/* Wonderware INSERT trigger on histInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  histInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT histInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_histInfo on histInfo for UPDATE as
/* Wonderware UPDATE trigger on histInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  histInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE histInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_intgConstInfo on intgConstInfo for INSERT as
/* Wonderware INSERT trigger on intgConstInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  intgConstInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT intgConstInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_intgConstInfo on intgConstInfo for UPDATE as
/* Wonderware UPDATE trigger on intgConstInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  intgConstInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE intgConstInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_intgDDEIOInfo on intgDDEIOInfo for INSERT as
/* Wonderware INSERT trigger on intgDDEIOInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  intgDDEIOInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT intgDDEIOInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_intgDDEIOInfo on intgDDEIOInfo for UPDATE as
/* Wonderware UPDATE trigger on intgDDEIOInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  intgDDEIOInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE intgDDEIOInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_intgVarInfo on intgVarInfo for INSERT as
/* Wonderware INSERT trigger on intgVarInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  intgVarInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT intgVarInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_intgVarInfo on intgVarInfo for UPDATE as
/* Wonderware UPDATE trigger on intgVarInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  intgVarInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE intgVarInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tD_InTouchDB on InTouchDB for DELETE as
/* Wonderware DELETE trigger on InTouchDB */
begin
  declare  @errno   int,
           @errmsg  varchar(255)
    /* Wonderware InTouchDB R/42 UDTChildren ON PARENT DELETE RESTRICT */
    if exists (
      select * from deleted,UDTChildren
      where
        /*  UDTChildren.dbHnd = deleted.dbHnd and
            UDTChildren.NodeKey = deleted.NodeKey */
        UDTChildren.dbHnd = deleted.dbHnd and
        UDTChildren.NodeKey = deleted.NodeKey
    )
    begin
      select @errno  = 30001,
             @errmsg = 'Cannot DELETE InTouchDB because UDTChildren exists.'
      goto error
    end

    /* Wonderware InTouchDB child of InTouchDB ON PARENT DELETE SET NULL */
    update InTouchDB
      set
        /* InTouchDB.ParentdbHnd = NULL,
           InTouchDB.ParentNodeKey = NULL */
        InTouchDB.ParentdbHnd = NULL,
        InTouchDB.ParentNodeKey = NULL
      from InTouchDB,deleted
      where
        /* InTouchDB.ParentdbHnd = deleted.dbHnd and
           InTouchDB.ParentNodeKey = deleted.NodeKey */
        InTouchDB.ParentdbHnd = deleted.dbHnd and
        InTouchDB.ParentNodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  strgDDEIOInfo ON PARENT DELETE CASCADE */
    delete strgDDEIOInfo
      from strgDDEIOInfo,deleted
      where
        /*  strgDDEIOInfo.dbHnd = deleted.dbHnd and
            strgDDEIOInfo.NodeKey = deleted.NodeKey */
        strgDDEIOInfo.dbHnd = deleted.dbHnd and
        strgDDEIOInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  realDDEIOInfo ON PARENT DELETE CASCADE */
    delete realDDEIOInfo
      from realDDEIOInfo,deleted
      where
        /*  realDDEIOInfo.dbHnd = deleted.dbHnd and
            realDDEIOInfo.NodeKey = deleted.NodeKey */
        realDDEIOInfo.dbHnd = deleted.dbHnd and
        realDDEIOInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  intgDDEIOInfo ON PARENT DELETE CASCADE */
    delete intgDDEIOInfo
      from intgDDEIOInfo,deleted
      where
        /*  intgDDEIOInfo.dbHnd = deleted.dbHnd and
            intgDDEIOInfo.NodeKey = deleted.NodeKey */
        intgDDEIOInfo.dbHnd = deleted.dbHnd and
        intgDDEIOInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  discDDEIOInfo ON PARENT DELETE CASCADE */
    delete discDDEIOInfo
      from discDDEIOInfo,deleted
      where
        /*  discDDEIOInfo.dbHnd = deleted.dbHnd and
            discDDEIOInfo.NodeKey = deleted.NodeKey */
        discDDEIOInfo.dbHnd = deleted.dbHnd and
        discDDEIOInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  realVarInfo ON PARENT DELETE CASCADE */
    delete realVarInfo
      from realVarInfo,deleted
      where
        /*  realVarInfo.dbHnd = deleted.dbHnd and
            realVarInfo.NodeKey = deleted.NodeKey */
        realVarInfo.dbHnd = deleted.dbHnd and
        realVarInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  intgVarInfo ON PARENT DELETE CASCADE */
    delete intgVarInfo
      from intgVarInfo,deleted
      where
        /*  intgVarInfo.dbHnd = deleted.dbHnd and
            intgVarInfo.NodeKey = deleted.NodeKey */
        intgVarInfo.dbHnd = deleted.dbHnd and
        intgVarInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  discVarInfo ON PARENT DELETE CASCADE */
    delete discVarInfo
      from discVarInfo,deleted
      where
        /*  discVarInfo.dbHnd = deleted.dbHnd and
            discVarInfo.NodeKey = deleted.NodeKey */
        discVarInfo.dbHnd = deleted.dbHnd and
        discVarInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  realConstInfo ON PARENT DELETE CASCADE */
    delete realConstInfo
      from realConstInfo,deleted
      where
        /*  realConstInfo.dbHnd = deleted.dbHnd and
            realConstInfo.NodeKey = deleted.NodeKey */
        realConstInfo.dbHnd = deleted.dbHnd and
        realConstInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  intgConstInfo ON PARENT DELETE CASCADE */
    delete intgConstInfo
      from intgConstInfo,deleted
      where
        /*  intgConstInfo.dbHnd = deleted.dbHnd and
            intgConstInfo.NodeKey = deleted.NodeKey */
        intgConstInfo.dbHnd = deleted.dbHnd and
        intgConstInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  discConstInfo ON PARENT DELETE CASCADE */
    delete discConstInfo
      from discConstInfo,deleted
      where
        /*  discConstInfo.dbHnd = deleted.dbHnd and
            discConstInfo.NodeKey = deleted.NodeKey */
        discConstInfo.dbHnd = deleted.dbHnd and
        discConstInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  strgInfo ON PARENT DELETE CASCADE */
    delete strgInfo
      from strgInfo,deleted
      where
        /*  strgInfo.dbHnd = deleted.dbHnd and
            strgInfo.NodeKey = deleted.NodeKey */
        strgInfo.dbHnd = deleted.dbHnd and
        strgInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  histInfo ON PARENT DELETE CASCADE */
    delete histInfo
      from histInfo,deleted
      where
        /*  histInfo.dbHnd = deleted.dbHnd and
            histInfo.NodeKey = deleted.NodeKey */
        histInfo.dbHnd = deleted.dbHnd and
        histInfo.NodeKey = deleted.NodeKey

    /* Wonderware InTouchDB  almGrpInfo ON PARENT DELETE CASCADE */
    delete almGrpInfo
      from almGrpInfo,deleted
      where
        /*  almGrpInfo.dbHnd = deleted.dbHnd and
            almGrpInfo.NodeKey = deleted.NodeKey */
        almGrpInfo.dbHnd = deleted.dbHnd and
        almGrpInfo.NodeKey = deleted.NodeKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_InTouchDB on InTouchDB for INSERT as
/* Wonderware INSERT trigger on InTouchDB */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB child of InTouchDB ON CHILD INSERT SET NULL */
  if
    /* update(ParentdbHnd) or
       update(ParentNodeKey) */
    update(ParentdbHnd) or
    update(ParentNodeKey)
  begin
    update InTouchDB
      set
        /* InTouchDB.ParentdbHnd = NULL,
           InTouchDB.ParentNodeKey = NULL */
        InTouchDB.ParentdbHnd = NULL,
        InTouchDB.ParentNodeKey = NULL
      from InTouchDB,inserted
      where
        /* InTouchDB.dbHnd = inserted.dbHnd and
           InTouchDB.NodeKey = inserted.NodeKey */
        InTouchDB.dbHnd = inserted.dbHnd and
        InTouchDB.NodeKey = inserted.NodeKey and
        not exists (
          select * from InTouchDB
          where
            /* inserted.ParentdbHnd = InTouchDB.dbHnd and
               inserted.ParentNodeKey = InTouchDB.NodeKey */
            inserted.ParentdbHnd = InTouchDB.dbHnd and
            inserted.ParentNodeKey = InTouchDB.NodeKey
        )
  end

  /* Wonderware InTouchNode  InTouchDB 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 InTouchDB because InTouchNode does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_InTouchDB on InTouchDB for UPDATE as
/* Wonderware UPDATE trigger on InTouchDB */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB R/42 UDTChildren ON PARENT UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    if exists (
      select * from deleted,UDTChildren
      where
        /*  UDTChildren.dbHnd = deleted.dbHnd and
            UDTChildren.NodeKey = deleted.NodeKey */
        UDTChildren.dbHnd = deleted.dbHnd and
        UDTChildren.NodeKey = deleted.NodeKey
    )
    begin
      select @errno  = 30005,
             @errmsg = 'Cannot UPDATE InTouchDB because UDTChildren exists.'
      goto error
    end
  end

  /* Wonderware InTouchDB child of InTouchDB ON PARENT UPDATE SET NULL */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    update InTouchDB
      set
        /* InTouchDB.ParentdbHnd = NULL,
           InTouchDB.ParentNodeKey = NULL */
        InTouchDB.ParentdbHnd = NULL,
        InTouchDB.ParentNodeKey = NULL
      from InTouchDB,deleted
      where
        /* InTouchDB.ParentdbHnd = deleted.dbHnd and
           InTouchDB.ParentNodeKey = deleted.NodeKey */
        InTouchDB.ParentdbHnd = deleted.dbHnd and
        InTouchDB.ParentNodeKey = deleted.NodeKey
  end

  /* Wonderware InTouchDB child of InTouchDB ON CHILD UPDATE SET NULL */
  if
    /* update(ParentdbHnd) or
       update(ParentNodeKey) */
    update(ParentdbHnd) or
    update(ParentNodeKey)
  begin
    update InTouchDB
      set
        /* InTouchDB.ParentdbHnd = NULL,
           InTouchDB.ParentNodeKey = NULL */
        InTouchDB.ParentdbHnd = NULL,
        InTouchDB.ParentNodeKey = NULL
      from InTouchDB,inserted
      where
        /* InTouchDB.dbHnd = inserted.dbHnd and
           InTouchDB.NodeKey = inserted.NodeKey */
        InTouchDB.dbHnd = inserted.dbHnd and
        InTouchDB.NodeKey = inserted.NodeKey and 
        not exists (
          select * from InTouchDB
          where
            /* inserted.ParentdbHnd = InTouchDB.dbHnd and
               inserted.ParentNodeKey = InTouchDB.NodeKey */
            inserted.ParentdbHnd = InTouchDB.dbHnd and
            inserted.ParentNodeKey = InTouchDB.NodeKey
        )
  end

  /* Wonderware InTouchNode  InTouchDB 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 InTouchDB because InTouchNode 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
/* Wonderware DELETE trigger on InTouchNode */
begin
  declare  @errno   int,
           @errmsg  varchar(255)
    /* Wonderware InTouchNode  DdeCfg ON PARENT DELETE CASCADE */
    delete DdeCfg
      from DdeCfg,deleted
      where
        /*  DdeCfg.NodeKey = deleted.NodeKey */
        DdeCfg.NodeKey = deleted.NodeKey

    /* Wonderware InTouchNode  InTouchDB ON PARENT DELETE CASCADE */
    delete InTouchDB
      from InTouchDB,deleted
      where
        /*  InTouchDB.NodeKey = deleted.NodeKey */
        InTouchDB.NodeKey = deleted.NodeKey


    return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_InTouchNode on InTouchNode for UPDATE as
/* Wonderware UPDATE trigger on InTouchNode */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchNode  DdeCfg ON PARENT UPDATE RESTRICT */
  if
    /* update(NodeKey) */
    update(NodeKey)
  begin
    if exists (
      select * from deleted,DdeCfg
      where
        /*  DdeCfg.NodeKey = deleted.NodeKey */
        DdeCfg.NodeKey = deleted.NodeKey
    )
    begin
      select @errno  = 30005,
             @errmsg = 'Cannot UPDATE InTouchNode because DdeCfg exists.'
      goto error
    end
  end

  /* Wonderware InTouchNode  InTouchDB ON PARENT UPDATE RESTRICT */
  if
    /* update(NodeKey) */
    update(NodeKey)
  begin
    if exists (
      select * from deleted,InTouchDB
      where
        /*  InTouchDB.NodeKey = deleted.NodeKey */
        InTouchDB.NodeKey = deleted.NodeKey
    )
    begin
      select @errno  = 30005,
             @errmsg = 'Cannot UPDATE InTouchNode because InTouchDB exists.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_realConstInfo on realConstInfo for INSERT as
/* Wonderware INSERT trigger on realConstInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  realConstInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT realConstInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_realConstInfo on realConstInfo for UPDATE as
/* Wonderware UPDATE trigger on realConstInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  realConstInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE realConstInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_realDDEIOInfo on realDDEIOInfo for INSERT as
/* Wonderware INSERT trigger on realDDEIOInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  realDDEIOInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT realDDEIOInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_realDDEIOInfo on realDDEIOInfo for UPDATE as
/* Wonderware UPDATE trigger on realDDEIOInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  realDDEIOInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE realDDEIOInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_realVarInfo on realVarInfo for INSERT as
/* Wonderware INSERT trigger on realVarInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  realVarInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT realVarInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_realVarInfo on realVarInfo for UPDATE as
/* Wonderware UPDATE trigger on realVarInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  realVarInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE realVarInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_strgDDEIOInfo on strgDDEIOInfo for INSERT as
/* Wonderware INSERT trigger on strgDDEIOInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  strgDDEIOInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT strgDDEIOInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_strgDDEIOInfo on strgDDEIOInfo for UPDATE as
/* Wonderware UPDATE trigger on strgDDEIOInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  strgDDEIOInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE strgDDEIOInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_strgInfo on strgInfo for INSERT as
/* Wonderware INSERT trigger on strgInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  strgInfo ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT strgInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_strgInfo on strgInfo for UPDATE as
/* Wonderware UPDATE trigger on strgInfo */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB  strgInfo ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE strgInfo because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tI_UDTChildren on UDTChildren for INSERT as
/* Wonderware INSERT trigger on UDTChildren */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB R/42 UDTChildren ON CHILD INSERT RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30002,
             @errmsg = 'Cannot INSERT UDTChildren because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

create trigger tU_UDTChildren on UDTChildren for UPDATE as
/* Wonderware UPDATE trigger on UDTChildren */
begin
  declare  @numrows int,
           @nullcnt int,
           @validcnt int,
           @insdbHnd int, 
           @insNodeKey int,
           @errno   int,
           @errmsg  varchar(255)

  select @numrows = @@rowcount
  /* Wonderware InTouchDB R/42 UDTChildren ON CHILD UPDATE RESTRICT */
  if
    /* update(dbHnd) or
       update(NodeKey) */
    update(dbHnd) or
    update(NodeKey)
  begin
    select @nullcnt = 0
    select @validcnt = count(*)
      from inserted,InTouchDB
        where
          /* inserted.dbHnd = InTouchDB.dbHnd and
             inserted.NodeKey = InTouchDB.NodeKey */
          inserted.dbHnd = InTouchDB.dbHnd and
          inserted.NodeKey = InTouchDB.NodeKey
    /*  */
    
    if @validcnt + @nullcnt != @numrows
    begin
      select @errno  = 30007,
             @errmsg = 'Cannot UPDATE UDTChildren because InTouchDB does not exist.'
      goto error
    end
  end


  return
error:
    raiserror @errno @errmsg
    rollback transaction
end
go

