home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Internet Business Development Kit / PRODUCT_CD.iso / sqlsvr / ppc / instmsdb.sql < prev    next >
Encoding:
Text File  |  1995-12-12  |  156.3 KB  |  4,729 lines

  1. /**********************************************************************/
  2. /* INSTMSDB.SQL                                                       */
  3. /*                                                                    */
  4. /* Installs the MSDB database and creates the Tasks, Alerts and       */
  5. /* Operators T-SQL database objects used by SQLDMO and SQLExecutive.  */
  6. /*                                                                    */
  7. /* Copyright Microsoft, Inc. 1994, 1995, 1996.                        */
  8. /* All Rights Reserved.                                               */
  9. /*                                                                    */
  10. /* Use, duplication, or disclosure by the United States Government    */
  11. /* is subject to restrictions as set forth in subdivision (c) (1)(ii) */
  12. /* of the Rights in Technical Data and Computer Software clause       */
  13. /* at CFR 252.227-7013.                                               */
  14. /* Microsoft, Inc. One Microsoft Way, Redmond WA. 98052.              */
  15. /**********************************************************************/
  16.  
  17. /**************************************************************/
  18. /**                                                          **/
  19. /**                        T A S K S                         **/
  20. /**                                                          **/
  21. /**************************************************************/
  22.  
  23. PRINT '----------------------------------'
  24. PRINT 'Starting execution of INSTMSDB.SQL'
  25. PRINT '----------------------------------'
  26. PRINT ''
  27. go
  28.  
  29. if not exists (select name from master.dbo.sysdatabases where name = 'msdb')
  30. begin
  31.     PRINT 'Creating the msdb database...'
  32.     PRINT ''
  33. end
  34. go
  35.  
  36. use master
  37. go
  38.  
  39. set nocount on
  40.  
  41. if not exists (select name from master.dbo.sysdatabases where name = 'msdb')
  42.     create database msdb on MSDBData = 6 log on MSDBLog = 2
  43. else
  44. begin
  45.     print 'Checking the size of the MSDBData device...'
  46.     exec ('dbcc updateusage(''msdb'') with no_infomsgs')
  47.  
  48.     /*
  49.     ** Determine amount of free space in msdb. We need at least 2MB (1024 pages) free.
  50.     */
  51.     declare @size_of_dev int
  52.     declare @free_db_space int
  53.     declare @free_dev_space int
  54.     declare @cmd varchar(255)
  55.  
  56.     create table #temp (size int)
  57.     exec ('insert into #temp select (select sum(size) from master.dbo.sysusages where dbid = (select dbid from master.dbo.sysdatabases where name = ''msdb'') and segmap & 0x3 = 0x3)
  58.                            - (select sum(reserved) from msdb.dbo.sysindexes where indid in (0, 1, 255))')
  59.     select @free_db_space = size from #temp
  60.         drop table #temp
  61.  
  62.     if (@free_db_space < 1024)
  63.     begin
  64.         /*
  65.         ** See if the msdb device has enough free space to alter the msdb database.
  66.         */
  67.         select @size_of_dev = (select sum(high-low+1) from master.dbo.sysdevices where name = 'MSDBData')
  68.         select @free_dev_space = @size_of_dev -
  69.                          (select sum(size)
  70.                       from master.dbo.sysusages
  71.                       where vstart between
  72.                               (select low from master.dbo.sysdevices where name = 'MSDBData')
  73.                       and
  74.                        (select high from master.dbo.sysdevices where name = 'MSDBData'))
  75.         if (@free_dev_space < 1024)
  76.         begin
  77.             print ''
  78.             print 'Attempting to expand the MSDBData device...'
  79.             select @cmd = 'disk resize name = MSDBData, size = ' + convert(varchar(10), @size_of_dev + 1024)
  80.             exec (@cmd)
  81.             if (@@error <> 0)
  82.                 raiserror('Could not expand msdb device.  See event viewer or errorlog for details.', 16, 127) with log
  83.           end
  84.  
  85.         print 'Attempting to alter the msdb database...'
  86.         exec ('alter database msdb on MSDBData = 2')
  87.         if @@error <> 0
  88.             raiserror('Unable to expand the msdb database - "Data segment full" errors may result.', 16, 127) with log
  89.     end
  90.     print ''
  91. end
  92. go
  93.  
  94. sp_dboption msdb, 'trunc. log on chkpt.', true
  95. go
  96.  
  97. use msdb
  98. go
  99.  
  100. checkpoint
  101. go
  102.  
  103. dump tran msdb with no_log
  104. go
  105.  
  106. if not exists (select name from sysusers where name = 'repl_subscriber')
  107. begin
  108.   exec sp_adduser 'repl_subscriber'
  109. end
  110.  
  111. if not exists (select name from sysusers where name = 'guest')
  112. begin
  113.   exec sp_adduser 'guest'
  114. end
  115. go
  116.  
  117. /**************************************************************/
  118. /* DROPS                                                      */
  119. /**************************************************************/
  120.  
  121. /* First, extract the build number from the version string */
  122. set nocount on
  123. declare @rebuild_needed bit
  124. declare @version varchar(30)
  125. declare @build_number int
  126. exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  127.                            'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\CurrentVersion',
  128.                            'CurrentVersion',
  129.                             @param = @version OUTPUT
  130. if (@version = null)
  131.   /* An error occurred reading the key, so don't force a rebuild */
  132.   select @build_number = 999999
  133. else
  134. if (@version like '%NT 4.2%')
  135.   /* We're running on a 4.2x or pre-4.2x server, so set the build number to 1 (to ensure a full build) */
  136.   select @build_number = 1
  137. else
  138.   /* We're running on a 6.x server so extract the current build number */
  139.   select @build_number = convert(int, right(@version, datalength(@version) - (patindex('%.[0-9][0-9].%',@version) + 4) + 1))
  140.  
  141. if (@build_number > 0) and (@build_number < 85)  /* The oldest build with the current schema */
  142. begin
  143.         select @rebuild_needed = 1
  144.         print ''
  145.         select 'Server Version ID' = @version, 'Table Rebuild Needed' = @rebuild_needed
  146.         print 'Dropping Tables...'
  147. end
  148. else
  149.         select @rebuild_needed = 0
  150.  
  151. /* Drop the tables ONLY if upgrading from a build EARLIER than the oldest build with the current schema */
  152. if (exists (select * from sysobjects where id = object_id('dbo.sysalerts') and sysstat & 0xf = 3) and (@rebuild_needed = 1))
  153. begin
  154.     print ''
  155.     print 'Dropping table sysalerts...'
  156.     drop table dbo.sysalerts
  157. end
  158.  
  159. if (exists (select * from sysobjects where id = object_id('sysoperators') and sysstat & 0xf = 3) and (@rebuild_needed = 1))
  160. begin
  161.     print ''
  162.     print 'Dropping table sysoperators...'
  163.     drop table sysoperators
  164. end
  165.  
  166. if (exists (select * from sysobjects where name = 'systasks' and sysstat & 0xf = 3) and (@rebuild_needed = 1))
  167. begin
  168.     print ''
  169.     print 'Dropping table systasks...'
  170.     drop table systasks
  171. end
  172.  
  173. if (exists (select * from sysobjects where name = 'syshistory' and sysstat & 0xf = 3) and (@rebuild_needed = 1))
  174. begin
  175.     print ''
  176.     print 'Dropping table syshistory...'
  177.     drop table syshistory
  178. end
  179.  
  180. if (exists (SELECT * from sysobjects where name = 'sysnotifications' and sysstat & 0xf = 3) and (@rebuild_needed = 1))
  181. begin
  182.     print ''
  183.     print 'Dropping table sysnotifications...'
  184.     drop table sysnotifications
  185. end
  186.  
  187. if (exists (select * from sysobjects where name = 'sysvolumelabel' and sysstat & 0xf = 3) and (@rebuild_needed = 1))
  188. begin
  189.     print ''
  190.     print 'Dropping table sysvolumelabel...'
  191.     drop table sysvolumelabel    
  192. end
  193. go
  194.  
  195. if (exists (select * from sysobjects where id = object_id('dbo.MSWork') and sysstat & 0xf = 3))
  196.     drop table MSWork
  197. if (exists (select * from sysobjects where id = object_id('dbo.sysalerts_temp') and sysstat & 0xf = 3))
  198.     drop table sysalerts_temp
  199. if (exists (select * from sysobjects where id = object_id('dbo.sysoperators_temp') and sysstat & 0xf = 3))
  200.     drop table sysoperators_temp
  201. if (exists (select * from sysobjects where id = object_id('dbo.sysnotifications_temp') and sysstat & 0xf = 3))
  202.     drop table sysnotifications_temp
  203. if (exists (select * from sysobjects where id = object_id('dbo.systasks_temp') and sysstat & 0xf = 3))
  204.     drop table systasks_temp
  205. if (exists (select * from sysobjects where id = object_id('dbo.syshistory_temp') and sysstat & 0xf = 3))
  206.     drop table syshistory_temp
  207. go
  208.  
  209. PRINT ''
  210. PRINT 'Dropping Task Procedures and Triggers...'
  211. go
  212. /* Now drop the procedures  and triggers */
  213. if exists (select * from sysobjects where name = 'syshistory_row_limiter' and sysstat & 0xf = 8)
  214.         drop trigger syshistory_row_limiter
  215. go
  216. if exists (select * from sysobjects where name = 'taskrefresh_ins' and sysstat & 0xf = 8)
  217.         drop trigger taskrefresh_ins
  218. go
  219. if exists (select * from sysobjects where name = 'taskrefresh_del' and sysstat & 0xf = 8)
  220.         drop trigger taskrefresh_del
  221. go
  222. if exists (select * from sysobjects where name = 'taskrefresh_upd' and sysstat & 0xf = 8)
  223.         drop trigger taskrefresh_upd
  224. go
  225. if exists (select * from sysobjects where name = 'sp_verifytaskdate' and sysstat & 0xf = 4)
  226.     drop proc sp_verifytaskdate
  227. go
  228. if exists (select * from sysobjects where name = 'sp_verifytasktime' and sysstat & 0xf = 4)
  229.     drop proc sp_verifytasktime
  230. go
  231. if exists (select * from sysobjects where name = 'sp_verifytasksched' and sysstat & 0xf = 4)
  232.     drop proc sp_verifytasksched
  233. go
  234. if exists (select * from sysobjects where name = 'sp_verifytask' and sysstat & 0xf = 4)
  235.     drop proc sp_verifytask
  236. go
  237. if exists (select * from sysobjects where name = 'sp_verifytaskid' and sysstat & 0xf = 4)
  238.     drop proc sp_verifytaskid
  239. go
  240. if exists (select * from sysobjects where name = 'sp_addtask' and sysstat & 0xf = 4)
  241.     drop proc sp_addtask
  242. go
  243. if exists (select * from sysobjects where name = 'sp_updatetask' and sysstat & 0xf = 4)
  244.     drop proc sp_updatetask
  245. go
  246. if exists (select * from sysobjects where name = 'sp_droptask' and sysstat & 0xf = 4)
  247.     drop proc sp_droptask
  248. go
  249. if exists (select * from sysobjects where name = 'sp_reassigntask' and sysstat & 0xf = 4)
  250.     drop proc sp_reassigntask
  251. go
  252. if exists (select * from sysobjects where name = 'sp_uniquetaskname' and sysstat & 0xf = 4)
  253.     drop proc sp_uniquetaskname
  254. go
  255. if exists (select * from sysobjects where name = 'sp_helptask' and sysstat & 0xf = 4)
  256.     drop proc sp_helptask
  257. go
  258. if exists (select * from sysobjects where name = 'sp_helphistory' and sysstat & 0xf = 4)
  259.     drop proc sp_helphistory
  260. go
  261. if exists (select * from sysobjects where name = 'sp_purgehistory' and sysstat & 0xf = 4)
  262.     drop proc sp_purgehistory
  263. go
  264. if exists (select * from sysobjects where name = 'sp_schedulerrefresh' and sysstat & 0xf = 4)
  265.     drop proc sp_schedulerrefresh
  266. go
  267. if exists (select * from sysobjects where name = 'sp_schedulerlog' and sysstat & 0xf = 4)
  268.     drop proc sp_schedulerlog
  269. go
  270. if exists (select * from sysobjects where name = 'sp_MScheckforownedtasks ' and sysstat & 0xf = 4)
  271.     drop proc sp_MScheckforownedtasks
  272. go
  273. if exists (select * from sysobjects where name = 'sp_MScheckforownedtasks ' and sysstat & 0xf = 4)
  274.     drop proc sp_MScheckforownedtasks
  275. go
  276. if exists (select * from sysobjects where name = 'sp_runtask' and sysstat & 0xf = 4)
  277.     drop proc sp_runtask
  278. go
  279. if exists (select * from sysobjects where name = 'sp_MStaskparameters' and sysstat & 0xf = 4)
  280.     drop proc sp_MStaskparameters
  281. go
  282. if exists (select * from sysobjects where name = 'systasks_view' and sysstat & 0xf = 2)
  283.     drop view systasks_view
  284. go
  285.  
  286. dump tran msdb with no_log
  287. go
  288.  
  289. /**************************************************************/
  290. /* MSWORK                                                     */
  291. /**************************************************************/
  292. PRINT ''
  293. PRINT 'Creating table MSWork...'
  294. go
  295. CREATE TABLE MSWork
  296. (
  297. spid   smallint,
  298. value1 varchar(255) NULL,
  299. value2 varchar(255) NULL,
  300. value3 varchar(255) NULL,
  301. value4 varchar(255) NULL,
  302. value5 varchar(255) NULL
  303. )
  304. go
  305.  
  306. /**************************************************************/
  307. /* SYSALERTS                                                  */
  308. /**************************************************************/
  309. if not exists(select * from sysobjects where id = object_id('dbo.sysalerts') and sysstat & 0xf = 3)
  310. begin
  311.   PRINT ''
  312.   PRINT 'Creating table sysalerts...'
  313.  
  314.   CREATE TABLE sysalerts_temp
  315.   (
  316.   id                int                    IDENTITY,
  317.   name                varchar(60)            NOT NULL,
  318.   event_source            varchar(30)            NOT NULL,
  319.   event_categoryname        varchar(30)            NULL,
  320.   event_id            varchar(20)            NULL,
  321.   message_id            int                NULL,
  322.   severity            int                NULL,
  323.   enabled            tinyint                NOT NULL,
  324.   delay_between_notifications    int                NOT NULL,
  325.   last_occurrence_date        int                NULL,
  326.   last_occurrence_time        int                NULL,
  327.   last_response_date        int                NULL,
  328.   last_response_time        int                NULL,
  329.   notification_message        varchar(255)            NULL,
  330.   include_event_description    tinyint                NOT NULL,
  331.   database_name            varchar(30)            NULL,
  332.   event_description_keyword    varchar(100)            NULL,
  333.   occurrence_count        int                NOT NULL,
  334.   count_reset_date        int                NULL,
  335.   count_reset_time        int                NULL,
  336.   task_id            int                NULL,
  337.   has_email_notification    int                NOT NULL,
  338.   has_pager_notification    int                NOT NULL,
  339.   flags                 int                NOT NULL
  340.   )
  341.   EXEC sp_rename 'sysalerts_temp', 'sysalerts'
  342.  
  343.   CREATE UNIQUE CLUSTERED INDEX ByName ON dbo.sysalerts(name)
  344.   CREATE UNIQUE INDEX ByID ON dbo.sysalerts(id)
  345. end
  346. go
  347.  
  348.  
  349. /**************************************************************/
  350. /* SYSOPERATORS                                               */
  351. /**************************************************************/
  352. if not exists(select * from sysobjects where id = object_id('dbo.sysoperators') and sysstat & 0xf = 3)
  353. begin
  354.   PRINT ''
  355.   PRINT 'Creating table sysoperators...'
  356.  
  357.   CREATE TABLE sysoperators_temp
  358.   (
  359.   id                int                IDENTITY,
  360.   name                varchar(50)            NOT NULL,
  361.   enabled            tinyint                NOT NULL,
  362.   email_address            varchar(100)            NULL,
  363.   last_email_date        int                NULL,
  364.   last_email_time        int                NULL,
  365.   pager_address            varchar(100)            NULL,
  366.   last_pager_date        int                NULL,
  367.   last_pager_time        int                NULL,
  368.   weekday_pager_start_time    int                NOT NULL,
  369.   weekday_pager_end_time    int                NOT NULL,
  370.   saturday_pager_start_time    int                NOT NULL,
  371.   saturday_pager_end_time    int                NOT NULL,
  372.   sunday_pager_start_time    int                NOT NULL,
  373.   sunday_pager_end_time        int                NOT NULL,
  374.   pager_days            tinyint                NOT NULL
  375.   )
  376.   EXEC sp_rename 'sysoperators_temp', 'sysoperators'
  377.  
  378.   CREATE UNIQUE CLUSTERED INDEX ByName ON dbo.sysoperators(name)
  379.   CREATE UNIQUE INDEX ByID ON dbo.sysoperators(id)
  380. end
  381. go
  382.  
  383.  
  384. /**************************************************************/
  385. /* SYSNOTIFICATIONS                                           */
  386. /**************************************************************/
  387. if not exists(select * from sysobjects where id = object_id('dbo.sysnotifications') and sysstat & 0xf = 3)
  388. begin
  389.   PRINT ''
  390.   PRINT 'Creating table sysnotifications...'
  391.  
  392.   CREATE TABLE sysnotifications_temp
  393.   (
  394.   alert_id            int                NOT NULL,
  395.   operator_id            int                NOT NULL,
  396.   notification_method        tinyint                NOT NULL
  397.   )
  398.   EXEC sp_rename 'sysnotifications_temp', 'sysnotifications'
  399.  
  400.   CREATE UNIQUE CLUSTERED INDEX ByAlertIDAndOperatorID ON dbo.sysnotifications(alert_id, operator_id)
  401. end
  402. go
  403.  
  404.  
  405. /**************************************************************/
  406. /* SYSTASKS                                                   */
  407. /**************************************************************/
  408. if not exists(select * from sysobjects where id = object_id('dbo.systasks') and sysstat & 0xf = 3)
  409. begin
  410.   PRINT ''
  411.   PRINT 'Creating table systasks...'
  412.  
  413.   create table systasks_temp
  414.   (
  415.   id                 int IDENTITY,        /* task id */
  416.   name                varchar(100),        /* task name:  Long enough for server_database_publication_NNNNNNN. */
  417.   subsystem            varchar(30),        /* task executive subsystem */
  418.   server            varchar(30)    null,    /* target server (replication only) */
  419.   username            varchar(30)    null,    /* user to setuser in database for this task */
  420.   ownerloginid            smallint,        /* login id of task creator (should REFERENCE master.dbo.syslogins but cross-db not allowed). */
  421.   databasename            varchar(30)    null,    /* database to use for this task */
  422.   enabled            tinyint,        /* invocable if nonzero (boolean; tinyint for expandability) */
  423.   freqtype            int,            /* main frequency type (day, week, month, monthrelative) */
  424.   freqinterval            int,            /* see docs */
  425.   freqsubtype            int,            /* for daily type; see docs */
  426.   freqsubinterval        int,            /* for daily type; see docs */
  427.   freqrelativeinterval         int,            /* see docs */
  428.   freqrecurrencefactor        int,            /* see docs */
  429.   activestartdate        int,            /* date for task to begin being scheduled */
  430.   activeenddate            int,            /* date for task to stop being scheduled */
  431.   activestarttimeofday        int,            /* time of day for task to begin being scheduled */
  432.   activeendtimeofday        int,            /* time of day for task to stop being scheduled */
  433.   lastrundate            int,            /* last day this task was run (yyyymmdd) */
  434.   lastruntime            int,            /* time of last day this task was run (hhmmss) */
  435.   nextrundate            int,            /* next day to run task */
  436.   nextruntime            int,            /* time of next day to run task */
  437.   runpriority            int,            /* nt execution priority for this task */
  438.   emailoperatorid        int         null,    /* id of operator to email on emailcompletionlevel */
  439.   retryattempts            int,            /* number of retries to attempt on failure */
  440.   retrydelay            int,            /* time in seconds to delay between retries */
  441.   datecreated            datetime,        /* date and time task was created */
  442.   datemodified            datetime,        /* date and time task was last modified */
  443.   command            varchar(255)     null,    /* command to be passed to executive subsystem */
  444.   lastruncompletionlevel    int,            /* completion level of last run (succeed, fail, running, abort, skipped) */
  445.   lastrunduration        int,            /* duration of last run (hhmmss) */
  446.   lastrunretries        int,             /* number of retries attempted for last run of this task */
  447.   loghistcompletionlevel     int,            /* completion level (succeed/fail/always) for which history records are logged */
  448.   emailcompletionlevel         int,            /* completion level (succeed/fail/always) for which email is sent to emailoperator */
  449.   description            varchar(255)    null,    /* task description */
  450.   tagadditionalinfo           varchar(96)    null,    /* additional tagging info for this task */
  451.   tagobjectid                 int        null,    /* id of object related to this task (e.g. publication) */
  452.   tagobjecttype          int        null    /* type of object related to this task (e.g. publication) */
  453.   )
  454.   exec sp_rename 'systasks_temp', 'systasks'
  455.  
  456.   create unique clustered index ucsystasks on systasks(name)
  457.   create unique nonclustered index uncsystasks on systasks(id)
  458. end
  459. go
  460.  
  461. PRINT ''
  462. PRINT 'Creating view systasks_view...'
  463. go
  464. CREATE VIEW systasks_view
  465. AS
  466. SELECT *
  467. FROM msdb.dbo.systasks
  468. WHERE ownerloginid = suser_id()
  469.    OR suser_name() IN ('sa', 'repl_publisher', 'repl_subscriber')
  470. go
  471.  
  472.  
  473. /************************************************************************/
  474. /* Systasks upgrade (add 'parameters' column if not already present)    */
  475. /************************************************************************/
  476. SET NOCOUNT ON
  477. IF NOT EXISTS (SELECT *
  478.                FROM msdb.dbo.syscolumns
  479.                WHERE id = object_id('dbo.systasks')
  480.                  AND name = 'parameters')
  481. BEGIN
  482.   PRINT ''
  483.   PRINT 'Upgrading systasks definition...'
  484.   ALTER TABLE msdb.dbo.systasks ADD parameters TEXT NULL
  485. END
  486. go
  487.  
  488.  
  489. /**************************************************************/
  490. /* SYSHISTORY                                                 */
  491. /**************************************************************/
  492. if not exists(select * from sysobjects where id = object_id('dbo.syshistory') and sysstat & 0xf = 3)
  493. begin
  494.   PRINT ''
  495.   PRINT 'Creating table syshistory...'
  496.  
  497.   create table syshistory_temp
  498.   (
  499.   id                int IDENTITY,        /* id of this history entry */
  500.   eventid             int        null,    /* id of sql event (alert) causing this, if not a task */
  501.   messageid            int        null,    /* sql message number */
  502.   severity            int        null,    /* sql severity level */
  503.   taskid            int        null,    /* task id (if not an alert) */
  504.   source            varchar(30)    null,    /* eventlog source of this entry */
  505.   category            varchar(30)    null,    /* eventlog category of this entry */
  506.   runstatus            int        null,    /* completion level of this task run (sqlole_completion_type), or eventlog state (sqlole_event_type) */
  507.   rundate            int,            /* date of task run or alert (yyyymmdd) */
  508.   runtime            int,            /* time of task run or alert (hhmmss) */
  509.   runduration            int,            /* duration of task run (hhmmss) */
  510.   reviewstatus            varchar(32)    null,    /* tbd */
  511.   emailoperatorid        int        null,    /* id of operator emailed, if any */
  512.   retries            int,            /* retries attempted on this run */
  513.   comments            varchar(255)    null,    /* tbd (subsystem entry) */
  514.   timesskipped            int            /* if nonzero, task skipped this many times due to down scheduler, */
  515.   )
  516.   exec sp_rename 'syshistory_temp', 'syshistory'
  517.  
  518.   create unique clustered index ucsyshistory on syshistory(id)
  519. end
  520. go
  521.  
  522.  
  523. /**************************************************************/
  524. /* SYSHISTORY_ROW_LIMITER TRIGGER                             */
  525. /**************************************************************/
  526. PRINT ''
  527. PRINT 'Creating trigger syshistory_row_limiter...'
  528. go
  529.  
  530. create trigger syshistory_row_limiter
  531. on msdb.dbo.syshistory
  532. for insert
  533. as
  534. begin
  535.         declare @oldest_id int
  536.         declare @max_rows int
  537.         declare @current_rows int
  538.         declare @limit_syshistory_rows int
  539.  
  540.         /* Are we limiting syshistory entries ? */
  541.         execute master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  542.                                       'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  543.                                       'SyshistoryLimitRows',
  544.                                       @param = @limit_syshistory_rows output
  545.         if (isnull(@limit_syshistory_rows, 0) = 0)
  546.                 return
  547.  
  548.         /* Get the id of the oldest row */
  549.         select @oldest_id = min(id)
  550.         from msdb.dbo.syshistory
  551.  
  552.         /* Get the maximum number of rows to keep from the registry */
  553.         execute master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  554.                                       'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  555.                                       'SyshistoryMaxRows',
  556.                                       @param = @max_rows output
  557.         if (isnull(@max_rows, 0) < 2)
  558.                 return
  559.  
  560.         select @current_rows = rows
  561.         from sysindexes
  562.         where id = object_id('msdb.dbo.syshistory')
  563.           and indid = 1
  564.  
  565.         /* Delete the oldest row if inserting the new row has pushed us over MaxSyshistoryRows */
  566.         if (@current_rows > (@max_rows - 1))
  567.                 delete from msdb.dbo.syshistory
  568.                 where id < (@oldest_id + (@current_rows - (@max_rows - 1)))
  569. end
  570. go
  571.  
  572.  
  573. /**************************************************************/
  574. /* SP_SCHEDULERSIGNAL (a 'master' database proc)              */
  575. /**************************************************************/
  576. PRINT ''
  577. PRINT 'Creating procedure sp_schedulersignal...'
  578. go
  579. USE master
  580. go
  581. EXEC sp_configure 'allow updates', 1
  582. RECONFIGURE WITH OVERRIDE
  583. PRINT 'The RECONFIGURE command was run.'
  584. go
  585.  
  586. IF EXISTS (SELECT * FROM sysobjects WHERE name = 'sp_schedulersignal' AND sysstat & 0xf = 4)
  587.   DROP PROC sp_schedulersignal
  588. go
  589. /* Clear down lingering permissions */
  590. DELETE FROM sysprotects WHERE id = object_id('xp_schedulersignal')
  591. go
  592.  
  593. /* Create the procedure */
  594. CREATE PROCEDURE sp_schedulersignal
  595. (
  596. @OpType      char(1),          /* One of R, O, I, T, A, G, D or E.                */
  597. @ID          int      = NULL,  /* Task ID (required for OpTypes R, O and I only). */
  598. @TriggerType char(1)  = NULL   /* One of I, U, D (required for OpType R only).    */
  599. )
  600. AS
  601. BEGIN
  602.   DECLARE @RetVal int
  603.   SELECT @RetVal = 0 /* Success */
  604.  
  605.   /* Parameter Validation */
  606.   IF (charindex(@OpType, 'ROITAGDE') = 0)
  607.   BEGIN
  608.     RAISERROR (14249, -1, -1)
  609.     RETURN 1 /* Failure */
  610.   END
  611.  
  612.   IF (charindex(@OpType, 'ROI') <> 0) AND ((@ID = NULL) OR NOT EXISTS (SELECT id FROM msdb.dbo.systasks WHERE id = @ID))
  613.   BEGIN
  614.     IF NOT ((@OpType = 'R') AND (@ID <> NULL) AND (@TriggerType = 'D'))
  615.     BEGIN
  616.       RAISERROR (14250, -1, -1)
  617.       RETURN 1 /* Failure */
  618.     END
  619.   END
  620.  
  621.   IF ((@OpType = 'R') AND ((@TriggerType = NULL) OR charindex(@TriggerType, 'IUD') = 0))
  622.   BEGIN
  623.     RAISERROR (14251, -1, -1)
  624.     RETURN 1 /* Failure */
  625.   END
  626.  
  627.   /* Parameters are valid, so now check execution permissions */
  628.   IF (charindex(@OpType, 'ROI') <> 0)
  629.   BEGIN
  630.     /* Caller must be SA, DBO, repl_subscriber, repl_publisher or the task owner */
  631.     IF NOT ((suser_id() = 1) OR
  632.             (upper(user_name()) = 'DBO') OR
  633.             (upper(user_name()) = 'REPL_SUBSCRIBER') OR
  634.             (upper(user_name()) = 'REPL_PUBLISHER') OR
  635.             (EXISTS (SELECT ownerloginid
  636.                      FROM msdb.dbo.systasks
  637.                      WHERE id = @ID AND ownerloginid = suser_id())))
  638.     BEGIN
  639.       IF NOT ((@OpType = 'R') AND (@ID <> NULL) AND (@TriggerType = 'D'))
  640.       BEGIN
  641.         RAISERROR (14252, -1, -1)
  642.         RETURN 1 /* Failure */
  643.       END
  644.     END
  645.   END
  646.  
  647.   /* Ok, let's do it... */
  648.   IF (@OpType = 'R')
  649.     EXEC @RetVal = master.dbo.xp_schedulersignal @OpType, @ID, @TriggerType
  650.   ELSE
  651.   IF (charindex(@OpType, 'OI') <> 0)
  652.     EXEC @RetVal = master.dbo.xp_schedulersignal @OpType, @ID
  653.   ELSE
  654.   IF (charindex(@OpType, 'TAGDE') <> 0)
  655.     EXEC @RetVal = master.dbo.xp_schedulersignal @OpType
  656.  
  657.   RETURN @RetVal
  658. END
  659. go
  660. EXEC sp_configure 'allow updates', 0
  661. RECONFIGURE WITH OVERRIDE
  662. PRINT 'The RECONFIGURE command was run.'
  663. go
  664. USE msdb
  665. go
  666.  
  667.  
  668. /**************************************************************/
  669. /* SP_VERIFYTASKDATE                                          */
  670. /**************************************************************/
  671. PRINT ''
  672. PRINT 'Creating procedure sp_verifytaskdate...'
  673. go
  674.  
  675. /* verify format of a date:  yyyymmdd */
  676. create proc sp_verifytaskdate
  677.  @date int,
  678.  @errmsg int
  679. as
  680.     if (@date = 0)
  681.         return 0
  682.     if ((((@date % 10000) / 100) > 12) or ((@date % 100) > 31))
  683.     begin
  684.         RAISERROR (@errmsg, -1, -1)
  685.         return 1
  686.     end
  687.     return 0
  688. go
  689. /* end sp_verifytaskdate */
  690.  
  691.  
  692. /**************************************************************/
  693. /* SP_VERIFYTASKTIME                                          */
  694. /**************************************************************/
  695. PRINT ''
  696. PRINT 'Creating procedure sp_verifytasktime...'
  697. go
  698.  
  699. /* verify format of a time:  hhmmss */
  700. create proc sp_verifytasktime
  701.  @time int,
  702.  @errmsg int
  703. as
  704.     if (@time = 0)
  705.         return 0
  706.     if ((@time / 10000) > 23
  707.             or ((@time % 10000) / 100) > 59
  708.             or (@time % 100) > 59)
  709.     begin
  710.         RAISERROR (@errmsg, -1, -1)
  711.         return 1
  712.     end
  713.     return 0
  714. go
  715. /* end sp_verifytasktime */
  716.  
  717.  
  718. /**************************************************************/
  719. /* SP_VERIFYTASKSCHED                                         */
  720. /**************************************************************/
  721. PRINT ''
  722. PRINT 'Creating procedure sp_verifytasksched...'
  723. go
  724.  
  725. /* verify that a task's frequency values are correctly defined.  Broken out of sp_verifytask for replication. */
  726. /* Default param values are for replication. */
  727. create proc sp_verifytasksched
  728.  @freqtype                int,
  729.  @freqinterval            int,
  730.  @freqsubtype            int,
  731.  @freqrelativeinterval    int,
  732.  @activestartdate        int = 0,
  733.  @activeenddate        int = 0     out,
  734.  @activestarttimeofday    int = 0,
  735.  @activeendtimeofday    int = 0  out,
  736.  @nextrundate            int = 0     out,
  737.  @nextruntime            int = 0     out,
  738.  @enabled           int = 0                     /* pass as 0 to prevent checking of start/end/nextrun date/times */
  739. as
  740.     declare @curdate int, @curtime int, @valid int
  741.     select @curdate = datepart(year, getdate()) * 10000 + datepart(month, getdate()) * 100 + datepart(day, getdate())
  742.     select @curtime = datepart(hour, getdate()) * 10000 + datepart(minute, getdate()) * 100 + datepart(second, getdate())
  743.  
  744.     /* verify that freqtype and freqsubtype are valid.  see sqlole.h. */
  745.     /* sqlolefreq_valid */
  746.     if (@freqtype & 0x007f = 0)
  747.     begin
  748.         RAISERROR (14200, -1, -1)
  749.         return 1
  750.     end
  751.  
  752.     /* sqlolefreqsub_valid */
  753.     if (@freqsubtype <> 0 and @freqsubtype & 0x000f = 0)
  754.     begin
  755.         RAISERROR (14201, -1, -1)
  756.         return 1
  757.     end
  758.  
  759.     /* verify that the interval is valid if it has a special meaning for this frequency type */
  760.     /* see sqlole\task.cpp for details of weekly (8; bitmask of weekdays) and monthlyrelative */
  761.     /* (20; single day type) interval validation. */
  762.     if ((@freqtype = 8 and @freqinterval & 0x007f <> @freqinterval) or
  763.             (@freqtype = 0x0020 and (@freqinterval < 1 or @freqinterval > 10)))
  764.     begin
  765.         RAISERROR (14202, -1, -1)
  766.         return 1
  767.     end
  768.     if (@freqtype = 0x0020 and (@freqrelativeinterval & 0x001f <> @freqrelativeinterval))
  769.     begin
  770.         RAISERROR (14203, -1, -1)
  771.         return 1
  772.     end
  773.  
  774.     /* verify dates, kinda:  ignore months not having 31 days */
  775.     /* for scheduler logic, which requires a math comparison of activestart% < activeend%, */
  776.     /* set to max values (from sqlole.h; sqlole_noenddate/time). */
  777.     if (@activeenddate = 0)
  778.     begin
  779.         select @activeenddate = 99991231
  780.     end else begin
  781.         exec @valid = sp_verifytaskdate @activeenddate, 14236
  782.         if (@valid <> 0)
  783.             return 1
  784.         if (@activeenddate < @activestartdate)
  785.         begin
  786.             RAISERROR (14204, -1, -1)
  787.             return 1
  788.         end
  789.     end
  790.  
  791.     /* verify times.. same math logic for max time of day. */
  792.     if (@activeendtimeofday = 0)
  793.     begin
  794.         select @activeendtimeofday = 235959
  795.     end else begin
  796.         exec @valid = sp_verifytasktime @activeendtimeofday, 14237
  797.         if (@valid <> 0)
  798.             return 1
  799.         if (@activeendtimeofday < @activestarttimeofday)
  800.         begin
  801.             RAISERROR (14205, -1, -1)
  802.             return 1
  803.         end
  804.     end
  805.  
  806.     /* verify activestartdate, activestarttimeofday, nextrundate and nextruntime if not ondemand (0x0002) */
  807.     if (@enabled = 0 or @freqtype = 2 or @freqtype = 64)
  808.     begin
  809.         select @nextrundate = 0
  810.         select @nextruntime = 0
  811.     end else begin
  812.         /* startdate/time; 0 will be valid. */
  813.         exec @valid = sp_verifytaskdate @activestartdate, 14238
  814.         if (@valid = 0)
  815.             exec @valid = sp_verifytasktime @activestarttimeofday, 14239
  816.         if (@valid <> 0)
  817.             return 1
  818.  
  819.         exec @valid = sp_verifytaskdate @nextrundate, 14240
  820.         if (@valid <> 0)
  821.             return 1
  822.         if (@curdate > @nextrundate)
  823.         begin
  824. /************ Changed for replication, if no problems, nuke this later.*****************
  825.             raiserror 66666 'Next run date cannot be less than current date'
  826.             return 1
  827. ***************************************************************************************/
  828.          select @nextrundate = 0
  829.         end
  830.         if (@nextrundate <> 0) and ((@activeenddate <> 0 and @nextrundate > @activeenddate) or (@nextrundate < @activestartdate))
  831.         begin
  832.             RAISERROR (14206, -1, -1)
  833.             return 1
  834.         end
  835.  
  836.         exec @valid = sp_verifytasktime @nextruntime, 14241
  837.         if (@valid <> 0)
  838.             return 1
  839.         if (@curdate = @nextrundate and @curtime > @nextruntime)
  840.         begin
  841. /************ Changed for replication, if no problems, nuke this later.*****************
  842.             raiserror 66666 'Next run time cannot be less than current time if next run date is the current date'
  843.             return 1
  844. ***************************************************************************************/
  845.          select @nextruntime = 0
  846.         end
  847.         if (@nextruntime <> 0) and ((@activeendtimeofday <> 0 and @nextruntime > @activeendtimeofday) or (@nextruntime < @activestarttimeofday))
  848.         begin
  849.             RAISERROR (14207, -1, -1)
  850.             return 1
  851.         end
  852.     end
  853.  
  854.     /* success */
  855.     return 0
  856. go
  857. /* end sp_verifytasksched */
  858.  
  859.  
  860. /**************************************************************/
  861. /* SP_VERIFYTASK                                              */
  862. /**************************************************************/
  863. PRINT ''
  864. PRINT 'Creating procedure sp_verifytask...'
  865. go
  866.  
  867. /* verify that a task is correctly defined.  also, fill in the id output params from the name input params. */
  868. create proc sp_verifytask
  869.  @id                    int,
  870.  @name                     varchar(100),
  871.  @server                varchar(30),
  872.  @databasename            varchar(30),
  873.  @enabled                int,
  874.  @freqtype                int,
  875.  @freqinterval            int,
  876.  @freqsubtype            int,
  877.  @freqrelativeinterval    int,
  878.  @activestartdate        int,
  879.  @activeenddate            int          out,
  880.  @activestarttimeofday    int,
  881.  @activeendtimeofday    int          out,
  882.  @nextrundate            int          out,
  883.  @nextruntime            int          out,
  884.  @runpriority            int,
  885.  @emailoperatorname        varchar(30),
  886.  @emailoperatorid        int          out,
  887.  @command                varchar(255),
  888.  @loghistcompletionlevel int,
  889.  @emailcompletionlevel int
  890. as
  891.     declare @valid int
  892.  
  893.     /* Make sure empty strings are interpreted as NULLs */
  894.     select @name = ltrim(@name)
  895.     select @server = ltrim(@server)
  896.     select @databasename = ltrim(@databasename)
  897.     select @emailoperatorname = ltrim(@emailoperatorname)
  898.     select @command = ltrim(@command)
  899.  
  900.     if (@name is null)
  901.     begin
  902.         RAISERROR (14208, -1, -1)
  903.         return 1
  904.     end
  905.  
  906.     if (@server is not null and not exists (select * from master.dbo.sysservers where srvname = @server))
  907.     begin
  908.         RAISERROR (14209, -1, -1, @server)
  909.         return 1
  910.     end
  911.  
  912.     if exists (select * from msdb.dbo.systasks where name = @name and id <> @id)
  913.     begin
  914.         declare @owner_login_id varchar(30)
  915.         select @owner_login_id = suser_name(ownerloginid) from systasks    where name = @name
  916.         RAISERROR (14210, -1, -1, @name, @owner_login_id)
  917.         return 1
  918.     end
  919.  
  920.     /*
  921.      * (@databasename currently not verified).
  922.      */
  923.  
  924.     /* Verify email operator. */
  925.     select @emailoperatorid = id from msdb.dbo.sysoperators where name = @emailoperatorname
  926.     if (@emailoperatorid is null and @emailoperatorname is not null and @emailoperatorname <> '')
  927.     begin
  928.         RAISERROR (14212, -1, -1, @emailoperatorname)
  929.         return 1
  930.     end
  931.  
  932.    /* Make sure the frequency info and start/end info is set okay. */
  933.  
  934.     exec @valid = sp_verifytasksched @freqtype,
  935.        @freqinterval,
  936.        @freqsubtype,
  937.        @freqrelativeinterval,
  938.        @activestartdate,
  939.        @activeenddate        out,
  940.        @activestarttimeofday,
  941.        @activeendtimeofday    out,
  942.        @nextrundate          out,
  943.        @nextruntime          out,
  944.        @enabled
  945.     if (@valid <> 0)
  946.         return 1
  947.  
  948.     /* Verify run priority: must be a valid value to pass to SetThreadPriority. */
  949.     if (@runpriority not in (-15, -2, -1, 0, 1, 2, 15))
  950.     begin
  951.         RAISERROR (14213, -1, -1)
  952.         return 1
  953.     end
  954.  
  955.     /* verify completion levels:  succeed, fail, always (see sqlole.h, sqlole_completion_type). */
  956.     /* sqlolecomp_always */
  957.     if (@loghistcompletionlevel & 0x0003 <> @loghistcompletionlevel)
  958.     begin
  959.         RAISERROR (14214, -1, -1)
  960.         return 1
  961.     end
  962.     if (@emailcompletionlevel & 0x0003 <> @emailcompletionlevel)
  963.     begin
  964.         RAISERROR (14215, -1, -1)
  965.         return 1
  966.     end
  967.  
  968.     /* success */
  969.     return 0
  970. go
  971. /* end sp_verifytask */
  972.  
  973. /**************************************************************/
  974. /* SP_VERIFYTASKID   Used by instrepl.sql                     */
  975. /**************************************************************/
  976. PRINT ''
  977. PRINT 'Creating procedure sp_verifytaskid...'
  978. go
  979. create procedure sp_verifytaskid
  980. @taskid int,
  981. @subsystem varchar (30) = '%'
  982. AS
  983.  
  984.    IF EXISTS (SELECT * FROM msdb.dbo.systasks WHERE id = @taskid AND
  985.       lower(subsystem) like lower(@subsystem))
  986.       return 0
  987.    ELSE
  988.       return 1
  989. go
  990.  
  991. /**************************************************************/
  992. /* SP_ADDTASK                                                 */
  993. /**************************************************************/
  994. PRINT ''
  995. PRINT 'Creating procedure sp_addtask...'
  996. go
  997.  
  998. create proc sp_addtask
  999.  @name                    varchar(100),
  1000.  @subsystem                varchar(30) = 'TSQL',
  1001.  @server                varchar(30) = null,
  1002.  @username                varchar(30) = null,
  1003.  @databasename            varchar(30) = null,
  1004.  @enabled                tinyint = 0,
  1005.  @freqtype                int = 2,  /* 2 == OnDemand */
  1006.  @freqinterval            int = 1,
  1007.  @freqsubtype            int = 1,
  1008.  @freqsubinterval        int = 1,
  1009.  @freqrelativeinterval  int = 1,
  1010.  @freqrecurrencefactor    int = 1,
  1011.  @activestartdate        int = 0,
  1012.  @activeenddate            int = 0,
  1013.  @activestarttimeofday    int = 0,
  1014.  @activeendtimeofday    int = 0,
  1015.  @nextrundate            int = 0,
  1016.  @nextruntime            int = 0,
  1017.  @runpriority            int = 0,
  1018.  @emailoperatorname        varchar(30) = null,
  1019.  @retryattempts            int = 0,
  1020.  @retrydelay            int = 10,
  1021.  @command                varchar(255) = null,
  1022.  @loghistcompletionlevel    int = 2,
  1023.  @emailcompletionlevel        int = 0,
  1024.  @description            varchar(255) = null,
  1025.  @tagadditionalinfo     varchar(96) = null,
  1026.  @tagobjectid           int = null,
  1027.  @tagobjecttype         int = null,
  1028.  @newid                 int = null OUT,
  1029.  @parameters            text = null        
  1030. as
  1031.     declare @emailoperatorid int
  1032.     declare @verify int
  1033.     declare @usernameintargetdb varchar(30)
  1034.     set nocount on
  1035.  
  1036.     declare @curdate int, @curtime int
  1037.     select @curdate = datepart(year, getdate()) * 10000 + datepart(month, getdate()) * 100 + datepart(day, getdate())
  1038.     select @curtime = datepart(hour, getdate()) * 10000 + datepart(minute, getdate()) * 100 + datepart(second, getdate())
  1039.  
  1040.     /* Get the username of the caller in the target database */
  1041.     if (@subsystem = 'TSQL')
  1042.     begin
  1043.         /* But first check if remote server name has been supplied and exit if so */
  1044.         if (@server <> null) and (upper(@server) <> upper(@@servername))
  1045.         begin
  1046.             raiserror(14253, -1, -1)
  1047.             return 1
  1048.         end
  1049.         select @server = null
  1050.  
  1051.         if (ltrim(rtrim(@databasename)) = null)
  1052.             select @databasename = 'master'
  1053.         delete from MSWork where spid = @@spid
  1054.  
  1055.         /* The insert into MSWork will always fail if the database is not found, but it does so with */
  1056.         /* a cryptic 208 ("xxx.dbo.sysusers not valid object") message, so pre-validate the database. */
  1057.         if (db_id(@databasename) is null) begin
  1058.             raiserror (14211, -1, -1, @databasename)
  1059.             return 1
  1060.         end
  1061.  
  1062.         /* This next step may fail with a 916 (and then an annoying 208), but that's */
  1063.             /* OK since it's good to know ahead of time that the task won't run */
  1064.         exec ('insert into MSWork(spid, value1) select @@spid, name from '+ @databasename +'.dbo.sysusers where suid = suser_id()')
  1065.         if (@@error <> 0)
  1066.             return 1
  1067.         exec ('if not exists (select * from MSWork where spid = @@spid) insert into MSWork(spid, value1) select @@spid, name from '+
  1068.                 @databasename +'.dbo.sysusers where suid = (select altsuid from '+ @databasename +'.dbo.sysalternates where suid = suser_id())')
  1069.         exec ('if not exists (select * from MSWork where spid = @@spid) insert into MSWork(spid, value1) select @@spid, name from '+ @databasename +'.dbo.sysusers where name = ''guest''')
  1070.         select @usernameintargetdb = value1 from MSWork where spid = @@spid
  1071.         delete from MSWork where spid = @@spid
  1072.  
  1073.         /* Now check if the caller has supplied a permissible @username */
  1074.         if (suser_id() = 1) and ((upper(@username) = 'SA') OR (upper(@username) = 'DBO'))
  1075.             select @username = null
  1076.         else
  1077.         if (suser_id() <> 1) and (ltrim(rtrim(@username)) = null)
  1078.             select @username = @usernameintargetdb
  1079.         else
  1080.         /* Only the SA or the DBO of the target db can set a "not me" @username */
  1081.         if (suser_id() <> 1) and (upper(@usernameintargetdb) <> 'DBO') and (isnull(@username, '') <> @usernameintargetdb)
  1082.                begin
  1083.             raiserror(14247, -1, -1, @username, @usernameintargetdb, @databasename, @databasename)
  1084.             return 1
  1085.         end
  1086.     end
  1087.  
  1088.     exec @verify = sp_verifytask 0, @name, @server, @databasename,
  1089.          @enabled,
  1090.          @freqtype,
  1091.          @freqinterval,
  1092.          @freqsubtype,
  1093.          @freqrelativeinterval,
  1094.          @activestartdate,
  1095.          @activeenddate out,
  1096.          @activestarttimeofday,
  1097.          @activeendtimeofday out,
  1098.          @nextrundate out,
  1099.          @nextruntime out,
  1100.          @runpriority,
  1101.          @emailoperatorname, @emailoperatorid out,
  1102.          @command,
  1103.          @loghistcompletionlevel,
  1104.          @emailcompletionlevel
  1105.     if (@verify <> 0)
  1106.         return 1
  1107.  
  1108.       /* insert the row. */
  1109.     insert msdb.dbo.systasks
  1110.     (
  1111.           name,
  1112.           subsystem,
  1113.           server,
  1114.           username,
  1115.           ownerloginid,
  1116.           databasename,
  1117.           enabled,
  1118.           freqtype,
  1119.           freqinterval,
  1120.           freqsubtype,
  1121.           freqsubinterval,
  1122.           freqrelativeinterval,
  1123.           freqrecurrencefactor,
  1124.           activestartdate,
  1125.           activeenddate,
  1126.           activestarttimeofday,
  1127.           activeendtimeofday,
  1128.           lastrundate,
  1129.           lastruntime,
  1130.           nextrundate,
  1131.           nextruntime,
  1132.           runpriority,
  1133.           emailoperatorid,
  1134.           retryattempts,
  1135.           retrydelay,
  1136.           datecreated,
  1137.           datemodified,
  1138.           command,
  1139.           lastruncompletionlevel,
  1140.           lastrunduration,
  1141.           lastrunretries,
  1142.           loghistcompletionlevel,
  1143.           emailcompletionlevel,
  1144.           description,
  1145.           tagadditionalinfo,
  1146.           tagobjectid,
  1147.           tagobjecttype,
  1148.           parameters
  1149.     )
  1150.     values
  1151.     (
  1152.          @name,
  1153.          @subsystem,
  1154.          @server,
  1155.          @username,
  1156.          suser_id(),
  1157.          @databasename,
  1158.          @enabled,
  1159.          @freqtype,
  1160.          @freqinterval,
  1161.          @freqsubtype,
  1162.          @freqsubinterval,
  1163.          @freqrelativeinterval,
  1164.          @freqrecurrencefactor,
  1165.          @activestartdate,
  1166.          @activeenddate,
  1167.          @activestarttimeofday,
  1168.          @activeendtimeofday,
  1169.         0,
  1170.          0,
  1171.          @nextrundate,
  1172.          @nextruntime,
  1173.          @runpriority,
  1174.          @emailoperatorid,
  1175.          @retryattempts,
  1176.          @retrydelay,
  1177.         getdate(),
  1178.         getdate(),
  1179.          @command,
  1180.         0,
  1181.         0,
  1182.         0,
  1183.          @loghistcompletionlevel,
  1184.          @emailcompletionlevel,
  1185.          @description,
  1186.         @tagadditionalinfo,
  1187.         @tagobjectid,
  1188.         @tagobjecttype,
  1189.          @parameters
  1190.     )
  1191.     if (@@error <> 0)
  1192.         return 1
  1193.  
  1194.     select @newid = id from msdb.dbo.systasks where name = @name
  1195.     return 0
  1196. go
  1197. /* end sp_addtask */
  1198.  
  1199.  
  1200. /**************************************************************/
  1201. /* SP_UPDATETASK                                              */
  1202. /**************************************************************/
  1203. PRINT ''
  1204. PRINT 'Creating procedure sp_updatetask...'
  1205. go
  1206.  
  1207. create proc sp_updatetask
  1208.  @currentname            varchar(100) = null,
  1209.  @id                    int = null,
  1210.  @name                    varchar(100) = null,
  1211.  @subsystem                varchar(30) = null,
  1212.  @server                varchar(30) = null,
  1213.  @username                varchar(30) = null,
  1214.  @databasename            varchar(30) = null,
  1215.  @enabled                tinyint = null,
  1216.  @freqtype                int = null,
  1217.  @freqinterval            int = null,
  1218.  @freqsubtype            int = null,
  1219.  @freqsubinterval        int = null,
  1220.  @freqrelativeinterval     int = null,
  1221.  @freqrecurrencefactor    int = null,
  1222.  @activestartdate        int = null,
  1223.  @activeenddate            int = null,
  1224.  @activestarttimeofday    int = null,
  1225.  @activeendtimeofday    int = null,
  1226.  @nextrundate            int = null,
  1227.  @nextruntime            int = null,
  1228.  @runpriority            int = null,
  1229.  @emailoperatorname        varchar(30) = null,
  1230.  @retryattempts            int = null,
  1231.  @retrydelay            int = null,
  1232.  @command                varchar(255) = null,
  1233.  @loghistcompletionlevel     int = null,
  1234.  @emailcompletionlevel         int = null,
  1235.  @description            varchar(255) = null,
  1236.  @tagadditionalinfo     varchar(96) = null,
  1237.  @tagobjectid           int = null,
  1238.  @tagobjecttype         int = null,
  1239.  @parameters            text = null        
  1240. as
  1241.     if (@currentname is null and @id is null)
  1242.     begin
  1243.         RAISERROR (14246, -1, -1)
  1244.         return 1
  1245.     end
  1246.  
  1247.     /* We'll key the update off task id, so get that first. */
  1248.     if (@id is not null)
  1249.     begin
  1250.         if not exists (select * from msdb.dbo.systasks where id = @id)
  1251.         begin
  1252.             RAISERROR (14216, -1, -1)
  1253.             return 1
  1254.         end
  1255.     end else begin
  1256.         select @id = id from msdb.dbo.systasks where name = @currentname
  1257.         if @id is null
  1258.         begin
  1259.             RAISERROR (14222, -1, -1, @currentname)
  1260.             return 1
  1261.         end
  1262.     end
  1263.  
  1264.     /* grab all the stuff we need into local variables, either from the input params or from the table. */
  1265.     /* to make this fast, load locals into vars, then copy into those vars from nonnull params. */
  1266.     declare @tname                    varchar(100),
  1267.             @tsubsystem                varchar(30),
  1268.             @tserver                varchar(30),
  1269.             @tusername                varchar(30),
  1270.             @tdatabasename            varchar(30),
  1271.             @tenabled                tinyint,
  1272.             @tfreqtype                int,
  1273.             @tfreqinterval            int,
  1274.             @tfreqsubtype            int,
  1275.             @tfreqsubinterval        int,
  1276.             @tfreqrelativeinterval     int,
  1277.             @tfreqrecurrencefactor    int,
  1278.             @tactivestartdate        int,
  1279.             @tactiveenddate            int,
  1280.             @tactivestarttimeofday    int,
  1281.             @tactiveendtimeofday    int,
  1282.             @tnextrundate            int,
  1283.             @tnextruntime            int,
  1284.             @trunpriority            int,
  1285.             @temailoperatorid             int,
  1286.             @temailoperatorname        varchar(30),
  1287.             @tretryattempts            int,
  1288.             @tretrydelay            int,
  1289.             @tcommand                varchar(255),
  1290.             @tloghistcompletionlevel int,
  1291.             @temailcompletionlevel     int,
  1292.             @tdescription            varchar(255),
  1293.             @townerloginid            int,
  1294.             @ttagadditionalinfo        varchar(96),
  1295.             @ttagobjectid            int,
  1296.             @ttagobjecttype            int
  1297.     declare @verify int
  1298.     declare @usernameintargetdb varchar(30)
  1299.     set nocount on
  1300.  
  1301.     /* load the local variables */
  1302.     select @tname                    = name,
  1303.             @tsubsystem                = subsystem,
  1304.             @tserver                = server,
  1305.             @tusername                = username,
  1306.             @tdatabasename            = databasename,
  1307.             @tenabled                = enabled,
  1308.             @tfreqtype                = freqtype,
  1309.             @tfreqinterval            = freqinterval,
  1310.             @tfreqsubtype            = freqsubtype,
  1311.             @tfreqsubinterval        = freqsubinterval,
  1312.             @tfreqrelativeinterval     = freqrelativeinterval,
  1313.             @tfreqrecurrencefactor    = freqrecurrencefactor,
  1314.             @tactivestartdate        = activestartdate,
  1315.             @tactiveenddate            = activeenddate,
  1316.             @tactivestarttimeofday    = activestarttimeofday,
  1317.             @tactiveendtimeofday    = activeendtimeofday,
  1318.             @tnextrundate            = nextrundate,
  1319.             @tnextruntime            = nextruntime,
  1320.             @trunpriority            = runpriority,
  1321.             @temailoperatorid             = emailoperatorid,
  1322.             @tretryattempts            = retryattempts,
  1323.             @tretrydelay            = retrydelay,
  1324.             @tcommand                = command,
  1325.             @tloghistcompletionlevel = loghistcompletionlevel,
  1326.             @temailcompletionlevel     = emailcompletionlevel,
  1327.             @tdescription            = description,
  1328.             @townerloginid             = ownerloginid,
  1329.             @ttagadditionalinfo     = tagadditionalinfo,
  1330.             @ttagobjectid             = tagobjectid,
  1331.             @ttagobjecttype         = tagobjecttype
  1332.         from msdb.dbo.systasks
  1333.         where id = @id
  1334.  
  1335.     /* check the ones we convert from name to id.  these also may be overridden below */
  1336.     select @temailoperatorname = name from msdb.dbo.systasks where id = @temailoperatorid
  1337.  
  1338.     /* make sure this guy is the task owner or the sa, or he can't do this. */
  1339.     if (suser_id() <> 1 and @townerloginid <> suser_id())
  1340.     begin
  1341.         RAISERROR (14217, -1, -1)
  1342.         return 1
  1343.     end
  1344.  
  1345.     /* overwrite them with any nonnull params */
  1346.     /* NOTE:  To null out a column in the table, pass '' -- I'll make it null in the next block below */
  1347.     if (@name is not null) select @tname = @name
  1348.     if (@subsystem is not null) select @tsubsystem = @subsystem
  1349.     if (@server is not null) select @tserver = @server
  1350.     if (@username is not null) select @tusername = @username
  1351.     if (@databasename is not null) select @tdatabasename = @databasename
  1352.     if (@enabled is not null) select @tenabled = @enabled
  1353.     if (@freqtype is not null) select @tfreqtype = @freqtype
  1354.     if (@freqinterval is not null) select @tfreqinterval = @freqinterval
  1355.     if (@freqsubtype is not null) select @tfreqsubtype = @freqsubtype
  1356.     if (@freqsubinterval is not null) select @tfreqsubinterval = @freqsubinterval
  1357.     if (@freqrelativeinterval is not null) select @tfreqrelativeinterval = @freqrelativeinterval
  1358.     if (@freqrecurrencefactor is not null) select @tfreqrecurrencefactor = @freqrecurrencefactor
  1359.     if (@activestartdate is not null) select @tactivestartdate = @activestartdate
  1360.     if (@activeenddate is not null) select @tactiveenddate = @activeenddate
  1361.     if (@activestarttimeofday is not null) select @tactivestarttimeofday = @activestarttimeofday
  1362.     if (@activeendtimeofday is not null) select @tactiveendtimeofday = @activeendtimeofday
  1363.     if (@nextrundate is not null) select @tnextrundate = @nextrundate
  1364.     if (@nextruntime is not null) select @tnextruntime = @nextruntime
  1365.     if (@runpriority is not null) select @trunpriority = @runpriority
  1366.     if (@emailoperatorname is not null) select @temailoperatorname = @emailoperatorname
  1367.     if (@retryattempts is not null) select @tretryattempts = @retryattempts
  1368.     if (@retrydelay is not null) select @tretrydelay = @retrydelay
  1369.     if (@command is not null) select @tcommand = @command
  1370.     if (@loghistcompletionlevel is not null) select @tloghistcompletionlevel = @loghistcompletionlevel
  1371.     if (@emailcompletionlevel is not null) select @temailcompletionlevel = @emailcompletionlevel
  1372.     if (@description is not null) select @tdescription = @description
  1373.     if (@tagadditionalinfo is not null) select @ttagadditionalinfo = @tagadditionalinfo
  1374.     if (@tagobjectid is not null) select @ttagobjectid = @tagobjectid
  1375.     if (@tagobjecttype is not null) select @ttagobjecttype = @tagobjecttype
  1376.  
  1377.    /* Check the nullables for a '' or 0 new value where appropriate, and use NULL (for a more readable systable) if found. */
  1378.    if (ltrim(@tserver) = null) select @tserver = null
  1379.    if (ltrim(@tusername) = null) select @tusername = null
  1380.    if (ltrim(@tdatabasename) = null) select @tdatabasename = null
  1381.    if (ltrim(@temailoperatorname) = null) select @temailoperatorname = null
  1382.    if (ltrim(@tdescription) = null) select @tdescription = null
  1383.    if (ltrim(@tcommand) = null) select @tcommand = null
  1384.    if (ltrim(@ttagadditionalinfo) = null) select @ttagadditionalinfo = null
  1385.    if (@ttagobjectid = 0) select @ttagobjectid = null
  1386.    if (@ttagobjecttype = 0) select @ttagobjecttype = null
  1387.  
  1388.     /* now verify the local variables */
  1389.     exec @verify = sp_verifytask @id, @tname, @server, @databasename,
  1390.          @tenabled,
  1391.          @tfreqtype,
  1392.          @tfreqinterval,
  1393.          @tfreqsubtype,
  1394.          @tfreqrelativeinterval,
  1395.          @tactivestartdate,
  1396.          @tactiveenddate out,
  1397.          @tactivestarttimeofday,
  1398.          @tactiveendtimeofday out,
  1399.          @tnextrundate out,
  1400.          @tnextruntime out,
  1401.          @trunpriority,
  1402.          @emailoperatorname, @temailoperatorid out,
  1403.          @tcommand,
  1404.          @tloghistcompletionlevel,
  1405.          @temailcompletionlevel
  1406.     if (@verify <> 0)
  1407.         return 1
  1408.  
  1409.     /* Get the username of the caller in the target database */
  1410.     if (@tsubsystem = 'TSQL')
  1411.     begin
  1412.         /* But first check if remote server name has been supplied and exit if so */
  1413.         if (@tserver <> null) and (upper(@tserver) <> upper(@@servername))
  1414.         begin
  1415.             raiserror(14253, -1, -1)
  1416.             return 1
  1417.         end
  1418.         select @tserver = null
  1419.  
  1420.         if (ltrim(rtrim(@tdatabasename)) = null)
  1421.             select @tdatabasename = 'master'
  1422.         delete from MSWork where spid = @@spid
  1423.  
  1424.         /* The insert into MSWork will always fail if the database is not found, but it does so with */
  1425.         /* a cryptic 208 ("xxx.dbo.sysusers not valid object") message, so pre-validate the database. */
  1426.         if (db_id(@tdatabasename) is null) begin
  1427.             raiserror (14211, -1, -1, @tdatabasename)
  1428.             return 1
  1429.         end
  1430.  
  1431.         /* This next step may fail with a 916 (and then an annoying 208), but that's */
  1432.             /* OK since it's good to know ahead of time that the task won't run */
  1433.         exec ('insert into MSWork(spid, value1) select @@spid, name from '+ @tdatabasename +'.dbo.sysusers where suid = suser_id()')
  1434.         if (@@error <> 0)
  1435.             return 1
  1436.         exec ('if not exists (select * from MSWork where spid = @@spid) insert into MSWork(spid, value1) select @@spid, name from '+
  1437.                 @tdatabasename +'.dbo.sysusers where suid = (select altsuid from '+ @tdatabasename +'.dbo.sysalternates where suid = suser_id())')
  1438.         exec ('if not exists (select * from MSWork where spid = @@spid) insert into MSWork(spid, value1) select @@spid, name from '+ @tdatabasename +'.dbo.sysusers where name = ''guest''')
  1439.         select @usernameintargetdb = value1 from MSWork where spid = @@spid
  1440.         delete from MSWork where spid = @@spid
  1441.  
  1442.         /* Now check if the caller has supplied a permissible @username */
  1443.         if (suser_id() = 1) and ((upper(@username) = 'SA') OR (upper(@username) = 'DBO'))
  1444.             select @tusername = null
  1445.         else
  1446.         if (suser_id() <> 1) and (ltrim(rtrim(@username)) = null)
  1447.             select @tusername = @usernameintargetdb
  1448.         else
  1449.         /* Only the SA or the DBO of the target db can set a "not me" @username */
  1450.         if (suser_id() <> 1) and (upper(@usernameintargetdb) <> 'DBO') and (isnull(@tusername, '') <> @usernameintargetdb)
  1451.                begin
  1452.             raiserror(14247, -1, -1, @tusername, @usernameintargetdb, @tdatabasename, @tdatabasename)
  1453.             return 1
  1454.         end
  1455.     end
  1456.  
  1457.     /* all seems valid, so generate the update statement */
  1458.     if (@parameters <> NULL)
  1459.     begin
  1460.         update msdb.dbo.systasks
  1461.         set parameters = @parameters
  1462.         where id = @id
  1463.     end
  1464.     update msdb.dbo.systasks set
  1465.             name = @tname,
  1466.             subsystem = @tsubsystem,
  1467.             server = @tserver,
  1468.             username = @tusername,
  1469.             databasename = @tdatabasename,
  1470.             enabled = @tenabled,
  1471.             freqtype = @tfreqtype,
  1472.             freqinterval = @tfreqinterval,
  1473.             freqsubtype = @tfreqsubtype,
  1474.             freqsubinterval = @tfreqsubinterval,
  1475.             freqrelativeinterval = @tfreqrelativeinterval,
  1476.             freqrecurrencefactor = @tfreqrecurrencefactor,
  1477.             activestartdate = @tactivestartdate,
  1478.             activeenddate = @tactiveenddate,
  1479.             activestarttimeofday = @tactivestarttimeofday,
  1480.             activeendtimeofday = @tactiveendtimeofday,
  1481.             nextrundate = @tnextrundate,
  1482.             nextruntime = @tnextruntime,
  1483.             runpriority = @trunpriority,
  1484.             emailoperatorid = @temailoperatorid,
  1485.             retryattempts = @tretryattempts,
  1486.             retrydelay = @tretrydelay,
  1487.             command = @tcommand,
  1488.             loghistcompletionlevel = @tloghistcompletionlevel,
  1489.             emailcompletionlevel = @temailcompletionlevel,
  1490.             description = @tdescription,
  1491.             datemodified = getdate(),
  1492.             tagadditionalinfo = @ttagadditionalinfo,
  1493.             tagobjectid = @ttagobjectid,
  1494.             tagobjecttype = @ttagobjecttype
  1495.         where id = @id
  1496.    if (@@error <> 0)
  1497.       return 1
  1498.  
  1499.     /* If any scheduling stuff changed or the subsystem changed or the command changed, */
  1500.     /* clear the last/next run details.                                                 */
  1501.     if (@freqtype is not null or
  1502.             @freqinterval is not null or
  1503.             @freqsubtype is not null or
  1504.             @freqsubinterval is not null or
  1505.             @freqrelativeinterval is not null or
  1506.             @freqrecurrencefactor is not null or
  1507.             @activestartdate is not null or
  1508.             @activeenddate is not null or
  1509.             @activestarttimeofday is not null or
  1510.             @activeendtimeofday is not null or
  1511.             @subsystem is not null or
  1512.             @command is not null
  1513.             )
  1514.         update msdb.dbo.systasks set 
  1515.         lastrundate = 0, 
  1516.         lastruntime = 0, 
  1517.         nextrundate = 0, 
  1518.         nextruntime = 0, 
  1519.         lastruncompletionlevel = 0,
  1520.         lastrunduration = 0,
  1521.         lastrunretries = 0
  1522.         where id = @id
  1523.    if (@@error <> 0)
  1524.       return 1
  1525.  
  1526.     return 0
  1527. go
  1528. /* end sp_updatetask */
  1529.  
  1530.  
  1531. /**************************************************************/
  1532. /* SP_DROPTASK                                                */
  1533. /**************************************************************/
  1534. PRINT ''
  1535. PRINT 'Creating procedure sp_droptask...'
  1536. go
  1537.  
  1538. create proc sp_droptask
  1539.  @name varchar(100) = null,
  1540.  @loginname varchar(30) = null,
  1541.  @id int = null
  1542. as
  1543.     if (@name is null and @id is null and @loginname is null) or
  1544.        (@name is not null and (@id is not null or @loginname is not null)) or
  1545.        (@id is not null and (@name is not null or @loginname is not null)) or
  1546.        (@loginname is not null and (@name is not null or @id is not null))
  1547.     begin
  1548.         RAISERROR (14245, -1, -1)
  1549.         return 1
  1550.     end
  1551.  
  1552.     /* First see if we should drop all tasks for a login. */
  1553.     declare @ownerid int, @uppersubsys varchar(30), @destserver varchar(30)
  1554.     if (@loginname is not null)
  1555.     begin
  1556.         select @ownerid = suser_id(@loginname)
  1557.         if (@ownerid is null)
  1558.         begin
  1559.             RAISERROR (14220, -1, -1, @loginname)
  1560.             return 1
  1561.         end
  1562.         if (suser_id() <> 1 and @ownerid <> suser_id())
  1563.         begin
  1564.             RAISERROR (14219, -1, -1)
  1565.             return 1
  1566.         end
  1567.         delete from msdb.dbo.syshistory where taskid in (select id from systasks where ownerloginid = @ownerid)
  1568.         delete from msdb.dbo.systasks where ownerloginid = @ownerid
  1569.         return 0
  1570.     end
  1571.  
  1572.     if (@name is not null)
  1573.        begin
  1574.        select @id = id, @ownerid = ownerloginid, @uppersubsys =
  1575.               UPPER(subsystem), @destserver = server from msdb.dbo.systasks
  1576.        where name = @name
  1577.          if (@id is null)
  1578.           begin
  1579.               RAISERROR (14222, -1, -1, @name)
  1580.               return 1
  1581.           end
  1582.        end
  1583.     else
  1584.        begin
  1585.        select @name = name, @ownerid = ownerloginid, @uppersubsys =
  1586.               UPPER(subsystem), @destserver = server from msdb.dbo.systasks
  1587.        where id = @id
  1588.          if (@name is null)
  1589.           begin
  1590.               declare @id_as_char varchar(10)
  1591.               select @id_as_char = convert(varchar, @id)
  1592.               RAISERROR (14222, -1, -1, @id_as_char)
  1593.               return 1
  1594.           end
  1595.        end
  1596.  
  1597.     if (suser_id() <> 1 and @ownerid <> suser_id() and NOT(@uppersubsys = 'DISTRIBUTION' and @@REMSERVER = @destserver))
  1598.     begin
  1599.         RAISERROR (14219, -1, -1)
  1600.         return 1
  1601.     end
  1602.     delete from msdb.dbo.syshistory where taskid = @id
  1603.     delete from msdb.dbo.systasks where id = @id
  1604.     return 0
  1605. go
  1606. /* end sp_droptask */
  1607.  
  1608.  
  1609. /**************************************************************/
  1610. /* SP_REASSIGNTASK                                            */
  1611. /**************************************************************/
  1612. PRINT ''
  1613. PRINT 'Creating procedure sp_reassigntask...'
  1614. go
  1615.  
  1616. create proc sp_reassigntask
  1617.   @taskname varchar(100) = null, 
  1618.   @newloginname varchar(30), 
  1619.   @oldloginname varchar(30) = null
  1620. as
  1621.     if (suser_id() <> 1)
  1622.     begin
  1623.         RAISERROR (14244, -1, -1)
  1624.         return 1
  1625.     end
  1626.  
  1627.     declare @oldid int, @newid int
  1628.     select @newid = suser_id(@newloginname)
  1629.  
  1630.     /* Got to have either task or oldlogin name (or both, though it's redundant). */
  1631.     if (@taskname is null and @oldloginname is null)
  1632.     begin
  1633.         RAISERROR (14255, -1, -1)
  1634.         return 1
  1635.     end
  1636.  
  1637.     /* Always check newid, but only check oldid if taskname is null. */
  1638.     if (@newid is null)
  1639.     begin
  1640.         RAISERROR (14220, -1, -1, @newloginname)
  1641.         return 1
  1642.     end
  1643.  
  1644.     if (@taskname is not null)
  1645.     begin
  1646.         if not exists (select * from systasks where name = @taskname)
  1647.         begin
  1648.             RAISERROR (14222, -1, -1, @taskname)
  1649.             return 1
  1650.         end
  1651.         update msdb.dbo.systasks set ownerloginid = @newid    where name = @taskname
  1652.         return 0
  1653.     end
  1654.  
  1655.     select @oldid = suser_id(@oldloginname)
  1656.     if (@oldid is null)
  1657.     begin
  1658.         RAISERROR (14220, -1, -1, @oldloginname)
  1659.         return 1
  1660.     end
  1661.  
  1662.     update msdb.dbo.systasks set ownerloginid = @newid    where ownerloginid = @oldid
  1663.    if (@@error <> 0)
  1664.       return 1
  1665.     return 0
  1666. go
  1667. /* end sp_reassigntask */
  1668.  
  1669. /**************************************************************/
  1670. /* SP_UNIQUETASKNAME                                          */
  1671. /**************************************************************/
  1672. PRINT ''
  1673. PRINT 'Creating procedure sp_uniquetaskname...'
  1674. go
  1675.  
  1676. create proc sp_uniquetaskname
  1677. @seed varchar(92)
  1678. as
  1679.     if exists (select * from systasks)
  1680.         select @seed + convert(varchar(7), (select min(id + 1) from systasks where
  1681.             @seed + convert(varchar(7), id + 1) not in (select name from systasks)))
  1682.     else
  1683.         select @seed + '1'
  1684. go
  1685. /* end sp_uniquetaskname */
  1686.  
  1687. /**************************************************************/
  1688. /* SP_HELPTASK                                                */
  1689. /**************************************************************/
  1690. PRINT ''
  1691. PRINT 'Creating procedure sp_helptask...'
  1692. go
  1693.  
  1694. create proc sp_helptask
  1695.  @taskname varchar(100) = null,
  1696.  @taskid int = null,
  1697.  @loginname varchar(30) = null,
  1698.  @operatorname varchar(30) = null,
  1699.  @subsystem varchar(30) = null,
  1700.  @mode varchar(10) = null            /* full or quick (default) */
  1701. as
  1702.     declare @operatorid int, @loginid int
  1703.  
  1704.     /* see if they wanted to qualify by owner; set @loginid if so. */
  1705.     if (@loginname is not null)
  1706.     begin
  1707.         if (suser_name() not in ("sa", "repl_subscriber", "repl_publisher", @loginname))
  1708.         begin
  1709.           RAISERROR(14254, -1, -1)
  1710.           return 1
  1711.         end
  1712.         select @loginid = suser_id(@loginname)
  1713.         if (@loginid is null)
  1714.         begin
  1715.             RAISERROR (14220, -1, -1, @loginname)
  1716.             return 1
  1717.         end
  1718.     end
  1719.  
  1720.     /* see if they wanted to qualify by operator; set @operatorid if so. */
  1721.     if (@operatorname is not null)
  1722.     begin
  1723.         select @operatorid = id from msdb.dbo.sysoperators where name = @operatorname
  1724.         if (@operatorid is null)
  1725.         begin
  1726.             RAISERROR (14221, -1, -1, @operatorname)
  1727.             return 1
  1728.         end
  1729.     end
  1730.  
  1731.     /* return task info based on params. if full specified, this info format is relied upon by */
  1732.     /* sqlole and starfighter; do not change it. */
  1733.     if (@mode = 'full')
  1734.     begin
  1735.         select t.name,
  1736.             t.id,
  1737.             t.subsystem,
  1738.             t.server,
  1739.             t.username,
  1740.             ownerloginname = suser_name(t.ownerloginid),
  1741.             t.databasename,
  1742.             t.enabled,
  1743.             t.freqtype,
  1744.             t.freqinterval,
  1745.             t.freqsubtype,
  1746.             t.freqsubinterval,
  1747.             t.freqrelativeinterval,
  1748.             t.freqrecurrencefactor,
  1749.             t.activestartdate,
  1750.             t.activeenddate,
  1751.             t.activestarttimeofday,
  1752.             t.activeendtimeofday,
  1753.             t.lastrundate,
  1754.             t.lastruntime,
  1755.             t.nextrundate,
  1756.             t.nextruntime,
  1757.             t.runpriority,
  1758.             emailoperatorname = a.name,
  1759.             t.retryattempts,
  1760.             t.retrydelay,
  1761.             t.datecreated,
  1762.             t.datemodified,
  1763.             t.command,
  1764.             t.lastruncompletionlevel,
  1765.             t.lastrunduration,
  1766.             t.lastrunretries,
  1767.             t.loghistcompletionlevel,
  1768.             t.emailcompletionlevel,
  1769.             t.description,
  1770.          t.tagadditionalinfo,
  1771.          t.tagobjectid,
  1772.          t.tagobjecttype
  1773.         from msdb.dbo.systasks_view t, msdb.dbo.sysoperators a where a.id =* t.emailoperatorid
  1774.                 and (@loginid is null or t.ownerloginid = @loginid)
  1775.                 and (@subsystem is null or t.subsystem like @subsystem)
  1776.                 and (@operatorid is null or t.emailoperatorid = @operatorid)
  1777.                 and (@taskname is null or t.name like @taskname)
  1778.                 and (@taskid is null or @taskid = t.id)
  1779.             order by t.name
  1780.     end else begin
  1781.         select
  1782.             name = substring(t.name, 1, 20),
  1783.             t.id,
  1784.             subsystem = substring(t.subsystem, 1, 15),
  1785.             server = substring(t.server, 1, 20),
  1786.             username = substring(t.username, 1, 20),
  1787.             dbname = substring(t.databasename, 1, 20),
  1788.             t.enabled
  1789.         from msdb.dbo.systasks_view t
  1790.             where (@loginid is null or t.ownerloginid = @loginid)
  1791.                 and (@subsystem is null or t.subsystem like @subsystem)
  1792.                 and (@operatorid is null or t.emailoperatorid = @operatorid)
  1793.                 and (@taskname is null or t.name like @taskname)
  1794.                 and (@taskid is null or @taskid = t.id)
  1795.             order by t.name
  1796.     end
  1797. go
  1798. /* end sp_helptask */
  1799.  
  1800.  
  1801. /**************************************************************/
  1802. /* TASKREFRESH_INS                                            */
  1803. /**************************************************************/
  1804. PRINT ''
  1805. PRINT 'Creating trigger taskrefresh_ins...'
  1806. go
  1807.  
  1808. /* SYSTASKS INSERT TRIGGER */
  1809.  
  1810. CREATE TRIGGER taskrefresh_ins
  1811. on msdb.dbo.systasks
  1812. for insert as
  1813. begin
  1814. declare @taskID int
  1815. declare @lastID int
  1816. select @lastID = 0
  1817. set rowcount 1
  1818. loop:
  1819.  
  1820.     Select @taskID = id from inserted where id > @lastID order by id
  1821.     if @taskID > 0
  1822.     BEGIN
  1823.         EXEC master.dbo.sp_schedulersignal 'R', @taskID, 'I'
  1824.         select @lastID = @taskID
  1825.         select @taskID = 0
  1826.         goto loop
  1827.     END
  1828. end
  1829. go
  1830.  
  1831.  
  1832. /**************************************************************/
  1833. /* TASKREFRESH_DEL                                            */
  1834. /**************************************************************/
  1835. PRINT ''
  1836. PRINT 'Creating trigger taskrefresh_del...'
  1837. go
  1838.  
  1839. CREATE TRIGGER taskrefresh_del
  1840. on msdb.dbo.systasks
  1841. for delete as
  1842. begin
  1843. declare @taskID int
  1844. declare @lastID int
  1845. select @lastID = 0
  1846. set rowcount 1
  1847. loop:
  1848.  
  1849.     Select @taskID = id from deleted where id > @lastID order by id
  1850.     if @taskID > 0
  1851.     BEGIN
  1852.         EXEC master.dbo.sp_schedulersignal 'R', @taskID, 'D'
  1853.         select @lastID = @taskID
  1854.         select @taskID = 0
  1855.         goto loop
  1856.     END
  1857.  
  1858. /* Now, clean up any dangling references in sysalerts to the deleted task(s) */
  1859. set rowcount 0
  1860. update msdb.dbo.sysalerts
  1861. set task_id = null
  1862. from deleted
  1863. where msdb.dbo.sysalerts.task_id  = deleted.id
  1864. end
  1865. go
  1866.  
  1867.  
  1868. /**************************************************************/
  1869. /* TASKREFRESH_UPD                                            */
  1870. /**************************************************************/
  1871. PRINT ''
  1872. PRINT 'Creating trigger taskrefresh_upd...'
  1873. go
  1874.  
  1875. CREATE TRIGGER taskrefresh_upd
  1876. on msdb.dbo.systasks
  1877. for update as
  1878. begin
  1879.  
  1880. declare @taskID int
  1881. declare @lastID int
  1882.  
  1883.  
  1884.  if update (id                      ) or
  1885.     update (name                  ) or
  1886.     update (subsystem             ) or
  1887.     update (server                ) or
  1888.     update (username              ) or
  1889.     update (ownerloginid          ) or
  1890.     update (databasename          ) or
  1891.     update (enabled               ) or
  1892.  
  1893.     update (freqtype              ) or
  1894.     update (freqinterval          ) or
  1895.     update (freqsubtype           ) or
  1896.     update (freqsubinterval       ) or
  1897.     update (freqrelativeinterval  ) or
  1898.     update (freqrecurrencefactor  ) or
  1899.     update (activestartdate       ) or     
  1900.     update (activeenddate         ) or
  1901.     update (activestarttimeofday  ) or
  1902.     update (activeendtimeofday    ) or
  1903.  
  1904.     update (runpriority           ) or
  1905.     update (emailoperatorid       ) or
  1906.     update (retryattempts         ) or
  1907.     update (retrydelay            ) or
  1908.     update (datecreated           ) or
  1909.     update (command               ) or
  1910.  
  1911.     update (loghistcompletionlevel) or
  1912.     update (emailcompletionlevel  ) or
  1913.  
  1914.     update (description           )
  1915.     
  1916.  begin
  1917.  
  1918.  
  1919.   select @lastID = 0
  1920.   set rowcount 1
  1921.   loop:
  1922.  
  1923.     Select @taskID = inserted.id
  1924.     from inserted , deleted  where inserted.id > @lastID and
  1925.     (inserted.id = deleted.id) and
  1926.     ((inserted.name                   <> deleted.name                   ) or
  1927.      (inserted.subsystem              <> deleted.subsystem             ) or
  1928.      (inserted.enabled                <> deleted.enabled               ) or
  1929.      (inserted.ownerloginid           <> deleted.ownerloginid          ) or
  1930.  
  1931.      (isnull(inserted.server, "")         <> isnull(deleted.server, "")       ) or
  1932.      (isnull(inserted.username, "")       <> isnull(deleted.username, "")     ) or
  1933.      (isnull(inserted.databasename, "")   <> isnull(deleted.databasename, "") ) or
  1934.      (isnull(inserted.emailoperatorid, 0) <> isnull(deleted.emailoperatorid, 0)) or
  1935.      (isnull(inserted.command, "")        <> isnull(deleted.command, "")      ) or
  1936.      (isnull(inserted.description, "")    <> isnull(deleted.description, "") or
  1937.  
  1938.      (inserted.freqtype               <> deleted.freqtype              ) or
  1939.      (inserted.freqinterval           <> deleted.freqinterval          ) or
  1940.      (inserted.freqsubtype            <> deleted.freqsubtype           ) or
  1941.      (inserted.freqsubinterval        <> deleted.freqsubinterval       ) or
  1942.      (inserted.freqrelativeinterval   <> deleted.freqrelativeinterval  ) or
  1943.      (inserted.freqrecurrencefactor   <> deleted.freqrecurrencefactor  ) or
  1944.      (inserted.activestartdate        <> deleted.activestartdate       ) or     
  1945.      (inserted.activeenddate          <> deleted.activeenddate         ) or
  1946.      (inserted.activestarttimeofday   <> deleted.activestarttimeofday  ) or
  1947.      (inserted.activeendtimeofday     <> deleted.activeendtimeofday    ) or
  1948.  
  1949.      (inserted.runpriority            <> deleted.runpriority           ) or
  1950.      (inserted.retryattempts          <> deleted.retryattempts         ) or
  1951.      (inserted.retrydelay             <> deleted.retrydelay            ) or
  1952.      (inserted.datecreated            <> deleted.datecreated           ) or
  1953.      (inserted.loghistcompletionlevel <> deleted.loghistcompletionlevel) or
  1954.      (inserted.emailcompletionlevel   <> deleted.emailcompletionlevel  ))
  1955.     
  1956.     )  order by inserted.id
  1957.  
  1958.     if @taskID > 0
  1959.     BEGIN
  1960.         EXEC master.dbo.sp_schedulersignal 'R', @taskID, 'U'
  1961.         select @lastID = @taskID
  1962.         select @taskID = 0
  1963.         goto loop
  1964.     END
  1965.  End
  1966. end
  1967. go
  1968.  
  1969.  
  1970. /**************************************************************/
  1971. /* SP_HELPHISTORY                                             */
  1972. /**************************************************************/
  1973. PRINT ''
  1974. PRINT 'Creating procedure sp_helphistory...'
  1975. go
  1976.  
  1977. create proc sp_helphistory
  1978.  @taskname                varchar(100) = null,
  1979.  @taskid                int = null,
  1980.  @eventid                 int = null,
  1981.  @messageid                int = null,
  1982.  @severity                int = null,
  1983.  @source                varchar(30) = null,
  1984.  @category                varchar(30) = null,
  1985.  @startdate                int = null,
  1986.  @enddate                int = null,
  1987.  @starttime                int = null,
  1988.  @endtime                int = null,
  1989.  @minimumtimesskipped    int = null,
  1990.  @minimumrunduration    int = null, /* hhmmss */
  1991.  @runstatusmask            int = null, /* SQLOLE_EVENT_TYPES for events; SQLOLE_COMPLETION_STATUS for tasks */
  1992.  @minimumretries        int = null,
  1993.  @oldestfirst            int = null,
  1994.  @mode varchar(10) = null            /* full or quick (default) */
  1995. as
  1996.     /* validate taskid if set, else task name if set. */
  1997.     if (@taskname is not null)
  1998.     begin
  1999.         select @taskid = id from msdb.dbo.systasks where name = @taskname
  2000.         if (@taskid is null)
  2001.         begin
  2002.             begin
  2003.                 RAISERROR (14222, -1, -1, @taskname)
  2004.                 return 1
  2005.             end
  2006.         end
  2007.     end else if (@taskid is not null)
  2008.     begin
  2009.         if not exists (select * from msdb.dbo.systasks where id = @taskid)
  2010.         begin
  2011.             RAISERROR (14223, -1, -1, @taskid)
  2012.             return 1
  2013.         end
  2014.     end
  2015.  
  2016.     /* ugly tsql hackaround to get sort-by-date on same statement.  normally we'd order by */
  2017.     /* most recent event first, i.e. desc. */
  2018.     declare @orderby int
  2019.     select @orderby = -1
  2020.     if (@oldestfirst is not null and @oldestfirst > 0)
  2021.         select @orderby = 1
  2022.  
  2023.     /* return task info based on params. if full specified, this info format is relied upon by */
  2024.     /* sqlole and starfighter; do not change it. */
  2025.     if (@mode = 'full')
  2026.     begin
  2027.         select h.id,
  2028.             h.eventid,
  2029.             h.messageid,
  2030.             h.severity,
  2031.             taskname = t.name,
  2032.             h.source,
  2033.             h.category,
  2034.             h.runstatus,
  2035.             h.rundate,
  2036.             h.runtime,
  2037.             h.runduration,
  2038.             h.reviewstatus,
  2039.             emailoperatorname = a.name,
  2040.             h.retries,
  2041.             h.comments,
  2042.             h.timesskipped
  2043.         from msdb.dbo.syshistory h, msdb.dbo.systasks_view t, msdb.dbo.sysoperators a
  2044.         where t.id = h.taskid and a.id =* h.emailoperatorid
  2045.             and (@taskid is null or @taskid = h.taskid)
  2046.             and (@eventid is null or @eventid = h.eventid)
  2047.             and (@messageid is null or @messageid = h.messageid)
  2048.             and (@severity is null or @severity = h.severity)
  2049.             and (@source is null or @source = h.source)
  2050.             and (@category is null or @category = h.category)
  2051.             and (@startdate is null or @startdate <= h.rundate)
  2052.             and (@enddate is null or @enddate >= h.rundate)
  2053.             and (@starttime is null or @starttime <= h.runtime)
  2054.             and (@endtime is null or @endtime >= h.runtime)
  2055.             and (@minimumtimesskipped is null or @minimumtimesskipped <= h.timesskipped)
  2056.             and (@minimumrunduration is null or @minimumrunduration <= h.runduration)
  2057.             and (@runstatusmask is null or @runstatusmask = 0 or @runstatusmask & h.runstatus <> 0)
  2058.             and (@minimumretries is null or @minimumretries <= h.retries)
  2059.         order by (h.id * @orderby)
  2060.     end else begin
  2061.         select
  2062.             taskname = t.name,
  2063.             h.source,
  2064.             h.runstatus,
  2065.             h.rundate,
  2066.             h.runtime,
  2067.             h.runduration,
  2068.             emailoperatorname = substring(a.name, 1, 10),
  2069.             h.retries
  2070.         from msdb.dbo.syshistory h, msdb.dbo.systasks_view t, msdb.dbo.sysoperators a
  2071.         where t.id = h.taskid and a.id =* h.emailoperatorid
  2072.             and (@taskid is null or @taskid = h.taskid)
  2073.             and (@eventid is null or @eventid = h.eventid)
  2074.             and (@messageid is null or @messageid = h.messageid)
  2075.             and (@severity is null or @severity = h.severity)
  2076.             and (@source is null or @source = h.source)
  2077.             and (@category is null or @category = h.category)
  2078.             and (@startdate is null or @startdate <= h.rundate)
  2079.             and (@enddate is null or @enddate >= h.rundate)
  2080.             and (@starttime is null or @starttime <= h.runtime)
  2081.             and (@endtime is null or @endtime >= h.runtime)
  2082.             and (@minimumtimesskipped is null or @minimumtimesskipped <= h.timesskipped)
  2083.             and (@minimumrunduration is null or @minimumrunduration <= h.runduration)
  2084.             and (@runstatusmask is null or @runstatusmask = 0 or @runstatusmask & h.runstatus <> 0)
  2085.             and (@minimumretries is null or @minimumretries <= h.retries)
  2086.         order by (h.id * @orderby)
  2087.     end
  2088. go
  2089. /* end sp_helphistory */
  2090.  
  2091.  
  2092. /**************************************************************/
  2093. /* SP_PURGEHISTORY                                            */
  2094. /**************************************************************/
  2095. PRINT ''
  2096. PRINT 'Creating procedure sp_purgehistory...'
  2097. go
  2098.  
  2099. create proc sp_purgehistory
  2100.  @taskname                varchar(100) = null,
  2101.  @taskid                int = null,
  2102.  @eventid                 int = null,
  2103.  @messageid                int = null,
  2104.  @severity                int = null,
  2105.  @source                varchar(30) = null,
  2106.  @category                varchar(30) = null,
  2107.  @startdate                int = null,
  2108.  @enddate                int = null,
  2109.  @starttime                int = null,
  2110.  @endtime                int = null,
  2111.  @minimumtimesskipped    int = null,
  2112.  @minimumrunduration    int = null, /* hhmmss */
  2113.  @runstatusmask            int = null, /* SQLOLE_EVENT_TYPES for events; SQLOLE_COMPLETION_STATUS for tasks */
  2114.  @minimumretries        int = null
  2115. as
  2116.     /* Validate taskname if set, else taskid if set (one is required if non-sa). */
  2117.     if (@taskname is not null)
  2118.     begin
  2119.         select @taskid = id from msdb.dbo.systasks where name = @taskname
  2120.         if (@taskid is null)
  2121.         begin
  2122.             RAISERROR (14222, -1, -1, @taskname)
  2123.             return 1
  2124.         end
  2125.     end
  2126.     else if (@taskid is not null)
  2127.     begin
  2128.         if not exists (select * from msdb.dbo.systasks where id = @taskid)
  2129.         begin
  2130.             RAISERROR (14223, -1, -1, @taskid)
  2131.             return 1
  2132.         end
  2133.     end
  2134.     else if (suser_id() <> 1)
  2135.     begin
  2136.         RAISERROR (14224, -1, -1)
  2137.         return 1
  2138.     end
  2139.  
  2140.     /* If not sa, we have @taskid set.  Make sure this guy is the task owner, or he can't do this. */
  2141.     if (suser_id() <> 1 and not exists (select * from msdb.dbo.systasks where id = @taskid and ownerloginid = suser_id()))
  2142.     begin
  2143.         RAISERROR (14224, -1, -1)
  2144.         return 1
  2145.     end
  2146.  
  2147.     delete msdb.dbo.syshistory
  2148.             where (@taskid is null or @taskid = taskid)
  2149.             and (@eventid is null or @eventid = eventid)
  2150.             and (@messageid is null or @messageid = messageid)
  2151.             and (@severity is null or @severity = severity)
  2152.             and (@source is null or @source = source)
  2153.             and (@category is null or @category = category)
  2154.             and (@startdate is null or @startdate <= rundate)
  2155.             and (@enddate is null or @enddate >= rundate)
  2156.             and (@starttime is null or @starttime <= runtime)
  2157.             and (@endtime is null or @endtime >= runtime)
  2158.             and (@minimumtimesskipped is null or @minimumtimesskipped <= timesskipped)
  2159.             and (@minimumrunduration is null or @minimumrunduration <= runduration)
  2160.             and (@runstatusmask is null or @runstatusmask = 0 or @runstatusmask & runstatus <> 0)
  2161.             and (@minimumretries is null or @minimumretries <= retries)
  2162. go
  2163. /* end sp_purgehistory */
  2164.  
  2165.  
  2166. /**************************************************************/
  2167. /* SP_SCHEDULERREFRESH                                        */
  2168. /**************************************************************/
  2169. PRINT ''
  2170. PRINT 'Creating procedure sp_schedulerrefresh...'
  2171. go
  2172.  
  2173. create proc sp_schedulerrefresh @id int = null as
  2174. select
  2175. t.id,
  2176. t.name,
  2177. subsystem,
  2178. server,
  2179. username,
  2180. l.name,
  2181. l.password,
  2182. databasename,
  2183. freqtype,
  2184. freqinterval,
  2185. freqsubtype,
  2186. freqsubinterval,
  2187. freqrelativeinterval,
  2188. freqrecurrencefactor,
  2189. activestartdate,
  2190. activeenddate,
  2191. activestarttimeofday,
  2192. activeendtimeofday,
  2193. lastrundate,
  2194. lastruntime,
  2195. nextrundate,
  2196. nextruntime,
  2197. runpriority,
  2198. a.email_address,
  2199. emailcompletionlevel,
  2200. retryattempts,
  2201. retrydelay,
  2202. loghistcompletionlevel,
  2203. command,
  2204. t.enabled,
  2205. emailoperatorid
  2206. from msdb.dbo.systasks t,master.dbo.syslogins l,msdb.dbo.sysoperators a
  2207. where (@id=null or (@id<>null and t.id=@id)) and
  2208.       l.suid=ownerloginid and
  2209.       a.id=*emailoperatorid
  2210. order by t.id
  2211. go
  2212.  
  2213.  
  2214. /**************************************************************/
  2215. /* SP_SCHEDULERLOG                                            */
  2216. /**************************************************************/
  2217. PRINT ''
  2218. PRINT 'Creating procedure sp_schedulerlog...'
  2219. go
  2220.  
  2221. create proc sp_schedulerlog @eventid int,@messageid int,@severity int,@taskid int,@source varchar(30),
  2222.                                 @category varchar(30),@runstatus int,@rundate int,@runtime int,@runduration int,
  2223.                                 @reviewstatus varchar(32),@emailoperatorid smallint,@retriesattempted int,
  2224.                                 @comments varchar(255),@timesskipped int as
  2225.  
  2226.     insert into msdb.dbo.syshistory (eventid,messageid,severity,taskid,source,category,runstatus,rundate,runtime,
  2227.                             runduration,reviewstatus,emailoperatorid,retries,comments,timesskipped)
  2228.         values (@eventid,@messageid,@severity,@taskid,@source,@category,@runstatus,@rundate,@runtime,
  2229.                 @runduration,@reviewstatus,@emailoperatorid,@retriesattempted,@comments,@timesskipped)
  2230. go
  2231.  
  2232.  
  2233. /**************************************************************/
  2234. /* SP_MSCHECKFOROWNEDTASKS                                    */
  2235. /**************************************************************/
  2236. PRINT ''
  2237. PRINT 'Creating procedure sp_MScheckforownedtasks...'
  2238. go
  2239.  
  2240. CREATE PROCEDURE sp_MScheckforownedtasks
  2241. (
  2242. @tablename varchar(92),
  2243. @loginname varchar(30)
  2244. )
  2245. AS
  2246. /*
  2247. ** This procedure is called by sp_droplogin to check if the login being dropped
  2248. ** still owns tasks.  The return value (the number of tasks owned) is passed back
  2249. ** via the supplied table name [this cumbersome approach is necessary because
  2250. ** sp_MScheckforownedtasks is invoked via an EXEC()].
  2251. */
  2252. BEGIN
  2253.   IF EXISTS (SELECT * FROM sysobjects WHERE (name = 'systasks') AND (sysstat & 0xf = 3))
  2254.     EXEC ('INSERT INTO ' + @tablename + ' SELECT count(*) FROM systasks WHERE ownerloginid = suser_id(''' + @loginname + ''')')
  2255. END
  2256. go
  2257.  
  2258.  
  2259. /**************************************************************/
  2260. /* SP_MSTASKPARAMETERS                                        */
  2261. /**************************************************************/
  2262. PRINT ''
  2263. PRINT 'Creating procedure sp_MStaskparameters...'
  2264. go
  2265.  
  2266. CREATE PROCEDURE sp_MStaskparameters
  2267.     @taskname varchar(100)
  2268. as
  2269.     /* Return a text column as multiple readtexts of maxcol length */
  2270.     if not exists (select * from msdb.dbo.systasks where name = @taskname) begin
  2271.         RAISERROR (14222, 11, -1, @taskname)
  2272.         return 1
  2273.     end
  2274.  
  2275.     declare @val varbinary(16), @len int, @ii int, @chunk int
  2276.     select @val = textptr(parameters), @len = datalength(parameters) from msdb.dbo.systasks where name = @taskname
  2277.     select @ii = 0, @chunk = 255
  2278.  
  2279.     /* Get all the rows of an maxcol size */
  2280.     while @len > @chunk begin
  2281.         readtext msdb.dbo.systasks.parameters @val @ii @chunk
  2282.         select @ii = @ii + @chunk, @len = @len - @chunk
  2283.     end
  2284.  
  2285.     /* Get the last chunk */
  2286.     if (@len > 0)
  2287.         readtext msdb.dbo.systasks.parameters @val @ii @len
  2288.     return 0
  2289. go
  2290.  
  2291. /**************************************************************/
  2292. /* SP_RUNTASK                                                 */
  2293. /**************************************************************/
  2294. PRINT ''
  2295. PRINT 'Creating procedure sp_runtask...'
  2296. go
  2297.  
  2298. CREATE PROCEDURE sp_runtask
  2299. @taskname varchar(100) = NULL,
  2300. @taskid   int          = NULL
  2301. AS
  2302. BEGIN
  2303.   DECLARE @msg    varchar(255)
  2304.   DECLARE @retval int
  2305.  
  2306.   /* We must have either a taskid or a taskname */
  2307.   IF ((@taskid = NULL) AND (@taskname = NULL)) OR
  2308.      ((@taskid != NULL) AND (@taskname != NULL))
  2309.   BEGIN
  2310.     PRINT 'USAGE: sp_runtask <task name> | @taskid = <task id>'
  2311.     RETURN(1)
  2312.   END
  2313.  
  2314.   /* Is the taskname valid? */
  2315.   IF (@taskid = NULL)
  2316.   BEGIN
  2317.     SELECT @taskid = id
  2318.     FROM msdb.dbo.systasks
  2319.     WHERE name = @taskname
  2320.     IF (@taskid = NULL)
  2321.     BEGIN
  2322.       SELECT @msg = 'Task ''' + @taskname + ''' does not exist.'
  2323.       PRINT @msg
  2324.       RETURN(1)
  2325.     END
  2326.   END
  2327.   ELSE
  2328.   /* Is the taskid valid? */
  2329.   BEGIN
  2330.     SELECT @taskname = name
  2331.     FROM msdb.dbo.systasks
  2332.     WHERE id = @taskid
  2333.     IF (@taskname = NULL)
  2334.     BEGIN
  2335.       SELECT @msg = 'Task #' + convert(varchar(10), @taskid) +' does not exist.'
  2336.       PRINT @msg
  2337.       RETURN(1)
  2338.     END
  2339.   END
  2340.  
  2341.   /* Run (start) the task */
  2342.   EXECUTE @retval = sp_schedulersignal 'O', @taskid
  2343.   IF (@retval = 0)
  2344.   BEGIN
  2345.     SELECT @msg = 'Task #' + convert(varchar(10), @taskid) + ' started successfully.'
  2346.     PRINT @msg
  2347.     RETURN(@retval)
  2348.   END
  2349. END
  2350. go
  2351.  
  2352.  
  2353. /************************************************************************/
  2354. /* Systasks username/databasename upgrade (TSQL and CmdExec tasks only) */
  2355. /************************************************************************/
  2356. PRINT ''
  2357. PRINT 'Upgrading systasks data...'
  2358. go
  2359.  
  2360. set nocount on
  2361. declare @msg varchar(255)
  2362. declare @row_count int
  2363.  
  2364. /* CmdExec Tasks (because of UI change) */
  2365. update systasks
  2366. set username = null, databasename = null
  2367. where subsystem = 'CmdExec'
  2368.   and ((username <> null) or (databasename <> null))
  2369. select @row_count = @@rowcount
  2370. if (@row_count > 0)
  2371. begin
  2372.     select @msg = convert(varchar(5), @row_count) + ' ''CmdExec'' Tasks were upgraded.'
  2373.     print @msg
  2374. end
  2375. go
  2376.  
  2377. /* TSQL Tasks */
  2378. declare systasks_upgrade cursor
  2379. for select id, ownerloginid, databasename, username, subsystem from systasks
  2380. for update of databasename, username
  2381.  
  2382. create table #username (username varchar(30))
  2383. go
  2384.  
  2385. set nocount on
  2386. declare @id int
  2387. declare @ownerloginid smallint
  2388. declare @databasename varchar(30)
  2389. declare @username varchar(30)
  2390. declare @usernameintargetdb varchar(30)
  2391. declare @subsystem varchar(30)
  2392. declare @msg varchar(255)
  2393. declare @SZownerloginid varchar(5)
  2394.  
  2395. open systasks_upgrade
  2396.  
  2397. fetch next from systasks_upgrade into @id, @ownerloginid, @databasename, @username, @subsystem
  2398. while (@@fetch_status <> -1)
  2399. begin
  2400.     truncate table #username
  2401.     if (@subsystem = 'TSQL')
  2402.     begin
  2403.         if not exists (select name from master.dbo.sysdatabases where name = isnull(@databasename, ''))
  2404.         begin
  2405.             select @msg = 'Updating database for ''TSQL'' task ' + convert(varchar, @id) + ' from ' + isnull(@databasename, '(null)') +' to master.'
  2406.             print @msg
  2407.             select @databasename = 'master'
  2408.             update systasks set databasename = @databasename where id = @id
  2409.         end
  2410.         select @SZownerloginid = convert(varchar(5), @ownerloginid)
  2411.         exec ('insert into #username(username) select name from '+ @databasename +'.dbo.sysusers where suid = '+ @SZownerloginid)
  2412.         exec ('if not exists (select * from #username) insert into #username(username) select name from '+ @databasename +'.dbo.sysusers where suid = (select altsuid from '+ @databasename +'.dbo.sysalternates where suid = '+ @SZownerloginid + ')')
  2413.         exec ('if not exists (select * from #username) insert into #username(username) select name from '+ @databasename +'.dbo.sysusers where name = ''guest''')
  2414.         exec ('if not exists (select * from #username) insert into #username(username) select ''No Available Username''')
  2415.         select @usernameintargetdb = username from #username
  2416.         if (@ownerloginid <> 1) and (upper(@usernameintargetdb) <> 'DBO') and (isnull(@username, '') <> @usernameintargetdb)
  2417.         begin
  2418.             select @msg = 'Updating username for ''TSQL'' task ' + convert(varchar, @id) + ' from ' + isnull(@username, '(null)') +' to ' + @usernameintargetdb + '.'
  2419.             print @msg
  2420.             update systasks set username = @usernameintargetdb where id = @id
  2421.         end
  2422.     end
  2423.     fetch next from systasks_upgrade into @id, @ownerloginid, @databasename, @username, @subsystem
  2424. end
  2425. go
  2426.  
  2427. drop table #username
  2428. deallocate systasks_upgrade
  2429. go
  2430.  
  2431. /************************************************************************/
  2432. /* Sysalerts upgrade (add 'flags' column if not already present)        */
  2433. /************************************************************************/
  2434. SET NOCOUNT ON
  2435. IF NOT EXISTS (SELECT *
  2436.                FROM msdb.dbo.syscolumns
  2437.                WHERE id = object_id('dbo.sysalerts')
  2438.                  AND name = 'flags')
  2439. BEGIN
  2440.   PRINT ''
  2441.   PRINT 'Upgrading sysalerts definition...'
  2442.   ALTER TABLE msdb.dbo.sysalerts ADD flags INT NULL
  2443.   EXEC ('UPDATE msdb.dbo.sysalerts SET flags = 0')
  2444. END
  2445. go
  2446.  
  2447.  
  2448.  
  2449. /**************************************************************/
  2450. /**                                                          **/
  2451. /**          A L E R T S  A N D  O P E R A T O R S           **/
  2452. /**                                                          **/
  2453. /**************************************************************/
  2454.  
  2455. /**************************************************************/
  2456. /* S T O R E D    P R O C E D U R E S                         */
  2457. /**************************************************************/
  2458.  
  2459. /**************************************************************/
  2460. /* NOTE: The new sysmessages needed are added by MESSAGES.SQL */
  2461. /**************************************************************/
  2462.  
  2463. DUMP TRANSACTION msdb WITH NO_LOG
  2464. go
  2465.  
  2466. /**************************************************************/
  2467. /* DROPS                                                      */
  2468. /**************************************************************/
  2469. PRINT ''
  2470. PRINT 'Dropping Alert/Operator Procedures and Triggers...'
  2471. go
  2472.  
  2473. IF EXISTS(SELECT *
  2474.           FROM sysobjects
  2475.           WHERE id = object_id('dbo.NewOrChangedNotification')
  2476.             AND sysstat & 0xf = 8)
  2477. BEGIN
  2478.   DROP TRIGGER NewOrChangedNotification
  2479. END
  2480. go
  2481.  
  2482. IF EXISTS(SELECT *
  2483.           FROM sysobjects
  2484.           WHERE id = object_id('dbo.RemovedNotification')
  2485.             AND sysstat & 0xf = 8)
  2486. BEGIN
  2487.   DROP TRIGGER RemovedNotification
  2488. END
  2489. go
  2490.  
  2491. IF EXISTS(SELECT *
  2492.           FROM sysobjects
  2493.           WHERE id = object_id('dbo.sp_validatealert')
  2494.             AND sysstat & 0xf = 4)
  2495. BEGIN
  2496.   DROP PROCEDURE dbo.sp_validatealert
  2497. END
  2498. go
  2499.  
  2500. IF EXISTS(SELECT *
  2501.           FROM sysobjects
  2502.           WHERE id = object_id('dbo.sp_addalert')
  2503.             AND sysstat & 0xf = 4)
  2504. BEGIN
  2505.   DROP PROCEDURE dbo.sp_addalert
  2506. END
  2507. go
  2508.  
  2509. IF EXISTS(SELECT *
  2510.           FROM sysobjects
  2511.           WHERE id = object_id('dbo.sp_updatealert')
  2512.             AND sysstat & 0xf = 4)
  2513. BEGIN
  2514.   DROP PROCEDURE dbo.sp_updatealert
  2515. END
  2516. go
  2517.  
  2518. IF EXISTS(SELECT *
  2519.           FROM sysobjects
  2520.           WHERE id = object_id('dbo.sp_dropalert')
  2521.             AND sysstat & 0xf = 4)
  2522. BEGIN
  2523.   DROP PROCEDURE dbo.sp_dropalert
  2524. END
  2525. go
  2526.  
  2527. IF EXISTS(SELECT *
  2528.           FROM sysobjects
  2529.           WHERE id = object_id('dbo.sp_validateoperator')
  2530.             AND sysstat & 0xf = 4)
  2531. BEGIN
  2532.   DROP PROCEDURE dbo.sp_validateoperator
  2533. END
  2534. go
  2535.  
  2536. IF EXISTS(SELECT *
  2537.           FROM sysobjects
  2538.           WHERE id = object_id('dbo.sp_addoperator')
  2539.             AND sysstat & 0xf = 4)
  2540. BEGIN
  2541.   DROP PROCEDURE dbo.sp_addoperator
  2542. END
  2543. go
  2544.  
  2545. IF EXISTS(SELECT *
  2546.           FROM sysobjects
  2547.           WHERE id = object_id('dbo.sp_updateoperator')
  2548.             AND sysstat & 0xf = 4)
  2549. BEGIN
  2550.   DROP PROCEDURE dbo.sp_updateoperator
  2551. END
  2552. go
  2553.  
  2554. IF EXISTS(SELECT *
  2555.           FROM sysobjects
  2556.           WHERE id = object_id('dbo.sp_dropoperator')
  2557.             AND sysstat & 0xf = 4)
  2558. BEGIN
  2559.   DROP PROCEDURE dbo.sp_dropoperator
  2560. END
  2561. go
  2562.  
  2563. IF EXISTS(SELECT *
  2564.           FROM sysobjects
  2565.           WHERE id = object_id('dbo.sp_addnotification')
  2566.             AND sysstat & 0xf = 4)
  2567. BEGIN
  2568.   DROP PROCEDURE dbo.sp_addnotification
  2569. END
  2570. go
  2571.  
  2572. IF EXISTS(SELECT *
  2573.           FROM sysobjects
  2574.           WHERE id = object_id('dbo.sp_updatenotification')
  2575.             AND sysstat & 0xf = 4)
  2576. BEGIN
  2577.   DROP PROCEDURE dbo.sp_updatenotification
  2578. END
  2579. go
  2580.  
  2581. IF EXISTS(SELECT *
  2582.           FROM sysobjects
  2583.           WHERE id = object_id('dbo.sp_dropnotification')
  2584.             AND sysstat & 0xf = 4)
  2585. BEGIN
  2586.   DROP PROCEDURE dbo.sp_dropnotification
  2587. END
  2588. go
  2589.  
  2590. IF EXISTS(SELECT *
  2591.           FROM sysobjects
  2592.           WHERE id = object_id('dbo.sp_helpalert')
  2593.             AND sysstat & 0xf = 4)
  2594. BEGIN
  2595.   DROP PROCEDURE dbo.sp_helpalert
  2596. END
  2597. go
  2598.  
  2599. IF EXISTS(SELECT *
  2600.           FROM sysobjects
  2601.           WHERE id = object_id('dbo.sp_helpoperator')
  2602.             AND sysstat & 0xf = 4)
  2603. BEGIN
  2604.   DROP PROCEDURE dbo.sp_helpoperator
  2605. END
  2606. go
  2607.  
  2608. IF EXISTS(SELECT *
  2609.           FROM sysobjects
  2610.           WHERE id = object_id('dbo.sp_helpnotification')
  2611.             AND sysstat & 0xf = 4)
  2612. BEGIN
  2613.   DROP PROCEDURE dbo.sp_helpnotification
  2614. END
  2615. go
  2616.  
  2617. DUMP TRANSACTION msdb WITH NO_LOG
  2618. go
  2619.  
  2620. /**************************************************************/
  2621. /* SP_VALIDATEALERT                                           */
  2622. /**************************************************************/
  2623.  
  2624. PRINT ''
  2625. PRINT 'Creating procedure sp_validatealert...'
  2626. go
  2627. CREATE PROCEDURE sp_validatealert
  2628. (
  2629. @new_name                      varchar(60),
  2630. @message_id                    int,
  2631. @severity                      int,
  2632. @enabled                       tinyint,
  2633. @delay_between_responses       int,
  2634. @notification_message          varchar(255),
  2635. @include_event_description_in  varchar(10),
  2636. @database_name                 varchar(30),
  2637. @event_description_keyword     varchar(100),
  2638. @task_name                     varchar(100),
  2639. @occurrence_count              int,
  2640. @raise_snmp_trap               tinyint
  2641. )
  2642. AS
  2643. BEGIN
  2644.   /* Is this user the SA? */
  2645.   IF (suser_id() <> 1)
  2646.   BEGIN
  2647.     RAISERROR(15003, 16, 1)
  2648.     RETURN(1)
  2649.   END
  2650.  
  2651.   /* Is the NewName unique? */
  2652.   IF EXISTS (SELECT *
  2653.              FROM msdb.dbo.sysalerts
  2654.              WHERE name = @new_name)
  2655.   BEGIN
  2656.     RAISERROR(14528, 16, 1)
  2657.     RETURN(1)
  2658.   END
  2659.  
  2660.   /* Remap NULL MessageID/Severity to zeros prior to validation */
  2661.   IF (@message_id = NULL) SELECT @message_id = 0
  2662.   IF (@severity = NULL) SELECT @severity = 0
  2663.   /* Has the user supplied MessageID OR Severity? */
  2664.   IF NOT ((@message_id = 0) AND (@severity NOT IN (0, NULL)))
  2665.   AND NOT ((@severity = 0) AND (@message_id NOT IN (0, NULL)))
  2666.   BEGIN
  2667.     RAISERROR(14500, 16, 1)
  2668.     RETURN(1)
  2669.   END
  2670.  
  2671.   /* Valid TaskName? */
  2672.   IF (ltrim(rtrim(@task_name)) <> NULL) AND (NOT EXISTS(SELECT *
  2673.                                                         FROM msdb.dbo.systasks
  2674.                                                         WHERE name = ltrim(rtrim(@task_name))
  2675.                                                         HAVING count(*) = 1))
  2676.   BEGIN
  2677.     RAISERROR(14501, 16, 1)
  2678.     RETURN(1)
  2679.     /* Is this task an 'On Demand' task? */
  2680.     IF NOT EXISTS(SELECT *
  2681.                   FROM msdb.dbo.systasks
  2682.                   WHERE (name = ltrim(rtrim(@task_name)))
  2683.                     AND (freqtype = 2))
  2684.     BEGIN
  2685.       RAISERROR(14531, 16, 1)
  2686.       RETURN(1)
  2687.     END
  2688.   END
  2689.  
  2690.   /* Valid Severity? */
  2691.   IF ((@severity < 0) OR (@severity > 25)) AND (@severity NOT IN (110, 120, 130, 140))
  2692.   BEGIN
  2693.     RAISERROR(14502, 16, 1)
  2694.     RETURN(1)
  2695.   END
  2696.  
  2697.   /* Valid MessageID? */
  2698.   IF (@message_id < 0)
  2699.   BEGIN
  2700.     RAISERROR(14518, 16, 1)
  2701.     RETURN(1)
  2702.   END
  2703.  
  2704.   /* Is it legal to set an alert on this MessageID ? */
  2705.   IF (@message_id in (4002, 1204))
  2706.   BEGIN
  2707.     RAISERROR(14533, 16, 1, @message_id)
  2708.     RETURN(1)
  2709.   END
  2710.  
  2711.   /* Valid IncludeEventDescriptionIn? */
  2712.   IF (@include_event_description_in NOT IN ('EMAIL', 'PAGER', 'BOTH', 'NONE'))
  2713.   BEGIN
  2714.     RAISERROR(14503, 16, 1)
  2715.     RETURN(1)
  2716.   END
  2717.  
  2718.   /* DelayBetweenResponses must be > 0 */
  2719.   IF (@delay_between_responses < 0)
  2720.   BEGIN
  2721.     RAISERROR(14504, 16, 1)
  2722.     RETURN(1)
  2723.   END
  2724.  
  2725.   /* OccurrenceCount must be > 0 */
  2726.   IF (@occurrence_count < 0)
  2727.   BEGIN
  2728.     RAISERROR(14505, 16, 1)
  2729.     RETURN(1)
  2730.   END
  2731.  
  2732.   /* Enabled must be 0 or 1 */
  2733.   IF (@enabled NOT IN (0, 1))
  2734.   BEGIN
  2735.     RAISERROR(14516, 16, 1)
  2736.     RETURN(1)
  2737.   END
  2738.  
  2739.   /* RaiseSNMPTrap must be 0 or 1 */
  2740.   IF (@raise_snmp_trap NOT IN (0, 1))
  2741.   BEGIN
  2742.     RAISERROR(14532, 16, 1)
  2743.     RETURN(1)
  2744.   END
  2745. END
  2746. go
  2747.  
  2748.  
  2749. /**************************************************************/
  2750. /* SP_ADDALERT                                                */
  2751. /**************************************************************/
  2752.  
  2753. PRINT ''
  2754. PRINT 'Creating procedure sp_addalert...'
  2755. go
  2756. CREATE PROCEDURE sp_addalert
  2757. (
  2758. @name                          varchar(60),
  2759. @message_id                    int,
  2760. @severity                      int,
  2761. @enabled                       tinyint = 1,
  2762. @delay_between_responses       int = 0,
  2763. @notification_message          varchar(255) = NULL,
  2764. @include_event_description_in  varchar(10) = 'NONE',
  2765. @database_name                 varchar(30) = NULL,
  2766. @event_description_keyword     varchar(100) = NULL,
  2767. @task_name                     varchar(100) = NULL,
  2768. @raise_snmp_trap               tinyint = 0
  2769. )
  2770. AS
  2771. BEGIN
  2772.   /* Turn empty strings into NULLs */
  2773.   IF (ltrim(@notification_message) = null) SELECT @notification_message = NULL
  2774.   IF (ltrim(@include_event_description_in) = null) SELECT @include_event_description_in = NULL
  2775.   IF (ltrim(@database_name) = null) SELECT @database_name = NULL
  2776.   IF (ltrim(@event_description_keyword) = null) SELECT @event_description_keyword = NULL
  2777.   IF (ltrim(@task_name) = null) SELECT @task_name = NULL
  2778.  
  2779.   DECLARE @event_source              varchar(30)
  2780.   DECLARE @event_category_name       varchar(30)
  2781.   DECLARE @event_id                  varchar(20)
  2782.   DECLARE @last_occurrence_date      int
  2783.   DECLARE @last_occurrence_time      int
  2784.   DECLARE @last_notification_date    int
  2785.   DECLARE @last_notification_time    int
  2786.   DECLARE @occurrence_count          int
  2787.   DECLARE @count_reset_date          int
  2788.   DECLARE @count_reset_time          int
  2789.   DECLARE @has_email_notification    int
  2790.   DECLARE @has_pager_notification    int
  2791.   DECLARE @task_id                   int
  2792.   DECLARE @include_event_desc_code   tinyint
  2793.  
  2794.   /* Is this user the SA? */
  2795.   IF (suser_id() <> 1)
  2796.   BEGIN
  2797.     RAISERROR(15003, 16, 1)
  2798.     RETURN(1)
  2799.   END
  2800.  
  2801.   /* Hard-code the new Alert defaults */
  2802.   SELECT @event_source = 'MSSQLServer'
  2803.   SELECT @event_category_name = NULL
  2804.   SELECT @event_id = NULL
  2805.   SELECT @last_occurrence_date = NULL
  2806.   SELECT @last_occurrence_time = NULL
  2807.   SELECT @last_notification_date = NULL
  2808.   SELECT @last_notification_time = NULL
  2809.   SELECT @occurrence_count = 0
  2810.   SELECT @count_reset_date = NULL
  2811.   SELECT @count_reset_time = NULL
  2812.   SELECT @has_email_notification = 0
  2813.   SELECT @has_pager_notification = 0
  2814.   SELECT @task_id = NULL
  2815.  
  2816.   /* Convert the include_event_description_in parameter to upper case */
  2817.   SELECT @include_event_description_in = upper(@include_event_description_in)
  2818.  
  2819.   /* Validate the Alert */
  2820.   DECLARE @return_code tinyint
  2821.   EXEC @return_code = sp_validatealert
  2822.   @name,
  2823.   @message_id,
  2824.   @severity,
  2825.   @enabled,
  2826.   @delay_between_responses,
  2827.   @notification_message,
  2828.   @include_event_description_in,
  2829.   @database_name,
  2830.   @event_description_keyword,
  2831.   @task_name,
  2832.   @occurrence_count,
  2833.   @raise_snmp_trap
  2834.   IF (@return_code <> 0) RETURN(1)
  2835.  
  2836.   /* Does this Alert already exist? */
  2837.   DECLARE @duplicate_id varchar(10)
  2838.   SELECT @duplicate_id = '(unknown)'
  2839.   SELECT @duplicate_id = convert(varchar(10), id)
  2840.   FROM msdb.dbo.sysalerts
  2841.   WHERE ((message_id = @message_id) OR (severity = @severity))
  2842.     AND (database_name = @database_name)
  2843.     AND (event_description_keyword = @event_description_keyword)
  2844.   IF (@duplicate_id <> '(unknown)')
  2845.   BEGIN
  2846.     RAISERROR(14506, 16, 1, @duplicate_id)
  2847.     RETURN(1)
  2848.   END
  2849.  
  2850.   /*Convert the TaskName into an ID */
  2851.   IF (@task_name <> NULL)
  2852.   BEGIN
  2853.     SELECT @task_id = id
  2854.     FROM msdb.dbo.systasks
  2855.     WHERE name = ltrim(rtrim(@task_name))
  2856.   END
  2857.  
  2858.   /* Convert IncludeEventDescriptionIn to a code */
  2859.   IF (@include_event_description_in = 'NONE') SELECT @include_event_desc_code = 0
  2860.   IF (@include_event_description_in = 'EMAIL') SELECT @include_event_desc_code = 1
  2861.   IF (@include_event_description_in = 'PAGER') SELECT @include_event_desc_code = 2
  2862.   IF (@include_event_description_in = 'BOTH') SELECT @include_event_desc_code = 3
  2863.  
  2864.   /* Convert zero MessageID/Severity into NULLs */
  2865.   IF (@message_id = 0) SELECT @message_id = NULL
  2866.   IF (@severity = 0) SELECT @severity = NULL
  2867.  
  2868.   /* Finally, do the actual INSERT */
  2869.   INSERT INTO msdb.dbo.sysalerts
  2870.   (
  2871.   name,
  2872.   event_source,
  2873.   event_categoryname,
  2874.   event_id,
  2875.   message_id,
  2876.   severity,
  2877.   enabled,
  2878.   delay_between_notifications,
  2879.   last_occurrence_date,
  2880.   last_occurrence_time,
  2881.   last_response_date,
  2882.   last_response_time,
  2883.   notification_message,
  2884.   include_event_description,
  2885.   database_name,
  2886.   event_description_keyword,
  2887.   occurrence_count,
  2888.   count_reset_date,
  2889.   count_reset_time,
  2890.   task_id,
  2891.   has_email_notification,
  2892.   has_pager_notification,
  2893.   flags
  2894.   )
  2895.   VALUES
  2896.   (
  2897.   @name,
  2898.   @event_source,
  2899.   @event_category_name,
  2900.   @event_id,
  2901.   @message_id,
  2902.   @severity,
  2903.   @enabled,
  2904.   @delay_between_responses,
  2905.   @last_occurrence_date,
  2906.   @last_occurrence_time,
  2907.   @last_notification_date,
  2908.   @last_notification_time,
  2909.   @notification_message,
  2910.   @include_event_desc_code,
  2911.   @database_name,
  2912.   @event_description_keyword,
  2913.   @occurrence_count,
  2914.   @count_reset_date,
  2915.   @count_reset_time,
  2916.   @task_id,
  2917.   @has_email_notification,
  2918.   @has_pager_notification,
  2919.   @raise_snmp_trap
  2920.   )
  2921.  
  2922.   /*
  2923.   ** Notify the SQLExecutive of the change. This xp causes a complete refresh (the only kind
  2924.   ** of refresh for Alerts) of the Schedulers sysalerts cache.
  2925.   */
  2926.   EXEC master.dbo.sp_schedulersignal 'A'
  2927.   RETURN(0)
  2928. END
  2929. go
  2930.  
  2931.  
  2932. /**************************************************************/
  2933. /* SP_UPDATEALERT                                             */
  2934. /**************************************************************/
  2935. PRINT ''
  2936. PRINT 'Creating procedure sp_updatealert...'
  2937. go
  2938. CREATE PROCEDURE sp_updatealert
  2939. (
  2940. @name                          varchar(60),
  2941. @new_name                      varchar(60) = NULL,
  2942. @enabled                       tinyint = NULL,
  2943. @message_id                    int = NULL,
  2944. @severity                      int = NULL,
  2945. @delay_between_responses       int = NULL,
  2946. @notification_message          varchar(255) = NULL,
  2947. @include_event_description_in  varchar(10) = NULL,
  2948. @database_name                 varchar(30) = NULL,
  2949. @event_description_keyword     varchar(100) = NULL,
  2950. @task_name                     varchar(100) = NULL,
  2951. @occurrence_count              int = NULL,
  2952. @count_reset_date              int = NULL,
  2953. @count_reset_time              int = NULL,
  2954. @last_occurrence_date          int = NULL,
  2955. @last_occurrence_time          int = NULL,
  2956. @last_response_date            int = NULL,
  2957. @last_response_time            int = NULL,
  2958. @raise_snmp_trap               tinyint = NULL
  2959. )
  2960. AS
  2961. BEGIN
  2962.   DECLARE @include_event_desc_code  tinyint
  2963.   DECLARE @task_id                  int
  2964.   DECLARE @flags                    int
  2965.  
  2966.   SELECT @task_id = NULL
  2967.  
  2968.   /* Is this user the SA? */
  2969.   IF (suser_id() <> 1)
  2970.   BEGIN
  2971.     RAISERROR(15003, 16, 1)
  2972.     RETURN(1)
  2973.   END
  2974.  
  2975.   /* Does this Alert exist? */
  2976.   IF NOT EXISTS(SELECT *
  2977.                 FROM msdb.dbo.sysalerts
  2978.                 WHERE name = @name)
  2979.   BEGIN
  2980.     RAISERROR(14507, 16, 1)
  2981.     RETURN(1)
  2982.   END
  2983.  
  2984.   /* Convert the @IncludeEventDescriptionIn parameter to upper case */
  2985.   IF (@include_event_description_in <> NULL) SELECT @include_event_description_in = upper(@include_event_description_in)
  2986.  
  2987.   BEGIN TRANSACTION
  2988.     IF (@enabled = NULL) SELECT @enabled = enabled FROM msdb.dbo.sysalerts WHERE name = @name
  2989.     IF (@message_id = NULL) SELECT @message_id = message_id FROM msdb.dbo.sysalerts WHERE name = @name
  2990.     IF (@severity = NULL) SELECT @severity = severity FROM msdb.dbo.sysalerts WHERE name = @name
  2991.     IF (@delay_between_responses = NULL) SELECT @delay_between_responses = delay_between_notifications FROM msdb.dbo.sysalerts WHERE name = @name
  2992.     IF (@notification_message = NULL) SELECT @notification_message = notification_message FROM msdb.dbo.sysalerts WHERE name = @name
  2993.     IF (@include_event_description_in = NULL) SELECT @include_event_desc_code = include_event_description FROM msdb.dbo.sysalerts WHERE name = @name
  2994.     IF (@database_name = NULL) SELECT @database_name = database_name FROM msdb.dbo.sysalerts WHERE name = @name
  2995.     IF (@event_description_keyword = NULL) SELECT @event_description_keyword = event_description_keyword FROM msdb.dbo.sysalerts WHERE name = @name
  2996.     IF (@task_name = NULL) SELECT @task_id = st.id FROM msdb.dbo.sysalerts sa, msdb.dbo.systasks st WHERE (sa.task_id = st.id) AND (sa.name = @name)
  2997.     IF (@occurrence_count = NULL) SELECT @occurrence_count = occurrence_count FROM msdb.dbo.sysalerts WHERE name = @name
  2998.     IF (@count_reset_date = NULL) SELECT @count_reset_date = count_reset_date FROM msdb.dbo.sysalerts WHERE name = @name
  2999.     IF (@count_reset_time = NULL) SELECT @count_reset_time = count_reset_time FROM msdb.dbo.sysalerts WHERE name = @name
  3000.     IF (@last_occurrence_date = NULL) SELECT @last_occurrence_date = last_occurrence_date FROM msdb.dbo.sysalerts WHERE name = @name
  3001.     IF (@last_occurrence_time = NULL) SELECT @last_occurrence_time = last_occurrence_time FROM msdb.dbo.sysalerts WHERE name = @name
  3002.     IF (@last_response_date = NULL) SELECT @last_response_date = last_response_date FROM msdb.dbo.sysalerts WHERE name = @name
  3003.     IF (@last_response_time = NULL) SELECT @last_response_time = last_response_time FROM msdb.dbo.sysalerts WHERE name = @name
  3004.     IF (@raise_snmp_trap = NULL) SELECT @raise_snmp_trap = flags & 0x1 FROM msdb.dbo.sysalerts WHERE name = @name
  3005.     SELECT @flags = flags FROM msdb.dbo.sysalerts WHERE name = @name
  3006.  
  3007.     /* Turn empty strings into NULLs */
  3008.     IF (ltrim(@new_name) = null) SELECT @new_name = NULL
  3009.     IF (ltrim(@notification_message) = null) SELECT @notification_message = NULL
  3010.     IF (ltrim(@include_event_description_in) = null) SELECT @include_event_description_in = NULL
  3011.     IF (ltrim(@database_name) = null) SELECT @database_name = NULL
  3012.     IF (ltrim(@event_description_keyword) = null) SELECT @event_description_keyword = NULL
  3013.     IF (ltrim(@task_name) = null) SELECT @task_name = NULL
  3014.  
  3015.     /* Would this alert match an already existing alert? */
  3016.     DECLARE @duplicate_id varchar(10)
  3017.     SELECT @duplicate_id = '(unknown)'
  3018.     SELECT @duplicate_id = convert(varchar(10), id)
  3019.     FROM msdb.dbo.sysalerts
  3020.     WHERE (message_id = @message_id)
  3021.       AND (severity = @severity)
  3022.       AND (database_name = @database_name)
  3023.       AND (event_description_keyword = @event_description_keyword)
  3024.       AND (name <> @name)
  3025.     IF (@duplicate_id <> '(unknown)')
  3026.     BEGIN
  3027.       RAISERROR(14506, 16, 1, @duplicate_id)
  3028.       ROLLBACK TRANSACTION
  3029.       RETURN(1)
  3030.     END
  3031.  
  3032.     /* Convert @IncludeEventDescriptionInCode to it's string evivalent */
  3033.     IF (@include_event_description_in = NULL)
  3034.     BEGIN
  3035.       IF (@include_event_desc_code = 0) SELECT @include_event_description_in = 'NONE'
  3036.       IF (@include_event_desc_code = 1) SELECT @include_event_description_in = 'EMAIL'
  3037.       IF (@include_event_desc_code = 2) SELECT @include_event_description_in = 'PAGER'
  3038.       IF (@include_event_desc_code = 3) SELECT @include_event_description_in = 'BOTH'
  3039.     END
  3040.  
  3041.     /* Validate the Alert */
  3042.     DECLARE @return_code tinyint
  3043.     EXEC @return_code = sp_validatealert
  3044.     @new_name,
  3045.     @message_id,
  3046.     @severity,
  3047.     @enabled,
  3048.     @delay_between_responses,
  3049.     @notification_message,
  3050.     @include_event_description_in,
  3051.     @database_name,
  3052.     @event_description_keyword,
  3053.     @task_name,
  3054.     @occurrence_count,
  3055.     @raise_snmp_trap
  3056.     IF (@return_code <> 0)
  3057.     BEGIN
  3058.       ROLLBACK TRANSACTION
  3059.       RETURN(1)
  3060.     END
  3061.  
  3062.     /* If the user didn't supply a NewName, use the old one. */
  3063.     /* NOTE: This must be done AFTER sp_validatealert.       */
  3064.     IF (@new_name = NULL) SELECT @new_name = @name
  3065.  
  3066.     /* Convert the TaskName into an ID */
  3067.     IF (@task_name <> NULL)
  3068.     BEGIN
  3069.       SELECT @task_id = id
  3070.       FROM msdb.dbo.systasks
  3071.       WHERE name = ltrim(rtrim(@task_name))
  3072.     END
  3073.  
  3074.     /* Convert IncludeEventDescriptionIn back to a code */
  3075.     IF (@include_event_description_in = 'NONE') SELECT @include_event_desc_code = 0
  3076.     IF (@include_event_description_in = 'EMAIL') SELECT @include_event_desc_code = 1
  3077.     IF (@include_event_description_in = 'PAGER') SELECT @include_event_desc_code = 2
  3078.     IF (@include_event_description_in = 'BOTH') SELECT @include_event_desc_code = 3
  3079.  
  3080.     /* Convert zero MessageID/Severity into NULLs */
  3081.     IF (@message_id = 0) SELECT @message_id = NULL
  3082.     IF (@severity = 0) SELECT @severity = NULL
  3083.  
  3084.     /* Turn the 1st 'flags' bit on or off accordingly */
  3085.     IF (@raise_snmp_trap = 0)
  3086.       SELECT @flags = @flags & 0xFFFE
  3087.     ELSE
  3088.       SELECT @flags = @flags | 0x0001
  3089.  
  3090.     /* Finally, do the actual UPDATE */
  3091.     UPDATE msdb.dbo.sysalerts SET
  3092.     name = @new_name,
  3093.     message_id = @message_id,
  3094.     severity = @severity,
  3095.     enabled = @enabled,
  3096.     delay_between_notifications = @delay_between_responses,
  3097.     notification_message = @notification_message,
  3098.     include_event_description = @include_event_desc_code,
  3099.     database_name = @database_name,
  3100.     event_description_keyword = @event_description_keyword,
  3101.     task_id = @task_id,
  3102.     occurrence_count = @occurrence_count,
  3103.     count_reset_date = @count_reset_date,
  3104.     count_reset_time = @count_reset_time,
  3105.     last_occurrence_date = @last_occurrence_date,
  3106.     last_occurrence_time = @last_occurrence_time,
  3107.     last_response_date = @last_response_date,
  3108.     last_response_time = @last_response_time,
  3109.     flags = @flags
  3110.     WHERE (name = @name)
  3111.   COMMIT TRANSACTION
  3112.  
  3113.   /*
  3114.   ** Notify SQLExecutive of the change.
  3115.   */
  3116.   EXEC master.dbo.sp_schedulersignal 'A'
  3117.   RETURN(0)
  3118. END
  3119. go
  3120.  
  3121.  
  3122. /**************************************************************/
  3123. /* SP_DROPALERT                                               */
  3124. /**************************************************************/
  3125.  
  3126. PRINT ''
  3127. PRINT 'Creating procedure sp_dropalert...'
  3128. go
  3129. CREATE PROCEDURE sp_dropalert
  3130. (
  3131. @name  varchar(60)
  3132. )
  3133. AS
  3134. BEGIN
  3135.   DECLARE @id int
  3136.  
  3137.   /* Is this user the SA? */
  3138.   IF (suser_id() <> 1)
  3139.   BEGIN
  3140.     RAISERROR(15003, 16, 1)
  3141.     RETURN(1)
  3142.   END
  3143.  
  3144.   /* Does this Alert exist? */
  3145.   IF NOT EXISTS (SELECT *
  3146.                  FROM msdb.dbo.sysalerts
  3147.                  WHERE name = @name)
  3148.   BEGIN
  3149.     RAISERROR(14507, 16, 1)
  3150.     RETURN(1)
  3151.   END
  3152.  
  3153.   /* Convert the Name to it's ID */
  3154.   SELECT @id = id
  3155.   FROM msdb.dbo.sysalerts
  3156.   WHERE name = @name
  3157.  
  3158.   BEGIN TRANSACTION
  3159.     /* Delete sysnotifications entries */
  3160.     DELETE FROM msdb.dbo.sysnotifications
  3161.     WHERE alert_id = @id
  3162.     /* Finally, do the actual DELETE */
  3163.     DELETE FROM msdb.dbo.sysalerts
  3164.     WHERE id = @id
  3165.   COMMIT TRANSACTION
  3166.  
  3167.   /*
  3168.   ** Notify the SQLExecutive of the change. This xp causes a complete refresh (the only kind
  3169.   ** of refresh for Alerts) of the Schedulers sysalerts cache.
  3170.   */
  3171.   EXEC master.dbo.sp_schedulersignal 'A'
  3172.   RETURN(0)
  3173. END
  3174. go
  3175.  
  3176.  
  3177. /**************************************************************/
  3178. /* SP_HELPALERT                                               */
  3179. /**************************************************************/
  3180. PRINT ''
  3181. PRINT 'Creating procedure sp_helpalert...'
  3182. go
  3183. CREATE PROCEDURE sp_helpalert
  3184. (
  3185. @having_name_like varchar(60) = '%',
  3186. @order_by varchar(60) = 'name'
  3187. )
  3188. AS
  3189. BEGIN
  3190.   DECLARE @FlagsColumn varchar(255)
  3191.  
  3192.   IF EXISTS (SELECT *
  3193.              FROM msdb.dbo.syscolumns
  3194.              WHERE id = object_id('dbo.sysalerts')
  3195.                AND name = 'flags')
  3196.     SELECT @FlagsColumn = 'flags = sa.flags '
  3197.   ELSE
  3198.     SELECT @FlagsColumn = 'flags = 0 '
  3199.  
  3200.   IF (@order_by NOT LIKE 'task_name%') AND (@order_by NOT LIKE 'task_id%')
  3201.     SELECT @order_by = 'sa.' + @order_by
  3202.   EXEC('SELECT
  3203.         sa.id,
  3204.         sa.name,
  3205.         sa.event_source,
  3206.         sa.event_categoryname,
  3207.         sa.event_id,
  3208.         sa.message_id,
  3209.         sa.severity,
  3210.         sa.enabled,
  3211.         sa.delay_between_notifications,
  3212.         sa.last_occurrence_date,
  3213.         sa.last_occurrence_time,
  3214.         sa.last_response_date,
  3215.         sa.last_response_time,
  3216.         sa.notification_message,
  3217.         sa.include_event_description,
  3218.         sa.database_name,
  3219.         sa.event_description_keyword,
  3220.         sa.occurrence_count,
  3221.         sa.count_reset_date,
  3222.         sa.count_reset_time,
  3223.         task_name = st.name,
  3224.         sa.has_email_notification,
  3225.         sa.has_pager_notification,
  3226.         task_id = st.id, ' + @FlagsColumn +
  3227.        'FROM msdb.dbo.sysalerts sa, msdb.dbo.systasks st
  3228.         WHERE (sa.task_id *= st.id)
  3229.           AND (sa.name LIKE ''' + @having_name_like + ''')
  3230.         ORDER BY ' + @order_by)
  3231. END
  3232. go
  3233.  
  3234.  
  3235. /**************************************************************/
  3236. /* SP_ADDOPERATOR                                             */
  3237. /**************************************************************/
  3238.  
  3239. PRINT ''
  3240. PRINT 'Creating procedure sp_addoperator...'
  3241. go
  3242. CREATE PROCEDURE sp_addoperator
  3243. (
  3244. @name                         varchar(50),
  3245. @enabled                      tinyint = 1,
  3246. @email_address                varchar(100) = NULL,
  3247. @pager_address                varchar(100) = NULL,
  3248. @weekday_pager_start_time     int = 090000, /* HHMMSS using 24 hour clock */
  3249. @weekday_pager_end_time       int = 180000, /* HHMMSS using 24 hour clock */
  3250. @saturday_pager_start_time    int = 090000, /* HHMMSS using 24 hour clock */
  3251. @saturday_pager_end_time      int = 180000, /* HHMMSS using 24 hour clock */
  3252. @sunday_pager_start_time      int = 090000, /* HHMMSS using 24 hour clock */
  3253. @sunday_pager_end_time        int = 180000, /* HHMMSS using 24 hour clock */
  3254. @pager_days                   tinyint = 0
  3255. )
  3256. AS
  3257. BEGIN
  3258.   /* Turn empty strings into NULLs */
  3259.   IF (ltrim(@email_address) = null) SELECT @email_address = NULL
  3260.   IF (ltrim(@pager_address) = null) SELECT @pager_address = NULL
  3261.  
  3262.   DECLARE @return_code tinyint
  3263.  
  3264.   /* Is this user the SA? */
  3265.   IF (suser_id() <> 1)
  3266.   BEGIN
  3267.     RAISERROR(15003, 16, 1)
  3268.     RETURN(1)
  3269.   END
  3270.  
  3271.   /* Does this Operator already exist? */
  3272.   IF EXISTS(SELECT *
  3273.             FROM msdb.dbo.sysoperators
  3274.             WHERE name = @name)
  3275.   BEGIN
  3276.     RAISERROR(14513, 16, 1)
  3277.     RETURN(1)
  3278.   END
  3279.  
  3280.   /* Valid Start/End Times? */
  3281.   EXEC @return_code = sp_verifytasktime @weekday_pager_start_time, 14522
  3282.   IF (@return_code <> 0) RETURN(1)
  3283.   EXEC @return_code = sp_verifytasktime @weekday_pager_end_time, 14523
  3284.   IF (@return_code <> 0) RETURN(1)
  3285.   EXEC @return_code = sp_verifytasktime @saturday_pager_start_time, 14524
  3286.   IF (@return_code <> 0) RETURN(1)
  3287.   EXEC @return_code = sp_verifytasktime @saturday_pager_end_time, 14525
  3288.   IF (@return_code <> 0) RETURN(1)
  3289.   EXEC @return_code = sp_verifytasktime @sunday_pager_start_time, 14526
  3290.   IF (@return_code <> 0) RETURN(1)
  3291.   EXEC @return_code = sp_verifytasktime @sunday_pager_end_time, 14527
  3292.   IF (@return_code <> 0) RETURN(1)
  3293.  
  3294.   /* Valid PagerDays? */
  3295.   IF (@pager_days < 0) OR (@pager_days > 127)
  3296.   BEGIN
  3297.     RAISERROR(14514, 16, 1)
  3298.     RETURN(1)
  3299.   END
  3300.  
  3301.   /* Enabled must be 0 or 1 */
  3302.   IF (@enabled NOT IN (0, 1))
  3303.   BEGIN
  3304.     RAISERROR(14516, 16, 1)
  3305.     RETURN(1)
  3306.   END
  3307.  
  3308.   /* Finally, do the INSERT */
  3309.   INSERT INTO msdb.dbo.sysoperators
  3310.   (
  3311.   name,
  3312.   enabled,
  3313.   email_address,
  3314.   last_email_date,
  3315.   last_email_time,
  3316.   pager_address,
  3317.   last_pager_date,
  3318.   last_pager_time,
  3319.   weekday_pager_start_time,
  3320.   weekday_pager_end_time,
  3321.   saturday_pager_start_time,
  3322.   saturday_pager_end_time,
  3323.   sunday_pager_start_time,
  3324.   sunday_pager_end_time,
  3325.   pager_days
  3326.   )
  3327.   VALUES
  3328.   (
  3329.   @name,
  3330.   @enabled,
  3331.   @email_address,
  3332.   NULL,
  3333.   NULL,
  3334.   @pager_address,
  3335.   NULL,
  3336.   NULL,
  3337.   @weekday_pager_start_time,
  3338.   @weekday_pager_end_time,
  3339.   @saturday_pager_start_time,
  3340.   @saturday_pager_end_time,
  3341.   @sunday_pager_start_time,
  3342.   @sunday_pager_end_time,
  3343.   @pager_days
  3344.   )
  3345.   RETURN(0)
  3346. END
  3347. go
  3348.  
  3349.  
  3350. /**************************************************************/
  3351. /* SP_UPDATEOPERATOR                                          */
  3352. /**************************************************************/
  3353.  
  3354. PRINT ''
  3355. PRINT 'Creating procedure sp_updateoperator...'
  3356. go
  3357. CREATE PROCEDURE sp_updateoperator
  3358. (
  3359. @name                         varchar(50),
  3360. @new_name                     varchar(50) = NULL,
  3361. @enabled                      tinyint = NULL,
  3362. @email_address                varchar(100) = NULL,
  3363. @pager_address                varchar(100) = NULL,
  3364. @weekday_pager_start_time     int = NULL, /* HHMMSS using 24 hour clock */
  3365. @weekday_pager_end_time       int = NULL, /* HHMMSS using 24 hour clock */
  3366. @saturday_pager_start_time    int = NULL, /* HHMMSS using 24 hour clock */
  3367. @saturday_pager_end_time      int = NULL, /* HHMMSS using 24 hour clock */
  3368. @sunday_pager_start_time      int = NULL, /* HHMMSS using 24 hour clock */
  3369. @sunday_pager_end_time        int = NULL, /* HHMMSS using 24 hour clock */
  3370. @pager_days                   tinyint = NULL
  3371. )
  3372. AS
  3373. BEGIN
  3374.   DECLARE @return_code               tinyint
  3375.   DECLARE @alert_fail_safe_operator  varchar(64)
  3376.  
  3377.   /* Is this user the SA? */
  3378.   IF (suser_id() <> 1)
  3379.   BEGIN
  3380.     RAISERROR(15003, 16, 1)
  3381.     RETURN(1)
  3382.   END
  3383.  
  3384.   /* Does this Operator exist? */
  3385.   IF NOT EXISTS(SELECT *
  3386.                 FROM msdb.dbo.sysoperators
  3387.                 WHERE name = @name)
  3388.   BEGIN
  3389.     RAISERROR(14508, 16, 1)
  3390.     RETURN(1)
  3391.   END
  3392.  
  3393.   /* Is the NewName unique? */
  3394.   IF (@new_name <> NULL) AND (EXISTS (SELECT *
  3395.                                       FROM msdb.dbo.sysoperators
  3396.                                       WHERE name = @new_name))
  3397.   BEGIN
  3398.     RAISERROR(14529, 16, 1)
  3399.     RETURN(1)
  3400.   END
  3401.  
  3402.   /* Valid Start/End Times? */
  3403.   IF (@weekday_pager_start_time <> NULL)
  3404.   BEGIN
  3405.     EXEC @return_code = sp_verifytasktime @weekday_pager_start_time, 14522
  3406.     IF (@return_code <> 0) RETURN(1)
  3407.   END
  3408.   IF (@weekday_pager_end_time <> NULL)
  3409.   BEGIN
  3410.     EXEC @return_code = sp_verifytasktime @weekday_pager_end_time, 14523
  3411.     IF (@return_code <> 0) RETURN(1)
  3412.   END
  3413.   IF (@saturday_pager_start_time <> NULL)
  3414.   BEGIN
  3415.     EXEC @return_code = sp_verifytasktime @saturday_pager_start_time, 14524
  3416.     IF (@return_code <> 0) RETURN(1)
  3417.   END
  3418.   IF (@saturday_pager_end_time <> NULL)
  3419.   BEGIN
  3420.     EXEC @return_code = sp_verifytasktime @saturday_pager_end_time, 14525
  3421.     IF (@return_code <> 0) RETURN(1)
  3422.   END
  3423.   IF (@sunday_pager_start_time <> NULL)
  3424.   BEGIN
  3425.     EXEC @return_code = sp_verifytasktime @sunday_pager_start_time, 14526
  3426.     IF (@return_code <> 0) RETURN(1)
  3427.   END
  3428.   IF (@sunday_pager_end_time <> NULL)
  3429.   BEGIN
  3430.     EXEC @return_code = sp_verifytasktime @sunday_pager_end_time, 14527
  3431.     IF (@return_code <> 0) RETURN(1)
  3432.   END
  3433.  
  3434.   /* Valid PagerDays? */
  3435.   IF (@pager_days <> NULL) AND ((@pager_days < 0) OR (@pager_days > 127))
  3436.   BEGIN
  3437.     RAISERROR(14514, 16, 1)
  3438.     RETURN(1)
  3439.   END
  3440.  
  3441.   /* Enabled must be 0 or 1 */
  3442.   IF (@enabled <> NULL) AND (@enabled NOT IN (0, 1))
  3443.   BEGIN
  3444.     RAISERROR(14516, 16, 1)
  3445.     RETURN(1)
  3446.   END
  3447.  
  3448.   BEGIN TRANSACTION
  3449.     IF (@new_name = NULL) SELECT @new_name = @name
  3450.     IF (@enabled = NULL) SELECT @enabled = enabled FROM msdb.dbo.sysoperators WHERE name = @name
  3451.     IF (@email_address = NULL) SELECT @email_address = email_address FROM msdb.dbo.sysoperators WHERE name = @name
  3452.     IF (@pager_address = NULL) SELECT @pager_address = pager_address FROM msdb.dbo.sysoperators WHERE name = @name
  3453.     IF (@weekday_pager_start_time = NULL) SELECT @weekday_pager_start_time = weekday_pager_start_time FROM msdb.dbo.sysoperators WHERE name = @name
  3454.     IF (@weekday_pager_end_time = NULL) SELECT @weekday_pager_end_time = weekday_pager_end_time FROM msdb.dbo.sysoperators WHERE name = @name
  3455.     IF (@saturday_pager_start_time = NULL) SELECT @saturday_pager_start_time = saturday_pager_start_time FROM msdb.dbo.sysoperators WHERE name = @name
  3456.     IF (@saturday_pager_end_time = NULL) SELECT @saturday_pager_end_time = saturday_pager_end_time FROM msdb.dbo.sysoperators WHERE name = @name
  3457.     IF (@sunday_pager_start_time = NULL) SELECT @sunday_pager_start_time = sunday_pager_start_time FROM msdb.dbo.sysoperators WHERE name = @name
  3458.     IF (@sunday_pager_end_time = NULL) SELECT @sunday_pager_end_time = sunday_pager_end_time FROM msdb.dbo.sysoperators WHERE name = @name
  3459.     IF (@pager_days = NULL) SELECT @pager_days = pager_days FROM msdb.dbo.sysoperators WHERE name = @name
  3460.  
  3461.     /* Turn empty strings into NULLs */
  3462.     IF (ltrim(@email_address) = null) SELECT @email_address = NULL
  3463.     IF (ltrim(@pager_address) = null) SELECT @pager_address = NULL
  3464.  
  3465.     /* Finally, do the UPDATE */
  3466.     UPDATE msdb.dbo.sysoperators SET
  3467.     name = @new_name,
  3468.     enabled = @enabled,
  3469.     email_address = @email_address,
  3470.     pager_address = @pager_address,
  3471.     weekday_pager_start_time = @weekday_pager_start_time,
  3472.     weekday_pager_end_time = @weekday_pager_end_time,
  3473.     saturday_pager_start_time = @saturday_pager_start_time,
  3474.     saturday_pager_end_time = @saturday_pager_end_time,
  3475.     sunday_pager_start_time = @sunday_pager_start_time,
  3476.     sunday_pager_end_time = @sunday_pager_end_time,
  3477.     pager_days = @pager_days
  3478.     WHERE (name = @name)
  3479.   COMMIT TRANSACTION
  3480.  
  3481.   /* Is this operator the Server.AlertFailSafeOperator? */
  3482.   EXECUTE master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  3483.                                 'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  3484.                                 'AlertFailSafeOperator',
  3485.                                 @param = @alert_fail_safe_operator OUTPUT
  3486.  
  3487.   /* If it is, we update the 3 'AlertFailSafe...' registry entries  and AlertNotificationMethod */
  3488.   IF (ltrim(rtrim(@alert_fail_safe_operator)) = ltrim(rtrim(@name)))
  3489.   BEGIN
  3490.     /* Update AlertFailSafeX values*/
  3491.     EXECUTE master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE',
  3492.                                    'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  3493.                                    'AlertFailSafeOperator',REG_SZ,@new_name
  3494.     EXECUTE master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE',
  3495.                                    'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  3496.                                    'AlertFailSafeEmailAddress',REG_SZ,@email_address
  3497.     EXECUTE master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE',
  3498.                                    'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  3499.                                    'AlertFailSafePagerAddress',REG_SZ,@pager_address
  3500.     /* Update AlertNotificationMethod values*/
  3501.     DECLARE @notification_method int
  3502.     EXECUTE master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  3503.                                   'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  3504.                                   'AlertNotificationMethod',@param = @notification_method OUTPUT
  3505.     IF (ltrim(rtrim(@email_address)) = null)
  3506.       SELECT @notification_method = @notification_method & ~1
  3507.     IF (ltrim(rtrim(@pager_address)) = null)
  3508.       SELECT @notification_method = @notification_method & ~2
  3509.     EXECUTE master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE',
  3510.                                    'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  3511.                                    'AlertNotificationMethod',REG_DWORD,@notification_method
  3512.     /* And finally, let the SQLExecutive know of the changes... */
  3513.     EXECUTE master.dbo.sp_schedulersignal 'G'
  3514.   END
  3515.  
  3516.   RETURN(0)
  3517. END
  3518. go
  3519.  
  3520.  
  3521. /**************************************************************/
  3522. /* SP_DROPOPERATOR                                            */
  3523. /**************************************************************/
  3524.  
  3525. PRINT ''
  3526. PRINT 'Creating procedure sp_dropoperator...'
  3527. go
  3528. CREATE PROCEDURE sp_dropoperator
  3529. (
  3530. @name varchar(50)
  3531. )
  3532. AS
  3533. BEGIN
  3534.   DECLARE @id                        int
  3535.   DECLARE @alert_fail_safe_operator  varchar(64)
  3536.   DECLARE @warning                   varchar(255)
  3537.  
  3538.   /* Is this user the SA? */
  3539.   IF (suser_id() <> 1)
  3540.   BEGIN
  3541.     RAISERROR(15003, 16, 1)
  3542.     RETURN(1)
  3543.   END
  3544.  
  3545.   /* Does this Operator exist? */
  3546.   IF NOT EXISTS (SELECT *
  3547.                  FROM msdb.dbo.sysoperators
  3548.                  WHERE name = @name)
  3549.   BEGIN
  3550.     RAISERROR(14508, 16, 1)
  3551.     RETURN(1)
  3552.   END
  3553.  
  3554.   /* Is this operator the Server.AlertFailSafeOperator? */
  3555.   EXECUTE master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  3556.                                 'SOFTWARE\Microsoft\MSSQLServer\SQLExecutive',
  3557.                                 'AlertFailSafeOperator',
  3558.                                 @param = @alert_fail_safe_operator OUTPUT
  3559.  
  3560.   /* If it is, we disallow the drop operation. */
  3561.   IF (ltrim(rtrim(@alert_fail_safe_operator)) = ltrim(rtrim(@name)))
  3562.   BEGIN
  3563.     SELECT @name = ltrim(rtrim(@name))
  3564.     RAISERROR(14530, 16, 1, @name, @name)
  3565.     RETURN(1)
  3566.   END
  3567.  
  3568.   /* Convert the Name to it's ID */
  3569.   SELECT @id = id
  3570.   FROM msdb.dbo.sysoperators
  3571.   WHERE name = @name
  3572.  
  3573.   BEGIN TRANSACTION
  3574.     /* Delete sysnotifications entries */
  3575.     DELETE FROM msdb.dbo.sysnotifications
  3576.     WHERE operator_id = @id
  3577.     /* Finally, do the actual DELETE */
  3578.     DELETE FROM msdb.dbo.sysoperators
  3579.     WHERE id = @id
  3580.   COMMIT TRANSACTION
  3581.   RETURN(0)
  3582. END
  3583. go
  3584.  
  3585.  
  3586. /**************************************************************/
  3587. /* SP_HELPOPERATOR                                            */
  3588. /**************************************************************/
  3589.  
  3590. PRINT ''
  3591. PRINT 'Creating procedure sp_helpoperator...'
  3592. go
  3593. CREATE PROCEDURE sp_helpoperator
  3594. (
  3595. @having_name_like varchar(50) = '%'
  3596. )
  3597. AS
  3598. BEGIN
  3599.   SELECT
  3600.   id,
  3601.   name,
  3602.   enabled,
  3603.   email_address,
  3604.   last_email_date,
  3605.   last_email_time,
  3606.   pager_address,
  3607.   last_pager_date,
  3608.   last_pager_time,
  3609.   weekday_pager_start_time,
  3610.   weekday_pager_end_time,
  3611.   saturday_pager_start_time,
  3612.   saturday_pager_end_time,
  3613.   sunday_pager_start_time,
  3614.   sunday_pager_end_time,
  3615.   pager_days
  3616.   FROM msdb.dbo.sysoperators
  3617.   WHERE (name LIKE @having_name_like)
  3618. END
  3619. go
  3620.  
  3621.  
  3622. /**************************************************************/
  3623. /* SP_ADDNOTIFICATION                                         */
  3624. /**************************************************************/
  3625.  
  3626. PRINT ''
  3627. PRINT 'Creating procedure sp_addnotification...'
  3628. go
  3629. CREATE PROCEDURE sp_addnotification
  3630. (
  3631. @alert_name           varchar(60),
  3632. @operator_name        varchar(50),
  3633. @notification_method  varchar(10)
  3634. )
  3635. AS
  3636. BEGIN
  3637.   DECLARE @alert_id                   int
  3638.   DECLARE @operator_id                int
  3639.   DECLARE @notification_method_code   tinyint
  3640.  
  3641.   /* Is this user the SA? */
  3642.   IF (suser_id() <> 1)
  3643.   BEGIN
  3644.     RAISERROR(15003, 16, 1)
  3645.     RETURN(1)
  3646.   END
  3647.  
  3648.   /* Is the AlertName valid? */
  3649.   IF NOT EXISTS(SELECT *
  3650.                 FROM msdb.dbo.sysalerts
  3651.                 WHERE name = ltrim(rtrim(@alert_name))
  3652.                 HAVING count(*) = 1)
  3653.   BEGIN
  3654.     RAISERROR(14507, 16, 1)
  3655.     RETURN(1)
  3656.   END
  3657.  
  3658.   /* Is the OperatorName valid? */
  3659.   IF NOT EXISTS(SELECT *
  3660.                 FROM msdb.dbo.sysoperators
  3661.                 WHERE name = ltrim(rtrim(@operator_name))
  3662.                 HAVING count(*) = 1)
  3663.   BEGIN
  3664.     RAISERROR(14508, 16, 1)
  3665.     RETURN(1)
  3666.   END
  3667.  
  3668.   /* Is the NotificationMethod valid? */
  3669.   SELECT @notification_method = upper(@notification_method)
  3670.   IF (@notification_method NOT IN ('EMAIL', 'PAGER', 'BOTH'))
  3671.   BEGIN
  3672.     RAISERROR(14517, 16, 1)
  3673.     RETURN(1)
  3674.   END
  3675.  
  3676.   /* Convert the AlertName to an ID */
  3677.   SELECT @alert_id = id
  3678.   FROM msdb.dbo.sysalerts
  3679.   WHERE name = ltrim(rtrim(@alert_name))
  3680.  
  3681.   /* Convert the OperatorName to an ID */
  3682.   SELECT @operator_id = id
  3683.   FROM msdb.dbo.sysoperators
  3684.   WHERE name = ltrim(rtrim(@operator_name))
  3685.  
  3686.   /* Convert the NotificationMethod to it's matching code */
  3687.   IF (@notification_method = 'EMAIL') SELECT @notification_method_code = 1
  3688.   IF (@notification_method = 'PAGER') SELECT @notification_method_code = 2
  3689.   IF (@notification_method = 'BOTH') SELECT @notification_method_code = 3
  3690.  
  3691.   /* Does this notification already exist? */
  3692.   /* NOTE: The unique index would catch this, but testing     */
  3693.   /*       for the problem here let's us control the message. */
  3694.   IF EXISTS(SELECT *
  3695.             FROM msdb.dbo.sysnotifications
  3696.             WHERE (alert_id = @alert_id)
  3697.               AND (operator_id = @operator_id))
  3698.   BEGIN
  3699.     RAISERROR(14515, 16, 1)
  3700.     RETURN(0)
  3701.   END
  3702.  
  3703.   /* Finally, do the INSERT */
  3704.   INSERT INTO sysnotifications
  3705.   (
  3706.   alert_id,
  3707.   operator_id,
  3708.   notification_method
  3709.   )
  3710.   VALUES
  3711.   (
  3712.   @alert_id,
  3713.   @operator_id,
  3714.   @notification_method_code
  3715.   )
  3716.   RETURN(0)
  3717. END
  3718. go
  3719.  
  3720.  
  3721. /**************************************************************/
  3722. /* SP_UPDATENOTIFICATION                                      */
  3723. /**************************************************************/
  3724.  
  3725. PRINT ''
  3726. PRINT 'Creating procedure sp_updatenotification...'
  3727. go
  3728. CREATE PROCEDURE sp_updatenotification
  3729. (
  3730. @alert_name           varchar(60),
  3731. @operator_name        varchar(50),
  3732. @notification_method  varchar(10)
  3733. )
  3734. AS
  3735. BEGIN
  3736.   DECLARE @alert_id                  int
  3737.   DECLARE @operator_id               int
  3738.   DECLARE @notification_method_code  tinyint
  3739.  
  3740.   /* Is this user the SA? */
  3741.   IF (suser_id() <> 1)
  3742.   BEGIN
  3743.     RAISERROR(15003, 16, 1)
  3744.     RETURN(1)
  3745.   END
  3746.  
  3747.   /* Is the AlertName valid? */
  3748.   IF NOT EXISTS(SELECT *
  3749.                 FROM msdb.dbo.sysalerts
  3750.                 WHERE name = ltrim(rtrim(@alert_name))
  3751.                 HAVING count(*) = 1)
  3752.   BEGIN
  3753.     RAISERROR(14507, 16, 1)
  3754.     RETURN(1)
  3755.   END
  3756.  
  3757.   /* Is the OperatorName valid? */
  3758.   IF NOT EXISTS(SELECT *
  3759.                 FROM msdb.dbo.sysoperators
  3760.                 WHERE name = ltrim(rtrim(@operator_name))
  3761.                 HAVING count(*) = 1)
  3762.   BEGIN
  3763.     RAISERROR(14508, 16, 1)
  3764.     RETURN(1)
  3765.   END
  3766.  
  3767.   /* Convert the AlertName to an ID */
  3768.   SELECT @alert_id = id
  3769.   FROM msdb.dbo.sysalerts
  3770.   WHERE name = ltrim(rtrim(@alert_name))
  3771.  
  3772.   /* Convert the OperatorName to an ID */
  3773.   SELECT @operator_id = id
  3774.   FROM msdb.dbo.sysoperators
  3775.   WHERE name = ltrim(rtrim(@operator_name))
  3776.  
  3777.   /* Does this notification exist? */
  3778.   IF NOT EXISTS(SELECT *
  3779.                 FROM msdb.dbo.sysnotifications
  3780.                 WHERE alert_id = @alert_id
  3781.                   AND operator_id = @operator_id)
  3782.   BEGIN
  3783.     RAISERROR(14509, 16, 1)
  3784.     RETURN(1)
  3785.   END
  3786.  
  3787.   /* Is the NotificationMethod valid? */
  3788.   SELECT @notification_method = upper(@notification_method)
  3789.   IF (@notification_method NOT IN ('EMAIL', 'PAGER', 'BOTH'))
  3790.   BEGIN
  3791.     RAISERROR(14517, 16, 1)
  3792.     RETURN(1)
  3793.   END
  3794.  
  3795.   /* Convert the NotificationMethod to it's matching code */
  3796.   IF (@notification_method = 'EMAIL') SELECT @notification_method_code = 1
  3797.   IF (@notification_method = 'PAGER') SELECT @notification_method_code = 2
  3798.   IF (@notification_method = 'BOTH') SELECT @notification_method_code = 3
  3799.  
  3800.   /* Do the INSERT */
  3801.   UPDATE msdb.dbo.sysnotifications
  3802.   SET notification_method = @notification_method_code
  3803.   WHERE (alert_id = @alert_id)
  3804.     AND (operator_id = @operator_id)
  3805.  
  3806.   RETURN(0)
  3807. END
  3808. go
  3809.  
  3810.  
  3811. /**************************************************************/
  3812. /* SP_DROPNOTIFICATION                                        */
  3813. /**************************************************************/
  3814.  
  3815. PRINT ''
  3816. PRINT 'Creating procedure sp_dropnotification...'
  3817. go
  3818. CREATE PROCEDURE sp_dropnotification
  3819. (
  3820. @alert_name     varchar(60),
  3821. @operator_name  varchar(50)
  3822. )
  3823. AS
  3824. BEGIN
  3825.   DECLARE @alert_id     int
  3826.   DECLARE @operator_id  int
  3827.  
  3828.   /* Is this user the SA? */
  3829.   IF (suser_id() <> 1)
  3830.   BEGIN
  3831.     RAISERROR(15003, 16, 1)
  3832.     RETURN(1)
  3833.   END
  3834.  
  3835.   /* Is the AlertName valid? */
  3836.   IF NOT EXISTS(SELECT *
  3837.                 FROM msdb.dbo.sysalerts
  3838.                 WHERE name = ltrim(rtrim(@alert_name))
  3839.                 HAVING count(*) = 1)
  3840.   BEGIN
  3841.     RAISERROR(14507, 16, 1)
  3842.     RETURN(1)
  3843.   END
  3844.  
  3845.   /* Is the OperatorName valid? */
  3846.   IF NOT EXISTS(SELECT *
  3847.                 FROM msdb.dbo.sysoperators
  3848.                 WHERE name = ltrim(rtrim(@operator_name))
  3849.                 HAVING count(*) = 1)
  3850.   BEGIN
  3851.     RAISERROR(14508, 16, 1)
  3852.     RETURN(1)
  3853.   END
  3854.  
  3855.   /* Convert the AlertName to an ID */
  3856.   SELECT @alert_id = id
  3857.   FROM msdb.dbo.sysalerts
  3858.   WHERE name = ltrim(rtrim(@alert_name))
  3859.  
  3860.   /* Convert the OperatorName to an ID */
  3861.   SELECT @operator_id = id
  3862.   FROM msdb.dbo.sysoperators
  3863.   WHERE name = ltrim(rtrim(@operator_name))
  3864.  
  3865.   /* Does this notification exist? */
  3866.   IF NOT EXISTS(SELECT *
  3867.                 FROM msdb.dbo.sysnotifications
  3868.                 WHERE alert_id = @alert_id
  3869.                   AND operator_id = @operator_id)
  3870.   BEGIN
  3871.     RAISERROR(14509, 16, 1)
  3872.     RETURN(1)
  3873.   END
  3874.  
  3875.   /* Finally, do the Delete */
  3876.   DELETE FROM msdb.dbo.sysnotifications
  3877.   WHERE (alert_id = @alert_id)
  3878.     AND (operator_id = @operator_id)
  3879.   RETURN(0)
  3880. END
  3881. go
  3882.  
  3883.  
  3884. /**************************************************************/
  3885. /* SP_HELPNOTIFICATION                                        */
  3886. /**************************************************************/
  3887. PRINT ''
  3888. PRINT 'Creating procedure sp_helpnotification...'
  3889. go
  3890. CREATE PROCEDURE sp_helpnotification
  3891. (
  3892. @object_type          char(9),  /* Either 'ALERTS' (Enum Alerts for given Operator),   */
  3893.                                 /*     or 'OPERATORS' (Enum Operators for given Alert) */
  3894. @name                 char(60), /* Either an Operator Name (if @ObjectType = 'ALERTS') */
  3895.                                 /*     or an Alert Name (if @ObjectType = 'OPERATORS') */
  3896. @enum_type            char(10), /* Either 'ALL' (Enumerate all objects)                                  */
  3897.                                 /*     or 'ACTUAL' (Enumerate only the associated objects)               */
  3898.                                 /*     or 'TARGET' (Enumerate only the objects matching @TargetName) */
  3899. @notification_method  char(10), /* Either 'EMAIL' (show only email notification info.),    */
  3900.                                 /*     or 'PAGER' (show only pager notification info.),    */
  3901.                                 /*     or 'BOTH' (show both pager and email notification info.) */
  3902. @target_name          char(60) = NULL /* Either an Alert Name (if @ObjectType = 'ALERTS')             */
  3903.                                       /*     or an Operator Name (if @ObjectType = 'OPERATORS')       */
  3904.                                       /* This parameter is only required if @EnumType = 'TARGET') */
  3905. )
  3906. AS
  3907. BEGIN
  3908.   DECLARE @id               int /*We will use this to store the decode of @Name */
  3909.   DECLARE @target_id        int /*We will use this to store the decode of @TargetName */
  3910.   DECLARE @select_clause_1  varchar(255)
  3911.   DECLARE @select_clause_2  varchar(255)
  3912.   DECLARE @from_clause      varchar(255)
  3913.   DECLARE @where_clause     varchar(255)
  3914.   DECLARE @bitmap           varchar(255)
  3915.  
  3916.   SELECT @object_type = upper(@object_type)
  3917.   SELECT @enum_type = upper(@enum_type)
  3918.   SELECT @notification_method = upper(@notification_method)
  3919.  
  3920.   /* Valid ObjectType? */
  3921.   IF (@object_type NOT IN ('ALERTS', 'OPERATORS'))
  3922.   BEGIN
  3923.     RAISERROR(14510, 16, 1)
  3924.     RETURN(1)
  3925.   END
  3926.  
  3927.   /* Valid AlertName? */
  3928.   IF (@object_type = 'OPERATORS') AND (NOT EXISTS (SELECT *
  3929.                                                    FROM msdb.dbo.sysalerts
  3930.                                                    WHERE name = @name))
  3931.   BEGIN
  3932.     RAISERROR(14507, 16, 1)
  3933.     RETURN(1)
  3934.   END
  3935.  
  3936.   /* Valid OperatorName? */
  3937.   IF (@object_type = 'ALERTS') AND (NOT EXISTS (SELECT *
  3938.                                                 FROM msdb.dbo.sysoperators
  3939.                                                 WHERE name = @name))
  3940.   BEGIN
  3941.     RAISERROR(14508, 16, 1)
  3942.     RETURN(1)
  3943.   END
  3944.  
  3945.   /* Valid EnumType? */
  3946.   IF (@enum_type NOT IN ('ALL', 'ACTUAL', 'TARGET'))
  3947.   BEGIN
  3948.     RAISERROR(14511, 16, 1)
  3949.     RETURN(1)
  3950.   END
  3951.  
  3952.   /* Valid Notification Method? */
  3953.   IF (@notification_method NOT IN ('EMAIL', 'PAGER', 'BOTH'))
  3954.   BEGIN
  3955.     RAISERROR(14512, 16, 1)
  3956.     RETURN(1)
  3957.   END
  3958.  
  3959.   /* If EnumType is 'TARGET', do we have a @TargetName parameter? */
  3960.   IF (@enum_type = 'TARGET') AND (@target_name = NULL)
  3961.   BEGIN
  3962.     RAISERROR(14519, 16, 1)
  3963.     RETURN(1)
  3964.   END
  3965.  
  3966.   /* If EnumType isn't 'TARGET', we shouldn't have an @TargetName parameter */
  3967.   IF (@enum_type <> 'TARGET') AND (@target_name <> NULL)
  3968.   BEGIN
  3969.     RAISERROR(14520, 16, 1)
  3970.     RETURN(1)
  3971.   END
  3972.  
  3973.   /* Transalate the Name into an ID */
  3974.   IF (@object_type = 'ALERTS')
  3975.   BEGIN
  3976.     SELECT @id = id
  3977.     FROM msdb.dbo.sysoperators
  3978.     WHERE (name = @name)
  3979.   END
  3980.   IF (@object_type = 'OPERATORS')
  3981.   BEGIN
  3982.     SELECT @id = id
  3983.     FROM msdb.dbo.sysalerts
  3984.     WHERE (name = @name)
  3985.   END
  3986.  
  3987.   /* Transalate the TargetName into a TargetID */
  3988.   IF (@target_name <> NULL) AND (@object_type = 'OPERATORS')
  3989.   BEGIN
  3990.     SELECT @target_id = id
  3991.     FROM msdb.dbo.sysoperators
  3992.     WHERE (name = @target_name )
  3993.   END
  3994.   IF (@target_name <> NULL) AND (@object_type = 'ALERTS')
  3995.   BEGIN
  3996.     SELECT @target_id = id
  3997.     FROM msdb.dbo.sysalerts
  3998.     WHERE (name = @target_name)
  3999.   END
  4000.   IF (@enum_type = 'TARGET') AND (@target_id = NULL) /* IE. the Target Name is invalid */
  4001.   BEGIN
  4002.     DECLARE @temp varchar(9)
  4003.     SELECT @temp = LOWER(@object_type)
  4004.     RAISERROR(14521, 16, 1, @temp)
  4005.     RETURN(1)
  4006.   END
  4007.  
  4008.  
  4009.   /* Ok, the parameters look good so generate the SQL then EXECUTE() it */
  4010.   IF (@object_type = 'OPERATORS') /* So we want a list of Operators for the supplied Alert ID */
  4011.   BEGIN
  4012.     SELECT @select_clause_1 = 'SELECT operator_id = o.id, operator_name = o.name, '
  4013.     SELECT @from_clause = 'FROM msdb.dbo.sysnotifications sn, msdb.dbo.sysoperators o '
  4014.   END
  4015.   IF (@object_type = 'ALERTS') /* So we want a list of Alerts for the supplied Operator ID */
  4016.   BEGIN
  4017.     SELECT @select_clause_1 = 'SELECT alert_id = a.id, alert_name = a.name, '
  4018.     SELECT @from_clause = 'FROM msdb.dbo.sysnotifications sn, msdb.dbo.sysalerts a '
  4019.   END
  4020.  
  4021.   IF (@notification_method = 'EMAIL') SELECT @bitmap = 'power(2, 0)'
  4022.   IF (@notification_method = 'PAGER') SELECT @bitmap = 'power(2, 1)'
  4023.   IF (@notification_method = 'BOTH') SELECT @bitmap = '0'
  4024.  
  4025.   IF (@notification_method = 'EMAIL') SELECT @select_clause_1 = @select_clause_1 + 'use_email = isnull((sn.notification_method&1) / power(2, 0), 0) '
  4026.   IF (@notification_method = 'PAGER') SELECT @select_clause_1 = @select_clause_1 + 'use_pager = isnull((sn.notification_method&2) / power(2, 1), 0) '
  4027.   IF (@notification_method = 'BOTH') SELECT @select_clause_1 = @select_clause_1 + 'use_email = isnull((sn.notification_method&1) / power(2, 0), 0), use_pager = isnull((sn.notification_method&2) / power(2, 1), 0) '
  4028.  
  4029.   IF (@object_type = 'OPERATORS') AND (@enum_type = 'ALL') SELECT @where_clause = 'WHERE (o.id *= sn.operator_id) AND (sn.alert_id = ' + convert(varchar(10), @id) + ')'
  4030.   IF (@object_type = 'OPERATORS') AND (@enum_type = 'ACTUAL') SELECT @where_clause = 'WHERE (o.id = sn.operator_id) AND (sn.alert_id = ' + convert(varchar(10), @id) + ') AND (sn.notification_method & ' + @bitmap + ' = ' + @bitmap + ')'
  4031.   IF (@object_type = 'OPERATORS') AND (@enum_type = 'TARGET') SELECT @where_clause = 'WHERE (o.id = sn.operator_id) AND (sn.operator_id = ' + convert(varchar(10), @target_id) + ') AND (sn.alert_id = ' + convert(varchar(10), @id) + ')'
  4032.   IF (@object_type = 'ALERTS') AND (@enum_type = 'ALL') SELECT @where_clause = 'WHERE (a.id *= sn.alert_id) AND (sn.operator_id = ' + convert(varchar(10), @id) + ')'
  4033.   IF (@object_type = 'ALERTS') AND (@enum_type = 'ACTUAL') SELECT @where_clause = 'WHERE (a.id = sn.alert_id) AND (sn.operator_id = ' + convert(varchar(10), @id) + ') AND (sn.notification_method & ' + @bitmap + ' = ' + @bitmap + ')'
  4034.   IF (@object_type = 'ALERTS') AND (@enum_type = 'TARGET') SELECT @where_clause = 'WHERE (a.id = sn.alert_id) AND (sn.alert_id = ' + convert(varchar(10), @target_id) + ') AND (sn.operator_id = ' + convert(varchar(10), @id) + ')'
  4035.  
  4036.   /* Additions for new has_email and has_pager columns */
  4037.   IF (@object_type = 'OPERATORS')
  4038.   BEGIN
  4039.     SELECT @select_clause_2 = ',has_email = convert(bit, isnull(ascii(substring(ltrim(rtrim(o.email_address)), 1, 1)), 0)),'
  4040.     SELECT @select_clause_2 = @select_clause_2 + 'has_pager = convert(bit, isnull(ascii(substring(ltrim(rtrim(o.pager_address)), 1, 1)), 0)) '
  4041.   END
  4042.   IF (@object_type = 'ALERTS')
  4043.   BEGIN
  4044.     SELECT @select_clause_2 = ',has_email = a.has_email_notification,'
  4045.     SELECT @select_clause_2 = @select_clause_2 + 'has_pager = a.has_pager_notification '
  4046.   END
  4047.  
  4048.   EXECUTE (@select_clause_1 + @select_clause_2 + @from_clause + @where_clause)
  4049.  
  4050.   RETURN(0)
  4051. END
  4052. go
  4053.  
  4054.  
  4055. /**************************************************************/
  4056. /* T R I G G E R S                                            */
  4057. /**************************************************************/
  4058.  
  4059. DUMP TRANSACTION msdb WITH NO_LOG
  4060. go
  4061.  
  4062. /**************************************************************/
  4063. /* NEWORCHANGEDNOTIFICATION                                   */
  4064. /**************************************************************/
  4065.  
  4066. PRINT ''
  4067. PRINT 'Creating trigger NewOrChangedNotification...'
  4068. go
  4069. CREATE TRIGGER NewOrChangedNotification
  4070. ON sysnotifications
  4071. FOR UPDATE, INSERT
  4072. AS
  4073. BEGIN
  4074.   /* First, throw out 'non-notification' rows */
  4075.   DELETE FROM msdb.dbo.sysnotifications
  4076.   WHERE (notification_method = 0)
  4077.  
  4078.   /* Update sysalerts.has_email_notification */
  4079.   UPDATE sysalerts
  4080.   SET has_email_notification = (SELECT count(*)
  4081.                                 FROM msdb.dbo.sysnotifications
  4082.                                 WHERE alert_id = sysalerts.id
  4083.                                   AND notification_method&1 = 1)
  4084.   FROM msdb.dbo.sysalerts, inserted
  4085.   WHERE inserted.alert_id = sysalerts.id
  4086.  
  4087.   /*Update sysalerts.has_pager_notification */
  4088.   UPDATE sysalerts
  4089.   SET has_pager_notification = (SELECT count(*)
  4090.                                 FROM msdb.dbo.sysnotifications
  4091.                                 WHERE alert_id = sysalerts.id
  4092.                                   AND notification_method&2 = 2)
  4093.   FROM msdb.dbo.sysalerts, inserted
  4094.   WHERE inserted.alert_id = sysalerts.id
  4095. END
  4096. go
  4097.  
  4098. /**************************************************************/
  4099. /* REMOVEDNOTIFICATION                                        */
  4100. /**************************************************************/
  4101.  
  4102. PRINT ''
  4103. PRINT 'Creating trigger RemovedNotification...'
  4104. go
  4105. CREATE TRIGGER RemovedNotification
  4106. ON sysnotifications
  4107. FOR DELETE
  4108. AS
  4109. BEGIN
  4110.   /* Update sysalerts.has_email_notification */
  4111.   UPDATE sysalerts
  4112.   SET has_email_notification = (SELECT count(*)
  4113.                                 FROM msdb.dbo.sysnotifications
  4114.                                 WHERE alert_id = sysalerts.id
  4115.                                   AND notification_method&1 = 1)
  4116.   FROM msdb.dbo.sysalerts, deleted
  4117.   WHERE deleted.alert_id = sysalerts.id
  4118.  
  4119.   /*Update sysalerts.has_pager_notification */
  4120.   UPDATE sysalerts
  4121.   SET has_pager_notification = (SELECT count(*)
  4122.                                 FROM msdb.dbo.sysnotifications
  4123.                                 WHERE alert_id = sysalerts.id
  4124.                                   AND notification_method&2 = 2)
  4125.   FROM msdb.dbo.sysalerts, deleted
  4126.   WHERE deleted.alert_id = sysalerts.id
  4127. END
  4128. go
  4129.  
  4130. DUMP TRANSACTION msdb WITH NO_LOG
  4131. go
  4132.  
  4133.  
  4134. /**************************************************************/
  4135. /* SP_MSSENDLARGEMAIL                                         */
  4136. /**************************************************************/
  4137.  
  4138. IF EXISTS (SELECT *
  4139.            FROM sysobjects
  4140.            WHERE name = 'sp_MSsendlargemail'
  4141.              AND sysstat & 0xf = 4)
  4142. BEGIN
  4143.   DROP PROCEDURE dbo.sp_MSsendlargemail
  4144. END
  4145. go
  4146.  
  4147. PRINT ''
  4148. PRINT 'Creating procedure sp_MSsendlargemail...'
  4149. go
  4150. CREATE PROCEDURE sp_MSsendlargemail
  4151. (
  4152. @recipients      text,
  4153. @copy_recipients text = '',
  4154. @subject         text = 'SQL Server Message',
  4155. @message         text
  4156. )
  4157. AS
  4158. SET NOCOUNT ON
  4159. DECLARE @TableName varchar(30)
  4160. DECLARE @LengthOfBody varchar(10)
  4161. SELECT @LengthOfBody = convert(varchar(10), datalength(@message) + 1)
  4162. SELECT @TableName = '##TempMailTable' + convert(varchar(30), abs(convert(int, @@dbts)))
  4163. EXEC ('CREATE TABLE ' + @TableName + ' (EmailBody text)')
  4164. EXEC ('SET QUOTED_IDENTIFIER OFF
  4165.        INSERT INTO ' + @TableName + ' values ("' + @message + '")')
  4166. EXEC ('SET QUOTED_IDENTIFIER OFF
  4167.        EXEC master.dbo.xp_sendmail
  4168.        @recipients = "' + @recipients + '",
  4169.        @copy_recipients = "' + @copy_recipients + '",
  4170.        @query = "SELECT EmailBody FROM '+ @TableName + '",
  4171.        @subject = "' + @subject + '",
  4172.        @width = 4096, /* Do NOT change this */
  4173.        @no_header = "True"')
  4174. EXEC ('DROP TABLE ' + @TableName)
  4175. go
  4176.  
  4177.  
  4178.  
  4179. /**************************************************************/
  4180. /**                                                          **/
  4181. /**       B A C K U P   H I S T O R Y   S U P P O R T        **/
  4182. /**                                                          **/
  4183. /**************************************************************/
  4184.  
  4185. /**************************************************************/
  4186. /* T A B L E S                                                */
  4187. /**************************************************************/
  4188.  
  4189. /**************************************************************/
  4190. /* SYSBACKUPHISTORY                                           */
  4191. /**************************************************************/
  4192. IF NOT EXISTS(SELECT * FROM sysobjects WHERE id = object_id('dbo.sysbackuphistory') AND sysstat & 0xf = 1)
  4193. BEGIN
  4194.   PRINT ''
  4195.   PRINT 'Creating table sysbackuphistory...'
  4196.  
  4197.   CREATE TABLE sysbackuphistory
  4198.   (
  4199.   backup_id         int             identity(1,1), -- Primary key
  4200.   constraint        pk_backup_id    primary key clustered (backup_id),  -- with clustered index
  4201.   id_number         smallint        not null,      -- Position of the backup on the volume
  4202.   backup_type       smallint        not null,      -- Database(1), Transaction(2), Table(3)
  4203.   database_name     varchar(30)     not null,      -- Database name
  4204.   table_owner       varchar(30)     null,          -- Single Table Owner
  4205.   table_name        varchar(30)     null,          -- Table name for table backups
  4206.   operator_name     char(30)        not null,      -- Name of person who performed the backup
  4207.   backup_start      datetime        not null,      -- Date and time of the oldest committed transaction
  4208.   backup_finish     datetime        not null,      -- Date and time of the last committed transaction
  4209.   server_sort       smallint        not null,      -- Database server sort order
  4210.   server_code_page  smallint        not null,      -- Database server code page
  4211.   striped_backup    smallint        not null,      -- Striped backup(1), non-striped backup(0)
  4212.   stripe_count      smallint        not null,      -- Number of devices in the stripeset
  4213.   stripe_set_name   varchar(30)     null,          -- Stripeset Name
  4214.   total_backup_size int             not null,      -- Total size of backup in bytes (not pages)
  4215.   current_sequence  char(14)        not null,      -- Currentsequence number
  4216.   new_sequence      char(14)        null           -- New sequence number
  4217.   )
  4218. END
  4219. go
  4220.  
  4221. /**************************************************************/
  4222. /* SYSBACKUPDETAIL                                            */
  4223. /**************************************************************/
  4224. IF NOT EXISTS(SELECT * FROM sysobjects WHERE id = object_id('dbo.sysbackupdetail') AND sysstat & 0xf = 1)
  4225. BEGIN
  4226.   PRINT ''
  4227.   PRINT 'Creating table sysbackupdetail...'
  4228.  
  4229.   CREATE TABLE sysbackupdetail
  4230.   (
  4231.   backup_id       int             not null,    -- Foreign key
  4232.   constraint      fk_backup_id    foreign key (backup_id)
  4233.   references      sysbackuphistory(backup_id), -- to sysbackuphistory
  4234.   device_type     smallint        not null,    -- Disk(2), Floppy(3), Tape(5) or Pipe(6)
  4235.   device_name     varchar(255)    not null,    -- Device or UNC Name
  4236.   backup_size     int             not null,    -- Size of backup on this device in bytes (not pages)
  4237.   volume_name     varchar(6)      null,        -- Volume label
  4238.   expiration_date datetime        null         -- Expiration date for the volume
  4239.   )
  4240. END
  4241. go
  4242.  
  4243. /**************************************************************/
  4244. /* SYSRESTOREHISTORY                                          */
  4245. /**************************************************************/
  4246. IF NOT EXISTS(SELECT * FROM sysobjects WHERE id = object_id('dbo.sysrestorehistory') AND sysstat & 0xf = 1)
  4247. BEGIN
  4248.   PRINT ''
  4249.   PRINT 'Creating table sysrestorehistory...'
  4250.  
  4251.   CREATE TABLE sysrestorehistory
  4252.   (
  4253.   restore_id           int           identity(1,1)  -- Primary key
  4254.   constraint           pk_restore_id primary key clustered (restore_id),    -- with clustered index
  4255.   id_number            smallint      not null,      -- Position of the backup on the volume
  4256.   backup_type          smallint      not null,      -- Database(1), Transaction(2), Table(3)
  4257.   source_database_name varchar(30)   not null,      -- Source (original) database name
  4258.   new_database_name    varchar(30)   not null,      -- New (destination) database name
  4259.   table_owner          varchar(30)   null,          -- Single Table Owner
  4260.   table_name           varchar(30)   null,          -- Table name for table backups
  4261.   operator_name        char(30)      not null,      -- Name of person who performed the backup
  4262.   backup_start         datetime      not null,      -- Date and time of the oldest committed transaction
  4263.   backup_finish        datetime      not null,      -- Date and time of the last committed transaction
  4264.   server_sort          smallint      not null,      -- Database server sort order
  4265.   server_code_page     smallint      not null,      -- Database server code page
  4266.   striped_backup       smallint      not null,      -- Striped backup(1), non-striped backup(0)
  4267.   stripe_Count         smallint      not null,      -- Number of devices in the stripeset
  4268.   stripe_set_name      varchar(30)   null,          -- Stripeset Name
  4269.   total_backup_size    int           not null,      -- Total size of backup in bytes (not pages)
  4270.   current_sequence     char(14)      not null,      -- Currentsequence number
  4271.   new_sequence         char(14)      null,          -- New sequence number
  4272.   restore_date         datetime      not null       -- Date/time restore performed
  4273.   )
  4274. END
  4275. go
  4276.  
  4277. /**************************************************************/
  4278. /* SYSRESTOREDETAIL                                           */
  4279. /**************************************************************/
  4280. IF NOT EXISTS(SELECT * FROM sysobjects WHERE id = object_id('dbo.sysrestoredetail') AND sysstat & 0xf = 1)
  4281. BEGIN
  4282.   PRINT ''
  4283.   PRINT 'Creating table sysrestoredetail...'
  4284.  
  4285.   CREATE TABLE sysrestoredetail
  4286.   (
  4287.   restore_id      int                            -- Foreign key
  4288.   constraint      fk_restore_id   foreign key (restore_id)
  4289.   references      sysrestorehistory(restore_id), -- to sysrestorehistory
  4290.   device_type     smallint        not null,      -- Disk(2), Floppy(3), Tape(5) or Pipe(6)
  4291.   device_name     varchar(255)    not null,      -- Device or UNC Name
  4292.   backup_size     int             not null,      -- Size of backup on this device in bytes (not pages)
  4293.   volume_name     varchar(6)      null,          -- Volume label
  4294.   expiration_date datetime        null           -- Expiration date for the volume
  4295.   )
  4296. END
  4297. go
  4298.  
  4299. /**************************************************************/
  4300. /* SYSVOLUMELABEL                                             */
  4301. /**************************************************************/
  4302. IF NOT EXISTS(SELECT * FROM sysobjects WHERE id = object_id('dbo.sysvolumelabel') AND sysstat & 0xf = 3)
  4303. BEGIN
  4304.   PRINT ''
  4305.   PRINT 'Creating table sysvolumelabel...'
  4306.  
  4307.   EXEC("CREATE TABLE sysvolumelabel
  4308.         (
  4309.         label_prefix   char(2)  not null,
  4310.         label_counter  int      not null
  4311.         )")
  4312.  
  4313.   EXEC("INSERT INTO sysvolumelabel (label_prefix, label_counter) VALUES ('SS', 0)")
  4314. END
  4315. go
  4316.  
  4317.  
  4318. /**************************************************************/
  4319. /* S T O R E D    P R O C E D U R E S                         */
  4320. /**************************************************************/
  4321.  
  4322. /**************************************************************/
  4323. /* SP_GET_VOLUME_LABEL (a 'master' database proc)             */
  4324. /**************************************************************/
  4325. PRINT ''
  4326. PRINT 'Creating procedure sp_get_volume_label...'
  4327. go
  4328.  
  4329. USE master
  4330. go
  4331. EXEC sp_configure 'allow updates', 1
  4332. RECONFIGURE WITH OVERRIDE
  4333. PRINT 'The RECONFIGURE command was run.'
  4334. go
  4335.  
  4336. IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'sp_get_volume_label' AND sysstat & 0xf = 4))
  4337.   DROP PROC sp_get_volume_label
  4338. go
  4339.  
  4340. CREATE PROCEDURE sp_get_volume_label
  4341. AS
  4342. BEGIN
  4343.   DECLARE @volume_counter int
  4344.   DECLARE @volume_prefix  char(2)
  4345.   DECLARE @volume_label   char(6)
  4346.   DECLARE @junk_counter   varchar(4)
  4347.   DECLARE @junk_string    char(6)
  4348.  
  4349.   BEGIN TRANSACTION
  4350.     UPDATE msdb.dbo.sysvolumelabel
  4351.     SET @volume_counter = label_counter = label_counter + 1,
  4352.     @volume_prefix = label_prefix = label_prefix
  4353.   COMMIT TRANSACTION
  4354.  
  4355.   IF (@volume_counter > 9999)
  4356.     UPDATE msdb.dbo.sysvolumelabel
  4357.     SET @volume_counter = label_counter = 1
  4358.  
  4359.   IF (datalength(@volume_prefix) <> 2)
  4360.     UPDATE msdb.dbo.sysvolumelabel
  4361.     SET @volume_prefix = label_prefix = 'DB'
  4362.  
  4363.   SELECT @junk_counter = convert(char,@volume_counter )
  4364.   SELECT @junk_string = upper(@volume_prefix) + '0000'
  4365.   SELECT @volume_label = stuff(@junk_string,(7-datalength(@junk_counter)),datalength(@junk_counter), @junk_counter)
  4366.   SELECT 'VolumeLabel' = @volume_label, 'Junk_string' = @junk_string, 'junk_counter'= @junk_counter, 'volume_counter'=@volume_counter
  4367. END
  4368. go
  4369.  
  4370. EXEC sp_configure 'allow updates', 0
  4371. RECONFIGURE WITH OVERRIDE
  4372. PRINT 'The RECONFIGURE command was run.'
  4373. go
  4374.  
  4375. USE msdb
  4376. go
  4377.  
  4378.  
  4379. /**************************************************************/
  4380. /* SP_SYSBACKUPHISTORY                                        */
  4381. /**************************************************************/
  4382. PRINT ''
  4383. PRINT 'Creating procedure sp_sysbackuphistory...'
  4384. go
  4385.  
  4386. IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'sp_sysbackuphistory' AND sysstat & 0xf = 4))
  4387.   DROP PROC sp_sysbackuphistory
  4388. go
  4389.  
  4390. -- Stored procedure to return backup history so that the most recent
  4391. -- backups appear at the top and the oldest appear at the bottom
  4392.  
  4393. CREATE PROCEDURE sp_sysbackuphistory (@db char(30) = null, @owner char(30) = null, @tablename char(30) = null )
  4394. AS 
  4395.  
  4396. BEGIN
  4397.   DECLARE @sm int
  4398.  
  4399.   SELECT @sm = 0
  4400.  
  4401.   IF (@db is null)
  4402.   BEGIN
  4403.     raiserror(4318,16,1)
  4404.     RETURN 1
  4405.   END
  4406.  
  4407.   IF (@tablename IS NULL AND @owner IS NOT NULL) OR 
  4408.      (@tablename IS NOT NULL AND @owner IS NULL)
  4409.   BEGIN
  4410.     raiserror(4319,16,1)
  4411.     RETURN 1
  4412.   END
  4413.  
  4414.   IF (@tablename is null) AND (@owner is null)
  4415.   BEGIN
  4416.     SELECT 'display'=1, backup_id, id_number, backup_type, database_name, table_owner,
  4417.            table_name, operator_name, backup_start, backup_finish, server_sort, server_code_page, striped_backup, stripe_count, stripe_set_name,
  4418.            total_backup_size, current_sequence, new_sequence
  4419.     INTO #tempHistory
  4420.     FROM sysbackuphistory
  4421.     WHERE database_name = @db 
  4422.       AND (backup_type = 1 OR backup_type = 2)
  4423.     ORDER BY backup_finish ASC
  4424.  
  4425.     UPDATE #tempHistory
  4426.     SET @sm = display = CASE backup_type
  4427.                         WHEN 1 THEN @sm + 1
  4428.                         ELSE @sm
  4429.                         END
  4430.  
  4431.     SELECT backup_id, backup_type, backup_start, backup_finish, database_name,
  4432.            id_number, table_owner, table_name, operator_name,
  4433.            server_sort, server_code_page, striped_backup, stripe_count,
  4434.            stripe_set_name, total_backup_size, current_sequence, new_sequence
  4435.     FROM #tempHistory
  4436.     ORDER BY display DESC
  4437.  
  4438.     DROP TABLE #tempHistory
  4439.   END
  4440.  
  4441.   ELSE
  4442.  
  4443.   BEGIN
  4444.     SELECT backup_id, backup_type, backup_start, backup_finish, database_name,
  4445.            id_number, table_owner, table_name, operator_name,
  4446.            server_sort, server_code_page, striped_backup, stripe_count,
  4447.            stripe_set_name, total_backup_size, current_sequence, new_sequence
  4448.     FROM sysbackuphistory
  4449.     WHERE (database_name = @db  AND backup_type  = 1 )
  4450.       OR (database_name = @db  and backup_type = 3 
  4451.         AND table_name = @tablename  AND table_owner = @owner)
  4452.     ORDER BY backup_finish DESC
  4453.   END
  4454. END
  4455. go
  4456.  
  4457.  
  4458.  
  4459.  
  4460. /**************************************************************/
  4461. /* CHECK IF ALL OBJECTS GOT CREATED AND SET THE CATEGORY BIT  */
  4462. /**************************************************************/
  4463. PRINT ''
  4464. PRINT 'Checking objects created by instmsdb.sql...'
  4465. go
  4466. EXEC sp_check_objects 'msdb'
  4467. PRINT ''
  4468. go
  4469.  
  4470. /* Ensure that 'allow updates' is turned off */
  4471. EXECUTE sp_configure 'allow updates', 0
  4472. go
  4473. reconfigure with override
  4474. PRINT 'The RECONFIGURE command was run.'
  4475. go
  4476.  
  4477.  
  4478. /**************************************************************/
  4479. /* INSTALL OBJECT PERMISSIONS                                 */
  4480. /**************************************************************/
  4481.  
  4482. EXEC('USE master GRANT EXEC ON sp_schedulersignal TO public USE msdb')
  4483. EXEC('USE master GRANT EXEC ON xp_enumqueuedtasks TO public USE msdb')
  4484. EXEC('GRANT EXEC ON sp_verifytaskdate TO public')
  4485. EXEC('GRANT EXEC ON sp_verifytasktime TO public')
  4486. EXEC('GRANT EXEC ON sp_verifytasksched TO public')
  4487. EXEC('GRANT EXEC ON sp_verifytask TO public')
  4488. EXEC('GRANT EXEC ON sp_verifytaskid TO public')
  4489. EXEC('GRANT EXEC ON sp_addtask TO public')
  4490. EXEC('GRANT EXEC ON sp_updatetask TO public')
  4491. EXEC('GRANT EXEC ON sp_droptask TO public')
  4492. EXEC('GRANT EXEC ON sp_reassigntask TO public')
  4493. EXEC('GRANT EXEC ON sp_uniquetaskname TO public')
  4494. EXEC('GRANT EXEC ON sp_helptask TO public')
  4495. EXEC('GRANT EXEC ON sp_helphistory TO public')
  4496. EXEC('GRANT EXEC ON sp_purgehistory TO public')
  4497. EXEC('GRANT EXEC ON sp_schedulerrefresh TO public')
  4498. EXEC('GRANT EXEC ON sp_helpalert TO public')
  4499. EXEC('GRANT EXEC ON sp_helpoperator TO public')
  4500. EXEC('GRANT EXEC ON sp_helpnotification TO public')
  4501. EXEC('GRANT EXEC ON sp_MStaskparameters TO public')
  4502. EXEC('GRANT ALL ON MSWork TO public')
  4503. EXEC('GRANT SELECT ON systasks_view TO public')
  4504. EXEC('GRANT SELECT ON syshistory TO public')
  4505. EXEC('GRANT SELECT ON sysalerts TO public')
  4506. EXEC('GRANT SELECT ON sysnotifications TO public')
  4507. EXEC('GRANT SELECT ON sysoperators TO public')
  4508. EXEC('REVOKE INSERT, UPDATE, DELETE, SELECT ON systasks FROM public')
  4509. EXEC('REVOKE INSERT, UPDATE, DELETE ON syshistory FROM public')
  4510. EXEC('REVOKE INSERT, UPDATE, DELETE ON sysalerts FROM public')
  4511. EXEC('REVOKE INSERT, UPDATE, DELETE ON sysnotifications FROM public')
  4512. EXEC('REVOKE INSERT, UPDATE, DELETE ON sysoperators FROM public')
  4513. go
  4514.  
  4515.  
  4516. /**************************************************************/
  4517. /* INSTALL DEFAULT ALERTS                                     */
  4518. /**************************************************************/
  4519. PRINT ''
  4520. PRINT 'Installing default alerts...'
  4521. go
  4522.  
  4523. EXEC sp_altermessage 1105, with_log, true
  4524. go
  4525. IF NOT EXISTS(SELECT *
  4526.               FROM msdb.dbo.sysalerts
  4527.               WHERE name = 'Demo: Full msdb'
  4528.                  OR (severity = null AND
  4529.                      message_id = 1105 AND
  4530.                      database_name = 'msdb' AND
  4531.                      event_description_keyword = null))
  4532. BEGIN
  4533.   EXEC msdb.dbo.sp_addalert
  4534.   @name = 'Demo: Full msdb',
  4535.   @message_id = 1105,
  4536.   @severity = 0,
  4537.   @enabled = 1,
  4538.   @delay_between_responses = 10,
  4539.   @database_name = 'msdb',
  4540.   @notification_message = null,
  4541.   @task_name = null,
  4542.   @event_description_keyword = null,
  4543.   @include_event_description_in = 'email'
  4544. END
  4545. go
  4546. IF NOT EXISTS(SELECT *
  4547.               FROM msdb.dbo.sysalerts
  4548.               WHERE name = 'Demo: Full tempdb'
  4549.                  OR (severity = null AND
  4550.                      message_id = 1105 AND
  4551.                      database_name = 'tempdb' AND
  4552.                      event_description_keyword = null))
  4553. BEGIN
  4554.   EXEC msdb.dbo.sp_addalert
  4555.   @name = 'Demo: Full tempdb',
  4556.   @message_id = 1105,
  4557.   @severity = 0,
  4558.   @enabled = 1,
  4559.   @delay_between_responses = 10,
  4560.   @database_name = 'tempdb',
  4561.   @notification_message = null,
  4562.   @task_name = null,
  4563.   @event_description_keyword = null,
  4564.   @include_event_description_in = 'email'
  4565. END
  4566. go
  4567.  
  4568. IF NOT EXISTS(SELECT *
  4569.               FROM msdb.dbo.sysalerts
  4570.               WHERE name = 'Demo: Sev. 19 Errors'
  4571.                  OR (severity = 19 AND
  4572.                      message_id = null AND
  4573.                      database_name = null AND
  4574.                      event_description_keyword = null))
  4575. BEGIN
  4576.   EXEC msdb.dbo.sp_addalert
  4577.   @name = 'Demo: Sev. 19 Errors',
  4578.   @message_id = 0,
  4579.   @severity = 19,
  4580.   @enabled = 1,
  4581.   @delay_between_responses = 10,
  4582.   @database_name = null,
  4583.   @notification_message = null,
  4584.   @task_name = null,
  4585.   @event_description_keyword = null,
  4586.   @include_event_description_in = 'email'
  4587. END
  4588. go
  4589. IF NOT EXISTS(SELECT *
  4590.               FROM msdb.dbo.sysalerts
  4591.               WHERE name = 'Demo: Sev. 20 Errors'
  4592.                  OR (severity = 20 AND
  4593.                      message_id = null AND
  4594.                      database_name = null AND
  4595.                      event_description_keyword = null))
  4596. BEGIN
  4597.   EXEC msdb.dbo.sp_addalert
  4598.   @name = 'Demo: Sev. 20 Errors',
  4599.   @message_id = 0,
  4600.   @severity = 20,
  4601.   @enabled = 1,
  4602.   @delay_between_responses = 10,
  4603.   @database_name = null,
  4604.   @notification_message = null,
  4605.   @task_name = null,
  4606.   @event_description_keyword = null,
  4607.   @include_event_description_in = 'email'
  4608. END
  4609. go
  4610. IF NOT EXISTS(SELECT *
  4611.               FROM msdb.dbo.sysalerts
  4612.               WHERE name = 'Demo: Sev. 21 Errors'
  4613.                  OR (severity = 21 AND
  4614.                      message_id = null AND
  4615.                      database_name = null AND
  4616.                      event_description_keyword = null))
  4617. BEGIN
  4618.   EXEC msdb.dbo.sp_addalert
  4619.   @name = 'Demo: Sev. 21 Errors',
  4620.   @message_id = 0,
  4621.   @severity = 21,
  4622.   @enabled = 1,
  4623.   @delay_between_responses = 10,
  4624.   @database_name = null,
  4625.   @notification_message = null,
  4626.   @task_name = null,
  4627.   @event_description_keyword = null,
  4628.   @include_event_description_in = 'email'
  4629. END
  4630. go
  4631. IF NOT EXISTS(SELECT *
  4632.               FROM msdb.dbo.sysalerts
  4633.               WHERE name = 'Demo: Sev. 22 Errors'
  4634.                  OR (severity = 22 AND
  4635.                      message_id = null AND
  4636.                      database_name = null AND
  4637.                      event_description_keyword = null))
  4638. BEGIN
  4639.   EXEC msdb.dbo.sp_addalert
  4640.   @name = 'Demo: Sev. 22 Errors',
  4641.   @message_id = 0,
  4642.   @severity = 22,
  4643.   @enabled = 1,
  4644.   @delay_between_responses = 10,
  4645.   @database_name = null,
  4646.   @notification_message = null,
  4647.   @task_name = null,
  4648.   @event_description_keyword = null,
  4649.   @include_event_description_in = 'email'
  4650. END
  4651. go
  4652. IF NOT EXISTS(SELECT *
  4653.               FROM msdb.dbo.sysalerts
  4654.               WHERE name = 'Demo: Sev. 23 Errors'
  4655.                  OR (severity = 23 AND
  4656.                      message_id = null AND
  4657.                      database_name = null AND
  4658.                      event_description_keyword = null))
  4659. BEGIN
  4660.   EXEC msdb.dbo.sp_addalert
  4661.   @name = 'Demo: Sev. 23 Errors',
  4662.   @message_id = 0,
  4663.   @severity = 23,
  4664.   @enabled = 1,
  4665.   @delay_between_responses = 10,
  4666.   @database_name = null,
  4667.   @notification_message = null,
  4668.   @task_name = null,
  4669.   @event_description_keyword = null,
  4670.   @include_event_description_in = 'email'
  4671. END
  4672. go
  4673. IF NOT EXISTS(SELECT *
  4674.               FROM msdb.dbo.sysalerts
  4675.               WHERE name = 'Demo: Sev. 24 Errors'
  4676.                  OR (severity = 24 AND
  4677.                      message_id = null AND
  4678.                      database_name = null AND
  4679.                      event_description_keyword = null))
  4680. BEGIN
  4681.   EXEC msdb.dbo.sp_addalert
  4682.   @name = 'Demo: Sev. 24 Errors',
  4683.   @message_id = 0,
  4684.   @severity = 24,
  4685.   @enabled = 1,
  4686.   @delay_between_responses = 10,
  4687.   @database_name = null,
  4688.   @notification_message = null,
  4689.   @task_name = null,
  4690.   @event_description_keyword = null,
  4691.   @include_event_description_in = 'email'
  4692. END
  4693. go
  4694. IF NOT EXISTS(SELECT *
  4695.               FROM msdb.dbo.sysalerts
  4696.               WHERE name = 'Demo: Sev. 25 Errors'
  4697.                  OR (severity = 25 AND
  4698.                      message_id = null AND
  4699.                      database_name = null AND
  4700.                      event_description_keyword = null))
  4701. BEGIN
  4702.   EXEC msdb.dbo.sp_addalert
  4703.   @name = 'Demo: Sev. 25 Errors',
  4704.   @message_id = 0,
  4705.   @severity = 25,
  4706.   @enabled = 1,
  4707.   @delay_between_responses = 10,
  4708.   @database_name = null,
  4709.   @notification_message = null,
  4710.   @task_name = null,
  4711.   @event_description_keyword = null,
  4712.   @include_event_description_in = 'email'
  4713. END
  4714. go
  4715.  
  4716. PRINT ''
  4717. PRINT '----------------------------------------------'
  4718. PRINT 'INSTMSDB.SQL created all objects successfully.'
  4719. PRINT '----------------------------------------------'
  4720. go
  4721.  
  4722. DUMP TRANSACTION msdb WITH NO_LOG
  4723. go
  4724.  
  4725. CHECKPOINT
  4726. go
  4727.  
  4728. /* End of INSTMSDB.SQL */
  4729.