/*-------------------------------------------------------------------------*/
/*  Add InSQL legacy support to a Historian Runtime database.              */
/*  This script is designed to be run against an existing Runtime          */
/*  database created using the generic Runtime build script.               */
/*                                                                         */
/*-------------------------------------------------------------------------*/


set QUOTED_IDENTIFIER OFF
set NOCOUNT ON
go

use master
go


/* Add INSQLD linked server for compatibility with Wonderware InSQL 7.1 */
/* ==================================================================== */

if exists (select * from master.dbo.sysservers where srvname = 'INSQLD')
  BEGIN
     exec sp_dropserver 'INSQLD', 'droplogins'
  END
go
sp_addlinkedserver 
        @server = 'INSQLD', 
        @srvproduct = '',
        @provider = 'INSQL'
go
sp_addlinkedsrvlogin 'INSQLD','TRUE',NULL,NULL,NULL
go

sp_serveroption INSQLD, 'collation compatible', TRUE
go



/* Add the ww* database roles and users for compatibility with Wonderware InSQL 7.x, 8.0 */
/* ===================================================================================== */

use master
go

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

use Runtime
go

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


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

use master
go

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

if (not exists (select name from syslogins where name = '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 SQL Server logins */

use master
go

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

use Runtime
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 Runtime */
if (not exists (select name from sysusers where name = 'wwdbo'))
begin
  exec sp_adduser wwdbo, wwdbo, db_owner
end
go

exec sp_defaultdb wwdbo, Runtime
go


/* Add v_ views referencing the INSQL and INSQLD linked servers for compatibility with Wonderware InSQL 7.1 */
/* ======================================================================================================== */

use Runtime
go


if exists (select name from sysobjects where name = 'v_AnalogHistory')
   BEGIN
      drop view v_AnalogHistory
   END
GO
CREATE VIEW v_AnalogHistory
AS
   SELECT * FROM INSQL.Runtime.dbo.AnalogHistory
go
GRANT SELECT ON v_AnalogHistory TO PUBLIC
GRANT INSERT, UPDATE on v_AnalogHistory TO aaAdministrators, aaPowerUsers
go

if exists (select name from sysobjects where name = 'v_AnalogLive')
   BEGIN
      drop view v_AnalogLive
   END
GO
CREATE VIEW v_AnalogLive AS
SELECT * FROM INSQL.Runtime.dbo.AnalogLive
go
GRANT SELECT ON v_AnalogLive TO PUBLIC
GRANT INSERT, UPDATE on v_AnalogLive TO aaAdministrators, aaPowerUsers
go

if exists (select name from sysobjects where name = 'v_DiscreteHistory')
   BEGIN
      drop view v_DiscreteHistory
   END
GO
CREATE VIEW v_DiscreteHistory AS
SELECT * FROM INSQLD.Runtime.dbo.DiscreteHistory
go
GRANT SELECT ON v_DiscreteHistory TO PUBLIC
GRANT INSERT, UPDATE on v_DiscreteHistory TO aaAdministrators, aaPowerUsers
go

if exists (select name from sysobjects where name = 'v_DiscreteLive')
   BEGIN
      drop view v_DiscreteLive
   END
GO
CREATE VIEW v_DiscreteLive AS
SELECT * FROM INSQLD.Runtime.dbo.DiscreteLive
go
GRANT SELECT ON v_DiscreteLive TO PUBLIC
GRANT INSERT, UPDATE on v_DiscreteLive TO aaAdministrators, aaPowerUsers
go

if exists (select name from sysobjects where name = 'v_StringHistory')
   BEGIN
      drop view v_StringHistory
   END
GO
CREATE VIEW v_StringHistory AS
SELECT * FROM INSQL.Runtime.dbo.StringHistory
go
GRANT SELECT ON v_StringHistory TO PUBLIC
GRANT INSERT, UPDATE on v_StringHistory TO aaAdministrators, aaPowerUsers
go

if exists (select name from sysobjects where name = 'v_StringLive')
   BEGIN
      drop view v_StringLive
   END
GO
CREATE VIEW v_StringLive AS
SELECT * FROM INSQL.Runtime.dbo.StringLive
go
GRANT SELECT ON v_StringLive TO PUBLIC
GRANT INSERT, UPDATE on v_StringLive TO aaAdministrators, aaPowerUsers
go


if exists (select name from sysobjects where name = 'v_History')
   BEGIN
      drop view v_History
   END
GO
CREATE VIEW v_History AS
SELECT * FROM INSQL.Runtime.dbo.History
go
GRANT SELECT ON v_History TO PUBLIC
GRANT INSERT, UPDATE on v_History TO aaAdministrators, aaPowerUsers

go
if exists (select name from sysobjects where name = 'v_Live')
   BEGIN
      drop view v_Live
   END
GO
CREATE VIEW v_Live AS
SELECT * FROM INSQL.Runtime.dbo.Live
go
GRANT SELECT ON v_Live TO PUBLIC
GRANT INSERT, UPDATE on v_Live TO aaAdministrators, aaPowerUsers
go


if exists (select name from sysobjects where name = 'v_HistoryBlock')
   BEGIN
      drop view v_HistoryBlock
   END
GO
CREATE VIEW v_HistoryBlock AS
SELECT * FROM INSQL.Runtime.dbo.HistoryBlock
go
GRANT SELECT ON v_HistoryBlock TO PUBLIC
go



/* Legacy ww_ stored procedures */
/* ============================ */

use Runtime
go


 /**********  ww_ActionStringSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.ww_ActionStringSelect'))
  DROP PROCEDURE dbo.ww_ActionStringSelect
GO

CREATE PROCEDURE ww_ActionStringSelect
  @TagName nvarchar(256)
AS
  EXEC aaActionStringSelect
    @TagName
GO

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

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

  EXEC @retInt = aaAddTag 
    @wTagName,
    @wTopicKey,
    @wIOServerKey,
    @wStorageNodeKey,
    @wDescription,
    @wAcquisitionType,
    @wStorageType,
    @wAcquisitionRate,
    @wStorageRate,
    @wItemName,
    @wTagType,
    @wTimeDeadband,
    @wCurrentEditor           

  RETURN @retInt
GO

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

CREATE procedure ww_AnalogDetail 
  @TagList nvarchar(4000)
AS
  EXEC aaAnalogDetail
    @TagList
GO

GRANT Execute on ww_AnalogDetail to Public
go
 
 /* The ww_AnalogTag* stored procs are implemented in their entirety here, since the AnalogTag
    table schema has changed, and along with it, the AnalogTag* stored procs. */
 /**********  ww_AnalogTagDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.ww_AnalogTagDelete'))
  DROP PROCEDURE dbo.ww_AnalogTagDelete
GO

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

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

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

  DECLARE @result int

  SELECT @result = 0

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

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

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

  RETURN @result
END
GO

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

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

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

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

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

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

  COMMIT TRAN
END
GO

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

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

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

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

  Execute (@SelectStatement)
GO

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

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

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

CREATE PROCEDURE ww_AnnotationInsert 
  @TagName       nvarchar(256),
  @UserKey       int = NULL,
  @DateTime      datetime = NULL,
  @DateCreated   datetime = NULL,
  @Content       ntext = NULL,
  @Value         real = 0.0
AS
INSERT INTO Annotation
  (  TagName,
  UserKey,
  DateTime,
  DateCreated,
  Content,
  Value
  )
VALUES
  (
  @TagName,
  User_ID(),
  @DateTime,
  GetDate(),
  @Content,
  @Value
  )

RETURN  SCOPE_IDENTITY()
GO

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

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

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

CREATE PROCEDURE ww_AnnotationUpdate 
  @AnnotationKey int,
  @TagName       nvarchar(256),
  @UserKey       int,
  @DateTime      datetime,
  @DateCreated   datetime,
  @Content       ntext,
  @Value         real
AS
UPDATE Annotation
SET
  TagName = @TagName,
  UserKey = User_ID(),
  DateTime = @DateTime,
  DateCreated = GetDate(),
  Content = @Content,
  Value = @Value
WHERE  AnnotationKey = @AnnotationKey
GO

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

CREATE PROCEDURE ww_CheckClientVersion
  @AppName nvarchar(255) = '',
  @AppVersion nvarchar(255) = ''
AS
  RETURN 0
GO

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

CREATE PROCEDURE ww_CheckWhichDb
  @dbType int
AS
  /*  This procedure checks that one is in the appropriate database  */
  /*  1=Runtime     */
  /*  2=Holding     */
  /*  3=Development */

  DECLARE @ThisdbType int
  DECLARE @dbStatus int
  SELECT @dbStatus = 0

  IF @dbType = 1  
    BEGIN
      /* This is the correct data base, test the consistency */
      SELECT @dbStatus = 0
    END
  ELSE
    BEGIN
      /* The user wants to be in another data base */
      /* Show an error message and return error status */
      RETURN 1
    END

  RETURN @dbStatus
GO

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

CREATE procedure ww_CleanupAfterCommit 
AS
  EXEC aaCleanupAfterCommit
GO

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

CREATE procedure ww_CommitChanges 
AS
  EXEC aaCommitChanges
GO

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

CREATE procedure ww_CommitChangesAtStartup 
AS
  EXEC aaCommitChangesAtStartup
GO

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

CREATE procedure ww_ContextDelete
  @ContextKey     int 
AS
  EXEC aaContextDelete
    @ContextKey
GO

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

CREATE procedure ww_ContextInsert
  @Description     nvarchar(50) = NULL 
AS
  EXEC aaContextInsert
    @Description
GO

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

CREATE procedure ww_ContextSelect
  @ContextKey    int = NULL 
AS
  EXEC aaContextSelect
    @ContextKey
GO

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

CREATE procedure ww_ContextUpdate
  @ContextKey    int,
  @Description nvarchar(50)
AS
  EXEC aaContextUpdate
    @ContextKey,
    @Description
GO

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

CREATE procedure ww_DBChangesPending 
AS
  EXEC aaDBChangesPending
GO

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

CREATE PROCEDURE ww_DBConfig
AS
  EXEC aaDBConfig
GO

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

CREATE PROCEDURE ww_DeleteOlderEvents
AS 
  EXEC aaDeleteOlderEvents
GO

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

CREATE PROCEDURE ww_DeleteOlderSummaries
AS 
  EXEC aaDeleteOlderSummaries
GO

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

CREATE procedure ww_DeleteTag 
  @TagName         nvarchar(256) 
AS
  EXEC aaDeleteTag
    @TagName
GO

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

CREATE PROCEDURE ww_DetectorStringSelect
  @TagName nvarchar(256)
AS
  EXEC aaDetectorStringSelect
    @TagName
GO

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

CREATE procedure ww_DiscreteDetail
  @TagList nvarchar(4000)
AS
  EXEC aaDiscreteDetail
    @TagList
GO

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

CREATE procedure ww_DiscreteTagDelete 
  @wwTagKey int
AS
  EXEC aaDiscreteTagDelete
    @wwTagKey
GO

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

CREATE PROCEDURE ww_DiscreteTagInsert 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @AcquisitionType tinyint      = 1,
  @StorageType     smallint     = 2,
  @StorageRate     int          = 0,
  @ItemName        nvarchar(256) = '',
  @TimeDeadband    int          = 0,
  @CreatedBy       nvarchar(30) = '',
  @DateCreated     datetime     = NULL,
  @CurrentEditor   int          = 0,
  @MessageKey      int          = 1,
  @InitialValue    tinyint      = 0,
  @TopicKey        int          = NULL,
  @IOServerKey     int          = NULL,
  @AIRetrievalMode  tinyint     = 0,
  @SamplesInActiveImage  int   = 0
AS
  DECLARE @retInt int

  EXEC @retInt = aaDiscreteTagInsert
    @TagName         ,
    @Description     ,
    @AcquisitionType ,
    @StorageType     ,
    @StorageRate     ,
    @ItemName        ,
    @TimeDeadband    ,
    @CreatedBy       ,
    @DateCreated     ,
    @CurrentEditor   ,
    @MessageKey      ,
    @InitialValue    ,
    @TopicKey        ,
    @IOServerKey     ,
    @AIRetrievalMode ,
    @SamplesInActiveImage

  RETURN @retInt
GO

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

CREATE procedure ww_DiscreteTagSelect 
  @wwTagKey int = NULL
AS
  EXEC aaDiscreteTagSelect
    @wwTagKey
GO

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

CREATE procedure ww_DiscreteTagUpdate 
  @wwTagKey        int, 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @AcquisitionType tinyint = 1,
  @StorageType     smallint,
  @StorageRate     int,
  @ItemName        nvarchar(256) = '',
  @TimeDeadband    int,
  @CreatedBy       nvarchar(30) = '',
  @DateCreated     datetime = NULL,
  @CurrentEditor   int,
  @MessageKey      int,
  @InitialValue    tinyint,
  @TopicKey        int,
  @IOServerKey     int,
  @AIRetrievalMode tinyint,
  @SamplesInActiveImage int = 0
AS
  EXEC aaDiscreteTagUpdate
    @wwTagKey        , 
    @TagName         ,
    @Description     ,
    @AcquisitionType ,
    @StorageType     ,
    @StorageRate     ,
    @ItemName        ,
    @TimeDeadband    ,
    @CreatedBy       ,
    @DateCreated     ,
    @CurrentEditor   ,
    @MessageKey      ,
    @InitialValue    ,
    @TopicKey        ,
    @IOServerKey     ,
    @AIRetrievalMode ,
    @SamplesInActiveImage
GO

GRANT exec on ww_DiscreteTagUpdate TO aaAdministrators
go
GRANT exec on ww_DiscreteTagUpdate TO aaPowerUsers
go

 /**********  ww_EngineeringUnitDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.ww_EngineeringUnitDelete'))
  DROP PROCEDURE dbo.ww_EngineeringUnitDelete
GO

CREATE PROCEDURE ww_EngineeringUnitDelete 
  @EUKey int
AS
  EXEC aaEngineeringUnitDelete
    @EUKey
GO

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

CREATE PROCEDURE ww_EngineeringUnitInsert 
  @Unit nvarchar(32),
  @DefaultTagRate int = 10000
AS 
  DECLARE @retInt int

  EXEC @retInt = aaEngineeringUnitInsert
    @Unit ,
    @DefaultTagRate

  RETURN @retInt
GO

GRANT  EXECUTE  ON ww_EngineeringUnitInsert  TO aaAdministrators
GO
GRANT  EXECUTE  ON ww_EngineeringUnitInsert  TO aaPowerUsers
go
 
 /* ww_EngineeringUnitSelect is implemented here for legacy support, since the
    new EngineeringUnit table schema has an additional column. */
 /**********  ww_EngineeringUnitSelect  **********/
if exists (select * from sysobjects where id = object_id('dbo.ww_EngineeringUnitSelect'))
  DROP PROCEDURE dbo.ww_EngineeringUnitSelect
GO

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

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

CREATE PROCEDURE ww_EngineeringUnitUpdate 
  @EUKey int,
  @Unit nvarchar(32),
  @DefaultTagRate int
AS
  EXEC aaEngineeringUnitUpdate 
    @EUKey,
    @Unit,
    @DefaultTagRate
GO

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

CREATE procedure ww_EventDetection 
  @TagName nvarchar(256),
  @Operator char(2),
  @DetectValue float(25),
  @Edge char(8),
  @Resolution int,
  @StartTime varchar(30),
  @EndTime varchar(30)
AS
  EXEC aaEventDetection 
    @TagName,
    @Operator,
    @DetectValue,
    @Edge,
    @Resolution,
    @StartTime,
    @EndTime
GO

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

CREATE procedure ww_EventHistory 
  @TagList nvarchar(4000),
  @StartTime nvarchar(50),
  @EndTime nvarchar(50)
AS
  EXEC aaEventHistorySelect
    @TagList,
    @StartTime,
    @EndTime
GO

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

CREATE procedure ww_EventHistoryInsert 
  @TagName          nvarchar(256),
  @DateTime         datetime,
  @DetectDateTime   datetime,
  @Edge int
AS
  DECLARE @retInt int

  EXEC @retInt = aaEventHistoryInsert
    @TagName       ,
    @DateTime      ,
    @DetectDateTime,
    @Edge

  -- RETURN @retInt
  select @retInt
GO

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

CREATE PROCEDURE ww_EventSnapshot 
  @TagList nvarchar(4000),
  @StartTime nvarchar(50),
  @EndTime nvarchar(50),
  @OrderBy nvarchar(2000)='Event'
AS
  EXEC aaEventSnapshotSelect
    @TagList,
    @StartTime,
    @EndTime,
    @OrderBy
GO

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

CREATE procedure ww_EventSnapshotInsert 
  @EventLogKey int,
  @EventTime datetime,
  @EventTagName nvarchar(256)
AS
  EXEC aaEventSnapshotInsert 
    @EventLogKey,
    @EventTime,
    @EventTagName
GO

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

CREATE procedure ww_EventTagDelete 
  @wwTagKey int
AS
  EXEC aaEventTagDelete 
    @wwTagKey
GO

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

CREATE procedure ww_EventTagDetail 
  @TagList nvarchar(4000)  = '%'
AS
  EXEC aaEventTagDetail 
    @TagList
GO

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

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

  EXEC @retInt = aaEventTagInsert 
    @TagName           ,
    @Description       ,
    @CreatedBy         ,
    @DateCreated       ,
    @CurrentEditor     ,
    @ScanRate          ,
    @TimeDeadband      ,
    @Logged            ,
    @Status            ,
    @PostDetectorDelay ,
    @UseThreadPool     ,
    @DetectorTypeKey   ,
    @DetectorString    ,
    @ActionTypeKey     ,
    @ActionString      ,
    @Priority          ,
    @Edge

  RETURN @retInt
GO

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

CREATE procedure ww_EventTagSelect 
  @wwTagKey int = NULL
AS
  EXEC aaEventTagSelect 
    @wwTagKey
GO

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

CREATE PROCEDURE ww_EventTagSelectAll
AS
  EXEC aaEventTagSelectAll
GO

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

CREATE PROCEDURE ww_EventTagSelectDeleted
AS
  EXEC aaEventTagSelectDeleted
GO

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

CREATE PROCEDURE ww_EventTagSelectDisabled
AS
  EXEC aaEventTagSelectDisabled
GO

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

CREATE PROCEDURE ww_EventTagSelectInserted
AS
  EXEC aaEventTagSelectInserted
GO

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

CREATE PROCEDURE ww_EventTagSelectUpdated
AS
  EXEC aaEventTagSelectUpdated
GO

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

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

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

CREATE procedure ww_GetDbRevision 
AS
  EXEC aaGetDbRevision
GO

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

CREATE procedure ww_GetLastTagKey 
  @TagType int
AS
  DECLARE @retInt int

  EXEC @retInt = aaGetLastTagKey
    @TagType

  RETURN @retInt
GO

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

CREATE procedure ww_HistoryBlockSelect 
  @fromdate datetime = NULL,
  @todate  datetime = NULL
AS
  EXEC aaHistoryBlockSelect
    @fromdate,
    @todate
GO

GRANT exec on ww_HistoryBlockSelect to Public
GO
 
 /* The ww_IODriver* stored procs are implemented in their entirety here, since the IODriver
    table schema has changed, and along with it, the IODriver* stored procs. */
 /**********  ww_IODriverDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.ww_IODriverDelete'))
  DROP PROCEDURE dbo.ww_IODriverDelete
GO

CREATE procedure ww_IODriverDelete 
  @IODriverKey int
AS
  DECLARE @Result int

  DELETE FROM IODriver
  WHERE  IODriverKey = @IODriverKey

if @@ERROR <> 0
begin
   goto error
end

return

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

  raiserror @errno @errmsg 
GO

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

CREATE PROCEDURE ww_IODriverInsert 
  @StorageNodeKey                 int = 1,
  @ComputerName                   nvarchar(255) = @@SERVERNAME,
  @StoreForwardMode               tinyint = 0,
  @StoreForwardPath               nvarchar(255) = '', 
  @MinMBThreshold                 int = 16,
  @AltComputerName                nvarchar(255) = ''
AS
BEGIN
  DECLARE @result int

  INSERT INTO IODriver
   (
   StorageNodeKey,
   ComputerName,
   StoreForwardMode,
   StoreForwardPath,
   MinMBThreshold,
   AltComputerName
   )
  VALUES
   (
   1,
   @ComputerName,
   @StoreForwardMode,
   @StoreForwardPath, 
   @MinMBThreshold,
   @AltComputerName
   )

   if @@ERROR <> 0
   begin
      goto error
   end

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

   return @result

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

     raiserror @errno @errmsg 
END

GO

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

CREATE procedure ww_IODriverSelect 
  @IODriverKey int = NULL
AS
IF @IODriverKey IS NULL 
BEGIN 
   SELECT IODriverKey,
          StorageNodeKey,
          ComputerName,
          StoreForwardMode,
          StoreForwardPath,
          MinMBThreshold,
          AltComputerName
   FROM   IODriver
END
ELSE
BEGIN
   SELECT IODriverKey,
          StorageNodeKey,
          ComputerName,
          StoreForwardMode,
          StoreForwardPath,
          MinMBThreshold,
          AltComputerName
   FROM   IODriver
   WHERE  IODriverKey = @IODriverKey
END

if @@ERROR <> 0
begin
   goto error
end

return

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

  raiserror @errno @errmsg 

GO

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

CREATE procedure ww_IODriverUpdate 
  @IODriverKey           int,
  @StorageNodeKey        int = 1,
  @ComputerName       nvarchar(255),
  @StoreForwardMode           tinyint,
  @StoreForwardPath             nvarchar(255),
  @MinMBThreshold          int = 16,
  @AltComputerName       nvarchar(255)
AS
UPDATE IODriver
SET
 ComputerName  = @ComputerName,
 StoreForwardMode  = @StoreForwardMode,
 StoreForwardPath = @StoreForwardPath,
 MinMBThreshold = @MinMBThreshold,
 AltComputerName = @AltComputerName
WHERE  IODriverKey = @IODriverKey

if @@ERROR <> 0
begin
   goto error
end

return

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

  raiserror @errno @errmsg 

GO

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

CREATE procedure ww_IOServerDelete 
  @IOServerKey int
AS
  EXEC aaIOServerDelete 
    @IOServerKey
GO

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

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

  EXEC @retInt = aaIOServerInsert
    @StorageNodeKey        ,
    @ApplicationName       ,
    @Description           ,
    @Path                  , 
    @ComputerName          ,
    @AutoStart             ,
    @ExeType               ,
    @InitializationStatus  ,
    @ProtocolType          ,
    @AltComputerName       ,
    @IODriverKey

  RETURN @retInt
GO

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

CREATE procedure ww_IOServerSelect 
  @IOServerKey int = NULL
AS
  EXEC aaIOServerSelect 
    @IOServerKey
GO

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

CREATE procedure ww_IOServerTypeDelete 
  @ApplicationName   nvarchar(32)
AS
  EXEC aaIOServerTypeDelete 
    @ApplicationName
GO

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

CREATE PROCEDURE ww_IOServerTypeInsert 
  @ApplicationName       nvarchar(32),
  @Description           nvarchar(50) = NULL,
  @ExeName                  nvarchar(255) = NULL, 
  @Revision          nchar(20) = NULL,
  @Platform             nchar(20) = NULL
AS
  EXEC aaIOServerTypeInsert 
    @ApplicationName   ,
    @Description       ,
    @ExeName           , 
    @Revision          ,
    @Platform
GO

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

CREATE procedure ww_IOServerTypeSelect 
  @ApplicationName nvarchar(32) = NULL
AS
  EXEC aaIOServerTypeSelect 
    @ApplicationName
GO

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

CREATE procedure ww_IOServerTypeUpdate 
  @ApplicationName       nvarchar(32),
  @Description           nvarchar(50),
  @ExeName             nvarchar(255),
  @Revision          nchar(20),
  @Platform           nchar(20)
AS
  EXEC aaIOServerTypeUpdate 
    @ApplicationName,
    @Description    ,
    @ExeName        ,
    @Revision       ,
    @Platform
GO

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

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

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

CREATE PROCEDURE ww_InSQLConfigNSExpand 
  @PKey int
AS
  EXEC aaHistorianConfigNSExpand 
    @PKey
GO

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

CREATE PROCEDURE ww_InSQLNSExpand 
  @PKey int
AS
  EXEC aaHistorianNSExpand 
    @PKey
GO

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

CREATE procedure ww_InSQLStatusSelect 
AS
  EXEC aaHistorianStatusSelect
GO

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

CREATE procedure ww_InSQLStatusSet 
  @DbStatus  int,
  @Acquisition int = 0,
  @Storage int = 0,
  @DBServer int = 0
AS
  EXEC aaHistorianStatusSet 
    @DbStatus,
    @Acquisition,
    @Storage,
    @DBServer
GO

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

CREATE procedure ww_InTouchNodeTagList 
  @nodekey int = NULL,
  @FilterStr nvarchar(100) = N'%'
AS
  EXEC aaInTouchNodeTagList
    @nodekey,
    @FilterStr
GO

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

CREATE procedure ww_LimitDelete
  @TagName   nvarchar(256),
  @ContextKey   int,
  @LimitNameKey   int 
AS
  EXEC aaLimitDelete
    @TagName,
    @ContextKey,
    @LimitNameKey
GO

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

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

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

CREATE procedure ww_LimitNameDelete
  @LimitNameKey     int 
AS
  EXEC aaLimitNameDelete
    @LimitNameKey
GO

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

CREATE procedure ww_LimitNameInsert
  @Name    nvarchar(20) = ''
AS
  DECLARE @retInt int

  EXEC @retInt = aaLimitNameInsert
    @Name

  RETURN @retInt
GO

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

CREATE procedure ww_LimitNameSelect
  @LimitNameKey    int = NULL 
AS
  EXEC aaLimitNameSelect
    @LimitNameKey
GO

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

CREATE procedure ww_LimitNameUpdate
  @LimitNameKey    int,
  @Name nvarchar(20)
AS
  EXEC aaLimitNameUpdate
    @LimitNameKey,
    @Name
GO

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

CREATE procedure ww_LimitSelect
  @TagName   nvarchar(256) = NULL 
AS
  EXEC aaLimitSelect
    @TagName
GO

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

CREATE procedure ww_LimitUpdate
  @TagName         nvarchar(256),
  @ContextKey      int,
  @LimitType       int,
  @Value           real,
  @LimitNameKey    int,
  @Priority        int,
  @Checked         bit,
  @Description     nvarchar(50) = NULL 
AS
  EXEC aaLimitUpdate
    @TagName      ,
    @ContextKey   ,
    @LimitType    ,
    @Value        ,
    @LimitNameKey ,
    @Priority     ,
    @Checked      ,
    @Description
GO

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

CREATE procedure ww_LoadInSQLProcedureBody 
  @objname varchar(92)
AS
  declare @dbname varchar(30)

  set nocount on

  select text from syscomments where id = object_id(@objname)

  return (0)
GO

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

CREATE PROCEDURE ww_MessageDelete 
  @MessageKey int
AS
  EXEC aaMessageDelete 
    @MessageKey
GO

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

CREATE PROCEDURE ww_MessageInsert 
  @Message0 nvarchar(15) = NULL,
  @Message1 nvarchar(15) = NULL
AS
  DECLARE @retInt int

  EXEC @retInt = aaMessageInsert
    @Message0,
    @Message1

  RETURN @retInt
GO

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

CREATE PROCEDURE ww_MessageSelect 
  @MessageKey int = NULL
AS
  EXEC aaMessageSelect 
    @MessageKey
GO

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

CREATE PROCEDURE ww_MessageUpdate 
  @MessageKey int,
  @Message0 nvarchar(15),
  @Message1 nvarchar(15)
AS
  EXEC aaMessageUpdate 
    @MessageKey,
    @Message0,
    @Message1
GO

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

CREATE procedure ww_ModLogStatus 
AS
  DECLARE @retInt int

  EXEC @retInt = aaModLogStatus
  RETURN @retInt
GO

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

CREATE PROCEDURE ww_PrivateNSAddGroup 
  @Name      nvarchar(255),
  @ParentKey int,
  @Type      int = 1000000
AS
  DECLARE @retInt int

  EXEC @retInt = aaPrivateNSAddGroup
    @Name,
    @ParentKey,
    @Type

  RETURN @retInt
GO

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

CREATE procedure ww_PrivateNSAddLeaf 
  @wwTagKey  int,
  @NameKey   int,
  @ServerKey int = 1
AS
  DECLARE @retInt int

  EXEC @retInt = aaPrivateNSAddLeaf 
    @wwTagKey,
    @NameKey,
    @ServerKey          

  RETURN @retInt
GO

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

CREATE PROCEDURE ww_PrivateNSDeleteGroup 
  @NameKey int
AS
  EXEC aaPrivateNSDeleteGroup 
    @NameKey
GO

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

CREATE PROCEDURE ww_PrivateNSDeleteLeaf 
  @NameKey  int,
  @wwTagKey int 
AS
  EXEC aaPrivateNSDeleteLeaf 
    @NameKey,
    @wwTagKey
GO

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

CREATE PROCEDURE ww_PrivateNSExpand
  @PKey      int,
  @FilterStr nvarchar(100) = NULL
AS
  EXEC aaPrivateNSExpand
    @PKey,
    @FilterStr
GO

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

CREATE PROCEDURE ww_PrivateNSSelect
AS
  EXEC aaPrivateNSSelect
GO

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

CREATE PROCEDURE ww_PrivateNSUpdateGroup 
  @NameKey int,
  @Name    nvarchar(255),
  @Type    int
AS 
  EXEC aaPrivateNSUpdateGroup 
    @NameKey,
    @Name,
    @Type
GO

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

CREATE procedure ww_PublicNSAddGroup 
  @Name      nvarchar(255),
  @ParentKey int,
  @Type      int = 1000000
AS
  DECLARE @retInt int

  EXEC @retInt = aaPublicNSAddGroup 
    @Name,
    @ParentKey,
    @Type           

  RETURN @retInt
GO

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

CREATE procedure ww_PublicNSAddLeaf 
  @wwTagKey  int,
  @NameKey   int,
  @ServerKey int = 1
AS
  DECLARE @retInt int

  EXEC @retInt = aaPublicNSAddLeaf 
    @wwTagKey,
    @NameKey,
    @ServerKey

  RETURN @retInt
GO

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

CREATE PROCEDURE ww_PublicNSDeleteGroup 
  @NameKey int
AS
  EXEC aaPublicNSDeleteGroup 
    @NameKey
GO

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

CREATE PROCEDURE ww_PublicNSDeleteLeaf  
  @NameKey int,
  @wwTagKey int 
AS
  EXEC aaPublicNSDeleteLeaf  
    @NameKey,
    @wwTagKey
GO

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

CREATE PROCEDURE ww_PublicNSExpand
  @PKey      int,
  @FilterStr nvarchar(100) = NULL
AS
  EXEC aaPublicNSExpand
    @PKey,
    @FilterStr
GO

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

CREATE PROCEDURE ww_PublicNSSelect
AS
  EXEC aaPublicNSSelect
GO

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

CREATE PROCEDURE ww_PublicNSUpdateGroup 
  @NameKey int,
  @Name  nvarchar(255),
  @Type int
AS
  EXEC aaPublicNSUpdateGroup 
    @NameKey,
    @Name,
    @Type
GO

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

CREATE PROCEDURE ww_RedirectToInTouch
  @IOServerKey int,
  @InTouchNodeKey int
AS
  EXEC aaRedirectToInTouch
    @IOServerKey,
    @InTouchNodeKey
GO

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

CREATE procedure ww_SetAISamples 
  @TagName nvarchar(256),
  @Samples int
AS
  EXEC aaSetAISamples 
    @TagName,
    @Samples
GO

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

CREATE procedure ww_SetCalculatedAISamples 
/* Internal Historian Stored Procedure, do not run manually */
AS
  EXEC aaSetCalculatedAISamples
GO

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

CREATE procedure ww_UpdateCalculatedAISamples 
  @tagkey int,
  @samples int
/* Internal Historian Stored Procedure, do not run manually */
AS
  EXEC aaUpdateCalculatedAISamples 
    @tagkey,
    @samples
GO

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

CREATE PROCEDURE ww_SetStorageRule 
  @type        tinyint,
  @key         int,
  @storagetype tinyint,
  @storagerate int = 0, 
  @timedb      int = 0,
  @valuedb     real = 0,
  @acqtype     tinyint = 1
AS
BEGIN
   /* This stored procedure is used by the configuration editor to set storage rules */
   /*  from various levels of the tag definition.  Parameters are                    */
   /*   @type: 1 = IOServer, 2 = Topic                                               */
   /*   @key: The IDENTITY key of the relevant type                                  */
   /*   @storagetype: 0 = no storage, 1 = cyclic, 2 = delta                          */
   /*   @storagerate: value of cyclic storage rate in seconds                        */
   /*   @timedb:  delta storage time deadband in milliseconds                        */
   /*   @valuedb: delta storage value deadband in percent                            */
   /*   @acqtype: 1 = acquisition on, 0 = acquisition off                            */
   /*    -1 means ignore                                                             */

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

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

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

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

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

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

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

   return 

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

     raiserror @errno @errmsg 
END

GO

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

CREATE PROCEDURE ww_SetTagStorage 
  @type tinyint,
  @list nvarchar(4000),
  @set  varchar(3)
AS
  EXEC aaSetTagStorage 
    @type,
    @list,
    @set
GO

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

CREATE procedure ww_SnapToSummary 
  @opkey int,
  @start datetime,
  @end datetime,
  @datestamp smalldatetime
AS
  EXEC aaSnapToSummary 
    @opkey,
    @start,
    @end,
    @datestamp
GO

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

CREATE procedure ww_SnapshotDetailSelect 
  @storagesize int = NULL
AS
  DECLARE @retInt int

  EXEC @retInt = aaSnapshotDetailSelect 
    @storagesize

  RETURN @retInt
GO

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

CREATE procedure ww_SnapshotDetailUpdate 
  @storagesize int,
  @snapshotsize int,
  @imagetime int,
  @thresholdtime int
AS
  EXEC aaSnapshotDetailUpdate 
    @storagesize,
    @snapshotsize,
    @imagetime,
    @thresholdtime
GO

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

CREATE PROCEDURE ww_SpaceManager
AS
   EXEC aaSpaceManager
GO

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

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

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

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

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

CREATE procedure ww_StringDetail 
  @TagList nvarchar(4000)
AS
  EXEC aaStringDetail 
    @TagList
GO

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

CREATE procedure ww_StringTagDelete 
  @wwTagKey int = NULL
AS
  EXEC aaStringTagDelete 
    @wwTagKey
GO

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

CREATE procedure ww_StringTagInsert 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @AcquisitionType tinyint = 1,
  @StorageType     smallint = 2,
  @StorageRate     int = 10000,
  @ItemName        nvarchar(256) = '',
  @TimeDeadband    int = 0,
  @CreatedBy       nvarchar(30) = '',
  @DateCreated     datetime = NULL,
  @MaxLength       smallint = 131,
  @InitialValue    nvarchar(512) = '',
  @TopicKey        int = NULL,
  @IOServerKey     int = NULL,
  @CurrentEditor   int = 0 ,
  @DoubleByte tinyint = 0,
  @SamplesInActiveImage int  = 0
AS
  DECLARE @retInt int

  EXEC @retInt = aaStringTagInsert 
    @TagName         ,
    @Description     ,
    @AcquisitionType ,
    @StorageType     ,
    @StorageRate     ,
    @ItemName        ,
    @TimeDeadband    ,
    @CreatedBy       ,
    @DateCreated     ,
    @MaxLength       ,
    @InitialValue    ,
    @TopicKey        ,
    @IOServerKey     ,
    @CurrentEditor   ,
    @DoubleByte      ,
    @SamplesInActiveImage           

  RETURN @retInt
GO

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

CREATE procedure ww_StringTagSelect 
  @wwTagKey int = NULL
AS
  EXEC aaStringTagSelect
    @wwTagKey
GO

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

CREATE procedure ww_StringTagUpdate 
  @wwTagKey        int,
  @TagName         nvarchar(256),
  @Description     nvarchar(512),
  @AcquisitionType tinyint = 1,
  @StorageType     smallint = 2,
  @StorageRate     int,
  @ItemName        nvarchar(256),
  @TimeDeadband    int,
  @CreatedBy       nvarchar(30) = '',
  @DateCreated     datetime = NULL,
  @MaxLength       smallint = 131,
  @InitialValue    nvarchar(512),
  @TopicKey        int,
  @IOServerKey     int,
  @CurrentEditor   int,
  @DoubleByte tinyint = 0,
  @SamplesInActiveImage int = 0 
AS
  EXEC aaStringTagUpdate 
    @wwTagKey        ,
    @TagName         ,
    @Description     ,
    @AcquisitionType ,
    @StorageType     ,
    @StorageRate     ,
    @ItemName        ,
    @TimeDeadband    ,
    @CreatedBy       ,
    @DateCreated     ,
    @MaxLength       ,
    @InitialValue    ,
    @TopicKey        ,
    @IOServerKey     ,
    @CurrentEditor   ,
    @DoubleByte      ,
    @SamplesInActiveImage
GO

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

CREATE procedure ww_SummaryActionInsert 
  @EventTagName nvarchar(256),
  @SumDateTime datetime
AS
  EXEC aaSummaryActionInsert 
    @EventTagName,
    @SumDateTime
GO

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

CREATE procedure ww_SummaryDetail 
  @TagList nvarchar(4000),
  @StartTime nvarchar(50),
  @EndTime nvarchar(50),
  @Orderby nvarchar(500) = 'TagName'
AS
  EXEC aaSummaryDetail 
    @TagList,
    @StartTime,
    @EndTime,
    @Orderby
GO

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

CREATE procedure ww_SummaryOperationDelete 
  @OperationKey int 
AS
  EXEC aaSummaryOperationDelete 
    @OperationKey
GO

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

CREATE procedure ww_SummaryOperationInsert 
  @TagName     nvarchar(256), 
  @CalcType    char(3), 
  @Duration    real,
  @Resolution  int,
  @TimeStamp   tinyint,
  @Description nvarchar(50) = NULL
AS
  DECLARE @retInt int

  EXEC @retInt = aaSummaryOperationInsert 
    @TagName    , 
    @CalcType   , 
    @Duration   ,
    @Resolution ,
    @TimeStamp  ,
    @Description

  RETURN @retInt
GO

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

CREATE procedure ww_SummaryOperationSelect 
  @EventTagName nvarchar(256) = NULL,
  @CalcType     char(3)      = NULL, 
  @Duration     real         = NULL,
  @Resolution   int          = NULL,
  @TimeStamp    tinyint      = NULL
AS
  EXEC aaSummaryOperationSelect 
    @EventTagName ,
    @CalcType     , 
    @Duration     ,
    @Resolution   ,
    @TimeStamp
GO

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

CREATE procedure ww_SummaryOperationUpdate 
  @OperationKey int,
  @TagName     nvarchar(256), 
  @CalcType    char(3), 
  @Duration    real,
  @Resolution  int,
  @TimeStamp   tinyint,
  @Description nvarchar(50) = NULL
AS
  EXEC aaSummaryOperationUpdate 
    @OperationKey,
    @TagName     , 
    @CalcType    , 
    @Duration    ,
    @Resolution  ,
    @TimeStamp   ,
    @Description
GO

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

CREATE procedure ww_SummaryTagListDelete 
  @SumVarKey int    
AS
  EXEC aaSummaryTagListDelete 
    @SumVarKey
GO

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

CREATE procedure ww_SummaryTagListInsert 
  @TagName      nvarchar(256),
  @OperationKey int,
  @LowerLimit   real        = NULL,
  @UpperLimit   real        = NULL,
  @Description  nvarchar(50) = NULL
AS
  DECLARE @retInt int

  EXEC @retInt = aaSummaryTagListInsert 
    @TagName     ,
    @OperationKey,
    @LowerLimit  ,
    @UpperLimit  ,
    @Description 

  RETURN @retInt
GO

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

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

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

CREATE procedure ww_SummaryTagListUpdate 
  @SumVarKey    int,
  @TagName      nvarchar(256),
  @OperationKey int,
  @LowerLimit   real        = NULL,
  @UpperLimit   real        = NULL,
  @Description  nvarchar(50) = NULL
AS
  EXEC aaSummaryTagListUpdate 
    @SumVarKey   ,
    @TagName     ,
    @OperationKey,
    @LowerLimit  ,
    @UpperLimit  ,
    @Description
GO

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

CREATE procedure ww_SystemConfigNSExpand
  @PKey  int, 
  @FKey1 int,
  @FKey2 int,
  @FKey3 int,
  @TokenType int,
  @FilterStr nvarchar(100) = NULL
AS
  EXEC aaSystemConfigNSExpand
    @PKey,
    @FKey1,
    @FKey2,
    @FKey3,
    @TokenType,
    @FilterStr
GO

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

CREATE procedure ww_SystemNSExpand
  @PKey  int, 
  @FKey1 int,
  @FKey2 int,
  @FKey3 int,
  @TokenType int,
  @FilterStr nvarchar(100) = NULL
AS
  EXEC aaSystemNSExpand
    @PKey,
    @FKey1,
    @FKey2,
    @FKey3,
    @TokenType,
    @FilterStr
GO

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

CREATE procedure ww_SystemNSExpand2
  @PKey      int,
  @FilterStr nvarchar(100) = NULL
AS
  EXEC aaSystemNSExpand2
    @PKey,
    @FilterStr
GO

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

CREATE procedure ww_SystemParameterSelect 
  @name nvarchar(50) = NULL
AS 
  DECLARE @retInt int

  EXEC @retInt = aaSystemParameterSelect 
    @name           

  RETURN @retInt
GO

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

CREATE procedure ww_SystemParameterUpdate 
  @name nvarchar(50),
  @value sql_variant,
  @description nvarchar(255) = NULL
AS
  EXEC aaSystemParameterUpdate 
    @name,
    @value,
    @description
GO

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

CREATE procedure ww_TagConfig 
AS
  EXEC aaTagConfig
GO

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

CREATE procedure ww_TagConfigModified 
AS
  EXEC aaTagConfigModified
GO

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

CREATE PROCEDURE ww_TagConfigSelect 
  @tagtype int,
  @key   int,
  @FilterStr nvarchar(100) = N'%'
AS
  EXEC aaTagConfigSelect 
    @tagtype,
    @key,
    @FilterStr
GO

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

CREATE procedure ww_TagInfo
  @TagList nvarchar(4000)
AS
  EXEC aaTagInfo
    @TagList
GO

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

CREATE procedure ww_TagType
  @TagList nvarchar(4000)
AS
  EXEC aaTagType
    @TagList
GO

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

CREATE procedure ww_TimeDetectorDetailInsert 
  @FrequencyID      int, 
  @TagName          nvarchar(256),
  @Periodicity      int,
  @StartDateTime    DateTime,
  @RunTimeDay       tinyint,
  @RunTimeHour      tinyint,
  @RunTimeMin       tinyint
AS
  DECLARE @retInt int

  EXEC @retInt = aaTimeDetectorDetailInsert 
    @FrequencyID  , 
    @TagName      ,
    @Periodicity  ,
    @StartDateTime,
    @RunTimeDay   ,
    @RunTimeHour  ,
    @RunTimeMin    

  RETURN @retInt
GO

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

CREATE procedure ww_TimeDetectorDetailSelect 
  @TagName nvarchar(256) = NULL
AS
  EXEC aaTimeDetectorDetailSelect 
    @TagName
GO

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

CREATE procedure ww_TimeDetectorDetailUpdate 
  @FrequencyID    int, 
  @TagName        nvarchar(256),
  @Periodicity    int,
  @StartDateTime  DateTime,
  @RunTimeDay     tinyint,
  @RunTimeHour    tinyint,
  @RunTimeMin     tinyint
AS
  DECLARE @retInt int

  EXEC @retInt = aaTimeDetectorDetailUpdate 
    @FrequencyID  , 
    @TagName      ,
    @Periodicity  ,
    @StartDateTime,
    @RunTimeDay   ,
    @RunTimeHour  ,
    @RunTimeMin      

  RETURN @retInt
GO

GRANT  EXECUTE  ON ww_TimeDetectorDetailUpdate  TO aaAdministrators
GO
GRANT  EXECUTE  ON ww_TimeDetectorDetailUpdate  TO aaPowerUsers
go
 
 /* The ww_Topic* stored procs are implemented in their entirety here, since the Topic
    table schema has changed, and along with it, the Topic* stored procs. */
 /**********  ww_TopicDelete  **********/
if exists (select * from sysobjects where id = object_id('dbo.ww_TopicDelete'))
  DROP PROCEDURE dbo.ww_TopicDelete
GO

CREATE procedure ww_TopicDelete 
  @TopicKey int
AS
  DELETE FROM Topic
    WHERE  TopicKey = @TopicKey
GO

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

CREATE procedure ww_TopicInsert 
  @StorageNodeKey int, 
  @IOServerKey    int, 
  @Name           nvarchar(80), 
  @TimeOut        int = 60000
AS 

BEGIN
  DECLARE @result int

  INSERT INTO Topic
    (
    IOServerKey, 
    StorageNodeKey, 
    Name, 
    TimeOut 
    )
  VALUES
    (
    @IOServerKey, 
    1, 
    @Name, 
    @TimeOut 
    )

   if @@ERROR <> 0
   begin
      goto error
   end

   /* Need to return the IODriverKey */
   /* @@IDENTITY cannot be used because of Insert trigger actions */
   set @result = (select TopicKey from Topic
                        where IOServerKey = @IOServerKey
                        and     Name = @Name)

   return @result

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

     raiserror @errno @errmsg 
END

GO

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

CREATE procedure ww_TopicSelect 
  @TopicKey int = NULL
AS
IF @TopicKey IS NULL 
BEGIN 
   SELECT TopicKey, StorageNodeKey, IOServerKey, Name, TimeOut
   FROM   Topic
END
ELSE
BEGIN
   SELECT TopicKey, StorageNodeKey, IOServerKey, Name, TimeOut    FROM   Topic
   WHERE  TopicKey = @TopicKey
END
GO

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

CREATE procedure ww_TopicUpdate 
  @TopicKey       int, 
  @StorageNodeKey int, 
  @IOServerKey    int, 
  @Name           nvarchar(80), 
  @TimeOut        int = 60000
AS 
BEGIN
  UPDATE Topic
  SET
    IOServerKey    = @IOServerKey,
    StorageNodeKey = 1, 
    Name           = @Name, 
    TimeOut        = @TimeOut
  WHERE TopicKey = @TopicKey

  RETURN @@Error
END
GO

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

CREATE procedure ww_UserAccessLevelSelect 
AS
  DECLARE @retInt int

  EXEC @retInt = aaUserAccessLevelSelect
  RETURN @retInt
GO

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

CREATE procedure ww_UserDetailUpdate 
AS
  EXEC aaUserDetailUpdate
GO

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

CREATE PROCEDURE ww_dbCheck
  @dbType int
AS 

/* This SP's function is to invalidate FS1000 clients */

  RAISERROR('This client application needs to be updated.',18,2) WITH SETERROR
  RETURN 1
GO

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

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

AS
  DECLARE @retInt int

  EXEC @retInt = aaInternalMDASAnalogTagInsert 
    @TagName         ,
    @Description     ,
    @StorageType     ,
    @StorageRate     ,
    @TimeDeadband    ,
    @CreatedBy       ,
    @DateCreated     ,
    @CurrentEditor   ,
    @Unit            ,
    @MinEU           ,
    @MaxEU           ,
    @MinRaw          ,
    @MaxRaw          ,
    @Scaling         ,
    @RawType         ,
    @ValueDeadband   ,
    @InitialValue    ,
    @IntegerSize     ,
    @SignedInteger   ,
    @StorageNodeKey  ,
    @AIRetrievalMode ,
    @SamplesInActiveImage

  RETURN @retInt
GO

GRANT exec on ww_MDASAnalogTagInsert to aaAdministrators
GO

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

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

GO

GRANT exec on ww_MDASAnalogTagUpdate to aaAdministrators
GO

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

CREATE procedure ww_MDASDiscreteTagInsert 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @TimeDeadband    int           = 0,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime      = NULL,
  @CurrentEditor   int           = 0,
  @Message0        nvarchar(64)  = 'OFF',
  @Message1        nvarchar(64)  = 'ON',
  @InitialValue    tinyint       = 0,
  @AIRetrievalMode tinyint       = 0,
  @SamplesInActiveImage int      = 0

AS
  DECLARE @retInt int

  EXEC @retInt = aaInternalMDASDiscreteTagInsert 
    @TagName         ,
    @Description     ,
    @TimeDeadband    ,
    @CreatedBy       ,
    @DateCreated     ,
    @CurrentEditor   ,
    @Message0        ,
    @Message1        ,
    @InitialValue    ,
    @AIRetrievalMode ,
    @SamplesInActiveImage

  RETURN @retInt
GO

GRANT exec on ww_MDASDiscreteTagInsert to aaAdministrators
GO

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

CREATE procedure ww_MDASDiscreteTagUpdate 
  @wwTagKey        int, 
  @Description     nvarchar(512) = '',
  @TimeDeadband    int = 0,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @CurrentEditor   int,
  @Message0        nvarchar(64) = 'OFF',
  @Message1        nvarchar(64) = 'ON',
  @InitialValue    tinyint = 0,
  @AIRetrievalMode tinyint = 0,
  @SamplesInActiveImage int  = 0
 
AS
  EXEC aaInternalMDASDiscreteTagUpdate
    @wwTagKey        ,
    @Description     ,
    @TimeDeadband    ,
    @CreatedBy       ,
    @DateCreated     ,
    @CurrentEditor   ,
    @Message0        ,
    @Message1        ,
    @InitialValue    ,
    @AIRetrievalMode ,
    @SamplesInActiveImage

GO

GRANT exec on ww_MDASDiscreteTagUpdate to aaAdministrators
GO

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

CREATE procedure ww_MDASStringTagInsert 
  @TagName         nvarchar(256),
  @Description     nvarchar(512) = '',
  @TimeDeadband    int           = 0,
  @CreatedBy       nvarchar(256)  = '',
  @DateCreated     datetime      = NULL,
  @MaxLength       smallint  = 131,
  @InitialValue    nvarchar(512)  = '',
  @CurrentEditor   int  = 0,
  @DoubleByte      tinyint = 0,
  @SamplesInActiveImage int = 0

AS
  DECLARE @retInt int

  EXEC @retInt = aaInternalMDASStringTagInsert 
    @TagName      ,
    @Description  ,
    @TimeDeadband ,
    @CreatedBy    ,
    @DateCreated  ,
    @MaxLength    ,
    @InitialValue ,
    @CurrentEditor,
    @DoubleByte   ,
    @SamplesInActiveImage

  RETURN @retInt
GO

GRANT exec on ww_MDASStringTagInsert to aaAdministrators
GO

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

CREATE procedure ww_MDASStringTagUpdate 
  @wwTagKey        int, 
  @Description     nvarchar(512) = '',
  @TimeDeadband    int = 0,
  @CreatedBy       nvarchar(256) = '',
  @DateCreated     datetime = NULL,
  @MaxLength       smallint = 131,
  @InitialValue    nvarchar(512) = '',
  @CurrentEditor   int,
  @DoubleByte      tinyint = 0,
  @SamplesInActiveImage int = 0
 
AS
  EXEC aaInternalMDASStringTagUpdate
    @wwTagKey     ,
    @Description  ,
    @TimeDeadband ,
    @CreatedBy    ,
    @DateCreated  ,
    @MaxLength    ,
    @InitialValue ,
    @CurrentEditor,
    @DoubleByte   ,
    @SamplesInActiveImage
GO

GRANT exec on ww_MDASStringTagUpdate to aaAdministrators
GO

GRANT exec on ww_MDASStringTagUpdate to aaPowerUsers
go
 
/* END: Legacy ww_ stored procedures */
/* ================================= */



/* Set up system functions */
/* ======================= */

/**********  fww_LicensedTagTotal  **********/
if exists (select * from sysobjects where id = object_id('dbo.fww_LicensedTagTotal'))
  DROP function dbo.fww_LicensedTagTotal
GO

create function fww_LicensedTagTotal(@TagType int = 0)
returns int
as
begin
   declare @result int
   if @TagType = 0
   begin
      set @result = (select COUNT(TagName) from Tag where IOServerKey <> 1 and TagType in (1,2,3,4,7,9))
   end
   else
   if @TagType in (1,2,3,4,7,9)
   begin
      set @result = (select COUNT(TagName) from Tag where IOServerKey <> 1 and TagType = @TagType)
   end
   else
   begin
      set @result = 0
   end
   return @result
end
go
grant exec on fww_LicensedTagTotal to public
go

/**********  fww_LicensedTagDetails  **********/
if exists (select * from sysobjects where id = object_id('dbo.fww_LicensedTagDetails'))
  DROP function dbo.fww_LicensedTagDetails
GO

create function fww_LicensedTagDetails()
returns table
as
return (
   select 'Tag Type' =
      CASE 
         WHEN (GROUPING(TagType) = 1) THEN 'Total'
         WHEN TagType = 1 THEN 'Analog'
         WHEN TagType = 2 THEN 'Discrete'
         WHEN TagType = 3 THEN 'String'
         WHEN TagType = 4 THEN 'Complex'
         WHEN TagType = 5 THEN 'Event'
      END,
      Count(TagName) as 'Tag Count',
      CASE WHEN (GROUPING(TagType) = 1) THEN Runtime.dbo.fww_LicensedTagTotal(0)
         ELSE Runtime.dbo.fww_LicensedTagTotal(TagType) END as 'Licensed Tags' 
from Tag
group by TagType with CUBE
)
go
grant select on Runtime.dbo.fww_LicensedTagDetails to public
go

/**********  fww_TagsInLicenseViolation  **********/
if exists (select * from sysobjects where id = object_id('dbo.fww_TagsInLicenseViolation'))
  DROP function dbo.fww_TagsInLicenseViolation
GO

create function fww_TagsInLicenseViolation()
   RETURNS @taglist TABLE (TagName nvarchar(256) NOT NULL, wwTagKey int,
                           [Description] nvarchar(512), Address nvarchar(512))
AS
BEGIN
   declare @tags table (TagCount int IDENTITY, TagName nvarchar(256), wwTagKey int, 
                        Description nvarchar(512), Address nvarchar(512))
   declare @allowedtags int

   set @allowedtags = (select convert(int, Value) from SystemParameter
                         where [Name] = 'LicenseTagCount')

   insert into @tags (TagName, wwTagKey, [Description], Address)
     select TagName, wwTagKey, t.[Description],
          '\\' + RTRIM(ios.ComputerName) + '\' + RTRIM(ios.ApplicationName)
                 + '!' + tp.[Name] + ':' + t.ItemName 
         from Tag t, Topic tp, IOServer ios
           where t.IOServerKey <> 1 and TagType <> 5
           and   t.TopicKey = tp.TopicKey
           and   tp.IOServerKey = ios.IOServerKey
     order by wwTagKey

   /* return the result */
   insert @taglist
    select TagName, wwTagKey, [Description], Address from @tags
      where TagCount > @allowedtags 
      order by wwTagKey

   return
END
go
grant select on Runtime.dbo.fww_TagsInLicenseViolation to public
go

/**********  fww_CheckLicenseViolation  **********/
if exists (select * from sysobjects where id = object_id('dbo.fww_CheckLicenseViolation'))
   drop function dbo.fww_CheckLicenseViolation
go

create function fww_CheckLicenseViolation()
returns int
as
begin
   declare @result int
   declare @allowedtags int
   declare @tagcount int

   set @allowedtags = (select convert(int, Value) from SystemParameter
                         where [Name] = 'LicenseTagCount')

   set @tagcount = (select dbo.fww_LicensedTagTotal(0))

   if @tagcount > @allowedtags
     set @result = @tagcount - @allowedtags
   else
     set @result = 0      

   return @result   
end
go
grant exec on Runtime.dbo.fww_CheckLicenseViolation to public
go

/**********  fww_InSQLgetdate  **********/
if exists (select * from sysobjects where id = object_id('dbo.fww_InSQLgetdate'))
   drop function dbo.fww_InSQLgetdate
go

create function fww_InSQLgetdate(@TimeZone nvarchar(100))
returns datetime
as
begin
  declare @TZDateTime datetime
  exec @TZDateTime = master..xp_TZgetdate @TimeZone, @TZDateTime OUTPUT
  return @TZDateTime
end
go
grant exec on dbo.fww_InSQLgetdate to public
go

/**********  fww_GetLocalizedText  **********/
if exists (select * from sysobjects where id = object_id('dbo.fww_GetLocalizedText'))
   drop function dbo.fww_GetLocalizedText
go

create function fww_GetLocalizedText (@LangID int)
returns table 
as
return 
(
/* This function returns the string from the LocalizedText table         */
/* for the requested language or english if the translation is not found */
   select TextKey, LanguageID, LocalizedText from LocalizedText 
      where LanguageID = @LangID
   UNION
   select TextKey, LanguageID, LocalizedText from LocalizedText
      where LanguageID = 1033
      GROUP BY TextKey, LanguageID, LocalizedText
         HAVING TextKey <> ALL
            (select TextKey from LocalizedText 
                where LanguageID = @LangID)
)
go
grant select on Runtime.dbo.fww_GetLocalizedText to public 
go



/* Backward compatibility views (pre-InSQL 8.0) */
/* ============================================ */

/* NamedSystemParameter */
/* PRE InSQL80 backward compatibility */
/* create a view and instead of triggers */

if exists (select name from sysobjects where name = 'NamedSystemParameter')
   begin
      drop view NamedSystemParameter
   end
go

create view NamedSystemParameter
as
select [Name],
       Type = CASE 
                 when convert(char(20),SQL_VARIANT_PROPERTY(Value, 'BaseType')) like '%char' then 'STRING'
                 when convert(char(20),SQL_VARIANT_PROPERTY(Value, 'BaseType')) like '%int' then 'NUMERIC'
                 when convert(char(20),SQL_VARIANT_PROPERTY(Value, 'BaseType')) like 'real' then 'NUMERIC'
               END,
       StringValue =  CASE 
                 when convert(char(20),SQL_VARIANT_PROPERTY(Value, 'BaseType')) like '%char'
                     then convert(varchar(255), Value)
                 else NULL
               END,
       NumericValue =  CASE 
                 when convert(char(20),SQL_VARIANT_PROPERTY(Value, 'BaseType')) like '%int'
                     then convert(real, Value)
                 when convert(char(20),SQL_VARIANT_PROPERTY(Value, 'BaseType')) like 'real'
                     then convert(real, Value)
                 else NULL
               END,
       Editable, Description
          from SystemParameter             
go
grant SELECT on NamedSystemParameter TO aaUsers
go
grant SELECT on  NamedSystemParameter TO aaPowerUsers
go
grant SELECT, UPDATE, INSERT, DELETE on  NamedSystemParameter TO aaAdministrators
go

/* Allow insert in SystemParameter via Instead of trigger */
create trigger tI_NSPInsert on NamedSystemParameter
INSTEAD OF INSERT
AS
begin
  if (select UPPER(Type) from inserted) = 'NUMERIC'
  begin
     insert into SystemParameter (Name, Value, Editable, Description)
      select Name, NumericValue, Editable, Description from inserted
  end
  else
  if (select UPPER(Type) from inserted) = 'STRING'
  begin
     insert into SystemParameter (Name, Value, Editable, Description)
      select Name, StringValue, Editable, Description from inserted                     
  end
  else
  begin
    declare @errno int
    declare @errmsg nvarchar(256)
    set @errno = 17040
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
    if @errmsg  is NULL
    begin
       set @errmsg = 'Need a valid NamedSystemParameter Type (STRING/NUMERIC)'
    end
    goto error
  end 

return

  error:
    raiserror @errno @errmsg
    rollback transaction
end
go

/* Allow update in SystemParameter via Instead of trigger */
create trigger tU_NSPUpdate on NamedSystemParameter
INSTEAD OF UPDATE
AS
begin
  if (select UPPER(Type) from inserted) = 'STRING'
  begin
     update SystemParameter set Value = i.StringValue,
          Description = i.Description, Editable = i.Editable
      from inserted i
      where SystemParameter.Name = i.Name
  end
  else
  if (select UPPER(Type) from inserted) = 'NUMERIC'
  begin
     update SystemParameter set Value = i.NumericValue,
          Description = i.Description, Editable = i.Editable
      from inserted i
      where SystemParameter.Name = i.Name
  end
  else
  begin
    declare @errno int
    declare @errmsg nvarchar(256)
    set @errno = 17040
    set @errmsg = (select LocalizedText from LocalizedText where TextKey = @errno and LanguageID = (select lcid from master..syslanguages where langid=@@LANGID))
    if @errmsg  is NULL
    begin
       set @errmsg = 'Need a valid NamedSystemParameter Type (STRING/NUMERIC)'
    end
    goto error
  end 

return

  error:
    raiserror @errno @errmsg
    rollback transaction
end
go


/* Create the Summary view as per InSQL 70 */
/* CR I0009117 */
if exists (SELECT * from sysobjects where name = 'DynDailyAvg')
  drop view DynDailyAvg
go
CREATE VIEW DynDailyAvg as
SELECT sv.TagName, sl.SummaryDate, sd.Value, sd.Quality  
 FROM SummaryOperation so ,SummaryTagList sv ,SummaryHistory sl, SummaryData sd
 WHERE so.CalcType = 'AVG'
 and so.Frequency = 'DAY'
 and so.SourceType = 'DYN'
 and so.OperationKey = sl.OperationKey
 and so.OperationKey = sv.OperationKey
 and sv.SumVarKey = sd.SumVarKey
 and sl.LogKey = sd.LogKey
go
GRANT SELECT on DynDailyAvg to Public 
go

if exists (SELECT * from sysobjects where name = 'DynDailySum')
  drop view DynDailySum
go
CREATE VIEW DynDailySum as
SELECT sv.TagName, sl.SummaryDate, sd.Value, sd.Quality  
 FROM SummaryOperation so ,SummaryTagList sv ,SummaryHistory sl, SummaryData sd
 WHERE so.CalcType = 'SUM'
 and so.Frequency = 'DAY'
 and so.SourceType = 'DYN'
 and so.OperationKey = sl.OperationKey
 and so.OperationKey = sv.OperationKey
 and sv.SumVarKey = sd.SumVarKey
 and sl.LogKey = sd.LogKey
go
GRANT SELECT on DynDailySum to Public 
go

if exists (SELECT * from sysobjects where name = 'DynHourlyAvg')
  drop view DynHourlyAvg
go
CREATE VIEW DynHourlyAvg as
SELECT sv.TagName, sl.SummaryDate, sd.Value, sd.Quality  
 FROM SummaryOperation so ,SummaryTagList sv ,SummaryHistory sl, SummaryData sd
 WHERE so.CalcType = 'AVG'
 and so.Frequency = 'HOUR'
 and so.SourceType = 'DYN'
 and so.OperationKey = sl.OperationKey
 and so.OperationKey = sv.OperationKey
 and sv.SumVarKey = sd.SumVarKey
 and sl.LogKey = sd.LogKey
go
GRANT SELECT on DynHourlyAvg to Public 
go

if exists (SELECT * from sysobjects where name = 'DynHourlyMin')
  drop view DynHourlyMin
go
CREATE VIEW DynHourlyMin as
SELECT sv.TagName, sl.SummaryDate, sd.Value, sd.Quality  
 FROM SummaryOperation so ,SummaryTagList sv ,SummaryHistory sl, SummaryData sd
 WHERE so.CalcType = 'MIN'
 and so.Frequency = 'HOUR'
 and so.SourceType = 'DYN'
 and so.OperationKey = sl.OperationKey
 and so.OperationKey = sv.OperationKey
 and sv.SumVarKey = sd.SumVarKey
 and sl.LogKey = sd.LogKey
go
GRANT SELECT on DynHourlyMin to Public 
go

if exists (SELECT * from sysobjects where name = 'DynHourlyMax')
  drop view DynHourlyMax
go
CREATE VIEW DynHourlyMax as
SELECT sv.TagName, sl.SummaryDate, sd.Value, sd.Quality  
 FROM SummaryOperation so ,SummaryTagList sv ,SummaryHistory sl, SummaryData sd
 WHERE so.CalcType = 'MAX'
 and so.Frequency = 'HOUR'
 and so.SourceType = 'DYN'
 and so.OperationKey = sl.OperationKey
 and so.OperationKey = sv.OperationKey
 and sv.SumVarKey = sd.SumVarKey
 and sl.LogKey = sd.LogKey
go
GRANT SELECT on DynHourlyMax to Public 
go

if exists (SELECT * from sysobjects where name = 'DynHourlySum')
  drop view DynHourlySum
go
CREATE VIEW DynHourlySum as
SELECT sv.TagName, sl.SummaryDate, sd.Value, sd.Quality  
 FROM SummaryOperation so ,SummaryTagList sv ,SummaryHistory sl, SummaryData sd
 WHERE so.CalcType = 'SUM'
 and so.Frequency = 'HOUR'
 and so.SourceType = 'DYN'
 and so.OperationKey = sl.OperationKey
 and so.OperationKey = sv.OperationKey
 and sv.SumVarKey = sd.SumVarKey
 and sl.LogKey = sd.LogKey
go
GRANT SELECT on DynHourlySum to Public 
go

if exists (SELECT * from sysobjects where name = 'InSQLSysObjects')
  drop view InSQLSysObjects
go
CREATE VIEW InSQLSysObjects as
SELECT * FROM HistorianSysObjects
go
GRANT SELECT on InSQLSysObjects to Public 
go


/* Update the UserDetail table to account for the ww* roles and logins */
use Runtime
go

EXEC aaUserDetailUpdate
go

UPDATE UserDetail
SET    AccessLevel = 2
WHERE  UserName LIKE N'wwUser%'
go

UPDATE UserDetail
SET    AccessLevel = 3
WHERE  UserName LIKE N'wwPower%'
go

UPDATE UserDetail
SET    AccessLevel = 4
WHERE  UserName LIKE N'wwAdmin%'
go
