home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Internet Business Development Kit / PRODUCT_CD.iso / sqlsvr / i386 / procsyst.sql < prev    next >
Encoding:
Text File  |  1995-12-09  |  538.9 KB  |  22,289 lines

  1.  
  2. /*
  3. ** ProcSyst.SQL        1995/12/09 11:34
  4. **
  5. ** (From old InstProc.SQL.  See also Configur.SQL.)
  6. **
  7. ** Copyright Microsoft, Inc. 1994, 1995, 1996
  8. ** All Rights Reserved.
  9. ** Use, duplication, or disclosure by the United States Government
  10. ** is subject to restrictions as set forth in subdivision (c) (1) (ii)
  11. ** of the Rights in Technical Data and Computer Software clause
  12. ** at CFR 252.227-7013. Microsoft, Inc. One Microsoft Way, Redmond WA
  13. ** 98052.
  14. */
  15.  
  16. go
  17. use master
  18. go
  19. dump tran master with no_log
  20. go
  21. set nocount on
  22. go
  23.  
  24. declare @vdt varchar(99)
  25. select  @vdt = convert(varchar,getdate(),113)
  26. raiserror('
  27. Starting Install\ProcSyst.SQL at  %s',1,1,@vdt) with nowait
  28. go
  29.  
  30. print ''
  31. print 'Making sure that updates to system tables are allowed.'
  32. go
  33.  
  34. declare  @dbcc_current_version    integer
  35.     ,@int1            integer
  36. dbcc getvalue('current_version')  --1=4.21A ,400-406=6.0 ,407-?=6.5 (See spt_values 'DBV')
  37. select @dbcc_current_version = @@error
  38.  
  39. if (     exists (select * from sysobjects where name='sp_configure')
  40.     AND  @dbcc_current_version = (select version from sysdatabases where name='master')
  41.     AND  1 <> (select value from syscurconfigs where config = 102)
  42.    )
  43.     begin                        --Query tree compatible
  44.     exec @int1 = sp_configure 'allow updates',1
  45.     if @@error <> 0 or @int1 <> 0
  46.         raiserror('Bad sp_configure exec at top of ProcSyst.SQL, killing spid.'
  47.             ,22,127) with log
  48.     reconfigure with override
  49.     end
  50. go
  51.  
  52. /*
  53. ** Make sure server was started in single user mode or that sp_configure was used
  54. ** to enable updates to system tables.
  55. */
  56.  
  57. if (select value from syscurconfigs where config = 102) <> 1
  58.     raiserror('
  59. Cannot run ProcSyst.SQL unless updates to system tables are enabled.
  60. Shutdown server and restart with the ''-m'' option or use sp_configure to
  61. enable updates to system tables.'
  62.             ,22,127) with log
  63. go
  64.  
  65. print ''
  66. print 'Dropping procedures that will be (re)created.'
  67. go
  68. /*
  69. ** Drop procedures that will be created by this script.
  70. */
  71.  
  72. if exists (select * from sysobjects
  73.         where sysstat & 0xf = 4
  74.             and name = 'sp_a_count_bits_on')
  75.              drop procedure sp_a_count_bits_on
  76.  
  77. if exists (select * from sysobjects
  78.         where sysstat & 0xf = 4
  79.             and name = 'sp_abort_xact')
  80.     drop procedure sp_abort_xact
  81.  
  82. if exists (select * from sysobjects
  83.         where sysstat & 0xf = 4
  84.             and name = 'sp_addalias')
  85.     drop procedure sp_addalias
  86.  
  87. if exists (select * from sysobjects
  88.         where sysstat & 0xf = 4
  89.             and name = 'sp_addextendedproc')
  90.     drop procedure sp_addextendedproc
  91.  
  92. if exists (select * from sysobjects
  93.         where sysstat & 0xf = 4
  94.             and name = 'sp_addgroup')
  95.     drop procedure sp_addgroup
  96.  
  97. if exists (select * from sysobjects
  98.         where sysstat & 0xf = 4
  99.             and name = 'sp_addlanguage')
  100.     drop procedure sp_addlanguage
  101.  
  102. if exists (select * from sysobjects
  103.         where sysstat & 0xf = 4
  104.             and name = 'sp_addlogin')
  105.     drop procedure sp_addlogin
  106.  
  107. if exists (select * from sysobjects
  108.         where sysstat & 0xf = 4
  109.             and name = 'sp_addmessage')
  110.     drop procedure sp_addmessage
  111.  
  112. if exists (select * from sysobjects
  113.         where sysstat & 0xf = 4
  114.             and name = 'sp_addremotelogin')
  115.     drop procedure sp_addremotelogin
  116.  
  117. if exists (select * from sysobjects
  118.         where sysstat & 0xf = 4
  119.             and name = 'sp_addsegment')
  120.     drop procedure sp_addsegment
  121. go
  122.  
  123. dump tran master with no_log
  124. go
  125.  
  126. if exists (select * from sysobjects
  127.         where sysstat & 0xf = 4
  128.             and name = 'sp_addserver')
  129.     drop procedure sp_addserver
  130.  
  131. if exists (select * from sysobjects
  132.         where sysstat & 0xf = 4
  133.             and name = 'sp_addtype')
  134.     drop procedure sp_addtype
  135.  
  136. if exists (select * from sysobjects
  137.         where sysstat & 0xf = 4
  138.             and name = 'sp_addumpdevice')
  139.     drop procedure sp_addumpdevice
  140.  
  141. if exists (select * from sysobjects
  142.         where sysstat & 0xf = 4
  143.             and name = 'sp_adduser')
  144.     drop procedure sp_adduser
  145.  
  146. if exists (select * from sysobjects
  147.                 where sysstat & 0xf = 4
  148.                         and name = 'sp_altermessage')
  149.         drop procedure sp_altermessage
  150.  
  151. if exists (select * from sysobjects
  152.         where sysstat & 0xf = 4
  153.             and name = 'sp_bindefault')
  154.     drop procedure sp_bindefault
  155.  
  156. if exists (select * from sysobjects
  157.         where sysstat & 0xf = 4
  158.             and name = 'sp_bindrule')
  159.     drop procedure sp_bindrule
  160.  
  161. if exists (select * from sysobjects
  162.         where sysstat & 0xf = 4
  163.             and name = 'sp_blockcnt')
  164.     drop procedure sp_blockcnt
  165.  
  166. if exists (select * from sysobjects
  167.         where sysstat & 0xf = 4
  168.             and name = 'sp_change_configstatus')
  169.              drop procedure sp_change_configstatus
  170.  
  171. if exists (select * from sysobjects
  172.         where sysstat & 0xf = 4
  173.             and name = 'sp_change_users_login')
  174.              drop procedure sp_change_users_login
  175.  
  176. if exists (select * from sysobjects
  177.         where sysstat & 0xf = 4
  178.             and name = 'sp_changedbowner')
  179.     drop procedure sp_changedbowner
  180.  
  181. if exists (select * from sysobjects
  182.         where sysstat & 0xf = 4
  183.             and name = 'sp_changegroup')
  184.     drop procedure sp_changegroup
  185.  
  186. if exists (select * from sysobjects
  187.         where sysstat & 0xf = 4
  188.             and name = 'sp_checknames')
  189.     drop procedure sp_checknames
  190.  
  191. if exists (select * from sysobjects
  192.         where sysstat & 0xf = 4
  193.             and name = 'sp_chklangparam')
  194.     drop procedure sp_chklangparam
  195.  
  196. if exists (select * from sysobjects
  197.         where sysstat & 0xf = 4
  198.             and name = 'sp_commit_xact')
  199.     drop procedure sp_commit_xact
  200.  
  201. if exists (select * from sysobjects
  202.         where sysstat & 0xf = 4
  203.             and name = 'sp_setlangalias')
  204.     drop procedure sp_setlangalias
  205.  
  206. if exists (select * from sysobjects
  207.         where sysstat & 0xf = 4
  208.             and name = 'sp_commonkey')
  209.     drop procedure sp_commonkey
  210. go
  211.  
  212. if exists (select * from sysobjects
  213.         where sysstat & 0xf = 4
  214.             and name = 'sp_configure')
  215.     drop procedure sp_configure
  216.  
  217. if exists (select * from sysobjects
  218.         where sysstat & 0xf = 4
  219.             and name = 'sp_create_removable')
  220.     drop procedure sp_create_removable
  221.  
  222. if exists (select * from sysobjects
  223.         where sysstat & 0xf = 4
  224.             and name = 'sp_certify_removable')
  225.     drop procedure sp_certify_removable
  226.  
  227. if exists (select * from sysobjects
  228.         where sysstat & 0xf = 4
  229.             and name = 'sp_check_removable')
  230.     drop procedure sp_check_removable
  231.  
  232. if exists (select * from sysobjects
  233.         where sysstat & 0xf = 4
  234.             and name = 'sp_cnst_csr')
  235.     drop procedure sp_cnst_csr
  236.  
  237. if exists (select * from sysobjects
  238.         where sysstat & 0xf = 4
  239.             and name = 'sp_coalesce_fragments')
  240.     drop procedure sp_coalesce_fragments
  241.  
  242. if exists (select * from sysobjects
  243.         where sysstat & 0xf = 4
  244.             and name = 'sp_dboption')
  245.     drop procedure sp_dboption
  246.  
  247. if exists (select * from sysobjects
  248.         where sysstat & 0xf = 4
  249.             and name = 'sp_dbinstall')
  250.     drop procedure sp_dbinstall
  251.  
  252. if exists (select * from sysobjects
  253.         where sysstat & 0xf = 4
  254.             and name = 'sp_dbremove')
  255.     drop procedure sp_dbremove
  256.  
  257. if exists (select * from sysobjects
  258.         where sysstat & 0xf = 4
  259.             and name = 'sp_defaultdb')
  260.     drop procedure sp_defaultdb
  261.  
  262. if exists (select * from sysobjects
  263.         where sysstat & 0xf = 4
  264.             and name = 'sp_defaultlanguage')
  265.     drop procedure sp_defaultlanguage
  266.  
  267. if exists (select * from sysobjects
  268.         where sysstat & 0xf = 4
  269.             and name = 'sp_depends')
  270.     drop procedure sp_depends
  271.  
  272. if exists (select * from sysobjects
  273.         where sysstat & 0xf = 4
  274.             and name = 'sp_devcreate')
  275.     drop procedure sp_devcreate
  276.  
  277. if exists (select * from sysobjects
  278.         where sysstat & 0xf = 4
  279.             and name = 'sp_devoption')
  280.     drop procedure sp_devoption
  281.  
  282. if exists (select * from sysobjects
  283.         where sysstat & 0xf = 4
  284.             and name = 'sp_diskdefault')
  285.     drop procedure sp_diskdefault
  286. go
  287.  
  288. if exists (select * from sysobjects
  289.         where sysstat & 0xf = 4
  290.             and name = 'sp_dropalias')
  291.     drop procedure sp_dropalias
  292.  
  293. if exists (select * from sysobjects
  294.         where sysstat & 0xf = 4
  295.             and name = 'sp_droparticle')
  296.     drop procedure sp_droparticle
  297.  
  298. if exists (select * from sysobjects
  299.         where sysstat & 0xf = 4
  300.             and name = 'sp_dropdevice')
  301.     drop procedure sp_dropdevice
  302.  
  303. if exists (select * from sysobjects
  304.         where sysstat & 0xf = 4
  305.             and name = 'sp_dropdumpdevice')
  306.     drop procedure sp_dropdumpdevice
  307.  
  308. if exists (select * from sysobjects
  309.         where sysstat & 0xf = 4
  310.             and name = 'sp_dropextendedproc')
  311.     drop procedure sp_dropextendedproc
  312. go
  313.  
  314. dump tran master with no_log
  315. go
  316. if exists (select * from sysobjects
  317.         where sysstat & 0xf = 4
  318.             and name = 'sp_dropgroup')
  319.     drop procedure sp_dropgroup
  320.  
  321. if exists (select * from sysobjects
  322.         where sysstat & 0xf = 4
  323.             and name = 'sp_dropkey')
  324.     drop procedure sp_dropkey
  325.  
  326. if exists (select * from sysobjects
  327.         where sysstat & 0xf = 4
  328.             and name = 'sp_droplanguage')
  329.     drop procedure sp_droplanguage
  330.  
  331. if exists (select * from sysobjects
  332.         where sysstat & 0xf = 4
  333.             and name = 'sp_droplogin')
  334.     drop procedure sp_droplogin
  335.  
  336. if exists (select * from sysobjects
  337.         where sysstat & 0xf = 4
  338.             and name = 'sp_dropmessage')
  339.     drop procedure sp_dropmessage
  340.  
  341. if exists (select * from sysobjects
  342.         where sysstat & 0xf = 4
  343.             and name = 'sp_droptype')
  344.     drop procedure sp_droptype
  345.  
  346. if exists (select * from sysobjects
  347.         where sysstat & 0xf = 4
  348.             and name = 'sp_dropuser')
  349.     drop procedure sp_dropuser
  350.  
  351. if exists (select * from sysobjects
  352.         where sysstat & 0xf = 4
  353.             and name = 'sp_dropremotelogin')
  354.     drop procedure sp_dropremotelogin
  355.  
  356. if exists (select * from sysobjects
  357.         where sysstat & 0xf = 4
  358.             and name = 'sp_dropsegment')
  359.     drop procedure sp_dropsegment
  360.  
  361. if exists (select * from sysobjects
  362.         where sysstat & 0xf = 4
  363.             and name = 'sp_dropserver')
  364.     drop procedure sp_dropserver
  365. go
  366.  
  367. if exists (select * from sysobjects
  368.         where sysstat & 0xf = 4
  369.             and name = 'sp_extendsegment')
  370.     drop procedure sp_extendsegment
  371.  
  372. if exists (select * from sysobjects
  373.         where sysstat & 0xf = 4
  374.             and name = 'sp_fixindex')
  375.     drop procedure sp_fixindex
  376.  
  377. if exists (select * from sysobjects
  378.         where sysstat & 0xf = 4
  379.             and name = 'sp_foreignkey')
  380.     drop procedure sp_foreignkey
  381. go
  382.  
  383. dump tran master with no_log
  384. go
  385.  
  386. if exists (select * from sysobjects
  387.         where sysstat & 0xf = 4
  388.             and name = 'sp_help')
  389.     drop procedure sp_help
  390.  
  391. if exists (select * from sysobjects
  392.         where sysstat & 0x0f = 4
  393.             and name = 'sp_help_setopts')
  394.              drop procedure sp_help_setopts
  395.  
  396. if exists (select * from sysobjects
  397.         where sysstat & 0x0f = 4
  398.             and name = 'sp_help_revdatabase')
  399.              drop procedure sp_help_revdatabase
  400.  
  401. if exists (select * from sysobjects
  402.         where sysstat & 0xf = 4
  403.             and name = 'sp_helpconstraint')
  404.     drop procedure sp_helpconstraint
  405.  
  406. if exists (select * from sysobjects
  407.         where sysstat & 0xf = 4
  408.             and name = 'sp_helpdb')
  409.     drop procedure sp_helpdb
  410.  
  411. if exists (select * from sysobjects
  412.         where sysstat & 0xf = 4
  413.             and name = 'sp_helpdevice')
  414.     drop procedure sp_helpdevice
  415.  
  416. if exists (select * from sysobjects
  417.         where sysstat & 0xf = 4
  418.             and name = 'sp_helpextendedproc')
  419.     drop procedure sp_helpextendedproc
  420.  
  421. if exists (select * from sysobjects
  422.         where sysstat & 0xf = 4
  423.             and name = 'sp_helpgroup')
  424.     drop procedure sp_helpgroup
  425.  
  426. if exists (select * from sysobjects
  427.         where sysstat & 0xf = 4
  428.             and name = 'sp_helpindex')
  429.     drop procedure sp_helpindex
  430.  
  431. if exists (select * from sysobjects
  432.         where sysstat & 0xf = 4
  433.             and name = 'sp_helpjoins')
  434.     drop procedure sp_helpjoins
  435.  
  436. if exists (select * from sysobjects
  437.         where sysstat & 0xf = 4
  438.             and name = 'sp_helpkey')
  439.     drop procedure sp_helpkey
  440. go
  441.  
  442. dump tran master with no_log
  443. go
  444.  
  445. if exists (select * from sysobjects
  446.         where sysstat & 0xf = 4
  447.             and name = 'sp_helplanguage')
  448.     drop procedure sp_helplanguage
  449.  
  450. if exists (select * from sysobjects
  451.         where sysstat & 0xf = 4
  452.             and name = 'sp_helplog')
  453.     drop procedure sp_helplog
  454.  
  455. if exists (select * from sysobjects
  456.         where sysstat & 0xf = 4
  457.             and name = 'sp_helplogins')
  458.              drop procedure sp_helplogins
  459.  
  460. if exists (select * from sysobjects
  461.         where sysstat & 0xf = 4
  462.             and name = 'sp_helprotect')
  463.     drop procedure sp_helprotect
  464.  
  465. if exists (select * from sysobjects
  466.         where sysstat & 0xf = 4
  467.             and name = 'sp_helptext')
  468.     drop procedure sp_helptext
  469.  
  470. if exists (select * from sysobjects
  471.         where sysstat & 0xf = 4
  472.             and name = 'sp_helpuser')
  473.     drop procedure sp_helpuser
  474.  
  475. if exists (select * from sysobjects
  476.         where sysstat & 0xf = 4
  477.             and name = 'sp_helpremotelogin')
  478.     drop procedure sp_helpremotelogin
  479.  
  480. if exists (select * from sysobjects
  481.         where sysstat & 0xf = 4
  482.             and name = 'sp_helpsegment')
  483.     drop procedure sp_helpsegment
  484.  
  485. if exists (select * from sysobjects
  486.         where sysstat & 0xf = 4
  487.             and name = 'sp_helpserver')
  488.     drop procedure sp_helpserver
  489.  
  490. if exists (select * from sysobjects
  491.         where sysstat & 0xf = 4
  492.             and name = 'sp_helpsort')
  493.     drop procedure sp_helpsort
  494.  
  495. if exists (select * from sysobjects
  496.         where sysstat & 0xf = 4
  497.             and name = 'sp_helpstartup')
  498.     drop procedure sp_helpstartup
  499.  
  500. if exists (select * from sysobjects
  501.         where sysstat & 0xf = 4
  502.             and name = 'sp_lock')
  503.     drop procedure sp_lock
  504.  
  505. if exists (select * from sysobjects
  506.         where sysstat & 0xf = 4
  507.             and name = 'sp_lock2')
  508.     drop procedure sp_lock2
  509.  
  510. if exists (select * from sysobjects
  511.         where sysstat & 0xf = 4
  512.             and name = 'sp_lockinfo')
  513.     drop procedure sp_lockinfo
  514. go
  515.  
  516. dump tran master with no_log
  517. go
  518.  
  519. if exists (select * from sysobjects
  520.         where sysstat & 0xf = 4
  521.             and name = 'sp_logdevice')
  522.     drop procedure sp_logdevice
  523.  
  524. if exists (select * from sysobjects
  525.         where sysstat & 0xf = 4
  526.             and name = 'sp_lookup')
  527.     drop procedure sp_lookup
  528.  
  529. if exists (select * from sysobjects
  530.         where sysstat & 0xf = 4
  531.             and name = 'sp_makestartup')
  532.     drop procedure sp_makestartup
  533.  
  534. if exists (select * from sysobjects
  535.         where sysstat & 0xf = 4
  536.             and name = 'sp_markreport')
  537.     drop procedure sp_markreport
  538.  
  539. if exists (select * from sysobjects
  540.         where sysstat & 0xf = 4
  541.             and name = 'sp_monitor')
  542.     drop procedure sp_monitor
  543.  
  544. if exists (select * from sysobjects
  545.         where sysstat & 0xf = 4
  546.             and name = 'sp_namecrack')
  547.     drop procedure sp_namecrack
  548.  
  549. if exists (select * from sysobjects
  550.         where sysstat & 0xf = 4
  551.             and name = 'sp_objectsegment')
  552.     drop procedure sp_objectsegment
  553.  
  554. if exists (select * from sysobjects
  555.         where sysstat & 0xf = 4
  556.             and name = 'sp_password')
  557.     drop procedure sp_password
  558.  
  559. if exists (select * from sysobjects
  560.         where sysstat & 0xf = 4
  561.             and name = 'sp_placeobject')
  562.     drop procedure sp_placeobject
  563.  
  564. if exists (select * from sysobjects
  565.         where sysstat & 0xf = 4
  566.             and name = 'sp_primarykey')
  567.     drop procedure sp_primarykey
  568.  
  569.  
  570. if exists (select * from sysobjects
  571.         where sysstat & 0xf = 4
  572.             and name = 'sp_probe_xact')
  573.     drop procedure sp_probe_xact
  574.  
  575. if exists (select * from sysobjects
  576.         where sysstat & 0xf = 4
  577.             and name = 'sp_processinfo')
  578.     drop procedure sp_processinfo
  579.  
  580. if (exists (select * from sysobjects
  581.         where sysstat & 0xf = 4
  582.             and name = 'sp_processmail'))
  583.     drop procedure sp_processmail
  584. go
  585.  
  586. if exists (select * from sysobjects
  587.         where sysstat & 0xf = 4
  588.             and name = 'sp_recompile')
  589.     drop procedure sp_recompile
  590.  
  591. if exists (select * from sysobjects
  592.         where sysstat & 0xf = 4
  593.             and name = 'sp_remoteoption')
  594.     drop procedure sp_remoteoption
  595.  
  596. if exists (select * from sysobjects
  597.         where sysstat & 0xf = 4
  598.             and name = 'sp_remove_xact')
  599.     drop procedure sp_remove_xact
  600.  
  601. if exists (select * from sysobjects
  602.         where sysstat & 0xf = 4
  603.             and name = 'sp_rename')
  604.     drop procedure sp_rename
  605.  
  606. if exists (select * from sysobjects
  607.         where sysstat & 0xf = 4
  608.             and name = 'sp_renamedb')
  609.     drop procedure sp_renamedb
  610.  
  611. if exists (select * from sysobjects
  612.         where sysstat & 0xf = 4
  613.             and name = 'sp_scan_xact')
  614.     drop procedure sp_scan_xact
  615.  
  616. if exists (select * from sysobjects
  617.         where sysstat & 0xf = 4
  618.             and name = 'sp_setnetname')
  619.     drop procedure sp_setnetname
  620.  
  621. if exists (select * from sysobjects
  622.         where sysstat & 0xf = 4
  623.             and name = 'sp_serveroption')
  624.     drop procedure sp_serveroption
  625.  
  626. if exists (select * from sysobjects
  627.         where sysstat & 0xf = 4
  628.             and name = 'sp_spaceused')
  629.     drop procedure sp_spaceused
  630.  
  631. if exists (select * from sysobjects
  632.         where sysstat & 0xf = 4
  633.             and name = 'sp_sqlexec')
  634.     drop procedure sp_sqlexec
  635.  
  636. if exists (select * from sysobjects
  637.         where sysstat & 0xf = 4
  638.             and name = 'sp_start_xact')
  639.     drop procedure sp_start_xact
  640.  
  641. if exists (select * from sysobjects
  642.         where sysstat & 0xf = 4
  643.             and name = 'sp_stat_xact')
  644.     drop procedure sp_stat_xact
  645. go
  646.  
  647. if exists (select * from sysobjects
  648.         where sysstat & 0xf = 4
  649.             and name = 'sp_tempdbspace')
  650.     drop procedure sp_tempdbspace
  651.  
  652. if exists (select * from sysobjects
  653.         where sysstat & 0xf = 4
  654.             and name = 'sp_unbindefault')
  655.     drop procedure sp_unbindefault
  656.  
  657. if exists (select * from sysobjects
  658.         where sysstat & 0xf = 4
  659.             and name = 'sp_unbindrule')
  660.     drop procedure sp_unbindrule
  661.  
  662. if exists (select * from sysobjects
  663.         where sysstat & 0xf = 4
  664.             and name = 'sp_unmakestartup')
  665.     drop procedure sp_unmakestartup
  666.  
  667.  
  668. if exists (select * from sysobjects where type='P ' and
  669.                  name='sp_user_counter1')
  670.         drop procedure sp_user_counter1
  671. if exists (select * from sysobjects where type='P ' and
  672.                  name='sp_user_counter2')
  673.         drop procedure sp_user_counter2
  674. if exists (select * from sysobjects where type='P ' and
  675.                  name='sp_user_counter3')
  676.         drop procedure sp_user_counter3
  677. if exists (select * from sysobjects where type='P ' and
  678.                  name='sp_user_counter4')
  679.         drop procedure sp_user_counter4
  680. if exists (select * from sysobjects where type='P ' and
  681.                  name='sp_user_counter5')
  682.         drop procedure sp_user_counter5
  683. if exists (select * from sysobjects where type='P ' and
  684.                  name='sp_user_counter6')
  685.         drop procedure sp_user_counter6
  686. if exists (select * from sysobjects where type='P ' and
  687.                  name='sp_user_counter7')
  688.         drop procedure sp_user_counter7
  689. if exists (select * from sysobjects where type='P ' and
  690.                  name='sp_user_counter8')
  691.         drop procedure sp_user_counter8
  692. if exists (select * from sysobjects where type='P ' and
  693.                  name='sp_user_counter9')
  694.         drop procedure sp_user_counter9
  695. if exists (select * from sysobjects where type='P ' and
  696.                  name='sp_user_counter10')
  697.         drop procedure sp_user_counter10
  698. go
  699. if exists (select * from sysobjects where type='P ' and
  700.                  name='sp_userdefcounters')
  701.         drop procedure sp_userdefcounters
  702. go
  703.  
  704.  
  705. if exists (select * from sysobjects
  706.         where sysstat & 0xf = 4
  707.             and name = 'sp_validaltlang')
  708.     drop procedure sp_validaltlang
  709.  
  710. if exists (select * from sysobjects
  711.         where sysstat & 0xf = 4
  712.             and name = 'sp_validlang')
  713.     drop procedure sp_validlang
  714.  
  715. if exists (select * from sysobjects
  716.         where sysstat & 0xf = 4
  717.             and name = 'sp_validname')
  718.     drop procedure sp_validname
  719.  
  720. if exists (select * from sysobjects
  721.         where sysstat & 0xf = 4
  722.             and name = 'sp_who')
  723.     drop procedure sp_who
  724.  
  725. if exists (select * from sysobjects
  726.         where sysstat & 0xf = 4
  727.             and name = 'sp_who2')
  728.     drop procedure sp_who2
  729. go
  730.  
  731. if exists (select * from sysobjects
  732.         where sysstat & 0xf = 4
  733.             and name = 'sp_xpoption')
  734.     drop procedure sp_xpoption
  735. go
  736.  
  737. if exists ( select * from sysobjects
  738.         where sysstat & 0xf = 4
  739.             and name = 'MS_sqlctrs_users' )
  740.     drop proc MS_sqlctrs_users
  741. go
  742.  
  743. dump tran master with no_log
  744. go
  745. print ''
  746. go
  747.  
  748.  
  749. raiserror('
  750. Special command to fix up freeoff on page 24 in all databases:
  751. dbcc dbr- (m-, f-)',1,1)
  752. go
  753. dbcc dbrepair (master, fixsysindex) --Why located in this file ?!
  754. go
  755.  
  756.  
  757.  
  758. ---------------------------------------------------------------
  759. ---------------------------------------------------------------
  760. raiserror('
  761. Creating the general purpose System Stored Procedures ....
  762. ',1,1)
  763. ---------------------------------------------------------------
  764. ---------------------------------------------------------------
  765. go
  766.  
  767.  
  768. print ' '
  769. print 'Creating several like sp_user_counter1.'
  770. go
  771.  
  772. create proc sp_user_counter1 as
  773. select 0
  774. go
  775. create proc sp_user_counter2 as
  776. select 0
  777. go
  778. create proc sp_user_counter3 as
  779. select 0
  780. go
  781. create proc sp_user_counter4 as
  782. select 0
  783. go
  784. create proc sp_user_counter5 as
  785. select 0
  786. go
  787. create proc sp_user_counter6 as
  788. select 0
  789. go
  790. create proc sp_user_counter7 as
  791. select 0
  792. go
  793. create proc sp_user_counter8 as
  794. select 0
  795. go
  796. create proc sp_user_counter9 as
  797. select 0
  798. go
  799. create proc sp_user_counter10 as
  800. select 0
  801. go
  802.  
  803. print ' '
  804. print 'Creating sp_userdefcounters.'
  805. go
  806. create proc sp_userdefcounters as
  807. exec sp_user_counter1
  808. exec sp_user_counter2
  809. exec sp_user_counter3
  810. exec sp_user_counter4
  811. exec sp_user_counter5
  812. exec sp_user_counter6
  813. exec sp_user_counter7
  814. exec sp_user_counter8
  815. exec sp_user_counter9
  816. exec sp_user_counter10
  817. go
  818.  
  819.  
  820. print ''
  821. print 'Creating procedure sp_blockcnt.'
  822. go
  823. --perfmon
  824. create procedure sp_blockcnt as
  825. select blockedusers=count(*) from sysprocesses where blocked <> 0
  826. go
  827.  
  828.  
  829. print ''
  830. print 'Creating procedure sp_tempdbspace.'
  831. go
  832. --new query to watch max tempdbspace from perfmon
  833. create proc sp_tempdbspace as
  834.  
  835. declare @dbsize dec(15,0)
  836. declare @freespace dec(15,0)
  837. declare @spaceused dec(15,0)
  838.  
  839. select @dbsize = sum(convert(dec(15),size))
  840.                from master..sysusages
  841.                where dbid = db_id("tempdb")
  842.  
  843. select  database_name = "tempdb",
  844.                database_size = (@dbsize / 512),
  845.            spaceused=(@dbsize/512-(@dbsize/512 -
  846.                                  (select sum(convert(dec(15),reserved))
  847.                 from tempdb..sysindexes
  848.     where indid in (0, 1, 255))/512))
  849. go
  850.  
  851.  
  852. print ''
  853. print 'Creating procedure sp_xpoption.'
  854. go
  855. CREATE PROCEDURE sp_xpoption --1995/11/18 15:25 #11536
  856.  
  857.     @pXPName      character varying(61)
  858.    ,@pOptionName  character varying(35)
  859.  
  860.    ,@pOptionValue character varying(5)    = Null
  861. as
  862.  
  863. Set nocount on
  864.  
  865. Declare
  866.        @RetCode            integer
  867.       ,@_rowcount          integer
  868.       ,@OptionNum          integer
  869.       ,@CurrentOptionValue integer
  870.       ,@XPName             character varying(30)
  871.       ,@OwnerName          character varying(30)
  872.       ,@OwnerId            integer
  873.       ,@WInt1              integer
  874.       ,@WVarchar1          character varying(35)
  875.  
  876. Select
  877.        @RetCode            = -6  --  -6=Error ,0=False/Off ,1=True/On
  878.       ,@OwnerId            = Null
  879.  
  880. IF (suser_id() <> 1)
  881.    begin
  882.    RaisError(15003,-1,-1)
  883.    Select @RetCode = -6
  884.    GOTO LABEL_86RETURN
  885.    end
  886.  
  887.  
  888. IF (     @pXPName       IS Null
  889.    or    @pOptionName   IS Null
  890.    )
  891.    begin
  892.    RaisError(15327,-1,-1)
  893.    Select @RetCode = -6
  894.    GOTO LABEL_86RETURN
  895.    end
  896.  
  897.  
  898. IF (@pXPName LIKE '%.%')  --qualified by owner, or assume self
  899.    begin
  900.    Select @WInt1 = isnull( charindex('.',@pXPName) , 0)
  901.    Select @OwnerName = substring(@pXPName,1,@WInt1-1)
  902.    Select @OwnerId   = user_id(@OwnerName)
  903.    Select @XPName    = substring(@pXPName,@WInt1+1,61)
  904.    end
  905. ELSE
  906.    begin
  907.    Select @XPName    = @pXPName
  908.    Select @OwnerId   = user_id()
  909.    Select @OwnerName = user_name(@OwnerId)
  910.    end
  911.  
  912.  
  913.  
  914. IF (1 <> (SELECT count(*) from master.dbo.sysobjects
  915.                    where type='X ' and uid=@OwnerId and name=@XPName)
  916.    )
  917.    begin
  918.    RaisError(15321,-1,-1,@pXPName)
  919.    Select @RetCode = -6
  920.    GOTO LABEL_86RETURN
  921.    end
  922.  
  923.  
  924.  
  925. Select @OptionNum =
  926.             CASE upper(@pOptionName)
  927.  
  928.                When 'IMPERSONATE_CLIENT'  Then 8192  -- 0x2000
  929.                When '1'                   Then 8192  -- Helpful to Japanese?
  930.  
  931.                Else                               0
  932.             END
  933.  
  934. IF (@OptionNum = 0)
  935.    begin
  936.    RaisError(15322,-1,-1,@pOptionName)
  937.    Select @RetCode = -6
  938.    GOTO LABEL_86RETURN
  939.    end
  940.  
  941.  
  942.  
  943.  
  944. IF (           @pOptionValue  IS NOT Null
  945.    and   upper(@pOptionValue) NOT IN ('TRUE' ,'FALSE')
  946.    )
  947.    begin
  948.    RaisError(15323,-1,-1,@pOptionValue)
  949.    Select @RetCode = -6
  950.    GOTO LABEL_86RETURN
  951.    end
  952.  
  953.  
  954.  
  955.  
  956. IF (@pOptionValue IS Null)
  957.    begin
  958.  
  959.    SELECT       @CurrentOptionValue = o.category & @OptionNum
  960.          from
  961.                 master.dbo.sysobjects  o
  962.          where
  963.                 o.type  = 'X '
  964.          and    o.uid   = @OwnerId
  965.          and    o.name  = @XPName
  966.  
  967.  
  968.    IF (@CurrentOptionValue > 0)
  969.       begin
  970.       Select @WVarchar1 = 'TRUE'
  971.             ,@RetCode   = 1
  972.       end
  973.    ELSE
  974.       begin
  975.       Select @WVarchar1 = 'FALSE'
  976.             ,@RetCode   = 0
  977.       end
  978.  
  979.  
  980.    Raiserror(15324,-1,-1 ,@pXPName ,@pOptionName ,@WVarchar1)
  981.  
  982.    GOTO LABEL_75DONE
  983.  
  984.    end
  985.  
  986.  
  987.  
  988.  
  989. IF (upper(@pOptionValue) = 'TRUE')
  990.    begin
  991.  
  992.    Select @RetCode   = 1
  993.  
  994.    UPDATE
  995.                 master.dbo.sysobjects
  996.          set
  997.                 category   = category | ( @OptionNum) --turn ON
  998.          where
  999.                 type       = 'X '
  1000.          and    uid        = @OwnerId
  1001.          and    name       = @XPName
  1002.          and    category   & @OptionNum   = 0
  1003.  
  1004.    Select @_rowcount = @@rowcount
  1005.  
  1006.    end
  1007. ELSE
  1008.    begin
  1009.  
  1010.    Select @RetCode   = 0
  1011.  
  1012.    UPDATE
  1013.                 master.dbo.sysobjects
  1014.          set
  1015.                 category   = category & (~@OptionNum) --turn OFF the bit
  1016.          where
  1017.                 type       = 'X '
  1018.          and    uid        = @OwnerId
  1019.          and    name       = @XPName
  1020.          and    category   & @OptionNum   > 0
  1021.  
  1022.    Select @_rowcount = @@rowcount
  1023.  
  1024.    end
  1025.  
  1026.  
  1027.  
  1028. IF (@_rowcount = 0)
  1029.    begin
  1030.    Raiserror(15325,-1,-1, @pXPName ,@pOptionName ,@pOptionValue)
  1031.    GOTO LABEL_75DONE
  1032.    end
  1033. ELSE
  1034.    begin
  1035.    Raiserror(15326,-1,-1, @pXPName ,@pOptionName ,@pOptionValue)
  1036.    GOTO LABEL_75DONE
  1037.    end
  1038.  
  1039.  
  1040. LABEL_75DONE:
  1041.  
  1042. LABEL_86RETURN:
  1043.  
  1044. Return @RetCode
  1045. go
  1046.  
  1047.  
  1048. print ''
  1049. print 'Creating procedure sp_validname.'
  1050. go
  1051. CREATE PROCEDURE sp_validname --1995/09/12 16:32
  1052.     @p_name   varchar(30)
  1053. AS
  1054. /***********************************************************
  1055.       This SP can screen out some bad names for things
  1056. like syslogins.name.
  1057.  
  1058.       This SP cannot aggressively challenge names
  1059. values, due to the lack of a code page for the Japanese
  1060. (1995/09/11).   Thus all bytes >0x7F will be treated
  1061. as DBCS lead bytes (trail byte values not checked).
  1062.  
  1063.       Datalength:    Returns number of 8-bit bytes,
  1064. not number of characters.
  1065.  
  1066.       Substring:     Parm number 2 (of 3) represents the
  1067. Nth character (DBCS and/or SBCS), not the Nth 8-bit
  1068. byte.   Parm 3 is the number of characters to return,
  1069. not the number of bytes to return.
  1070.  
  1071.       MS SQL 6.0 identifiers must not exceed 30
  1072. 8-bit bytes.
  1073. ***********************************************************/
  1074.  
  1075.  
  1076. Set nocount on
  1077.  
  1078. --------  This sproc verifies the name is a legal identifier, DBCS or SBCS.
  1079.  
  1080. Declare
  1081.     @current               int
  1082.    ,@last                  int
  1083.  
  1084. Declare
  1085.     @curchar               tinyint
  1086.    ,@atsign                tinyint
  1087.    ,@underscore            tinyint
  1088.    ,@poundsign             tinyint
  1089.    ,@dollarsign            tinyint
  1090.    ,@big_A                 tinyint
  1091.    ,@small_a               tinyint
  1092.    ,@big_Z                 tinyint
  1093.    ,@small_z               tinyint
  1094.    ,@digit_0               tinyint
  1095.    ,@digit_9               tinyint
  1096.  
  1097. Declare
  1098.     @alpha_s_1             tinyint
  1099.    ,@alpha_s_2             tinyint
  1100.    ,@alpha_s_3             tinyint
  1101.  
  1102.    ,@alpha_2_start         tinyint
  1103.    ,@alpha_2_end           tinyint
  1104.  
  1105.    ,@alpha_3_start         tinyint
  1106.    ,@alpha_3_end           tinyint
  1107.    ,@alpha_4_start         tinyint
  1108.    ,@alpha_4_end           tinyint
  1109.    ,@alpha_5_start         tinyint
  1110.    ,@alpha_5_end           tinyint
  1111.    ,@alpha_6_start         tinyint
  1112.    ,@alpha_6_end           tinyint
  1113.    ,@alpha_7_start         tinyint
  1114.    ,@alpha_7_end           tinyint
  1115.  
  1116. Declare
  1117.     @binname               varbinary(30)
  1118.    ,@recognized_cp_yn      char(1)
  1119.    ,@charset_name          varchar(30)
  1120.  
  1121.  
  1122. ----------------------------------------
  1123.  
  1124.  
  1125. --------  Ensure that the name specified is non-null.
  1126.  
  1127.  
  1128. IF (@p_name is null)
  1129.    begin
  1130.    raiserror (15004,-1,-1)
  1131.    return (1)
  1132.    end
  1133.  
  1134. Select  @binname = convert(varbinary,@p_name)
  1135.  
  1136.  
  1137. --------  Assign ANSI char ranges.
  1138.  
  1139.  
  1140. Select
  1141.     @atsign       = ascii('@')
  1142.    ,@underscore   = ascii('_')
  1143.    ,@poundsign    = ascii('#')
  1144.    ,@dollarsign   = ascii('$')
  1145.    ,@big_A        = ascii('A')
  1146.    ,@small_a      = ascii('a')
  1147.    ,@big_Z        = ascii('Z')
  1148.    ,@small_z      = ascii('z')
  1149.    ,@digit_0      = ascii('0')
  1150.    ,@digit_9      = ascii('9')
  1151.  
  1152.  
  1153. --------  Get the Character Set ID (csid).
  1154.  
  1155.  
  1156. SELECT
  1157.              @charset_name    = Min(cs1.name)
  1158.       from
  1159.              master..syscharsets    cs1  --static row
  1160.             ,master..syscharsets    cs2  --row genned by install
  1161.       where
  1162.              cs1.id           = cs2.csid
  1163.       and
  1164.              cs1.type         = 1001
  1165.       and    cs2.type         = 2001
  1166.       and
  1167.              cs2.id           =
  1168.                   (SELECT      value
  1169.                      from      master..sysconfigures
  1170.                      where     config  = 1123  --default sortorder id
  1171.                   )
  1172.  
  1173.  
  1174.  
  1175. --------  Define character hex ranges ("codepoints")  ---------------
  1176.  
  1177.  
  1178. ----  SBCS values >=0x80 are just for looks, will be treated as DBCS later.
  1179.  
  1180.  
  1181. Select @recognized_cp_yn    = 'N'
  1182.  
  1183.  
  1184. IF @charset_name = 'iso_1'
  1185.    begin
  1186.    Select @recognized_cp_yn = 'Y'
  1187.  
  1188.    Select
  1189.           @alpha_2_start = 0xC0, @alpha_2_end = 0xD6
  1190.          ,@alpha_3_start = 0xD8, @alpha_3_end = 0xF6
  1191.          ,@alpha_4_start = 0xF8, @alpha_4_end = 0xFF
  1192.          ,@alpha_5_start = 0x41, @alpha_5_end = 0x5A
  1193.          ,@alpha_6_start = 0x61, @alpha_6_end = 0x7A
  1194.          ,@alpha_7_start = 0x61, @alpha_7_end = 0x7A
  1195.          ,@alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41
  1196.    end
  1197.  
  1198.  
  1199. IF @charset_name = 'cp850'
  1200.    begin
  1201.    Select @recognized_cp_yn = 'Y'
  1202.  
  1203.    Select
  1204.           @alpha_2_start = 0x80, @alpha_2_end = 0x9D
  1205.          ,@alpha_3_start = 0xA0, @alpha_3_end = 0xA5
  1206.          ,@alpha_4_start = 0xB5, @alpha_4_end = 0xB7
  1207.          ,@alpha_5_start = 0xC6, @alpha_5_end = 0xC7
  1208.          ,@alpha_6_start = 0xD0, @alpha_6_end = 0xD8
  1209.          ,@alpha_7_start = 0xE0, @alpha_7_end = 0xED
  1210.          ,@alpha_s_1 = 0xDE, @alpha_s_2 = 0xF4, @alpha_s_3 = 0xF5
  1211.    end
  1212.  
  1213.  
  1214.  
  1215. IF @charset_name = 'cp437'
  1216.    begin
  1217.    Select @recognized_cp_yn = 'Y'
  1218.  
  1219.    select @alpha_2_start = 0x80, @alpha_2_end = 0x9A,
  1220.                    @alpha_3_start = 0xA0, @alpha_3_end = 0xA5,
  1221.                    @alpha_4_start = 0xE0, @alpha_4_end = 0xEE,
  1222.                    @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1223.                    @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1224.                    @alpha_7_start = 0x61, @alpha_7_end = 0x7A,
  1225.                    @alpha_s_1 = 0x9E, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41
  1226.    end
  1227.  
  1228.  
  1229. IF @charset_name = 'cp1250'
  1230.    begin
  1231.    Select @recognized_cp_yn = 'Y'
  1232.  
  1233.    select @alpha_2_start = 0x9C, @alpha_2_end = 0x9F,
  1234.                    @alpha_3_start = 0xBE, @alpha_3_end = 0xFF,
  1235.                    @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1236.                    @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1237.                    @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1238.                    @alpha_7_start = 0x8C, @alpha_7_end = 0x8F,
  1239.                    @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41
  1240.    end
  1241.  
  1242.  
  1243. IF @charset_name = 'cp1251'
  1244.    begin
  1245.    Select @recognized_cp_yn = 'Y'
  1246.  
  1247.    select @alpha_2_start = 0x9C, @alpha_2_end = 0x9F,
  1248.                    @alpha_3_start = 0xA1, @alpha_3_end = 0xA3,
  1249.                    @alpha_4_start = 0xB2, @alpha_4_end = 0xFF,
  1250.                    @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1251.                    @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1252.                    @alpha_7_start = 0x8C, @alpha_7_end = 0x90,
  1253.                    @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41
  1254.    end
  1255.  
  1256.  
  1257. IF @charset_name = 'cp1253'
  1258.    begin
  1259.    Select @recognized_cp_yn = 'Y'
  1260.  
  1261.    select @alpha_2_start = 0xBE, @alpha_2_end = 0xD1,
  1262.                    @alpha_3_start = 0xD3, @alpha_3_end = 0xFE,
  1263.                    @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1264.                    @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1265.                    @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1266.                    @alpha_7_start = 0xB8, @alpha_7_end = 0xBA,
  1267.                    @alpha_s_1 = 0xA2, @alpha_s_2 = 0xBC, @alpha_s_3 = 0x41
  1268.    end
  1269.  
  1270.  
  1271. IF @charset_name = 'cp1254'
  1272.    begin
  1273.    Select @recognized_cp_yn = 'Y'
  1274.  
  1275.    select @alpha_2_start = 0xD8, @alpha_2_end = 0xFF,
  1276.                    @alpha_3_start = 0x9F, @alpha_3_end = 0x9F,
  1277.                    @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1278.                    @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1279.                    @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1280.                    @alpha_7_start = 0xC0, @alpha_7_end = 0xD6,
  1281.                    @alpha_s_1 = 0x83, @alpha_s_2 = 0x8A, @alpha_s_3 = 0x9A
  1282.    end
  1283.  
  1284.  
  1285. IF @charset_name = 'cp1255'
  1286.    begin
  1287.    Select @recognized_cp_yn = 'Y'
  1288.  
  1289.    select @alpha_2_start = 0x41, @alpha_2_end = 0x5A,
  1290.                    @alpha_3_start = 0x41, @alpha_3_end = 0x5A,
  1291.                    @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1292.                    @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1293.                    @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1294.                    @alpha_7_start = 0xE0, @alpha_7_end = 0xFA,
  1295.                    @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41
  1296.    end
  1297.  
  1298.  
  1299. IF @charset_name = 'cp1256'
  1300.    begin
  1301.    Select @recognized_cp_yn = 'Y'
  1302.  
  1303.    select @alpha_2_start = 0x80, @alpha_2_end = 0x9A,
  1304.                    @alpha_3_start = 0xA0, @alpha_3_end = 0xA5,
  1305.                    @alpha_4_start = 0xE0, @alpha_4_end = 0xEE,
  1306.                    @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1307.                    @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1308.                    @alpha_7_start = 0x61, @alpha_7_end = 0x7A,
  1309.                    @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41
  1310.    end
  1311.  
  1312.  
  1313. IF @charset_name = 'cp1257'
  1314.    begin
  1315.    Select @recognized_cp_yn = 'Y'
  1316.  
  1317.    select @alpha_2_start = 0x9C, @alpha_2_end = 0x9F,
  1318.                    @alpha_3_start = 0xC0, @alpha_3_end = 0xFE,
  1319.                    @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1320.                    @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1321.                    @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1322.                    @alpha_7_start = 0x8C, @alpha_7_end = 0x8F,
  1323.                    @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41
  1324.    end
  1325.  
  1326.  
  1327.  
  1328. --------  If no code page?
  1329.  
  1330.  
  1331. IF (@recognized_cp_yn = 'N')  --Allow anything.
  1332.    begin
  1333.  
  1334.    Select
  1335.           @alpha_2_start = 0x00, @alpha_2_end = 0xFF
  1336.          ,@alpha_3_start = 0x00, @alpha_3_end = 0xFF
  1337.          ,@alpha_4_start = 0x00, @alpha_4_end = 0xFF
  1338.          ,@alpha_5_start = 0x00, @alpha_5_end = 0xFF
  1339.          ,@alpha_6_start = 0x00, @alpha_6_end = 0xFF
  1340.          ,@alpha_7_start = 0x00, @alpha_7_end = 0xFF
  1341.          ,@alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41
  1342.    end
  1343.  
  1344.  
  1345.  
  1346. ----------------------------------------------------------------------
  1347. --             Validate the first byte (not first character).
  1348. ----------------------------------------------------------------------
  1349.  
  1350.  
  1351. Select @curchar = convert(tinyint,substring(@binname, 1, 1))
  1352.  
  1353.  
  1354. IF (not (   (@curchar between @alpha_2_start and @alpha_2_end)
  1355.          or (@curchar between @alpha_3_start and @alpha_3_end)
  1356.          or (@curchar between @alpha_4_start and @alpha_4_end)
  1357.          or (@curchar between @alpha_5_start and @alpha_5_end)
  1358.          or (@curchar between @alpha_6_start and @alpha_6_end)
  1359.          or (@curchar between @alpha_7_start and @alpha_7_end)
  1360.  
  1361.          or (@curchar >= @big_A    and  @curchar <= @big_Z)
  1362.          or (@curchar >= @small_a  and  @curchar <= @small_z)
  1363.  
  1364.          or  @curchar  = @alpha_s_1
  1365.          or  @curchar  = @alpha_s_2
  1366.          or  @curchar  = @alpha_s_3
  1367.          or  @curchar  = @poundsign
  1368.          or  @curchar  = @underscore
  1369.  
  1370.          or  @curchar >= 0x80  --DBCS lead byte a possibility.
  1371.         )
  1372.    )
  1373.    begin
  1374.    raiserror(15005,-1,-1,@p_name)
  1375.    return (1)
  1376.    end
  1377.  
  1378.  
  1379.  
  1380. ----------------------------------------------------------------------
  1381. --          Now validate remaining bytes (DBCS lead byte sensitive).
  1382. ----------------------------------------------------------------------
  1383.  
  1384.  
  1385. Select
  1386.     @current   = 1
  1387.    ,@last      = datalength(@p_name)
  1388.  
  1389.  
  1390. -- Now check the rest of the characters.
  1391.  
  1392. -------------------------
  1393. WHILE (@current <= @last)
  1394.    begin
  1395.  
  1396.    select @curchar = convert(tinyint,substring(@binname, @current, 1))
  1397.  
  1398.  
  1399.    if (    @current > 1
  1400.        AND
  1401.             (not (  (@curchar between @alpha_2_start and @alpha_2_end)
  1402.                  or (@curchar between @alpha_3_start and @alpha_3_end)
  1403.                  or (@curchar between @alpha_4_start and @alpha_4_end)
  1404.                  or (@curchar between @alpha_5_start and @alpha_5_end)
  1405.                  or (@curchar between @alpha_6_start and @alpha_6_end)
  1406.                  or (@curchar between @alpha_7_start and @alpha_7_end)
  1407.  
  1408.                  or (@curchar >= @big_A    and  @curchar <= @big_Z)
  1409.                  or (@curchar >= @small_a  and  @curchar <= @small_z)
  1410.  
  1411.                  or  @curchar  = @alpha_s_1
  1412.                  or  @curchar  = @alpha_s_2
  1413.                  or  @curchar  = @alpha_s_3
  1414.                  or  @curchar  = @poundsign
  1415.                  or  @curchar  = @underscore
  1416.  
  1417.                  or  @curchar >= 0x80  --DBCS
  1418.  
  1419.                  or  @curchar  = @atsign
  1420.                  or  @curchar  = @dollarsign
  1421.                  or (@curchar >= @digit_0  and  @curchar <= @digit_9)
  1422.                  )
  1423.             )
  1424.       )
  1425.       begin
  1426.       raiserror(15006,-1,-1,@p_name)
  1427.       return (1)
  1428.       end
  1429.  
  1430.  
  1431.    IF (convert(varbinary(1),@curchar) >= 0x80)  --Admit could be SBCS Greek >=0x80, but...
  1432.       Select @current = @current + 2
  1433.    ELSE
  1434.       Select @current = @current + 1
  1435.  
  1436.  
  1437.    end  --loop
  1438.  
  1439.  
  1440. Return (0)
  1441. go
  1442. --
  1443.  
  1444.  
  1445. print ''
  1446. print 'Creating procedure sp_validlang.'
  1447. go
  1448. create procedure sp_validlang
  1449. @name    varchar(30)
  1450. as
  1451.  
  1452. /* Check to see if this language is in Syslanguages. */
  1453. if exists (select * from syslanguages where name = @name)
  1454.     or @name = 'us_english'        /* us_english is always valid. */
  1455.     return(0)
  1456.  
  1457. raiserror(15033,-1,-1,@name)
  1458. return (1)
  1459. go
  1460.  
  1461. print ''
  1462. print 'Creating procedure sp_chklangparam.'
  1463. go
  1464. create procedure sp_chklangparam
  1465. @namelist varchar(251),        /* month or day name list */
  1466. @msgparam varchar(30),        /* name of list, for error messages */
  1467. @numnames int,            /* correct number of names in the list */
  1468. @maxnamelen int            /* maximum length of any name in list */
  1469. as
  1470.  
  1471.     /*
  1472.     ** sp_chklangparam is called by sp_addlanguage to check the lists of
  1473.     ** full month names, short month names, and day names.  It returns a status
  1474.     ** indicating whether any errors were found:
  1475.     **    0 - name list is valid
  1476.     **    1 - spaces were found, which are not allowed
  1477.     **    2 - not enough names in the list (must be exactly @numnames of them)
  1478.     **    3 - too many names in the list (must be exactly @numnames of them)
  1479.     **    4 - some name(s) are too long
  1480.     **    5 - some name(s) have non-aphabetic characters
  1481.     */
  1482.  
  1483.     declare @totallen        int
  1484.     declare @mthlen            int
  1485.     declare @mthname        varchar(251)
  1486.     declare @msg            varchar(255)
  1487.     declare @csid            tinyint
  1488.     declare @csname            varchar(30)
  1489.     declare @alpha_0_start        tinyint
  1490.     declare @alpha_0_end        tinyint
  1491.     declare @alpha_1_start        tinyint
  1492.     declare @alpha_1_end        tinyint
  1493.     declare @alpha_2_start        tinyint
  1494.     declare @alpha_2_end        tinyint
  1495.     declare @alpha_3_start        tinyint
  1496.     declare @alpha_3_end        tinyint
  1497.     declare @alpha_4_start        tinyint
  1498.     declare @alpha_4_end        tinyint
  1499.     declare @alpha_5_start        tinyint
  1500.     declare @alpha_5_end        tinyint
  1501.     declare @alpha_6_start        tinyint
  1502.     declare @alpha_6_end        tinyint
  1503.     declare @alpha_7_start        tinyint
  1504.     declare @alpha_7_end        tinyint
  1505.     declare @alpha_s_1        tinyint
  1506.     declare @alpha_s_2        tinyint
  1507.     declare @alpha_s_3        tinyint
  1508.     declare @alpha_s_4        tinyint
  1509.     declare @curchar        tinyint
  1510.     declare @next            int
  1511.  
  1512.     /* Get the Character Set id (csid) */
  1513.     select @csid = csid from master..syscharsets
  1514.         where id = (select value from master..sysconfigures
  1515.             where config = 1123)
  1516.  
  1517.     /* Get the Character Set Name (csname) */
  1518.     select @csname = name from master..syscharsets
  1519.         where id = @csid and type < 2000
  1520.  
  1521.     /* Make sure the list has no blanks. */
  1522.     if ( charindex( ' ', @namelist ) <> 0 )
  1523.     begin
  1524.         raiserror(15057,-1,-1,@msgparam)
  1525.         return (1)
  1526.     end
  1527.  
  1528.     if @csid = 1
  1529.         /* Set up the alphabetic codepoint ranges for iso_1. */
  1530.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1531.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1532.            @alpha_2_start = 0xC0, @alpha_2_end = 0xD6,
  1533.            @alpha_3_start = 0xD8, @alpha_3_end = 0xF6,
  1534.                @alpha_4_start = 0xF8, @alpha_4_end = 0xFF,
  1535.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1536.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1537.                @alpha_7_start = 0x61, @alpha_7_end = 0x7A,
  1538.            @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41,
  1539.            @alpha_s_4 = 0x2D
  1540.  
  1541.     if @csid = 2
  1542.         /* Set up the alphabetic codepoint ranges for cp850. */
  1543.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1544.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1545.            @alpha_2_start = 0x80, @alpha_2_end = 0x9D,
  1546.            @alpha_3_start = 0xA0, @alpha_3_end = 0xA5,
  1547.                @alpha_4_start = 0xB5, @alpha_4_end = 0xB7,
  1548.                @alpha_5_start = 0xC6, @alpha_5_end = 0xC7,
  1549.                @alpha_6_start = 0xD0, @alpha_6_end = 0xD8,
  1550.                @alpha_7_start = 0xE0, @alpha_7_end = 0xED,
  1551.            @alpha_s_1 = 0xDE, @alpha_s_2 = 0xF4, @alpha_s_3 = 0xF5,
  1552.            @alpha_s_4 = 0x2D
  1553.  
  1554.     if @csid = 3
  1555.         /* Set up the alphabetic codepoint ranges for cp437. */
  1556.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1557.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1558.            @alpha_2_start = 0x80, @alpha_2_end = 0x9A,
  1559.            @alpha_3_start = 0xA0, @alpha_3_end = 0xA5,
  1560.                @alpha_4_start = 0xE0, @alpha_4_end = 0xEE,
  1561.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1562.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1563.                @alpha_7_start = 0x61, @alpha_7_end = 0x7A,
  1564.            @alpha_s_1 = 0x9E, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41,
  1565.            @alpha_s_4 = 0x2D
  1566.  
  1567.     if @csid = 4
  1568.         /* Set up the alphabetic codepoint ranges for cp1250. */
  1569.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1570.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1571.            @alpha_2_start = 0x9C, @alpha_2_end = 0x9F,
  1572.            @alpha_3_start = 0xBE, @alpha_3_end = 0xFF,
  1573.                @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1574.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1575.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1576.                @alpha_7_start = 0x8C, @alpha_7_end = 0x8F,
  1577.            @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41,
  1578.            @alpha_s_4 = 0x41
  1579.  
  1580.     if @csid = 5
  1581.         /* Set up the alphabetic codepoint ranges for cp1251. */
  1582.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1583.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1584.            @alpha_2_start = 0x9C, @alpha_2_end = 0x9F,
  1585.            @alpha_3_start = 0xA1, @alpha_3_end = 0xA3,
  1586.                @alpha_4_start = 0xB2, @alpha_4_end = 0xFF,
  1587.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1588.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1589.                @alpha_7_start = 0x8C, @alpha_7_end = 0x90,
  1590.            @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41,
  1591.            @alpha_s_4 = 0x41
  1592.  
  1593.     if @csid = 6
  1594.         /* Set up the alphabetic codepoint ranges for cp1253. */
  1595.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1596.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1597.            @alpha_2_start = 0xBE, @alpha_2_end = 0xD1,
  1598.            @alpha_3_start = 0xD3, @alpha_3_end = 0xFE,
  1599.                @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1600.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1601.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1602.                @alpha_7_start = 0xB8, @alpha_7_end = 0xBA,
  1603.            @alpha_s_1 = 0xA2, @alpha_s_2 = 0xBC, @alpha_s_3 = 0x41,
  1604.            @alpha_s_4 = 0x41
  1605.  
  1606.     if @csid = 7
  1607.         /* Set up the alphabetic codepoint ranges for cp1254. */
  1608.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1609.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1610.            @alpha_2_start = 0xD8, @alpha_2_end = 0xFF,
  1611.            @alpha_3_start = 0x9F, @alpha_3_end = 0x9F,
  1612.                @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1613.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1614.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1615.                @alpha_7_start = 0xC0, @alpha_7_end = 0xD6,
  1616.            @alpha_s_1 = 0x83, @alpha_s_2 = 0x8A, @alpha_s_3 = 0x9A,
  1617.            @alpha_s_4 = 0x41
  1618.  
  1619.     if @csid = 8
  1620.         /* Set up the alphabetic codepoint ranges for cp1255. */
  1621.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1622.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1623.            @alpha_2_start = 0x41, @alpha_2_end = 0x5A,
  1624.            @alpha_3_start = 0x41, @alpha_3_end = 0x5A,
  1625.                @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1626.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1627.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1628.                @alpha_7_start = 0xE0, @alpha_7_end = 0xFA,
  1629.            @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41,
  1630.            @alpha_s_4 = 0x41
  1631.  
  1632.     if @csid = 9
  1633.         /* Set up the alphabetic codepoint ranges for cp1256. */
  1634.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1635.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1636.           @alpha_2_start = 0x80, @alpha_2_end = 0x9A,
  1637.            @alpha_3_start = 0xA0, @alpha_3_end = 0xA5,
  1638.                @alpha_4_start = 0xE0, @alpha_4_end = 0xEE,
  1639.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1640.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1641.                @alpha_7_start = 0x61, @alpha_7_end = 0x7A,
  1642.            @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41,
  1643.            @alpha_s_4 = 0x41
  1644.  
  1645.     if @csid = 10
  1646.         /* Set up the alphabetic codepoint ranges for cp1257. */
  1647.         select @alpha_0_start = 0x41, @alpha_0_end = 0x5A,
  1648.            @alpha_1_start = 0x61, @alpha_1_end = 0x7A,
  1649.            @alpha_2_start = 0x9C, @alpha_2_end = 0x9F,
  1650.            @alpha_3_start = 0xC0, @alpha_3_end = 0xFE,
  1651.                @alpha_4_start = 0x41, @alpha_4_end = 0x5A,
  1652.                @alpha_5_start = 0x41, @alpha_5_end = 0x5A,
  1653.                @alpha_6_start = 0x61, @alpha_6_end = 0x7A,
  1654.                @alpha_7_start = 0x8C, @alpha_7_end = 0x8F,
  1655.            @alpha_s_1 = 0x41, @alpha_s_2 = 0x41, @alpha_s_3 = 0x41,
  1656.            @alpha_s_4 = 0x41
  1657.  
  1658.     select @totallen = datalength( @namelist )
  1659.     while ( @totallen > 0 )
  1660.     begin
  1661.         /* Move to the next name in the list. */
  1662.         select @namelist = right( @namelist, @totallen )
  1663.  
  1664.         /* If this is not the last name in the list then there must
  1665.         ** be another comma.
  1666.         */
  1667.         if ( @numnames > 1 )
  1668.         begin
  1669.             select @mthlen = charindex( ',', @namelist ) - 1
  1670.             if ( @mthlen < 0 )
  1671.             begin
  1672.                 raiserror(15058,-1,-1,@msgparam)
  1673.                 return(2)
  1674.             end
  1675.         end
  1676.  
  1677.         /* This is the last name in the list, so there cannot be
  1678.         ** another comma.  This name is all remaining characters
  1679.         ** in the list.
  1680.         */
  1681.         else
  1682.         begin
  1683.             if ( charindex( ',', @namelist ) <> 0 )
  1684.             begin
  1685.                 raiserror(15059,-1,-1,@msgparam)
  1686.                 return(3)
  1687.             end
  1688.             select @mthlen = @totallen
  1689.         end
  1690.  
  1691.         /* Check the name length. */
  1692.         if ( @mthlen > @maxnamelen )
  1693.         begin
  1694.             raiserror(15283,-1,-1,@msgparam)
  1695.             return(4)
  1696.         end
  1697.  
  1698.         /*
  1699.         ** Check to see that the names contain only true
  1700.         ** Alphabetic characters; not even DIGITs are allowed.
  1701.         */
  1702.         select @next = 1
  1703.         while @next <= @mthlen
  1704.         begin
  1705.             select @curchar = convert(binary(1),
  1706.             substring(@namelist, @next, 1))
  1707.             if (not
  1708.             (
  1709.                (@curchar between @alpha_0_start and @alpha_0_end)
  1710.             or (@curchar between @alpha_1_start and @alpha_1_end)
  1711.             or (@curchar between @alpha_2_start and @alpha_2_end)
  1712.             or (@curchar between @alpha_3_start and @alpha_3_end)
  1713.             or (@curchar between @alpha_4_start and @alpha_4_end)
  1714.             or (@curchar between @alpha_5_start and @alpha_5_end)
  1715.             or (@curchar between @alpha_6_start and @alpha_6_end)
  1716.             or (@curchar between @alpha_7_start and @alpha_7_end)
  1717.             or @curchar = @alpha_s_1
  1718.             or @curchar = @alpha_s_2
  1719.             or @curchar = @alpha_s_3
  1720.             or @curchar = @alpha_s_4
  1721.             )
  1722.             )
  1723.             begin
  1724.                 raiserror(15060,-1,-1,@msgparam,@csname)
  1725.             return(5)
  1726.             end
  1727.  
  1728.             select @next = @next + 1
  1729.         end
  1730.  
  1731.         /* Move to the next name in the list. */
  1732.         select @numnames = @numnames - 1
  1733.         select @totallen = @totallen - @mthlen - 1
  1734.     end
  1735.  
  1736.     /* No problems were found with the name list. */
  1737.     return (0)
  1738. go
  1739.  
  1740. print ''
  1741. print 'Creating procedure sp_namecrack.'
  1742. go
  1743. create procedure sp_namecrack
  1744. @name    varchar(123),
  1745. @site    varchar(30) = null output,
  1746. @db    varchar(30) = null output,
  1747. @owner    varchar(30) = null output,
  1748. @object    varchar(30) = null output
  1749. as
  1750.  
  1751. select @site = null, @db = null, @owner = null, @object = null
  1752.  
  1753. /*
  1754. **  Is there a site name?
  1755. */
  1756. if @name like '%.%.%.%'
  1757. begin
  1758.     select @site = substring(@name, 1, charindex('.', @name) - 1)
  1759.     select @name = substring(@name, charindex('.', @name) + 1, 125)
  1760. end
  1761.  
  1762. /*
  1763. **  Is there a database name?
  1764. */
  1765. if @name like '%.%.%'
  1766. begin
  1767.     select @db = substring(@name, 1, charindex('.', @name) - 1)
  1768.     select @name = substring(@name, charindex('.', @name) + 1, 125)
  1769. end
  1770.  
  1771. /*
  1772. **  Is there a owner?
  1773. */
  1774. if @name like '%.%'
  1775. begin
  1776.     select @owner = substring(@name, 1, charindex('.', @name) - 1)
  1777.     select @name = substring(@name, charindex('.', @name) + 1, 125)
  1778. end
  1779.  
  1780. select @object = @name
  1781.  
  1782. return (0)
  1783. go
  1784.  
  1785. print ''
  1786. print 'Creating procedure sp_addalias.'
  1787. go
  1788. create procedure sp_addalias
  1789. @loginame varchar(30),        /* the name of the pretender */
  1790. @name_in_db varchar(30)        /* who the pretender wants to pretend to be */
  1791. as
  1792.  
  1793. declare @suid    int        /* the suid of the pretender */
  1794. declare @asuid    int        /* the suid of the person to impersonate */
  1795. declare    @name    varchar(30)
  1796. declare @dbname sysname
  1797.  
  1798. /*
  1799. **  You must be SA or the dbo to execute this sproc.
  1800. */
  1801. if suser_id() <> 1 and user_id() <> 1
  1802.     begin
  1803.         raiserror(15000,-1,-1)
  1804.         return (1)
  1805.     end
  1806.  
  1807. /*
  1808. **  Make sure that the pretender has an account.
  1809. */
  1810. select @suid = suid from syslogins where name = @loginame
  1811.  
  1812. if @suid is NULL
  1813.     begin
  1814.         raiserror(15007,-1,-1,@loginame)
  1815.         return (1)
  1816.     end
  1817.  
  1818. /*
  1819. **  Get the suid of the person we want to pretend to be.
  1820. **  All user ids are <= 16383 and group ids are > 16383.
  1821. */
  1822. select @asuid = suid from sysusers where name = @name_in_db and uid <= 16383
  1823.  
  1824. /*
  1825. **  Does the user to be impersonated exist in the current database?
  1826. */
  1827. if @asuid is NULL
  1828.     begin
  1829.         raiserror(15008,-1,-1,@name_in_db)
  1830.         return (1)
  1831.     end
  1832.  
  1833. /*
  1834. **  Is the login to be aliased already a user in the current db?
  1835. */
  1836. if exists (select * from sysusers where suid = @suid)
  1837.     begin
  1838.         select @name = name,@dbname = db_name() from sysusers
  1839.             where suid = @suid
  1840.         raiserror(15278,-1,-1,@loginame,@name,@dbname)
  1841.         return (1)
  1842.     end
  1843.  
  1844. /*
  1845. **  Is the person already aliased to a user?
  1846. */
  1847. if exists (select * from sysalternates where suid = @suid)
  1848.     begin
  1849.         raiserror(15022,-1,-1)
  1850.         return (1)
  1851.     end
  1852.  
  1853. /*
  1854. **  Add the alias.
  1855. */
  1856. insert into sysalternates (suid, altsuid)
  1857.     values (@suid, @asuid)
  1858.  
  1859. print 'Alias user added.'
  1860.  
  1861. return (0)
  1862. go
  1863.  
  1864. print ''
  1865. print 'Creating procedure sp_addextendedproc.'
  1866. go
  1867. create procedure sp_addextendedproc
  1868. @functname varchar(30),        /* name of function to call */
  1869. @dllname varchar(255)        /* name of DLL containing function */
  1870. as
  1871. /*
  1872. **  If we're in a transaction, disallow the addition of the
  1873. **  extended stored procedure.
  1874. */
  1875. if @@trancount > 0
  1876. begin
  1877.     raiserror(15002,-1,-1,'sp_addextendedproc')
  1878.     return (1)
  1879. end
  1880.  
  1881. /*
  1882. ** Create the extended procedure mapping.
  1883. */
  1884. dbcc addextendedproc( @functname, @dllname)
  1885. return (0)
  1886. go
  1887.  
  1888. print ''
  1889. print 'Creating procedure sp_addgroup.'
  1890. go
  1891. create procedure sp_addgroup
  1892. @grpname varchar(30)            /* new group name */
  1893. as
  1894.  
  1895. declare @gid int            /* group id */
  1896.  
  1897. /*
  1898. **  You must be SA or the dbo to execute this sproc.
  1899. */
  1900. if suser_id() <> 1 and user_id() <> 1
  1901.     begin
  1902.         raiserror(15000,-1,-1)
  1903.         return (1)
  1904.     end
  1905.  
  1906. /*
  1907. **  Check to see that the @grpname is valid.
  1908. */
  1909. declare @returncode    int
  1910. execute @returncode = sp_validname @grpname
  1911. if @returncode <> 0
  1912.     return(1)
  1913.  
  1914. /*
  1915. **  See if the new group name is already being used as a user or group name.
  1916. */
  1917. select @gid = uid from sysusers where name = @grpname
  1918.  
  1919. /*
  1920. **  User ids are > 0 and  <= 16383 and group ids are > 16383.
  1921. */
  1922. if @gid is not null
  1923. begin
  1924.     if @gid > 0 and @gid <= 16383
  1925.         raiserror(15023,-1,-1,@grpname)
  1926.     else
  1927.         raiserror(15024,-1,-1,@grpname)
  1928.  
  1929.     return (1)
  1930. end
  1931.  
  1932. /*
  1933. **  Now get the group id for the new group.  Look for the first available
  1934. **  hole > 16383.
  1935. */
  1936. select @gid = min(s1.uid)+1 from sysusers s1
  1937.     where uid < 32767    /* Don't cause arithmetic overflow. */
  1938.     and uid >= 16383
  1939.     and not exists
  1940.         (select * from sysusers s2
  1941.             where s2.uid = s1.uid+1)
  1942.  
  1943. /*
  1944. **  This is the first group.
  1945. */
  1946. if @gid is null
  1947.     select @gid = 16384
  1948.  
  1949. /*
  1950. **  Create the group.
  1951. */
  1952. insert into sysusers (uid, suid, gid, name, environ)
  1953. values (@gid, -@gid, @gid, @grpname, '')
  1954.  
  1955. print 'New group added.'
  1956.  
  1957. return (0)
  1958. go
  1959.  
  1960.  
  1961. print ''
  1962. print 'Creating procedure sp_addlogin.'
  1963. go
  1964. CREATE PROCEDURE sp_addlogin
  1965.  
  1966. -- 1995/09/12 16:05
  1967.  
  1968.     @pLoginName         varchar(30)
  1969.    ,@pPassword          varchar(30) = Null
  1970.    ,@pDefaultDB         varchar(30) = 'master'
  1971.    ,@pDefaultLanguage   varchar(30) = Null
  1972.    ,@pLoginSUID         smallint    = Null
  1973. AS
  1974.  
  1975. Set nocount on
  1976.  
  1977. Declare
  1978.     @RetCode               int
  1979.    ,@IntA                  int
  1980.  
  1981.    ,@High2Int              smallint
  1982.    ,@NewSUID               smallint
  1983.    ,@LowRegSUID            smallint
  1984.  
  1985.    ,@charLowRegSUID        varchar(12)
  1986.    ,@WorkName              varchar(30)
  1987.  
  1988.  
  1989. --------  Initial values.
  1990.  
  1991. Select
  1992.     @RetCode               = 1   -- 0=Good ,1=Bad.
  1993.    ,@NewSUID               = Null
  1994.    ,@High2Int              = 32767
  1995.    ,@LowRegSUID            = 10
  1996.  
  1997. Select
  1998.     @charLowRegSUID        = convert(varchar,@LowRegSUID)
  1999.  
  2000.  
  2001.  
  2002. ----------------------------------------------------------------------
  2003. ----------------------------------------------------------------------
  2004. --*         Simple validations of input parms.
  2005. ----------------------------------------------------------------------
  2006. ----------------------------------------------------------------------
  2007.  
  2008.  
  2009.  
  2010. --------  An open txn risks improper recovery.
  2011.  
  2012.  
  2013. IF (@@trancount > 0)
  2014.    begin
  2015.    RaisError(15002,-1,-1,'sp_addlogin')
  2016.    GOTO LABEL_86RETURN
  2017.    end
  2018.  
  2019.  
  2020. --------  Only SA can run this.
  2021.  
  2022.  
  2023. IF (suser_id() <> 1)
  2024.    begin
  2025.    RaisError(15003,-1,-1)
  2026.    GOTO LABEL_86RETURN
  2027.    end
  2028.  
  2029.  
  2030. --------  Verify login name is valid.
  2031.  
  2032.  
  2033. Execute @IntA = sp_validname @pLoginName
  2034.  
  2035. IF (@IntA <> 0)
  2036.    begin
  2037.    --msg handle by called sproc.
  2038.    GOTO LABEL_86RETURN
  2039.    end
  2040.  
  2041.  
  2042. --------  Validate default language.
  2043.  
  2044.  
  2045. IF (@pDefaultLanguage IS NOT Null)
  2046.    begin
  2047.    Execute @IntA = sp_validlang @pDefaultLanguage
  2048.  
  2049.    IF (@IntA <> 0)
  2050.       begin
  2051.       --msg handle by called sproc.
  2052.       GOTO LABEL_86RETURN
  2053.       end
  2054.    end
  2055.  
  2056.  
  2057. --------  Verify login name is new.
  2058.  
  2059.  
  2060. IF (exists (select * from syslogins where name = @pLoginName))
  2061.    begin
  2062.    RaisError(15025,-1,-1,@pLoginName)
  2063.    GOTO LABEL_86RETURN
  2064.    end
  2065.  
  2066.  
  2067. --------  Verify the default database name is known.
  2068.  
  2069.  
  2070. IF NOT (exists (select * from sysdatabases where name = @pDefaultDB))
  2071.    begin
  2072.    RaisError(15010,-1,-1,@pDefaultDB)
  2073.    GOTO LABEL_86RETURN
  2074.    end
  2075.  
  2076.  
  2077.  
  2078. ----------------------------------------------------------------------
  2079. ----------------------------------------------------------------------
  2080. --*         Parms are valid, try to add login.
  2081. ----------------------------------------------------------------------
  2082. ----------------------------------------------------------------------
  2083.  
  2084.  
  2085.  
  2086. --------  Did the executioner supply an suid value?  -----------
  2087.  
  2088.  
  2089. IF (@pLoginSUID IS NOT Null)
  2090.    begin
  2091.  
  2092.    IF (@pLoginSUID <= 1)
  2093.       begin
  2094.       RaisError(15301,-1,-1 ,@pLoginSUID)
  2095.       GOTO LABEL_86RETURN
  2096.       end
  2097.  
  2098.  
  2099.    Select    @IntA      = min(suid)
  2100.             ,@WorkName  = min(name)
  2101.       from   syslogins
  2102.       where  suid       = @pLoginSUID
  2103.  
  2104.    IF (@IntA IS NOT Null)
  2105.       begin
  2106.       RaisError(15296,-1,-1 ,@pLoginSUID ,@WorkName)
  2107.       GOTO LABEL_86RETURN
  2108.       end
  2109.  
  2110.  
  2111.    Select @NewSUID = @pLoginSUID
  2112.  
  2113.    GOTO LABEL_07INSERT
  2114.  
  2115.    end
  2116.  
  2117.  
  2118.  
  2119. --------  Try the faster way of generating a new suid.  --------------
  2120.  
  2121.  
  2122. -- 16382=repl_publisher  ,16383=repl_subscriber
  2123.  
  2124.  
  2125. SELECT
  2126.              @IntA      = Max(suid)
  2127.       from
  2128.              syslogins
  2129.       where
  2130.       suid       < 16299  --avoids repl_%
  2131.  
  2132.  
  2133. IF     EXISTS (
  2134.                SELECT   *
  2135.                  from   syslogins
  2136.                  where  suid=(@IntA+1)
  2137.               )
  2138.    Select @IntA = @High2Int  --Acts as a defeating switch.
  2139.  
  2140.  
  2141. IF (@IntA < @High2Int)  --True almost always.
  2142.    begin
  2143.  
  2144.    Select @NewSUID = @IntA + 1
  2145.  
  2146.    IF (      @NewSUID < @LowRegSUID)
  2147.       Select @NewSUID = @LowRegSUID
  2148.  
  2149.    GOTO LABEL_07INSERT
  2150.  
  2151.    end
  2152.  
  2153.  
  2154. --------  Instead, scan for an available new suid number.  ------------
  2155.  
  2156.  
  2157. SELECT     --Find lowest in-use suid where the next number is available.
  2158.                 @NewSUID = min(log1.suid)
  2159.       from
  2160.                 syslogins  log1
  2161.       where
  2162.                 log1.suid  < @High2Int  --Avoid arithmetic overflow.
  2163.       and       log1.suid >= @LowRegSUID
  2164.       and
  2165.                 NOT exists    --Faster than plain cursor loop.
  2166.                   (
  2167.                    SELECT  log2.*
  2168.                      from  syslogins   log2
  2169.                      where log2.suid   = log1.suid + 1
  2170.                   )
  2171.  
  2172.  
  2173.  
  2174. IF (@NewSUID IS Null)
  2175.    begin
  2176.    RaisError(15297,-1,-1 ,@pLoginName)
  2177.    GOTO LABEL_86RETURN
  2178.    end
  2179. ELSE
  2180.    begin
  2181.    Select   @NewSUID = @NewSUID + 1
  2182.  
  2183.    GOTO LABEL_07INSERT
  2184.  
  2185.    end
  2186.  
  2187.  
  2188.  
  2189. ----------------------------------------------------------------------
  2190. --*            We have a good new suid number.
  2191. ----------------------------------------------------------------------
  2192.  
  2193.  
  2194. --------  Yes, a good suid number is in hand, add login.
  2195.  
  2196.  
  2197.    --Logic can never hit this raiserror/goto, precautionary.
  2198. RaisError('Bad logic in sp_addlogin, should never hit this statement (a1).' ,16,127)
  2199. GOTO LABEL_86RETURN
  2200.  
  2201.  
  2202.  
  2203. LABEL_07INSERT:   --@NewSUID must be set properly by now.
  2204.  
  2205.  
  2206.  
  2207. INSERT
  2208.          into
  2209.                 syslogins
  2210.             (
  2211.              suid
  2212.             ,status
  2213.             ,accdate
  2214.  
  2215.             ,totcpu ,totio ,spacelimit ,timelimit ,resultlimit
  2216.  
  2217.             ,dbname
  2218.             ,name
  2219.             ,password
  2220.             ,language
  2221.             )
  2222.          Values
  2223.             (
  2224.              @NewSUID
  2225.             ,8          -- 0x08 bit means pw encrypt new alogorithm
  2226.             ,getdate()
  2227.  
  2228.             ,0 ,0 ,0 ,0 ,0
  2229.  
  2230.             ,@pDefaultDB
  2231.             ,@pLoginName
  2232.             ,pwdencrypt(@pPassword)
  2233.             ,@pDefaultLanguage
  2234.             )
  2235.  
  2236.  
  2237. IF (@@error = 0)
  2238.    begin
  2239.    Raiserror(15298,-1,-1 ,@pLoginName ,@NewSUID)
  2240.    Select @RetCode   = 0
  2241.    end
  2242.  
  2243.  
  2244.  
  2245. ----------------------------------------------------------------------
  2246. --*               Finalization.
  2247. ----------------------------------------------------------------------
  2248.  
  2249.  
  2250. LABEL_86RETURN:
  2251.  
  2252.  
  2253. Return @RetCode
  2254. go
  2255.  
  2256.  
  2257.  
  2258. print ' '
  2259. print 'Creating procedure sp_change_users_login.'
  2260. go
  2261. CREATE PROCEDURE sp_change_users_login -- 1995/09/25 09:31
  2262.  
  2263.     @pAction               varchar(10)  = Null
  2264.  
  2265.    ,@pUserNamePattern      varchar(40)  = Null
  2266.    ,@pLoginName            varchar(30)  = Null
  2267. AS
  2268.  
  2269. Set nocount on
  2270.  
  2271. Declare
  2272.     @RetCode               int
  2273.    ,@IntA                  int
  2274.    ,@CountFixesByUpd       int
  2275.    ,@CountFixesByAddLogin  int
  2276.  
  2277.    ,@DBName                varchar(30)
  2278.  
  2279. Declare
  2280.     @110Name               varchar(30)
  2281.    ,@110UID                smallint
  2282.    ,@110SUID               smallint
  2283.    ,@LoginSUID             smallint
  2284.  
  2285.  
  2286. ---------------  Initial values.
  2287.  
  2288.  
  2289. Select
  2290.     @DBName                = db_name()
  2291.    ,@CountFixesByUpd       = 0
  2292.    ,@CountFixesByAddLogin  = 0
  2293.    ,@RetCode               = 0  -- 0=Good ,1=Bad.
  2294.  
  2295.  
  2296. ---------------  Validate the action  -----------------------
  2297.  
  2298.  
  2299. IF (          @pAction            IS     Null
  2300.     OR
  2301.         (     @pAction            IS NOT Null
  2302.          AND  Upper(@pAction) NOT IN ('REPORT','UPDATE_ONE','AUTO_FIX')
  2303.         )
  2304.    )
  2305.    begin
  2306.    RaisError(15286,-1,-1,@pAction)
  2307.    Select @RetCode = 1
  2308.    GOTO LABEL_86RETURN
  2309.    end
  2310.  
  2311. Select @pAction = Upper(@pAction)
  2312.  
  2313.  
  2314. ---------------  Exclude certain special logins  ------------------
  2315.  
  2316.  
  2317. IF (     lower(@pLoginName) IN
  2318.       ('sa' ,'probe' ,'repl_publisher' ,'repl_subscriber')
  2319.     AND        @pLoginName  IS NOT Null
  2320.    )
  2321.    begin
  2322.    RaisError(15287,-1,-1,@pLoginName)
  2323.    Select @RetCode = 1
  2324.    GOTO LABEL_86RETURN
  2325.    end
  2326.  
  2327.  
  2328. ---------------  Only the SA can run certain actions  -----------------
  2329.  
  2330.  
  2331. IF (     suser_id() <> 1
  2332.     AND  @pAction   IN ('AUTO_FIX')
  2333.    )
  2334.    begin
  2335.    RaisError(15288,-1,-1,'SA',@pAction)
  2336.    Select @RetCode = 1
  2337.    GOTO LABEL_86RETURN
  2338.    end
  2339.  
  2340.  
  2341. ---------------  Only SA or DBO can run certain actions  -------------
  2342.  
  2343.  
  2344. IF (     (suser_id() <> 1  AND  user_id() <> 1)
  2345.     AND  @pAction   IN ('UPDATE_ONE')
  2346.    )
  2347.    begin
  2348.    RaisError(15288,-1,-1,'SA or DBO',@pAction)
  2349.    Select @RetCode = 1
  2350.    GOTO LABEL_86RETURN
  2351.    end
  2352.  
  2353.  
  2354. -----------  Pre-existing open txn not allowed (recovery problemmatic) ----------
  2355.  
  2356.  
  2357. IF (@@trancount > 0)
  2358.    begin
  2359.    RaisError(15289,-1,-1)
  2360.    Select @RetCode = 1
  2361.    GOTO LABEL_86RETURN
  2362.    end
  2363.  
  2364.  
  2365. ---------------- Validate parm value combinations  -----------------
  2366.  
  2367.  
  2368. IF (@pAction   = 'REPORT')
  2369.    begin
  2370.  
  2371.    IF (     @pUserNamePattern IS NOT Null
  2372.        OR   @pLoginName       IS NOT Null
  2373.       )
  2374.       begin
  2375.       RaisError(15290,-1,-1,@pAction,@pUserNamePattern,@pLoginName)
  2376.       Select @RetCode = 1
  2377.       GOTO LABEL_86RETURN
  2378.       end
  2379.    end
  2380.  
  2381.  
  2382. IF (@pAction   = 'UPDATE_ONE')
  2383.    begin
  2384.  
  2385.    IF (     @pUserNamePattern IS     Null
  2386.        OR   @pLoginName       IS     Null
  2387.       )
  2388.       begin
  2389.       RaisError(15290,-1,-1,@pAction,@pUserNamePattern,@pLoginName)
  2390.       Select @RetCode = 1
  2391.       GOTO LABEL_86RETURN
  2392.       end
  2393.    end
  2394.  
  2395.  
  2396. IF (@pAction   = 'AUTO_FIX')
  2397.    begin
  2398.  
  2399.    IF (     @pUserNamePattern IS     Null
  2400.        OR   @pLoginName       IS NOT Null
  2401.       )
  2402.       begin
  2403.       RaisError(15290,-1,-1,@pAction,@pUserNamePattern,@pLoginName)
  2404.       Select @RetCode = 1
  2405.       GOTO LABEL_86RETURN
  2406.       end
  2407.    end
  2408.  
  2409.  
  2410.  
  2411. ----------------------------------------------------------------------
  2412. ----------------------------------------------------------------------
  2413. --                      ACTIONS
  2414. ----------------------------------------------------------------------
  2415. ----------------------------------------------------------------------
  2416.  
  2417.  
  2418. IF (@pAction   =    'UPDATE_ONE')
  2419.    GOTO LABEL_ACTION_UPDATE_ONE
  2420.  
  2421. IF (@pAction   =    'AUTO_FIX')
  2422.    GOTO LABEL_ACTION_AUTO_FIX
  2423.  
  2424. IF (@pAction   =    'REPORT')
  2425.    GOTO LABEL_ACTION_REPORT
  2426.  
  2427.  
  2428. ----------------------------------------------------------------------
  2429. --                      Action = REPORT
  2430. ----------------------------------------------------------------------
  2431.  
  2432.  
  2433. LABEL_ACTION_REPORT:
  2434.  
  2435.  
  2436.  
  2437. SELECT
  2438.              UserName   = u1.name
  2439.             ,UserSUID   = u1.suid
  2440.       from
  2441.              sysusers   u1
  2442.       where
  2443.              u1.suid    > 0
  2444.       and
  2445.              NOT EXISTS
  2446.                (
  2447.                 SELECT     l1.*
  2448.                   from     master.dbo.syslogins   l1
  2449.                   where    l1.suid     = u1.suid
  2450.                )
  2451.       order by
  2452.              u1.name
  2453.  
  2454.  
  2455.  
  2456. GOTO LABEL_77FINALIZATION
  2457.  
  2458.  
  2459.  
  2460. ----------------------------------------------------------------------
  2461. --                      Action = UPDATE_ONE
  2462. ----------------------------------------------------------------------
  2463.  
  2464.  
  2465. LABEL_ACTION_UPDATE_ONE:
  2466.  
  2467.  
  2468.  
  2469. IF (NOT EXISTS (SELECT * from sysusers where name = @pUserNamePattern))
  2470.    begin
  2471.    RaisError(15291,-1,-1,'User',@pUserNamePattern)
  2472.    Select @RetCode = 1
  2473.    GOTO LABEL_86RETURN
  2474.    end
  2475.  
  2476.  
  2477. SELECT
  2478.              @LoginSUID    = Min(suid)
  2479.       from
  2480.              master.dbo.syslogins
  2481.       where
  2482.              name          = @pLoginName
  2483.       and    name     NOT IN
  2484.                         ('sa' ,'probe'
  2485.                         ,'repl_publisher' ,'repl_subscriber'
  2486.                         )
  2487.       and    suid          > 0
  2488.  
  2489.  
  2490. IF (@LoginSUID IS Null)
  2491.    begin
  2492.    RaisError(15291,-1,-1,'Login',@pUserNamePattern)
  2493.    Select @RetCode = 1
  2494.    GOTO LABEL_86RETURN
  2495.    end
  2496.  
  2497.  
  2498. UPDATE
  2499.              sysusers
  2500.       set
  2501.              suid    = @LoginSUID
  2502.       where
  2503.              name    = @pUserNamePattern
  2504.       and    uid     > 0
  2505.       and    suid    > 0
  2506.       and    suid   <> @LoginSUID
  2507.  
  2508.  
  2509.  
  2510. IF (@@error = 0  AND  @@rowcount = 1)
  2511.    Select @CountFixesByUpd = 1
  2512.  
  2513.  
  2514.  
  2515. GOTO LABEL_77FINALIZATION
  2516.  
  2517.  
  2518.  
  2519. ----------------------------------------------------------------------
  2520. --                      Action = AUTO_FIX
  2521. ----------------------------------------------------------------------
  2522.  
  2523.  
  2524. LABEL_ACTION_AUTO_FIX:
  2525.  
  2526.  
  2527.  
  2528. ---------------  Cursor 110  -----------------
  2529.  
  2530.  
  2531. EXECUTE(
  2532. '
  2533. DECLARE Cursor110_Users Cursor
  2534.    -- Insensitive Scroll
  2535.    For
  2536. SELECT
  2537.              u1.name
  2538.             ,u1.uid
  2539.             ,u1.suid
  2540.       from
  2541.              sysusers               u1
  2542.       where
  2543.              name    LIKE ''' + @pUserNamePattern + '''
  2544.       and
  2545.              suid     > 0  --Bypass Groups, Public, Guest etc.
  2546.       and
  2547.              name  NOT IN
  2548.                      (''sa'' ,''probe''
  2549.                      ,''repl_publisher'' ,''repl_subscriber''
  2550.                      )
  2551.       and
  2552.              NOT Exists
  2553.                (
  2554.                 SELECT     *
  2555.                   from     master.dbo.syslogins   l1
  2556.                   where    l1.suid  = u1.suid
  2557.                )
  2558. '
  2559. )
  2560.  
  2561.  
  2562. OPEN Cursor110_Users
  2563.  
  2564.  
  2565.  
  2566. ---------------
  2567. WHILE (110=110)         ---------  LOOP 110: thru Users  -----------
  2568.    begin
  2569.  
  2570.  
  2571.    FETCH
  2572.                 Next
  2573.          from
  2574.                 Cursor110_Users
  2575.          into
  2576.                 @110Name
  2577.                ,@110UID
  2578.                ,@110SUID
  2579.  
  2580.  
  2581.    IF (@@fetch_status <> 0)
  2582.       begin
  2583.       DEALLOCATE Cursor110_Users
  2584.       BREAK  --loop 110
  2585.       end
  2586.  
  2587.  
  2588. -----------  Handle case where Name already in use.
  2589.  
  2590.    SELECT
  2591.                 @LoginSUID    = Min(suid)
  2592.          from
  2593.                 master.dbo.syslogins   l1
  2594.          where
  2595.                 l1.name    = @110Name
  2596.  
  2597.  
  2598.  
  2599.    IF (@LoginSUID IS NOT Null)
  2600.       begin
  2601.  
  2602.       BEGIN TRANSACTION
  2603.  
  2604.  
  2605.       UPDATE
  2606.                 sysusers
  2607.          set
  2608.                 suid       = @LoginSUID
  2609.          where
  2610.                 name       = @110Name
  2611.  
  2612.  
  2613.       UPDATE
  2614.                 sysalternates
  2615.          set
  2616.                 suid       = @LoginSUID
  2617.          where
  2618.                 suid       = @110SUID
  2619.  
  2620.  
  2621.  
  2622.       COMMIT TRANSACTION
  2623.  
  2624.  
  2625.       Select @CountFixesByUpd = @CountFixesByUpd + 1
  2626.       Raiserror(15292,-1,-1,@110Name)
  2627.  
  2628.  
  2629.       CONTINUE  --loop 110
  2630.  
  2631.       end
  2632.  
  2633.  
  2634. --------------  Instead, simple sp_addlogin.
  2635.  
  2636.  
  2637.    EXECUTE(
  2638.    '
  2639.    Execute sp_addlogin
  2640.                 ''' + @110Name + '''
  2641.                ,Null
  2642.                ,''' + @DBName + '''
  2643.    '
  2644.    )
  2645.  
  2646.  
  2647.    Select @CountFixesByAddLogin = @CountFixesByAddLogin + 1
  2648.    Raiserror(15293,-1,-1,@110Name)
  2649.  
  2650.    end  --loop 110
  2651.  
  2652.  
  2653.  
  2654. Raiserror(15294,-1,-1,@CountFixesByAddLogin)
  2655.  
  2656.  
  2657.  
  2658. GOTO LABEL_77FINALIZATION
  2659.  
  2660.  
  2661.  
  2662. ------------------  Finalization  ------------------
  2663.  
  2664.  
  2665. LABEL_77FINALIZATION:
  2666.  
  2667.  
  2668. Raiserror(15295,-1,-1,@CountFixesByUpd)
  2669.  
  2670.  
  2671. LABEL_86RETURN:
  2672.  
  2673.  
  2674. Return @RetCode
  2675. go
  2676.  
  2677.  
  2678. /* Create procedure to add user defined messages. */
  2679. print ''
  2680. print 'Creating procedure sp_addmessage.'
  2681. go
  2682. create procedure sp_addmessage
  2683. @msgnum int = null,        -- Number of new message.
  2684. @severity smallint = null,    -- Severity of new message.
  2685. @msgtext varchar(255) = null,    -- Text of new message.
  2686. @lang varchar(30) = null,       -- language (name) of new message
  2687. @with_log varchar(5) = 'FALSE', -- Whether the message will ALWAYS go to the NT event log
  2688. @replace varchar(7) = null    -- Optional parameter to specify that
  2689.                 -- existing message with same number
  2690.                 -- should be overwritten.
  2691. as
  2692. declare @retcode int
  2693. declare @langid smallint
  2694. declare @dlevel smallint
  2695.  
  2696. if @msgnum is null or @severity is null or @msgtext is null
  2697.     begin
  2698.         raiserror(15071,-1,-1)
  2699.         return(1)
  2700.     end
  2701.  
  2702. /*
  2703. ** User defined messages must be > 50000.
  2704. */
  2705. if @msgnum <= 50000
  2706.     begin
  2707.         raiserror(15040,-1,-1)
  2708.         return(1)
  2709.     end
  2710.  
  2711. /*
  2712. ** Valid severity range for user defined messges is 1 to 25.
  2713. */
  2714. if @severity not between 1 and 25
  2715.     begin
  2716.         raiserror(15041,-1,-1)
  2717.         return(1)
  2718.     end
  2719.  
  2720. /*
  2721. ** Only the SA may add messages with severity > 18 or which set the WITH_LOG option to 'true'
  2722. */
  2723. if suser_id() <> 1 and ((@severity > 18) or (rtrim(upper(@with_log)) = 'TRUE'))
  2724.     begin
  2725.         raiserror(15042,-1,-1)
  2726.         return (1)
  2727.     end
  2728.  
  2729. /*
  2730. ** Verify the language
  2731. */
  2732. if @lang is not null
  2733.     begin
  2734.         exec @retcode = sp_validlang @lang
  2735.         if @retcode <>  0
  2736.             return(1)
  2737.     end
  2738. else
  2739.     select @lang = @@language
  2740.  
  2741. /*
  2742. ** Get langid from syslanguages; us_english won't exist, so use 0.
  2743. */
  2744. select @langid = isnull((select langid from syslanguages where name = @lang),0)
  2745.  
  2746. /*
  2747. ** @with_log must be 'TRUE' or 'FALSE'
  2748. */
  2749. if (upper(@with_log) not in ('TRUE', 'FALSE'))
  2750.     begin
  2751.         raiserror(15271,-1,-1)
  2752.         return (1)
  2753.     end
  2754.  
  2755. /*
  2756. ** Set the dlevel bit accordingly
  2757. */
  2758. if (rtrim(upper(@with_log)) = 'TRUE')
  2759.         select @dlevel = 0x80
  2760. else
  2761.         select @dlevel = 0x0
  2762.  
  2763. /*
  2764. ** If we're adding a non-us_english message, make sure the us_english version already exists.
  2765. */
  2766. if (@langid not in (0, null)) and not exists (select * from sysmessages where error=@msgnum and langid in (0, null))
  2767.     begin
  2768.         raiserror(15279,-1,-1,@lang)
  2769.         return(1)
  2770.     end
  2771.  
  2772. /*
  2773. **  Does this message already exist, and if so are we REPLACEing it?
  2774. */
  2775. if (select count(*) from sysmessages where error=@msgnum and langid=@langid) > 0
  2776.     if lower(@replace) = 'replace'
  2777.         begin
  2778.             print 'Replacing message.'
  2779.             delete from sysmessages where error = @msgnum and langid = @langid
  2780.         end
  2781.     else
  2782.         begin
  2783.             /*
  2784.             ** The 'replace' option wasn't specified and a
  2785.             ** msg. with the number already exists.
  2786.             */
  2787.             raiserror(15043,-1,-1)
  2788.             return(1)
  2789.         end
  2790.  
  2791. /*
  2792. **  Create the message.
  2793. */
  2794. insert into sysmessages(error,severity,description,dlevel,langid)
  2795.     values (@msgnum,@severity,@msgtext,@dlevel,@langid)
  2796.  
  2797. if (@@error = 0)
  2798.     print 'New message added.'
  2799.  
  2800. return (0)
  2801. go
  2802.  
  2803.  
  2804. print ''
  2805. print 'Creating procedure sp_addumpdevice.'
  2806. go
  2807. create procedure sp_addumpdevice -- 1995/09/07 12:01
  2808. @devtype varchar(10),      /* disk, tape, or diskette */
  2809. @logicalname   varchar(30),      /* logical name of the device */
  2810. @physicalname  varchar(127),     /* physical name of the device */
  2811. @cntrltype  smallint = null,  /* controller type - ignored. */
  2812. @devstatus  varchar(40) = 'noskip'  /* device characteristics */
  2813. as
  2814.  
  2815. declare @status smallint      /* status bits for device */
  2816. declare @returncode int
  2817.  
  2818. /*
  2819. **  An open txn might jeopardize a recovery.
  2820. */
  2821. if @@trancount > 0
  2822.    begin
  2823.       raiserror(15002,-1,-1,'sp_addumpdevice')
  2824.       return (1)
  2825.    end
  2826.  
  2827. /*
  2828. **  You must be SA to execute this sproc.
  2829. */
  2830. if suser_id() <> 1
  2831.    begin
  2832.       raiserror(15003,-1,-1)
  2833.       return (1)
  2834.    end
  2835.  
  2836. /*
  2837. **  Check to see that the @logicalname is valid.
  2838. */
  2839. exec @returncode = sp_validname @logicalname
  2840. if @returncode <> 0
  2841.    return(1)
  2842.  
  2843. select @devtype=lower(@devtype)
  2844.  
  2845. /*
  2846. **  Check out the @devtype.
  2847. */
  2848. if @devtype not in ('disk', 'tape', 'diskette', 'pipe')
  2849.    begin
  2850.       raiserror(15044,-1,-1,@devtype)
  2851.       return (1)
  2852.    end
  2853.  
  2854. /*
  2855. **  Check the args are not NULL.
  2856. */
  2857. if @logicalname is null
  2858.    begin
  2859.       raiserror(15045,-1,-1)
  2860.       return(1)
  2861.    end
  2862.  
  2863. if @physicalname is null
  2864.    begin
  2865.       raiserror(15046,-1,-1)
  2866.       return(1)
  2867.    end
  2868.  
  2869. /*
  2870. **  Make sure physical file name would be unique among devices.
  2871. */
  2872. if exists (select * from sysdevices where phyname = @physicalname)
  2873.    begin
  2874.       raiserror(15061,-1,-1,@physicalname)
  2875.       return (1)
  2876.    end
  2877.  
  2878. /*
  2879. **  Prohibit certain special english words from being logical names.
  2880. */
  2881. if (@logicalname IN ('disk' ,'diskette' ,'tape' ,'floppy'))
  2882.    begin
  2883.       raiserror(15285,-1,-1,@logicalname)
  2884.       return (1)
  2885.    end
  2886.  
  2887. /*
  2888. **  Make sure that a device with @logicalname doesn't already exist.
  2889. */
  2890. if exists (select * from sysdevices where name = @logicalname)
  2891.    begin
  2892.       raiserror(15026,-1,-1,@logicalname)
  2893.       return (1)
  2894.    end
  2895.  
  2896. /*
  2897. **  Always turn on the dump status bit.
  2898. */
  2899. select @status = 16
  2900.  
  2901. /*
  2902. **  If @devtype is a tape then check to see if devstatus is 'skip'.
  2903. */
  2904. if @devtype = 'tape'
  2905.    begin
  2906.       if @devstatus not in ('noskip','skip')
  2907.          begin
  2908.             raiserror(15047,-1,-1)
  2909.             return (1)
  2910.          end
  2911.  
  2912.       if @devstatus = 'skip' select @status = @status | 8
  2913.    end
  2914.  
  2915. /*
  2916. **  If a disk then the cntrltype = 2
  2917. */
  2918. if @devtype = 'disk'
  2919.    begin
  2920.       insert into sysdevices
  2921.          (low, high, status, cntrltype, name, phyname)
  2922.          values
  2923.          (0, 0, @status, 2, @logicalname, @physicalname)
  2924.       print '''Disk'' device added.'
  2925.    end
  2926.  
  2927. /*
  2928. **  If a diskette then the cntrltype in (3,4)
  2929. */
  2930. if @devtype = 'diskette'
  2931.    begin
  2932.       insert into sysdevices
  2933.          (low, high, status, cntrltype, name, phyname)
  2934.          values
  2935.          (0, 0, @status, 3, @logicalname, @physicalname)
  2936.       print '''Diskette'' device added.'
  2937.    end
  2938.  
  2939. /*
  2940. **  Tape device.
  2941. */
  2942. if @devtype = 'tape'
  2943.    begin
  2944.       insert into sysdevices
  2945.          (low, high, status, cntrltype, name, phyname)
  2946.          values
  2947.          (0, 0, @status, 5, @logicalname,@physicalname)
  2948.       print '''Tape'' device added.'
  2949.    end
  2950.  
  2951. /*
  2952. ** Pipe.
  2953. */
  2954. if @devtype = 'pipe'
  2955.    begin
  2956.       insert into sysdevices
  2957.          (low, high, status, cntrltype, name, phyname)
  2958.          values
  2959.          (0, 0, @status, 6, @logicalname,@physicalname)
  2960.       print '''Pipe'' device added.'
  2961.    end
  2962.  
  2963. return (0)
  2964. go
  2965.  
  2966.  
  2967. print ''
  2968. print 'Creating procedure sp_adduser.'
  2969. go
  2970. create procedure sp_adduser
  2971. @loginame varchar(30),            -- user's login name in syslogins
  2972. @name_in_db varchar(30) = NULL,        -- user's name to add to current db
  2973. @grpname varchar(30) = NULL        -- group to put new user in
  2974. as
  2975.  
  2976. declare @suid        int        -- user's system id
  2977. declare @grpid        int        -- group id of group to put user in
  2978. declare @uid        int        -- new user's id
  2979. declare @returncode    int
  2980.  
  2981. /*
  2982. **  You must be SA or the dbo to execute this sproc.
  2983. */
  2984. if suser_id() <> 1 and user_id() <> 1
  2985. begin
  2986.     raiserror(15000,-1,-1)
  2987.     return (1)
  2988. end
  2989.  
  2990. /*
  2991. **  If no new user name is given, use the login name.
  2992. */
  2993. if @name_in_db is null
  2994.     select @name_in_db = @loginame
  2995.  
  2996. /*
  2997. **  Check to see that the @name_in_db is valid.
  2998. */
  2999. exec @returncode = sp_validname @name_in_db
  3000. if @returncode <> 0
  3001.     return(1)
  3002.  
  3003. /*
  3004. **  Check to see if the user already exists in the database.
  3005. */
  3006. if exists (select * from sysusers where name = @name_in_db)
  3007.     begin
  3008.         raiserror(15023,-1,-1,@name_in_db)
  3009.         return (1)
  3010.     end
  3011.  
  3012. /*
  3013. ** The repl_subscriber user can only be mapped to the repl_subscriber
  3014. ** login.
  3015. */
  3016. if (@loginame='repl_subscriber' or @name_in_db='repl_subscriber')
  3017.     and @loginame<>@name_in_db
  3018.         begin
  3019.             raiserror(15070,-1,-1)
  3020.             return(1)
  3021.         end
  3022.  
  3023. /*
  3024. **  Check to see that the user has a login name.
  3025. **  We'll also initialize @grpid to 0 while we're here.
  3026. */
  3027. select @suid = suid, @grpid = 0 from syslogins where name = @loginame
  3028.  
  3029. /*
  3030. ** If the login doesn't exist and it isn't the special case
  3031. ** where user was specified as 'guest', return an error.
  3032. */
  3033. if @suid is null and (@name_in_db <> 'guest' or @loginame <> 'guest')
  3034.     begin
  3035.         raiserror(15007,-1,-1,@loginame)
  3036.         return (1)
  3037.     end
  3038.  
  3039. /*
  3040. ** Can't map guest user to a real login.
  3041. */
  3042. if @suid is not null and @name_in_db = 'guest' and @loginame <> 'guest'
  3043.     begin
  3044.         raiserror(15062,-1,-1)
  3045.         return (1)
  3046.     end
  3047.  
  3048. /*
  3049. **  If they specified 'guest' and we got to here, add the guest user.
  3050. */
  3051. if @name_in_db = 'guest' and @loginame = 'guest'
  3052.     begin
  3053.         /*
  3054.         **  Add the guest user and return.
  3055.         */
  3056.         insert into sysusers (uid, suid, gid, name)
  3057.             values (2, -1, 0, 'guest')
  3058.         print 'The ''guest'' user has been added.'
  3059.         return (0)
  3060.     end
  3061.  
  3062. /*
  3063. **  See if the login already has an account under a different user name.
  3064. **  That is, is the user's suid already in the sysusers table.
  3065. */
  3066. if exists (select * from sysusers where suid = @suid)
  3067.     begin
  3068.         raiserror(15063,-1,-1)
  3069.         return (1)
  3070.     end
  3071.  
  3072. /*
  3073. **  See if the user is known in the database already with an alias.
  3074. **  That is, does the user's suid appear in the sysalternates table.
  3075. */
  3076. if exists (select * from sysalternates where suid = @suid)
  3077.     begin
  3078.         raiserror(15022,-1,-1)
  3079.         return (1)
  3080.     end
  3081.  
  3082. /*
  3083. **  If a group name is given, check to see that it is valid.
  3084. **  User ids are > 0 and <= 16383 and group ids are > 16383.
  3085. */
  3086. if @grpname IS NOT NULL
  3087. begin
  3088.     select @grpid = -1
  3089.     select @grpid = gid from sysusers
  3090.     where name = @grpname and (uid > 16383 or uid = 0)
  3091.  
  3092.     if @grpid = -1
  3093.     begin
  3094.         raiserror(15014,-1,-1,@grpname)
  3095.         return (1)
  3096.     end
  3097. end
  3098.  
  3099. /*
  3100. **  Calculate the first available uid.
  3101. */
  3102. if @name_in_db='repl_subscriber'
  3103.     select @uid=16383
  3104. else
  3105.     if (select count(*) from sysusers where uid between 3 and 16382) = 0
  3106.         select @uid=3
  3107.     else
  3108.         select @uid=min(s1.uid)+1 from sysusers s1
  3109.         where uid < 16382    /* Don't go into uid range of groups. */
  3110.         and uid > 1
  3111.         and not exists
  3112.             (select * from sysusers s2
  3113.             where s2.uid = s1.uid+1)
  3114.  
  3115. /* Error if no more user id's available */
  3116. if @uid is null
  3117.     begin
  3118.         raiserror(15065,-1,-1)
  3119.         return (1)
  3120.     end
  3121.  
  3122.  
  3123. insert into sysusers (uid, suid, gid, name)
  3124.     values (@uid, @suid, @grpid, @name_in_db)
  3125.  
  3126. print 'New user added.'
  3127.  
  3128. return (0)
  3129. go
  3130.  
  3131. print ''
  3132. print 'Creating procedure sp_addremotelogin.'
  3133. go
  3134. create procedure sp_addremotelogin
  3135. @remoteserver    varchar(30),        /* name of remote server */
  3136. @loginame varchar(30) = NULL,        /* user's remote name */
  3137. @remotename varchar(30) = NULL        /* user's local user name */
  3138. as
  3139.  
  3140. /*
  3141. **  If we're in a transaction, disallow this since it might make recovery
  3142. **  impossible.
  3143. */
  3144. if @@trancount > 0
  3145.     begin
  3146.         raiserror(15002,-1,-1,'sp_addremotelogin')
  3147.         return (1)
  3148.     end
  3149.  
  3150. /*
  3151. **  Check that the server name is valid.
  3152. */
  3153. if not exists (select * from sysservers
  3154.         where srvname = @remoteserver)
  3155.     begin
  3156.         raiserror(15015,-1,-1,@remoteserver)
  3157.         return (1)
  3158.     end
  3159.  
  3160. /*
  3161. **  There are three cases to handle.
  3162. **
  3163. **    1) if only @remoteserver is given then a entry is made in
  3164. **        sysremotelogins that means anyone that doesn't have
  3165. **        an exact of mapped match in sysremotelogins will use
  3166. **        their remotename as their local name and it will be looked
  3167. **        up in syslogins.
  3168. **
  3169. **    2) if @remotename is omitted then it means that anyone from the
  3170. **        remote server logging in that doesn't have a complete
  3171. **        match in sysremotelogins will be mapped to @loginame.
  3172. **
  3173. **    3) if @remotename and @loginame are given then it is a straight
  3174. **        remote login for sysremotelogins.
  3175. */
  3176.  
  3177. /*
  3178. **  Case 1:  Only @remoteserver given.
  3179. */
  3180. if @loginame is null and @remotename is null
  3181. begin
  3182.     /*
  3183.     **  Check that there is not already an entry for local mapping.
  3184.     */
  3185.     if exists (select *
  3186.         from sysremotelogins l, sysservers s
  3187.             where l.remoteserverid = s.srvid
  3188.                 and s.srvname = @remoteserver
  3189.                 and l.remoteusername is null)
  3190.     begin
  3191.         raiserror(15066,-1,-1,@remoteserver)
  3192.         return (1)
  3193.     end
  3194.  
  3195.     /*
  3196.     **  Add the entry.
  3197.     */
  3198.     insert into sysremotelogins
  3199.         (remoteserverid, remoteusername, suid, status)
  3200.     select srvid, null, -1, 0
  3201.         from sysservers
  3202.             where srvname = @remoteserver
  3203.     print 'New remote login created.'
  3204.     return (0)
  3205.  
  3206. end
  3207.  
  3208. /*
  3209. **  Check that the @loginame is valid.  These is needed for both
  3210. **  case 2 and 3.
  3211. */
  3212. if not exists (select * from syslogins where name = @loginame)
  3213.     begin
  3214.         raiserror(15067,-1,-1,@loginame)
  3215.         return (1)
  3216.     end
  3217.  
  3218. /*
  3219. **  Check to make sure that there is not already a @remotename for
  3220. **  the @remoteserver.
  3221. */
  3222. if exists (select *
  3223.         from sysremotelogins l, sysservers s
  3224.             where l.remoteserverid = s.srvid
  3225.             and s.srvname = @remoteserver
  3226.             and l.remoteusername = @remotename)
  3227.     begin
  3228.         select @remotename = isnull(@remotename,'NULL')
  3229.         raiserror(15068,-1,-1,@remotename,@remoteserver)
  3230.         return (1)
  3231.     end
  3232.  
  3233. /*
  3234. **  Case 2: We want to make an entry into sysremotelogins that will map
  3235. **    any non-exact matches to a particular local user.
  3236. */
  3237. if @remotename is null
  3238. begin
  3239.     /*
  3240.     **  Check that there is not already an entry for local mapping.
  3241.     */
  3242.     if exists (select *
  3243.         from sysremotelogins l, sysservers s
  3244.             where l.remoteserverid = s.srvid
  3245.             and s.srvname = @remoteserver
  3246.             and l.remoteusername is null)
  3247.         begin
  3248.             raiserror(15066,-1,-1,@remoteserver)
  3249.             return (1)
  3250.         end
  3251.  
  3252.     /*
  3253.     **  Go ahead and make the entry.
  3254.     */
  3255.     insert into sysremotelogins
  3256.         (remoteserverid, remoteusername, suid, status)
  3257.     select srvid, null, suser_id(@loginame), 0
  3258.         from sysservers
  3259.                 where srvname = @remoteserver
  3260.  
  3261.     print 'New remote login created.'
  3262.     return (0)
  3263. end
  3264.  
  3265. /*
  3266. **  Case 3:  All the parameters have been supplied.  All we need to check
  3267. **    is that the entry isn't already in sysremotelogins.
  3268. **    We've verified the @remoteserver and @loginame above.
  3269. */
  3270. if @loginame IS NOT NULL and @remotename IS NOT NULL
  3271. begin
  3272.     /*
  3273.     **  Make sure that the @loginame and @remotename are a
  3274.     **  unique combination.
  3275.     */
  3276.     if exists (select *
  3277.         from sysremotelogins l, sysservers s
  3278.             where l.remoteusername = @remotename
  3279.                 and l.remoteserverid = s.srvid
  3280.                 and s.srvname = @remoteserver
  3281.                 and l.suid = suser_id(@loginame))
  3282.     begin
  3283.         raiserror(15068,-1,-1,@remotename,@remoteserver)
  3284.         return (1)
  3285.     end
  3286.  
  3287.     /*
  3288.     **  Go ahead the do the insert.
  3289.     */
  3290.     insert into sysremotelogins
  3291.         (remoteserverid, remoteusername, suid, status)
  3292.     select srvid, @remotename, suser_id(@loginame), 0
  3293.         from sysservers
  3294.             where srvname = @remoteserver
  3295.     print 'New remote login created.'
  3296.     return (0)
  3297. end
  3298.  
  3299. /*
  3300. **  We got here because the syntax was incorrect.
  3301. */
  3302. raiserror(15072,-1,-1)
  3303. return (1)
  3304. go
  3305.  
  3306. print ''
  3307. print 'Creating procedure sp_addsegment.'
  3308. go
  3309. create procedure sp_addsegment
  3310. @segname    varchar(30),    /* segment name */
  3311. @devname    varchar(30)    /* device name to put segment on */
  3312. as
  3313.  
  3314. declare @dbuid        smallint    /* id of the owner of the database */
  3315. declare @segbit        int        /* this is the bit to turn on in sysusages */
  3316. declare @retcode    int
  3317. declare @dbname        varchar(30)
  3318.  
  3319. /*
  3320. **  If we're in a transaction, disallow this since it might make recovery
  3321. **  impossible.
  3322. */
  3323. if @@trancount > 0
  3324.     begin
  3325.         raiserror(15002,-1,-1,'sp_addsegment')
  3326.         return (1)
  3327.     end
  3328.  
  3329. /*
  3330. **  You must be SA or the dbo to execute this sproc.
  3331. */
  3332. if suser_id() <> 1 and user_id() <> 1
  3333.     begin
  3334.         raiserror(15000,-1,-1)
  3335.         return (1)
  3336.     end
  3337.  
  3338. /*
  3339. **  See if the device exists.
  3340. */
  3341. if not exists (select * from sysdevices where name like @devname)
  3342.     begin
  3343.         raiserror(15012,-1,-1,@devname)
  3344.         return (1)
  3345.     end
  3346.  
  3347. /*
  3348. **    Check that the device is a database device.
  3349. */
  3350.  
  3351. if not exists (select * from sysdevices
  3352.         where name like @devname
  3353.             and cntrltype in (0,7))
  3354.     begin
  3355.         raiserror(15035,-1,-1,@devname)
  3356.         return (1)
  3357.     end
  3358.  
  3359. /*
  3360. **  Now see if the @dbname uses the @devname
  3361. */
  3362. if not exists (select *
  3363.         from sysusages u, sysdevices d
  3364.             where d.name = @devname
  3365.                 and u.vstart between d.low and d.high
  3366.                 and u.dbid = db_id())
  3367. begin
  3368.     select @dbname=db_name()
  3369.     raiserror(15073,-1,-1,@devname,@dbname)
  3370.     return (1)
  3371. end
  3372.  
  3373. /*
  3374. **  Check to see if the device is marked as a log device.
  3375. **  If so, return error.
  3376. */
  3377. if exists (select * from sysusages u, sysdevices d
  3378.         where d.name = @devname
  3379.         and u.vstart between d.low and d.high
  3380.         and u.dbid = db_id()
  3381.         and segmap = 4)
  3382.     begin
  3383.         raiserror(15074,-1,-1,@devname)
  3384.         return (1)
  3385.     end
  3386.  
  3387. /*
  3388. ** Check for valid identifier.
  3389. */
  3390. execute @retcode = sp_validname @segname
  3391. if @retcode <> 0
  3392.     return (1)
  3393.  
  3394. /*
  3395. **  Now go ahead and define the new segment and add it to the segmap
  3396. **  of sysusages.
  3397. **  NOTE: Don't update master..sysusages and syssegments as a xact since
  3398. **      it could cause problems for recovery.
  3399. */
  3400.  
  3401. /*
  3402. **  Check that @segname doesn't already exist.
  3403. */
  3404. if exists (select * from syssegments holdlock where name = @segname)
  3405. begin
  3406.     raiserror(15027,-1,-1,@segname)
  3407.     return (1)
  3408. end
  3409.  
  3410. /*
  3411. **  Figure out the next segment number to use.
  3412. **  Segment number may be 0-31.
  3413. */
  3414. select @segbit = 3
  3415. while @segbit < 32
  3416. begin
  3417.     /*
  3418.     **  Did we find one?
  3419.     */
  3420.     if exists (select *
  3421.             from syssegments
  3422.                 where segment = @segbit)
  3423.     begin
  3424.         select @segbit = @segbit + 1
  3425.     end
  3426.  
  3427.     /*
  3428.     **  We found an opening so break out.
  3429.     */
  3430.     else break
  3431.  
  3432. end
  3433.  
  3434. if @segbit >= 32
  3435. begin
  3436.     raiserror(15075,-1,-1)
  3437.     return (1)
  3438. end
  3439.  
  3440. /*
  3441. **  Add the new segment.
  3442. */
  3443. insert into syssegments (segment, name, status)
  3444.     values (@segbit, @segname, 0)
  3445.  
  3446. /*
  3447. **  Now set the segments on @devname sysusages.
  3448. */
  3449. if (@segbit < 31)
  3450.     select @segbit = power(2, @segbit)
  3451. else
  3452.     /*
  3453.     **  Since this is segment 31, power(2, 31) will overflow
  3454.     **  since segmap is an int.  We'll grab the machine-dependent
  3455.     **  bit mask from spt_values to set the right bit.
  3456.     */
  3457.     select @segbit = low
  3458.         from master.dbo.spt_values
  3459.             where type = 'E'
  3460.                 and number = 2
  3461. update sysusages
  3462.     set segmap = segmap | @segbit
  3463.         from sysusages u,
  3464.             sysdevices d
  3465.         where d.name = @devname
  3466.             and u.vstart between d.low and d.high
  3467.             and u.dbid = db_id()
  3468.  
  3469. /*
  3470. **  Now we need to activate the new segment map.
  3471. */
  3472. select @dbname = db_name()
  3473. dbcc dbrepair (@dbname, remap)
  3474. print 'Segment created.'
  3475.  
  3476. return (0)
  3477. go
  3478.  
  3479. print ''
  3480. print 'Creating procedure sp_addserver.'
  3481. go
  3482. create procedure sp_addserver
  3483. @server    varchar(30),            /* server name */
  3484. @local    varchar(10) = NULL,        /* local server */
  3485. @duplicate_ok varchar(13) = NULL     /* duplicate_ok */
  3486. as
  3487.  
  3488. declare @srvid smallint
  3489.  
  3490. /*
  3491. **  If we're in a transaction, disallow this since it might make recovery
  3492. **  impossible.
  3493. */
  3494. if @@trancount > 0
  3495.     begin
  3496.         raiserror(15002,-1,-1,'sp_addserver')
  3497.         return (1)
  3498.     end
  3499.  
  3500. /*
  3501. **  Server names must be unique so check.
  3502. */
  3503. if exists (select * from sysservers where srvname = @server)
  3504.     begin
  3505.         if @duplicate_ok = 'duplicate_ok'
  3506.            return (0)
  3507.         raiserror(15028,-1,-1,@server)
  3508.         return (1)
  3509.     end
  3510.  
  3511. /*
  3512. **  Check to see that the @server is valid.
  3513. */
  3514. declare @returncode    int
  3515. execute @returncode = sp_validname @server
  3516. if @returncode <> 0
  3517.     return(1)
  3518.  
  3519. /*
  3520. **  If this is the not the local server, then get the first available srvid.
  3521. */
  3522. if @local is null
  3523.     begin
  3524.         /* If no servers are found, use #1 */
  3525.         select @srvid = isnull(min(srvid)+1,1)
  3526.             from sysservers s1
  3527.             where srvid < 32767    /* Avoid arithmetic overflow if
  3528.                         ** srvid = max smallint exists. */
  3529.             and not exists
  3530.                 (select * from sysservers s2
  3531.                 where s2.srvid = s1.srvid+1)
  3532.  
  3533.         insert into sysservers
  3534.             (srvid, srvstatus, srvname, srvnetname)
  3535.             values
  3536.             (@srvid, 1, @server, @server)
  3537.     end
  3538.  
  3539. /*
  3540. **  If @local = 'local' then this is the local server and its
  3541. **  srvid = 0.
  3542. */
  3543. else
  3544.     begin
  3545.         if lower(@local) <> 'local'
  3546.             begin
  3547.                 raiserror(15089,-1,-1)
  3548.                 return(1)
  3549.             end
  3550.  
  3551.         if exists (select * from sysservers where srvid = 0)
  3552.             begin
  3553.                 raiserror(15090,-1,-1)
  3554.                 return (1)
  3555.             end
  3556.  
  3557.         insert into sysservers
  3558.             (srvid, srvstatus, srvname, srvnetname)
  3559.             values (0, 0, @server, @server)
  3560.     end
  3561.  
  3562. print 'Server added.'
  3563. return (0)
  3564. go
  3565.  
  3566. dump tran master with no_log
  3567. go
  3568.  
  3569. print ''
  3570. print 'Creating procedure sp_addtype.'
  3571. go
  3572. create procedure sp_addtype
  3573. @typename varchar(30),        -- name of user-defined type
  3574. @phystype varchar(30),        -- physical system type of user-defined type
  3575. @nulltype varchar(8) = null    -- nullability of new type
  3576. as
  3577.  
  3578. declare @len int        -- length of user type
  3579. declare @type tinyint        -- typeid of physical type
  3580. declare @tlen tinyint        -- length of physical type
  3581. declare @typeid smallint    -- user typeid of physical type
  3582. declare @var bit        -- is physical type variable length?
  3583. declare @nonull bit        -- default is getansinull()
  3584. declare @nullegal bit        -- does physical type allow NULLs?
  3585. declare @prec int        -- precision of the datatype
  3586. declare @scale int        -- scale of the datatype
  3587. declare @tprec tinyint        -- precision of the datatype read from systypes
  3588. declare @tscale tinyint        -- scale of the datatype read from systypes
  3589.  
  3590. select @nulltype = lower(@nulltype)
  3591.  
  3592. /*
  3593. **  Types based on 'bit' cannot be nullable.
  3594. */
  3595. if lower(@phystype) = 'bit'
  3596.     if @nulltype is null    -- If user didn't specify nullability,
  3597.                 -- make sure it doesn't get set to nullable
  3598.                 -- by getansinull()
  3599.         select @nulltype = 'not null'
  3600.     else            -- Also make sure that user doesn't try
  3601.                 -- to explicitly set it to nullable.
  3602.         if @nulltype = 'null'
  3603.             begin
  3604.                 raiserror(15276,-1,-1)
  3605.                 return(1)
  3606.             end
  3607.  
  3608. /*
  3609. **  Should the user type allow NULLs?
  3610. */
  3611. if @nulltype is null
  3612.     select @nonull = abs(getansinull()-1)
  3613. else if @nulltype = 'null'
  3614.     select @nonull = 0
  3615. else if @nulltype in ('not null','nonull')
  3616.     select @nonull = 1
  3617. else
  3618.     begin
  3619.         raiserror(15085,-1,-1)
  3620.         return (1)
  3621.     end
  3622.  
  3623. /*
  3624. **  Check to see that the @typename is valid.
  3625. */
  3626. declare @returncode int
  3627. execute @returncode = sp_validname @typename
  3628. if @returncode <> 0
  3629.     return(1)
  3630.  
  3631. /*
  3632. **  Check to see if the user type already exists or a system type
  3633. **  whose name = lower(@typename) (or a synomym) already exists.
  3634. */
  3635. if exists (select * from systypes where name = @typename)
  3636.         or lower(@typename)
  3637.         in ('character','character varying','char varying',
  3638.             'integer','dec','binary varying')
  3639.  
  3640.     begin
  3641.         raiserror(15029,-1,-1,@typename)
  3642.         return (1)
  3643.     end
  3644.  
  3645. /*
  3646. ** Make physical typename all lower case to ensure case insensitivity.
  3647. */
  3648. select @phystype = lower(@phystype)
  3649.  
  3650. /*
  3651. ** Can't supply length with sysname type.
  3652. */
  3653. if @phystype like 'sysname%(%'
  3654.     begin
  3655.         raiserror(15270,-1,-1)
  3656.         return(1)
  3657.     end
  3658.  
  3659. /*
  3660. ** initialize the length to be NULL first.
  3661. */
  3662. select @len = NULL
  3663.  
  3664. /*
  3665. ** If precision and scale were given with the type - extract them
  3666. */
  3667. if @phystype like '_%(_%,_%)'
  3668. begin
  3669.     select @prec = convert(int, substring(@phystype,
  3670.         charindex('(',@phystype) + 1,
  3671.         charindex(',',@phystype) - 1 - charindex('(',@phystype)))
  3672.  
  3673.     select @scale = convert(int, substring(@phystype,
  3674.         charindex(',',@phystype) + 1,
  3675.         charindex(')',@phystype) - 1 - charindex(',',@phystype)))
  3676.     /*
  3677.     ** Extract the physical type name
  3678.     */
  3679.     select @phystype = substring(@phystype, 1,
  3680.            charindex('(', @phystype) - 1)
  3681. end
  3682. else
  3683.  
  3684. /*
  3685. **  If a length was given with the user datatype, extract it.
  3686. */
  3687. if @phystype like '_%(%)'
  3688. begin
  3689.     select @len = convert(int, substring(@phystype,
  3690.         charindex('(',@phystype) + 1,
  3691.         charindex(')',@phystype) - 1 - charindex('(',@phystype)))
  3692.  
  3693.     /*
  3694.     ** Extract the physical type name
  3695.     */
  3696.     select @phystype = substring(@phystype, 1,
  3697.            charindex('(', @phystype) - 1)
  3698. end
  3699.  
  3700. if @phystype='character'
  3701.     select @phystype='char'
  3702. else if @phystype='character varying'
  3703.     select @phystype='varchar'
  3704. else if @phystype='char varying'
  3705.     select @phystype='varchar'
  3706. else if @phystype='integer'
  3707.     select @phystype='int'
  3708. else if @phystype='dec'
  3709.     select @phystype='decimal'
  3710. else if @phystype='binary varying'
  3711.     select @phystype='varbinary'
  3712.  
  3713. /*
  3714. **  Make sure that the physical type exists and get its characteristics.
  3715. **  System physical types have a usertype < 100 and are owned by the
  3716. **  dbo (userid = 1).
  3717. */
  3718. select @type = type, @tlen = length, @typeid = usertype,
  3719.     @var = variable, @nullegal = allownulls, @tprec = prec,
  3720.     @tscale = scale
  3721. from systypes
  3722.     where usertype < 100 and name = @phystype and uid = 1
  3723.  
  3724. if @type is null
  3725. begin
  3726.     raiserror(15036,-1,-1,@phystype)
  3727.     return (1)
  3728. end
  3729.  
  3730. /*
  3731. **  Disallow user-defined datatypes on timestamps.  This is done because
  3732. **  a timestamp is not a basic type but is really a binary.  There is,
  3733. **  therefore, no way to tell if a user-defined datatype is mapped to
  3734. **  a binary or a timestamp.  Timestamps can't have rules or defaults.
  3735. */
  3736. if @phystype = 'timestamp'
  3737. begin
  3738.     raiserror(15038,-1,-1)
  3739.     return (1)
  3740. end
  3741.  
  3742. /*
  3743. **  Check if the NULL status of the user type is consistent with the NULL status
  3744. **  of the physical type.  Here are the possible cases.
  3745. **
  3746. **           physical type
  3747. **          NULLs      NONULLs
  3748. **            -----------------
  3749. ** user    NULLs    |  ok    |  no
  3750. ** type NONULLs    |  ok    |  ok
  3751. */
  3752. if @nonull = 0 and @nullegal = 0
  3753.     begin
  3754.         raiserror(15037,-1,-1,@phystype)
  3755.         return (1)
  3756.     end
  3757.  
  3758. /*
  3759. **  We'll use the variable @nullegal when we update the systypes table
  3760. **  so we need to set it to reflect if NULLs are allowed (@nonull = 0)
  3761. **  or NO NULLs are allowed (@nonull = 1).
  3762. */
  3763. if @nonull = 0
  3764.     select @nullegal = 1
  3765. else
  3766.     select @nullegal = 0
  3767.  
  3768.  
  3769. /* Decide about precision, scale, length
  3770. ** First check from NUMERIC, DECIMAL
  3771. */
  3772. if (@typeid = 24) or  (@typeid = 10)
  3773. begin
  3774.     /* Type is NUMERIC or DECIMAL */
  3775.  
  3776.     if @len > 0
  3777.         begin
  3778.             /* Length is really the precision
  3779.             ** Since no scale is specified then scale
  3780.             ** is minimum(Default, precision). Default = 4
  3781.             */
  3782.             select @prec = @len
  3783.             select @scale = 0
  3784.         end
  3785.     else
  3786.         if (@prec is NULL)
  3787.             begin
  3788.                 select @prec = 18
  3789.                 select @scale = 0
  3790.             end
  3791.  
  3792.     if (@prec > 38) or (@prec < 1)
  3793.         begin
  3794.             raiserror(15086,-1,-1)
  3795.             return (1)
  3796.         end
  3797.  
  3798.     if (@scale > @prec) or (@scale < 0)
  3799.         begin
  3800.             /*
  3801.             ** Illegal scale specified -- must be less than precision
  3802.             ** and positive.
  3803.             */
  3804.             raiserror(15087,-1,-1)
  3805.             return (1)
  3806.         end
  3807.  
  3808.     /* Compute length from precision */
  3809.     if (@prec <= 2)
  3810.         select @len = 2
  3811.  
  3812.     if (@prec > 2) and (@prec <= 4)
  3813.         select @len = 3
  3814.  
  3815.     if (@prec > 4) and (@prec <= 7)
  3816.         select @len = 4
  3817.  
  3818.     if (@prec > 7) and (@prec <= 9)
  3819.         select @len = 5
  3820.  
  3821.     if (@prec > 9) and (@prec <= 12)
  3822.         select @len = 6
  3823.  
  3824.     if (@prec > 12) and (@prec <= 14)
  3825.         select @len = 7
  3826.  
  3827.     if (@prec > 14) and (@prec <= 16)
  3828.         select @len = 8
  3829.  
  3830.     if (@prec > 16) and (@prec <= 19)
  3831.         select @len = 9
  3832.  
  3833.     if (@prec > 19) and (@prec <= 21)
  3834.         select @len = 10
  3835.  
  3836.     if (@prec > 21) and (@prec <= 24)
  3837.         select @len = 11
  3838.  
  3839.     if (@prec > 24) and (@prec <= 26)
  3840.         select @len = 12
  3841.  
  3842.     if (@prec > 26) and (@prec <= 28)
  3843.         select @len = 13
  3844.  
  3845.     if (@prec > 28) and (@prec <= 31)
  3846.         select @len = 14
  3847.  
  3848.     if (@prec > 31) and (@prec <= 33)
  3849.         select @len = 15
  3850.  
  3851.     if (@prec > 33) and (@prec <= 36)
  3852.         select @len = 16
  3853.  
  3854.     if (@prec > 36) and (@prec <= 38)
  3855.         select @len = 17
  3856. end
  3857. else
  3858.  
  3859. /*
  3860. **  Typeids 1 (char), 2 (varchar), 3 (binary) and 4 (varbinary) are the
  3861. **  only ones which allow a length to be specified.
  3862. */
  3863. if @typeid > 4
  3864.     begin
  3865.         /*
  3866.         **  We can't use a length and we got one.
  3867.         */
  3868.         if @len > 0
  3869.             begin
  3870.                 raiserror(15088,-1,-1)
  3871.                 return (1)
  3872.             end
  3873.  
  3874.         /*
  3875.         **  Use the fixed length of the physical type.
  3876.         */
  3877.         select @len = @tlen
  3878.         select @prec = @tprec
  3879.         select @scale = @tscale
  3880.     end
  3881. else
  3882.     begin
  3883.         /*
  3884.         **  We need a length and we didn't get one.
  3885.         */
  3886.         if @len is null
  3887.             begin
  3888.                 raiserror(15091,-1,-1)
  3889.                 return (1)
  3890.             end
  3891.  
  3892.         if @len <= 0 or @len > 255
  3893.             begin
  3894.                 raiserror(15092,-1,-1)
  3895.                 return (1)
  3896.             end
  3897.  
  3898.         select @prec = @len
  3899.         select @scale = @tscale
  3900.     end
  3901.  
  3902. /*
  3903. **  Finally, get the maximum existing user type so we use it + 1 for this
  3904. **  new type.
  3905. */
  3906. select @typeid = max(usertype)
  3907.     from systypes
  3908.  
  3909. /*
  3910. **  There are no user defined types yet so use the first number (101).
  3911. */
  3912. if @typeid < 100
  3913.     select @typeid = 100
  3914.  
  3915. insert systypes (uid, variable, type, length, tdefault,
  3916.     domain, name, usertype, allownulls, prec, scale)
  3917. select user_id(), @var, @type, @len, 0, 0, @typename, @typeid + 1, @nullegal,
  3918.       @prec, @scale
  3919.  
  3920. print 'Type added.'
  3921.  
  3922. return (0)
  3923. go
  3924.  
  3925. print ''
  3926. print 'Creating procedure sp_addlanguage.'
  3927. go
  3928. create procedure sp_addlanguage
  3929. @language varchar(30),
  3930. @alias varchar(30) = NULL,
  3931. @months varchar(251),
  3932. @shortmons varchar(119),
  3933. @days varchar(216),
  3934. @datefmt char(3),
  3935. @datefirst tinyint
  3936. as
  3937.  
  3938. declare @msg varchar(250)
  3939. declare @nextlangid smallint
  3940. declare @returncode int
  3941.  
  3942. /*  Check to see if the language exists. */
  3943. if exists (select * from syslanguages where name = @language)
  3944.     begin
  3945.         raiserror(15039,-1,-1,@language)
  3946.         return (1)
  3947.     end
  3948.  
  3949. /* Check to see that the list of full month names is valid. */
  3950. execute @returncode = sp_chklangparam @months, 'full month', 12, 20
  3951. if @returncode <> 0
  3952.     return (1)
  3953.  
  3954. /* Check to see that the list of short month names is valid. */
  3955. execute @returncode = sp_chklangparam @shortmons, 'short month', 12, 9
  3956. if @returncode <> 0
  3957.     return (1)
  3958.  
  3959. /* Check to see that the list of day names is valid. */
  3960. execute @returncode = sp_chklangparam @days, 'day', 7, 30
  3961. if @returncode <> 0
  3962.     return (1)
  3963.  
  3964. /* Check to see that the @datefmt is valid. */
  3965. if (@datefmt <> 'mdy' and @datefmt <> 'dmy' and @datefmt <> 'ymd' and @datefmt <> 'ydm'
  3966.     and @datefmt <> 'myd' and @datefmt <> 'dym')
  3967. begin
  3968.     raiserror(15093,-1,-1,@datefmt)
  3969.     return (1)
  3970. end
  3971.  
  3972. /*
  3973. **  Check to see that the @datefirst is valid.
  3974. */
  3975. if (@datefirst < 1 or @datefirst > 7)
  3976. begin
  3977.     select @msg = convert(char(3), @datefirst)
  3978.     raiserror(15094,-1,-1,@msg)
  3979.     return (1)
  3980. end
  3981.  
  3982. /*
  3983. **  If the user didn't specify the alias name, the alias name is same as
  3984. **  the official name.
  3985. */
  3986. if @alias is null
  3987. begin
  3988.     select @alias =  @language
  3989. end
  3990.  
  3991. /*  Check to see if the alias exists. */
  3992.  
  3993. if exists (select * from syslanguages where alias = @alias)
  3994.     begin
  3995.         raiserror(15034,-1,-1,@alias)
  3996.         return (1)
  3997.     end
  3998.  
  3999. if @language = 'us_english'
  4000. begin
  4001.     /*  The language id of us_english is 0. */
  4002.     insert syslanguages (langid, dateformat, datefirst, upgrade,
  4003.         name, alias, months, shortmonths, days)
  4004.     select 0, @datefmt, @datefirst, 0,
  4005.         @language, @alias, @months, @shortmons, @days
  4006. end
  4007. else
  4008. begin
  4009.  
  4010.     if (select max(langid) from syslanguages) is null
  4011.         select @nextlangid = 1
  4012.     else
  4013.         select @nextlangid = (select max(langid)+1
  4014.         from syslanguages)
  4015.  
  4016.     insert into syslanguages
  4017.         (langid, dateformat, datefirst, upgrade, name, alias,
  4018.             months, shortmonths, days)
  4019.     select @nextlangid, @datefmt, @datefirst, 0,
  4020.         @language, @alias, @months, @shortmons, @days
  4021. end
  4022.  
  4023.  
  4024. /* If the insert failed, say so. */
  4025. if @@error <> 0
  4026.     begin
  4027.         raiserror(15095,-1,-1)
  4028.         return(1)
  4029.     end
  4030.  
  4031. print 'New language inserted.'
  4032. go
  4033.  
  4034. print ''
  4035. print 'Creating procedure sp_altermessage.'
  4036. go
  4037. create procedure sp_altermessage
  4038. @message_id       int,
  4039. @parameter        varchar(30),
  4040. @parameter_value  varchar(5)
  4041. as
  4042. begin
  4043.   declare @rows_affected  varchar(16)
  4044.   declare @msg            varchar(128)
  4045.  
  4046.   select @parameter = upper(@parameter)
  4047.   select @parameter_value = upper(@parameter_value)
  4048.  
  4049.   /*
  4050.   **  You must be SA or the dbo to execute this sproc.
  4051.   */
  4052.   if (suser_id() <> 1)
  4053.   begin
  4054.           raiserror(15003, 16, 1)
  4055.           return (1)
  4056.   end
  4057.  
  4058.   /*
  4059.   ** Does this message exist?
  4060.   */
  4061.   if (not exists (select * from master.dbo.sysmessages
  4062.                   where error = @message_id))
  4063.   begin
  4064.           raiserror(15179,-1,-1,@message_id)
  4065.           return (1)
  4066.   end
  4067.  
  4068.   /*
  4069.   ** Is Parameter 'WITH_LOG'?
  4070.   */
  4071.   if (@parameter <> 'WITH_LOG')
  4072.   begin
  4073.     raiserror(15176,-1,-1)
  4074.     return (1)
  4075.   end
  4076.  
  4077.   /*
  4078.   ** Is ParameterValue TRUE or FALSE?
  4079.   */
  4080.   if (@parameter_value not in ('TRUE', 'FALSE'))
  4081.   begin
  4082.           raiserror(15277,-1,-1)
  4083.           return (1)
  4084.   end
  4085.  
  4086.   /*
  4087.   ** Determine the number of messages affected
  4088.   */
  4089.   select @rows_affected = convert(varchar(16), count(*)) from master.dbo.sysmessages
  4090.        where error = @message_id
  4091.   select @msg = @rows_affected + ' Messages altered.'
  4092.  
  4093.   /*
  4094.   ** Turn dlevel bit 7 on or off
  4095.   */
  4096.   if (@parameter_value = 'TRUE')
  4097.   begin
  4098.           update master.dbo.sysmessages
  4099.                   set dlevel = dlevel | 0x80
  4100.                           where error = @message_id
  4101.           if (@@error = 0)
  4102.           begin
  4103.                   if (convert(int, @rows_affected) = 1) PRINT 'Message altered.'
  4104.                   if (convert(int, @rows_affected) > 1) PRINT @msg
  4105.           end
  4106.   end
  4107.   else
  4108.   if (@parameter_value = 'FALSE')
  4109.   begin
  4110.           update master.dbo.sysmessages
  4111.                   set dlevel = dlevel & 0x7FFFFF7F
  4112.                           where error = @message_id
  4113.           if (@@error = 0)
  4114.           begin
  4115.                   if (convert(int, @rows_affected) = 1) PRINT 'Message altered.'
  4116.                   if (convert(int, @rows_affected) > 1) PRINT @msg
  4117.           end
  4118.   end
  4119.   return (0)
  4120. end
  4121. go
  4122.  
  4123. print ''
  4124. print 'Creating procedure sp_defaultlanguage.'
  4125. go
  4126. create procedure sp_defaultlanguage
  4127. @loginame varchar(30),            /* login name of the user */
  4128. @language varchar(30) = NULL        /* default language for the new user */
  4129. as
  4130.  
  4131. declare @msg varchar(250)
  4132. declare @returncode int
  4133.  
  4134. /*
  4135. **  Only the system administrator (sa) can run this command.
  4136. **  Check to make sure the executor is the sa.
  4137. */
  4138. if (suser_id() <> 1 and suser_id() <> suser_id(@loginame))
  4139. begin
  4140.     raiserror(15096,-1,-1,@loginame,@loginame)
  4141.     return (1)
  4142. end
  4143.  
  4144. /*
  4145. **  Check to see that the @language is valid.
  4146. */
  4147. if @language is not null
  4148. begin
  4149.     execute @returncode = sp_validlang @language
  4150.     if @returncode <> 0
  4151.         return(1)
  4152. end
  4153.  
  4154. /*
  4155. **  Make sure the login already exists.
  4156. */
  4157. if not exists (select * from syslogins where name = @loginame)
  4158.     begin
  4159.         raiserror(15007,-1,-1,@loginame)
  4160.         return (1)
  4161.     end
  4162.  
  4163. /*
  4164. **  Set the default language for this user.
  4165. */
  4166. update syslogins
  4167.     set language = @language
  4168.          where name = @loginame
  4169.  
  4170. select @msg =  @loginame + '''s default language is changed to ' + @language
  4171. print @msg
  4172.  
  4173. return (0)
  4174. go
  4175.  
  4176. print ''
  4177. print 'Creating procedure sp_helplanguage.'
  4178. go
  4179. create procedure sp_helplanguage
  4180. @language varchar(30) = NULL
  4181. as
  4182.  
  4183. /* Print all languages if the user didn't give the language name. */
  4184. if @language is null
  4185. begin
  4186.     if exists (select * from syslanguages)
  4187.         select * from syslanguages
  4188.     else
  4189.         print 'No alternate languages are available.'
  4190.  
  4191.     /* Find out whether us_english is there or not. */
  4192.     if not exists (select * from syslanguages
  4193.             where name = 'us_english')
  4194.         print 'us_english is always available, even though it is not in syslanguages.'
  4195.  
  4196.     return (0)
  4197. end
  4198.  
  4199. /*  Report information on this language. */
  4200. if exists (select * from syslanguages where name = @language)
  4201.     begin
  4202.         select * from syslanguages where name = @language
  4203.         return (0)
  4204.     end
  4205.  
  4206. if exists (select * from syslanguages where alias = @language)
  4207.     begin
  4208.         select * from syslanguages where alias = @language
  4209.         return (0)
  4210.     end
  4211.  
  4212. /* Couldn't find this language. */
  4213. if @language = 'us_english'
  4214.     begin
  4215.         print 'us_english is always available, even though it is not in syslanguages.'
  4216.         return (0)
  4217.     end
  4218. else
  4219.     begin
  4220.         raiserror(15033,-1,-1,@language)
  4221.         return (1)
  4222.     end
  4223. go
  4224.  
  4225. print ''
  4226. print 'Creating procedure sp_droplanguage.'
  4227. go
  4228. create procedure sp_droplanguage
  4229. @language varchar(30),
  4230. @dropmessages varchar(30) = NULL
  4231. as
  4232.  
  4233. declare @langid smallint
  4234. declare @dropmsgs int
  4235.  
  4236.  
  4237. /*  Check to see if the language exists. */
  4238. if not exists (select * from syslanguages where name = @language)
  4239.     begin
  4240.         raiserror(15033,-1,-1,@language)
  4241.         return (1)
  4242.     end
  4243.  
  4244. /* Get language id from syslanguages. */
  4245. select @langid = (select langid
  4246.             from syslanguages
  4247.                 where name = @language)
  4248.  
  4249. /*  Check to see if 'dropmessages' is requested. */
  4250. select @dropmsgs = 0
  4251. if @dropmessages is null
  4252.     begin
  4253.         if exists (select * from sysmessages where langid = @langid)
  4254.             begin
  4255.                 /*
  4256.                 **  Cannot drop a language if the language has associated
  4257.                 **  entries in the sysmessages.
  4258.                 */    
  4259.                 raiserror(15097,-1,-1,@language)
  4260.                 return (1)
  4261.             end
  4262.     end
  4263. else
  4264.     begin
  4265.         if @dropmessages <> 'dropmessages'
  4266.             begin
  4267.                 raiserror(15098,-1,-1)
  4268.                 return (1)
  4269.             end
  4270.  
  4271.         select @dropmsgs = 1
  4272.     end
  4273.  
  4274. /*
  4275. **  Drop the language and delete messages from Sysmessages if there is any.
  4276. */
  4277. if @dropmsgs = 1
  4278.     delete sysmessages where langid = @langid
  4279.  
  4280. delete syslanguages
  4281.     where langid = @langid
  4282.  
  4283. print 'Language deleted.'
  4284.  
  4285. go
  4286.  
  4287. print ''
  4288. print 'Creating procedure sp_setlangalias.'
  4289. go
  4290. create procedure sp_setlangalias
  4291. @language varchar(30),
  4292. @alias varchar(30)
  4293. as
  4294.  
  4295. declare @returncode int
  4296.  
  4297. /*  Check to see if the language exists. */
  4298. exec @returncode = sp_validlang @language
  4299. if @returncode <> 0
  4300.     return (1)
  4301.  
  4302. /*  Check to see if the alias exists. */
  4303.  
  4304. if exists (select * from syslanguages where alias = @language)
  4305.     begin
  4306.         raiserror(15034,-1,-1,@alias)
  4307.         return (1)
  4308.     end
  4309.  
  4310. /* Reset the alternate language name. */
  4311. update syslanguages set alias = @alias where name = @language
  4312.  
  4313. /* If the update failed, say so. */
  4314. if @@error <> 0
  4315.     begin
  4316.         raiserror(15099,-1,-1)
  4317.         return(1)    
  4318.     end
  4319.  
  4320. print 'Language alias reset.'
  4321. go
  4322.  
  4323. print ''
  4324. print 'Creating procedure sp_bindefault.'
  4325. go
  4326. create procedure sp_bindefault
  4327. @defname varchar(92),            /* name of the default */
  4328. @objname varchar(61),            /* table or usertype name */
  4329. @futureonly varchar(15) = NULL        /* flag to indicate extent of binding */
  4330. as
  4331.  
  4332. declare @defid int            /* id of the default to bind */
  4333. declare @futurevalue varchar(15)    /* the value of @futureonly that causes
  4334.                     ** the binding to be limited */
  4335.  
  4336. set nocount on
  4337.  
  4338. select @futurevalue = 'futureonly'    /* initialize @futurevalue */
  4339.  
  4340. /*
  4341. **  When a default or rule is bound to a user-defined datatype, it is also
  4342. **  bound, by default, to any columns of the user datatype that are currently
  4343. **  using the existing default or rule as their default or rule.  This default
  4344. **  action may be overridden by setting @futureonly = @futurevalue when the
  4345. **  procedure is invoked.  In this case existing columns with the user
  4346. **  datatype won't have their existing default or rule changed.
  4347. */
  4348.  
  4349. /*
  4350. **  Check to see that the object names are local to the current database.
  4351. */
  4352. if (@objname like '%.%.%')
  4353.    or
  4354.    (@defname like '%.%.%' and
  4355.     substring(@defname, 1, charindex('.', @defname) - 1) <> db_name())
  4356. begin
  4357.     raiserror(15076,-1,-1)
  4358.     return (1)
  4359. end
  4360.  
  4361. /*
  4362. **  Check that the @futureonly argument, if supplied, is correct.
  4363. */
  4364. if (@futureonly IS NOT NULL)
  4365.     if (@futureonly <> @futurevalue)
  4366.         begin
  4367.             raiserror(15100,-1,-1)
  4368.             return (1)
  4369.         end
  4370.  
  4371. /*
  4372. **  Check to see that the default exists and get its id.
  4373. */
  4374. select @defid = (select id from sysobjects
  4375.             where id = object_id(@defname)
  4376.                 and sysstat & 0xf = 6)    -- default object
  4377.  
  4378. if @defid is NULL
  4379.     begin
  4380.         raiserror(15016,-1,-1,@defname)
  4381.         return (1)
  4382.     end
  4383.  
  4384. /*
  4385. **  If @objname is of the form tab.col then we are binding to a column.
  4386. **  Otherwise its a datatype.  In the column case, we need to extract
  4387. **  and verify the table and column names and make sure the user owns
  4388. **  the table that is getting the default bound. We also need to ensure
  4389. **  that we don't overwrite any DRI style defaults.
  4390. */
  4391. if @objname like '%.%'
  4392. begin
  4393.     declare @tabname varchar(30)        /* name of table */
  4394.     declare @colname varchar(30)        /* name of column */
  4395.  
  4396.     /*
  4397.     **  Get the table name out.
  4398.     */
  4399.     select @tabname = substring(@objname, 1, charindex('.', @objname) - 1)
  4400.     select @colname = substring(@objname, charindex('.', @objname) + 1, 61)
  4401.  
  4402.  
  4403.     /*
  4404.     **  If the column type is timestamp, disallow the bind.
  4405.     **  Defaults can't be bound to timestamp columns.
  4406.     */
  4407.     if exists (select *
  4408.             from syscolumns c
  4409.                 where c.id = object_id(@tabname)
  4410.             and c.name = @colname
  4411.             and c.usertype = 80)
  4412.     begin
  4413.         raiserror(15101,-1,-1)
  4414.         return (1)
  4415.     end
  4416.  
  4417.     /*
  4418.     **  If the column category is identity, disallow the bind.
  4419.     **  Defaults can't be bound to identity columns.
  4420.     */
  4421.     if exists (select *
  4422.             from syscolumns c
  4423.                 where c.id = object_id(@tabname)
  4424.             and c.name = @colname
  4425.             and c.status & 128 = 128)
  4426.     begin
  4427.         raiserror(15102,-1,-1)
  4428.         return (1)
  4429.     end
  4430.  
  4431.  
  4432.         /*
  4433.     **  Check to see if the column was created with or altered
  4434.         **  to have a DRI style default value.
  4435.     */
  4436.     if exists (select *
  4437.             from syscolumns c,sysconstraints t
  4438.                 where c.id = object_id(@tabname)
  4439.             and c.name = @colname
  4440.                         and t.id = c.id
  4441.                         and t.colid = c.colid
  4442.                         and t.status & 0xf = 5)
  4443.     begin
  4444.         raiserror(15103,-1,-1)
  4445.         return (1)
  4446.     end
  4447.  
  4448.         update syscolumns
  4449.         set cdefault = @defid
  4450.             from syscolumns, sysobjects
  4451.         where syscolumns.id = object_id(@tabname)
  4452.             and syscolumns.name = @colname
  4453.             and sysobjects.id = object_id(@tabname)
  4454.             and uid = user_id()
  4455.             and sysobjects.sysstat & 0xf = 3      /* user table */
  4456.  
  4457.     /*
  4458.     **  Did the bind happen?
  4459.     */
  4460.     if @@rowcount <> 1
  4461.     begin
  4462.         raiserror(15104,-1,-1,@tabname,@colname)
  4463.         return (1)
  4464.     end
  4465.  
  4466.     /*
  4467.     **  Since binding a default is a schema change, update schema count
  4468.     **  for the object in the sysobjects table.
  4469.     */
  4470.     update sysobjects
  4471.         set schema_ver = schema_ver + 1
  4472.             from sysobjects
  4473.                 where id = object_id(@tabname)
  4474.                     and uid = user_id()
  4475.  
  4476.     print 'Default bound to column.'
  4477.  
  4478. end
  4479. else
  4480. begin
  4481.     /*
  4482.     **  We're binding to a user type.  In this case, the @objname
  4483.     **  is really the name of the user datatype.
  4484.     **  When we bind to a user type, any existing columns get changed
  4485.     **  to the new binding unless their current binding is not equal
  4486.     **  to the current binding for the usertype or if they set the
  4487.     **  @futureonly parameter to @futurevalue.
  4488.     */
  4489.     declare @olddefault int    /* current default for type */
  4490.  
  4491.     /*
  4492.     **  Get the current default for the datatype.
  4493.     */
  4494.     select @olddefault = tdefault
  4495.         from systypes
  4496.     where name = @objname
  4497.         and uid = user_id()
  4498.         and usertype > 100
  4499.  
  4500.     if @olddefault is null
  4501.         begin
  4502.             raiserror(15105,-1,-1)
  4503.             return (1)
  4504.         end
  4505.  
  4506.     update systypes
  4507.         set tdefault = @defid
  4508.             from systypes
  4509.         where name = @objname
  4510.             and uid = user_id()
  4511.             and usertype > 100
  4512.  
  4513.  
  4514.     print 'Default bound to datatype.'
  4515.  
  4516.     /*
  4517.     **  Now see if there are any columns with the usertype that
  4518.     **  need the new binding.
  4519.     */
  4520.     if isnull(@futureonly, '') <> @futurevalue
  4521.         and exists (select *
  4522.             from syscolumns, systypes
  4523.                 where syscolumns.usertype = systypes.usertype
  4524.                     and systypes.name = @objname
  4525.                     and systypes.usertype > 100
  4526.                     and systypes.uid = user_id()
  4527.                     and (syscolumns.cdefault = @olddefault
  4528.                     or syscolumns.cdefault = 0 ) )
  4529.     begin
  4530.         /*
  4531.         **  Update syscolumns with new binding.
  4532.         */
  4533.         update syscolumns
  4534.             set cdefault = systypes.tdefault
  4535.                 from syscolumns, systypes
  4536.             where syscolumns.usertype = systypes.usertype
  4537.                 and systypes.name = @objname
  4538.                 and systypes.usertype > 100
  4539.                 and systypes.uid = user_id()
  4540.                                 and (syscolumns.cdefault = @olddefault
  4541.                                           or  syscolumns.cdefault = 0 )
  4542.  
  4543.         /*
  4544.         **  Update the table schema to indicate that something
  4545.         **  has changed in the table's schema.
  4546.         */
  4547.         update sysobjects
  4548.             set schema_ver = schema_ver + 1
  4549.                 from sysobjects, syscolumns, systypes
  4550.             where sysobjects.id = syscolumns.id
  4551.                 and syscolumns.usertype = systypes.usertype
  4552.                 and systypes.name = @objname
  4553.                 and systypes.usertype > 100
  4554.                 and systypes.uid = user_id()
  4555.                                 and (syscolumns.cdefault = @olddefault
  4556.                                           or  syscolumns.cdefault = 0 )
  4557.  
  4558.         print 'The new default has been bound to columns(s) of the specified user datatype.'
  4559.     end
  4560. end
  4561.  
  4562. return (0)
  4563. go
  4564.  
  4565. print ''
  4566. print 'Creating procedure sp_bindrule.'
  4567. go
  4568. create procedure sp_bindrule
  4569. @rulename varchar(92),            /* name of the rule */
  4570. @objname varchar(61),            /* table or usertype name */
  4571. @futureonly varchar(15) = NULL        /* column name */
  4572. as
  4573.  
  4574. declare @ruleid int            /* id of the rule to bind */
  4575. declare @futurevalue varchar(15)    /* the value of @futureonly that causes
  4576.                     ** the binding to be limited */
  4577.  
  4578. set nocount on
  4579.  
  4580. select @futurevalue = 'futureonly'    /* initialize @futurevalue */
  4581.  
  4582. /*
  4583. **  When a default or rule is bound to a user-defined datatype, it is also
  4584. **  bound, by default, to any columns of the user datatype that are currently
  4585. **  using the existing default or rule as their default or rule.  This default
  4586. **  action may be overridden by setting @futureonly = @futurevalue when the
  4587. **  procedure is invoked.  In this case existing columns with the user
  4588. **  datatype won't have their existing default or rule changed.
  4589. */
  4590.  
  4591. /*
  4592. **  Check to see that the object names are local to the current database.
  4593. */
  4594. if (@objname like '%.%.%')
  4595.    or
  4596.    (@rulename like '%.%.%' and
  4597.     substring(@rulename, 1, charindex('.', @rulename) - 1) <> db_name())
  4598.     begin
  4599.         raiserror(15077,-1,-1)
  4600.         return (1)
  4601.     end
  4602.  
  4603. /*
  4604. **  Check that the @futureonly argument, if supplied, is correct.
  4605. */
  4606. if (@futureonly IS NOT NULL)
  4607.     begin
  4608.         if (@futureonly <> @futurevalue)
  4609.             begin
  4610.                 raiserror(15106,-1,-1)
  4611.                 return (1)
  4612.             end
  4613.     end
  4614.  
  4615. /*
  4616. **  Check to see that the rule exists and get its id.
  4617. */
  4618. select @ruleid = (select id from sysobjects
  4619.             where id = object_id(@rulename)
  4620.                 and sysstat & 0xf = 7)    -- rule object
  4621.  
  4622. if @ruleid is NULL
  4623.     begin
  4624.         raiserror(15017,-1,-1,@rulename)
  4625.         return (1)
  4626.     end
  4627.  
  4628. /*
  4629. **  If @objname is of the form tab.col then we are binding to a column.
  4630. **  Otherwise its a datatype.  In the column case, we need to extract
  4631. **  and verify the table and column names and make sure the user owns
  4632. **  the table that is getting the rule bound.
  4633. */
  4634. if @objname like '%.%'
  4635. begin
  4636.     declare @tabname varchar(30)        /* name of table */
  4637.     declare @colname varchar(30)        /* name of column */
  4638.  
  4639.     /*
  4640.     **  Get the table name out.
  4641.     */
  4642.     select @tabname = substring(@objname, 1, charindex('.', @objname) - 1)
  4643.     select @colname = substring(@objname, charindex('.', @objname) + 1, 61)
  4644.  
  4645.     /*
  4646.     **  If the column type is image, text, or timestamp, disallow the bind.
  4647.     **  Rules can't be bound to image, text, or timestamp columns.
  4648.     **  The qualification to check for types is a little strange because
  4649.     **  text and image are real, basic data types while timestamp is not.
  4650.     **  Timestamp is really a binary.  The types are checked in case
  4651.     **  there is a user-defined datatype that is an image or text.
  4652.     **  User-defined datatypes mapping to timestamp are not allowed
  4653.     **  by sp_addtype.
  4654.     */
  4655.     if exists (select *
  4656.             from sysobjects o, syscolumns c
  4657.         where c.id = object_id(@tabname)
  4658.             and c.name = @colname
  4659.             and c.name = @colname
  4660.             and o.id = object_id(@tabname)
  4661.             and o.sysstat & 0xf = 3
  4662.             and (c.type in (35, 34) or c.usertype = 80))
  4663.         begin
  4664.             raiserror(15107,-1,-1)
  4665.             return (1)
  4666.         end
  4667.  
  4668.     update syscolumns
  4669.         set domain = @ruleid
  4670.             from syscolumns, sysobjects
  4671.         where syscolumns.id = object_id(@tabname)
  4672.             and syscolumns.name = @colname
  4673.             and sysobjects.id = object_id(@tabname)
  4674.             and uid = user_id()
  4675.             and sysobjects.sysstat & 0xf = 3      /* user table */
  4676.  
  4677.     /*
  4678.     **  Did the bind happen?
  4679.     */
  4680.     if @@rowcount <> 1
  4681.     begin
  4682.         raiserror(15104,-1,-1,@tabname,@colname)
  4683.         return (1)
  4684.     end
  4685.  
  4686.     /*
  4687.     **  Since binding a rule is a schema change, update schema count
  4688.     **  for the object in the sysobjects table.
  4689.     */
  4690.     update sysobjects set schema_ver = schema_ver + 1
  4691.         from sysobjects
  4692.         where id = object_id(@tabname)
  4693.             and uid = user_id()
  4694.  
  4695.     print 'Rule bound to table column.'
  4696.  
  4697. end
  4698. else
  4699. begin
  4700.     /*
  4701.     **  We're binding to a user type.  In this case, the @objname
  4702.     **  is really the name of the user datatype.
  4703.     **  When we bind to a user type, any existing columns get changed
  4704.     **  to the new binding unless their current binding is not equal
  4705.     **  to the current binding for the usertype or if they set the
  4706.     **  @futureonly parameter to @futurevalue.
  4707.     */
  4708.     declare @oldrule int            /* current rule for type */
  4709.  
  4710.     /*
  4711.     **  If the column type is image, text, or timestamp, disallow the bind.
  4712.     **  Rules can't be bound to image or text columns.
  4713.     */
  4714.     if exists (select * from systypes
  4715.             where name = @objname
  4716.                 and (type in (35, 34) or usertype = 80))
  4717.         begin
  4718.             raiserror(15107,-1,-1)
  4719.             return (1)
  4720.         end
  4721.  
  4722.     /*
  4723.     **  Get the current rule for the datatype.
  4724.     */
  4725.     select @oldrule = domain from systypes
  4726.     where name = @objname
  4727.         and uid = user_id()
  4728.         and usertype > 100
  4729.  
  4730.     if @oldrule is null
  4731.         begin
  4732.             raiserror(15105,-1,-1)
  4733.             return (1)
  4734.         end
  4735.  
  4736.     update systypes set domain = @ruleid
  4737.             from systypes
  4738.         where name = @objname
  4739.             and uid = user_id()
  4740.             and usertype > 100
  4741.  
  4742.  
  4743.     print 'Rule bound to datatype.'
  4744.  
  4745.     /*
  4746.     **  Now see if there are any columns with the usertype that
  4747.     **  need the new binding.
  4748.     */
  4749.     if isnull(@futureonly, '') <> @futurevalue
  4750.         and exists (select *
  4751.             from syscolumns, systypes
  4752.                 where syscolumns.usertype = systypes.usertype
  4753.                     and systypes.name = @objname
  4754.                     and systypes.usertype > 100
  4755.                     and systypes.uid = user_id()
  4756.                                         and (syscolumns.domain = @oldrule
  4757.                                           or  syscolumns.domain = 0 )     )
  4758.     begin
  4759.         print 'The new rule has been bound to column(s) of the specified user datatype.'
  4760.         /*
  4761.         **  Update syscolumns with new binding.
  4762.         */
  4763.         update syscolumns
  4764.             set domain = systypes.domain
  4765.                 from syscolumns, systypes
  4766.             where syscolumns.usertype = systypes.usertype
  4767.                 and systypes.name = @objname
  4768.                 and systypes.usertype > 100
  4769.                 and systypes.uid = user_id()
  4770.                                 and (syscolumns.domain = @oldrule
  4771.                                   or  syscolumns.domain = 0 )
  4772.  
  4773.         /*
  4774.         **  Update the table schema to indicate that something
  4775.         **  has changed in the table's schema.
  4776.         */
  4777.         update sysobjects
  4778.             set schema_ver = schema_ver + 1
  4779.                 from sysobjects, syscolumns, systypes
  4780.             where sysobjects.id = syscolumns.id
  4781.                 and syscolumns.usertype = systypes.usertype
  4782.                 and systypes.name = @objname
  4783.                 and systypes.usertype > 100
  4784.                 and systypes.uid = user_id()
  4785.                                 and (syscolumns.domain = @oldrule
  4786.                                   or  syscolumns.domain = 0 )
  4787.     end
  4788. end
  4789.  
  4790. return (0)
  4791. go
  4792.  
  4793. print ''
  4794. print 'Creating procedure sp_changedbowner.'
  4795. go
  4796. create procedure sp_changedbowner
  4797. @loginame varchar(30),         /* login to become dbo */
  4798. @map      varchar(10) = NULL   /* True to map aliases, else drop  */
  4799. as
  4800.  
  4801. declare @suid    smallint
  4802. declare @oldsuid smallint
  4803.  
  4804. /*
  4805. **  Only the SA can change the owner of a database.
  4806. */
  4807. if suser_id() <> 1
  4808. begin
  4809.     raiserror(15108,-1,-1)
  4810.     return(1)
  4811. end
  4812.  
  4813. /*
  4814. **  Can't change the owner of the master database.
  4815. */
  4816. if db_id() = 1
  4817. begin
  4818.     raiserror(15109,-1,-1)
  4819.     return(1)
  4820. end
  4821.  
  4822. /*
  4823. **  Make sure that @loginame exists and has a login.
  4824. */
  4825. select @suid = suid from syslogins where name = @loginame
  4826.  
  4827. if @suid is null
  4828.     begin
  4829.         raiserror(15007,-1,-1,@loginame)
  4830.         return(1)
  4831.     end
  4832.  
  4833. /*
  4834. **  Make sure that @loginame isn't already a user or alias in the database.
  4835. */
  4836. if exists (select * from sysusers where suid = @suid)
  4837.     begin
  4838.         raiserror(15110,-1,-1)
  4839.         return(1)
  4840.     end
  4841.  
  4842. if exists (select * from sysalternates where suid = @suid)
  4843.     begin
  4844.         raiserror(15111,-1,-1)
  4845.         return(1)
  4846.     end
  4847.  
  4848. /*
  4849. ** find old (current) dbo's suid
  4850. */
  4851. select @oldsuid = suid
  4852.     from sysusers
  4853.         where uid = 1
  4854.  
  4855. begin transaction
  4856.  
  4857. /*
  4858. **  Now change the suid of the owner of the database to the suid of @loginame.
  4859. */
  4860. update sysusers
  4861.     set suid = @suid
  4862.         where uid = 1
  4863.  
  4864. /*
  4865. ** if the user requested that aliases be mapped to new dbo, do that.
  4866. */
  4867. if lower(@map) = 'true'
  4868. begin
  4869.  
  4870.     if exists (select *
  4871.             from sysalternates
  4872.                 where altsuid = @oldsuid)
  4873.     begin
  4874.         update sysalternates
  4875.             set altsuid = @suid
  4876.                 where altsuid = @oldsuid
  4877.  
  4878.         print 'The dependent aliases were mapped to the new dbo.'
  4879.     end
  4880. end
  4881. /* else drop the aliases to the old dbo */
  4882. else
  4883. begin
  4884.  
  4885.     if exists (select *
  4886.             from sysalternates
  4887.                 where altsuid = @oldsuid)
  4888.     begin
  4889.         delete from sysalternates
  4890.             where altsuid = @oldsuid
  4891.  
  4892.         print 'The dependent aliases were dropped.'
  4893.     end
  4894. end
  4895.  
  4896.  
  4897. /*
  4898. **  Reflect the new owner of the database in sysdatabases.
  4899. */
  4900. update sysdatabases
  4901.     set suid = @suid
  4902.         where dbid = db_id()
  4903.  
  4904. commit transaction
  4905.  
  4906. /*
  4907. **  Checkpoint the database so that the in-memory data structure for the
  4908. **  database will be consistent with sysdatabases.
  4909. */
  4910. checkpoint
  4911.  
  4912. print 'Database owner changed.'
  4913.  
  4914. return (0)
  4915. go
  4916.  
  4917. print ''
  4918. print 'Creating procedure sp_changegroup.'
  4919. go
  4920. create procedure sp_changegroup
  4921. @grpname varchar(30),            /* group name */
  4922. @username varchar(30)            /* user name to add to group */
  4923. as
  4924.  
  4925. declare @gid int            /* group id */
  4926. declare @uid int            /* user id */
  4927.  
  4928. /*
  4929. **  You must be SA or the dbo to execute this sproc.
  4930. */
  4931. if suser_id() <> 1 and user_id() <> 1
  4932.     begin
  4933.         raiserror(15000,-1,-1)
  4934.         return (1)
  4935.     end
  4936.  
  4937. /*
  4938. **  See if the group name exists.
  4939. */
  4940. select @gid = uid from sysusers where name = @grpname
  4941.     and (uid > 16383 or uid = 0)
  4942.  
  4943. /*
  4944. **  If no such group, quit.
  4945. **  User ids are <= 16383 and group ids are > 16383 or = 0.
  4946. */
  4947. if @gid is null
  4948.     begin
  4949.         raiserror(15014,-1,-1,@grpname)
  4950.         return (1)
  4951.     end
  4952.  
  4953. /*
  4954. **  See if the user name exists.
  4955. */
  4956. select @uid = uid from sysusers where name = @username
  4957.     and (uid <= 16383 and uid > 0)
  4958.  
  4959. /*
  4960. **  If no such user in the database, quit.
  4961. */
  4962. if @uid is null
  4963.     begin
  4964.         raiserror(15008,-1,-1,@username)
  4965.         return (1)
  4966.     end
  4967.  
  4968. /*
  4969. **  Everything is consistent so change the group.
  4970. */
  4971. update sysusers set gid = @gid
  4972.     from sysusers where uid = @uid
  4973.  
  4974. /*
  4975. **  We need to invalidate the protection cache since objects have
  4976. **  changed ownership.  This command will invalidate the current
  4977. **  protection cache so when protections are checked the new and
  4978. **  correct protections will be used.
  4979. */
  4980. grant all to null
  4981.  
  4982. print 'Group changed.'
  4983.  
  4984. return (0)
  4985. go
  4986.  
  4987. print ''
  4988. print 'Creating procedure sp_checknames.'
  4989. go
  4990. create procedure sp_checknames
  4991. @mode varchar(20) = NULL        /* mode of operation; e.g. 'silent' */
  4992. as
  4993.  
  4994. declare @msilent    int        /* set to 1 if 'silent' mode is on */
  4995. declare @ret_val    int        /* set to 1 if we find funny char */
  4996. declare @codepoint    tinyint        /* set to 1 if we find funny char */
  4997. declare @dbname        varchar(30)    /* holds database name */
  4998. declare @msg        varchar(90)    /* used for messages to user */
  4999. declare @pat        varchar(132)    /* holds the pattern to search for */
  5000.  
  5001. set nocount on
  5002.  
  5003. if (@mode like '%help%')
  5004. begin
  5005.     print 'sp_checknames is used to search for non 7-bit ASCII characters'
  5006.     print 'in several important columns of system tables.  The following'
  5007.     print 'columns are searched:'
  5008.     print ' '
  5009.     print '    In ''master'':'
  5010.     print '        sysdatabases.name'
  5011.     print '        sysdevices.name'
  5012.     print '        syslogins.name'
  5013.     print '        syslogins.dbname'
  5014.     print '        sysremotelogins.remoteusername'
  5015.     print '        sysservers.srvname'
  5016.     print '        sysservers.srvnetname'
  5017.     print ' '
  5018.     print '    In all databases:'
  5019.     print '        syscolumns.name'
  5020.     print '        sysindexes.name'
  5021.     print '        sysobjects.name'
  5022.     print '        syssegments.name'
  5023.     print '        systypes.name'
  5024.     print '        sysusers.name'
  5025.     print ' '
  5026.  
  5027.     return (0)
  5028. end
  5029.  
  5030. /*
  5031. **  First, initialize return value, and set up mode variables:
  5032. */
  5033. select @ret_val = 0
  5034.  
  5035. if (@mode like '%silent%')
  5036.     select @msilent = 1
  5037. else
  5038.     select @msilent = 0
  5039.  
  5040.  
  5041. /*
  5042. **  Now, initialize the pattern string we will search for:
  5043. */
  5044. select @pat = '%[', @codepoint = 127
  5045. while (@codepoint < 255)
  5046. begin
  5047.     select @codepoint = @codepoint + 1
  5048.     select @pat = @pat + char(@codepoint)
  5049. end
  5050. select @pat = @pat + ']%'
  5051.  
  5052.  
  5053. /*
  5054. **  Get the database name we are in:
  5055. */
  5056. select @dbname = db_name()
  5057.  
  5058. if (@msilent = 0)
  5059. begin
  5060.     print ' '
  5061.     select @msg = 'Looking for non 7-bit ASCII characters in the system ' +
  5062.             'tables of database:  ''' + @dbname + ''''
  5063.     print @msg
  5064.     print ' '
  5065. end
  5066.  
  5067.  
  5068. /*
  5069. **  Look through these only if in the master database:
  5070. */
  5071. if (@dbname = 'master')
  5072. begin
  5073.     if exists (select name from sysdatabases
  5074.             where name like @pat)
  5075.     begin
  5076.     if (@msilent = 1)
  5077.         return (1)
  5078.  
  5079.     select @ret_val = 1
  5080.     print ' '
  5081.     print '==============================================================='
  5082.     print 'Table.Column name:  ''sysdatabases.name'''
  5083.     print ' '
  5084.     print 'The following database names contain non 7-bit ASCII characters.'
  5085.     print 'If you wish to change their names, use ''sp_renamedb'':'
  5086.     print ' '
  5087.     select dbid,name from sysdatabases
  5088.             where name like @pat
  5089.     end
  5090.  
  5091.     if exists (select name from sysdevices where name like @pat)
  5092.     begin
  5093.     if (@msilent = 1)
  5094.         return (1)
  5095.  
  5096.     select @ret_val = 1
  5097.     print ' '
  5098.     print '==============================================================='
  5099.     print 'Table.Column name:  ''sysdevices.name'''
  5100.     print ' '
  5101.     print 'The following device names contain non 7-bit ASCII characters.'
  5102.     print 'If you wish to change their names, use ''UPDATE'':'
  5103.         print ' '
  5104.     select name from sysdevices where name like @pat
  5105.     end
  5106.  
  5107.     if exists (select name from syslogins where name like @pat)
  5108.     begin
  5109.     if (@msilent = 1)
  5110.         return (1)
  5111.  
  5112.     select @ret_val = 1
  5113.     print ' '
  5114.     print '==============================================================='
  5115.     print 'Table.Column name:  ''syslogins.name'''
  5116.         print ' '
  5117.     print 'The following login names contain non 7-bit ASCII characters.'
  5118.     print 'If you wish to change these names, use ''sp_droplogin'' and'
  5119.     print '''sp_addlogin'':'
  5120.         print ' '
  5121.     select suid,name from syslogins
  5122.             where name like @pat
  5123.     end
  5124.  
  5125.     if exists (select dbname from master.dbo.syslogins
  5126.             where dbname like @pat)
  5127.     begin
  5128.     if (@msilent = 1)
  5129.         return (1)
  5130.  
  5131.     select @ret_val = 1
  5132.     print ' '
  5133.     print '==============================================================='
  5134.     print 'Table.Column name:  ''syslogins.dbname'''
  5135.     print ' '
  5136.     print 'The following logins have default database names that contain'
  5137.     print 'non 7-bit ASCII characters.  If you wish to change them use'
  5138.     print '''sp_defaultdb'':'
  5139.         print ' '
  5140.     select suid,name,dbname from master.dbo.syslogins
  5141.             where dbname like @pat
  5142.     end
  5143.  
  5144.     if exists (select remoteusername from master.dbo.sysremotelogins
  5145.             where remoteusername like @pat)
  5146.     begin
  5147.     if (@msilent = 1)
  5148.         return (1)
  5149.  
  5150.     select @ret_val = 1
  5151.     print ' '
  5152.     print '==============================================================='
  5153.     print 'Table.Column name:  ''sysremotelogins.remoteusername'''
  5154.         print ' '
  5155.     print 'The following remote login names contain non 7-bit ASCII'
  5156.     print 'characters.  If you wish to change these names, use'
  5157.     print '''sp_dropremotelogin'' and ''sp_addremotelogin'':'
  5158.         print ' '
  5159.     select remoteserverid,remoteusername from master.dbo.sysremotelogins
  5160.             where remoteusername like @pat
  5161.     end
  5162.  
  5163.     if exists (select srvname from master.dbo.sysservers
  5164.             where srvname like @pat)
  5165.     begin
  5166.     if (@msilent = 1)
  5167.         return (1)
  5168.  
  5169.     select @ret_val = 1
  5170.     print ' '
  5171.     print '==============================================================='
  5172.     print 'Table.Column name:  ''sysservers.srvname'''
  5173.         print ' '
  5174.     print 'The following server names contain non 7-bit ASCII characters.'
  5175.     print 'If you wish to change their names, use ''sp_dropserver'' and'
  5176.     print '''sp_addserver'':'
  5177.         print ' '
  5178.     select srvid,srvname from master.dbo.sysservers
  5179.             where srvname like @pat
  5180.     end
  5181.  
  5182.     if exists (select srvnetname from master.dbo.sysservers
  5183.             where srvnetname like @pat)
  5184.     begin
  5185.     if (@msilent = 1)
  5186.         return (1)
  5187.  
  5188.     select @ret_val = 1
  5189.     print ' '
  5190.     print '==============================================================='
  5191.     print 'Table.Column name:  ''sysservers.srvnetname'''
  5192.         print ' '
  5193.     print 'The following servers have ''initialization file'' names that contain'
  5194.     print 'non 7-bit ASCII characters.  If you wish to change these names,'
  5195.     print 'use ''UPDATE'':'
  5196.         print ' '
  5197.     select srvid,srvname,srvnetname from master.dbo.sysservers
  5198.             where srvnetname like @pat
  5199.     end
  5200.  
  5201. end
  5202.  
  5203.  
  5204. /*
  5205. **  For *ALL* databases, we want to look through these:
  5206. */
  5207. if exists (select name from dbo.syscolumns
  5208.         where name like @pat)
  5209. begin
  5210.     if (@msilent = 1)
  5211.     return (1)
  5212.  
  5213.     select @ret_val = 1
  5214.     print ' '
  5215.     print '==============================================================='
  5216.     print 'Table.Column name:  ''syscolumns.name'''
  5217.     print ' '
  5218.     print 'The following column and parameter names contain non 7-bit ASCII'
  5219.     print 'characters.  If you wish to change these names, use ''sp_rename'':'
  5220.     print ' '
  5221.     select objname=o.name,colname=c.name from dbo.syscolumns c, dbo.sysobjects o
  5222.         where c.name like @pat and o.id = c.id
  5223. end
  5224.  
  5225. if exists (select name from dbo.sysindexes
  5226.         where name like @pat
  5227.               and indid > 0)
  5228. begin
  5229.     if (@msilent = 1)
  5230.     return (1)
  5231.  
  5232.     select @ret_val = 1
  5233.     print ' '
  5234.     print '==============================================================='
  5235.     print 'Table.Column name:  ''sysindexes.name'''
  5236.     print ' '
  5237.     print 'The following index names contain non 7-bit ASCII characters.'
  5238.     print 'If you wish to change these names, use ''UPDATE'':'
  5239.     print ' '
  5240.     select id,indid,name from dbo.sysindexes
  5241.         where name like @pat
  5242.         and indid > 0
  5243. end
  5244.  
  5245. if exists (select name from dbo.sysobjects
  5246.         where name like @pat)
  5247. begin
  5248.     if (@msilent = 1)
  5249.     return (1)
  5250.  
  5251.     select @ret_val = 1
  5252.     print ' '
  5253.     print '==============================================================='
  5254.     print 'Table.Column name:  ''sysobjects.name'''
  5255.     print ' '
  5256.     print 'The following object names contain non 7-bit ASCII characters.'
  5257.     print 'If you wish to change these names, use ''sp_rename'':'
  5258.     print ' '
  5259.     select owner=u.name,o.name from dbo.sysobjects o,dbo.sysusers u
  5260.         where o.name like @pat and o.uid=u.uid
  5261. end
  5262.  
  5263. if exists (select name from dbo.syssegments
  5264.         where name like @pat)
  5265. begin
  5266.     if (@msilent = 1)
  5267.     return (1)
  5268.  
  5269.     select @ret_val = 1
  5270.     print ' '
  5271.     print '==============================================================='
  5272.     print 'Table.Column name:  ''syssegments.name'''
  5273.     print ' '
  5274.     print 'The following segment names contain non 7-bit ASCII characters.'
  5275.     print 'If you wish to change these names, use ''UPDATE'':'
  5276.     print ' '
  5277.     select segment,name from dbo.syssegments
  5278.         where name like @pat
  5279. end
  5280.  
  5281. if exists (select name from dbo.systypes
  5282.         where name like @pat)
  5283. begin
  5284.     if (@msilent = 1)
  5285.     return (1)
  5286.  
  5287.     select @ret_val = 1
  5288.     print ' '
  5289.     print '==============================================================='
  5290.     print 'Table.Column name:  ''systypes.name'''
  5291.     print ' '
  5292.     print 'The following datatype names contain non 7-bit ASCII characters.'
  5293.     print 'If you wish to change these names, use ''sp_rename'':'
  5294.     print ' '
  5295.     select name from dbo.systypes
  5296.         where name like @pat
  5297. end
  5298.  
  5299. if exists (select name from dbo.sysusers
  5300.         where name like @pat)
  5301. begin
  5302.     if (@msilent = 1)
  5303.     return (1)
  5304.  
  5305.     select @ret_val = 1
  5306.     print ' '
  5307.     print '==============================================================='
  5308.     print 'Table.Column name:  ''sysusers.name'''
  5309.     print ' '
  5310.     print 'The following user or group names contain non 7-bit ASCII'
  5311.     print 'characters.  If you wish to change these names, use ''UPDATE'':'
  5312.     print ' '
  5313.     select suid,uid,name from dbo.sysusers
  5314.         where name like @pat
  5315. end
  5316.  
  5317. if (@ret_val = 0  and  @msilent = 0)
  5318. begin
  5319.     select @msg = 'Good news!  Database ''' + @dbname + ''' has no obj/user/etc.'
  5320.     print @msg
  5321.     print 'names that contain non 7-bit ASCII characters.'
  5322. end
  5323.  
  5324. return (@ret_val)
  5325. go
  5326.  
  5327. dump tran master with no_log
  5328. go
  5329. print ''
  5330. print 'Creating procedure sp_start_xact.'
  5331. go
  5332. create procedure sp_start_xact
  5333.     @applname varchar(30),
  5334.     @xactname varchar(30),
  5335.     @count      int,
  5336.     @password varchar(30) = NULL
  5337. AS
  5338.  
  5339. set nocount on
  5340.  
  5341. BEGIN
  5342.     BEGIN TRANSACTION
  5343.         INSERT spt_committab VALUES
  5344.         (
  5345.             0,
  5346.             getdate(),
  5347.             getdate(),
  5348.             @count,
  5349.             @count,
  5350.             'b',
  5351.             @applname,
  5352.             @xactname,
  5353.             @password
  5354.         )
  5355.  
  5356.         UPDATE spt_committab
  5357.             set commid = 1 + (select max(commid) from spt_committab)
  5358.             where commid = 0
  5359.  
  5360.         SELECT max(commid) from spt_committab
  5361.     COMMIT TRANSACTION
  5362. END
  5363. go
  5364.  
  5365. print ''
  5366. print 'Creating procedure sp_commit_xact.'
  5367. go
  5368. create procedure sp_commit_xact
  5369.     @commid    int,
  5370.     @password varchar(30) = NULL
  5371. AS
  5372. if exists (select *
  5373.     from spt_committab
  5374.     where commid = @commid
  5375.     and password = @password)
  5376. begin
  5377.     /*
  5378.     **  If status is aborted, return a 1 to indicate a failure.
  5379.     */
  5380.     if exists (select *
  5381.             from spt_committab
  5382.                 where commid = @commid
  5383.                     and status = 'a')
  5384.     begin
  5385.         select 1
  5386.         return (1)
  5387.     end
  5388.  
  5389.     /*  Mark the xact as committed. */
  5390.     UPDATE spt_committab
  5391.         SET status = 'c', lastchange = getdate()
  5392.         WHERE commid = @commid
  5393.     select 0
  5394.     return (0)
  5395. end
  5396. else
  5397. begin
  5398.     /* Error so return (1) */
  5399.     raiserror 30000 'Commit service xact id doesn''t exist.'
  5400.     select 1
  5401.     return (1)
  5402. end
  5403. go
  5404.  
  5405. print ''
  5406. print 'Creating procedure sp_abort_xact.'
  5407. go
  5408. CREATE PROCEDURE sp_abort_xact
  5409.     @commid    int,
  5410.     @password varchar(30) = NULL
  5411. AS
  5412. if exists (select *
  5413.     from spt_committab
  5414.     where commid = @commid
  5415.     and password = @password)
  5416. begin
  5417.     UPDATE spt_committab
  5418.         SET status = 'a' , lastchange = getdate()
  5419.         WHERE commid = @commid
  5420. END
  5421. else
  5422. begin
  5423.     raiserror 30001 'Commit service xact id doesn''t exist.'
  5424. end
  5425. go
  5426.  
  5427. print ''
  5428. print 'Creating procedure sp_remove_xact.'
  5429. go
  5430. CREATE PROCEDURE sp_remove_xact
  5431.     @commid    int,
  5432.     @count    int,
  5433.     @password varchar(30) = NULL
  5434. AS
  5435. if exists (select *
  5436.     from spt_committab
  5437.     where commid = @commid
  5438.     and password = @password)
  5439. begin
  5440.     /*
  5441.     ** Decrement outnum by @count.
  5442.     */
  5443.     UPDATE spt_committab
  5444.         SET outnum = outnum - @count, lastchange = GETDATE()
  5445.         WHERE commid = @commid
  5446.  
  5447.     /*
  5448.     **  Delete the row if outnum < 1
  5449.     */
  5450.     DELETE spt_committab
  5451.         WHERE commid = @commid
  5452.             and outnum < 1
  5453.  
  5454. end
  5455. else
  5456. begin
  5457.     raiserror 30002 'Commit service xact id doesn''t exist.'
  5458. end
  5459. go
  5460.  
  5461. print ''
  5462. print 'Creating procedure sp_stat_xact.'
  5463. go
  5464. create procedure sp_stat_xact
  5465.     @commid    int
  5466. AS
  5467. BEGIN
  5468.     IF EXISTS
  5469.     (
  5470.         SELECT status
  5471.             FROM spt_committab
  5472.             WHERE commid = @commid
  5473.     )
  5474.         SELECT status
  5475.             FROM spt_committab
  5476.             WHERE commid = @commid
  5477.     ELSE
  5478.         SELECT status = 'u'
  5479. END
  5480. go
  5481.  
  5482. print ''
  5483. print 'Creating procedure sp_probe_xact.'
  5484. go
  5485. create procedure sp_probe_xact
  5486.     @commid    int
  5487. AS
  5488. BEGIN
  5489.     declare @stat    char(1)
  5490.  
  5491.     begin tran
  5492.         IF EXISTS ( SELECT status
  5493.                 FROM spt_committab
  5494.                     WHERE commid = @commid)
  5495.         begin
  5496.             SELECT @stat = status
  5497.                 FROM spt_committab
  5498.                     WHERE commid = @commid
  5499.  
  5500.             if (@stat <> 'c')
  5501.             begin
  5502.                 update spt_committab
  5503.                     set status = 'a'
  5504.                         where commid = @commid
  5505.                 select status = 'a'
  5506.             end
  5507.             else select status = @stat
  5508.         end
  5509.         else select status = 'u'
  5510.     commit tran
  5511.  
  5512. END
  5513. go
  5514.  
  5515. print ''
  5516. print 'Creating procedure sp_processinfo.'
  5517. go
  5518. create procedure sp_processinfo
  5519. as
  5520. /* ====================================================*/
  5521. /* sp_processinfo - returns detailed lock              */
  5522. /* information for the server                          */
  5523. /* Microsoft SQL Server - copyright 94                 */
  5524. /* ====================================================*/
  5525.  
  5526. declare @lkdbnm varchar(32)
  5527. declare @lkdbid smallint
  5528. declare @lkobjid int
  5529. declare @UserDBID smallint
  5530. declare @usrdbnm varchar(32)
  5531. declare @User_ID smallint
  5532. declare @grpid smallint
  5533. declare @stmt varchar(255)
  5534.  
  5535. /* ===========================================================*/
  5536. /* build temp table with processes and their associated locks */
  5537. /* ===========================================================*/
  5538.  
  5539. select  distinct
  5540.  
  5541.     'FullName'    = '                                               ',
  5542.     'LoginName'    = lo.name,
  5543.     'UserID'    = p.uid,
  5544.     'UName'    = '                                ',
  5545.  
  5546.     'ProcessID'    = p.spid,
  5547.     'Status'    = p.status,
  5548.     'DBID'        = p.dbid,
  5549.     'DbName'    = d.name,    
  5550.     'Command'    = p.cmd,
  5551.     'Host'        = p.hostname,
  5552.     'Application'    = p.program_name,    
  5553.     'Blocking'    = 0,
  5554.     'Blockedby'    = p.blocked,
  5555.  
  5556.     'LockType'    = l.type,
  5557.     'LKObjDBID'    = l.dbid,    
  5558.     'LKObjDB'    = '                                ',
  5559.     'LKObjID'    = l.id,
  5560.     'LKObj'        = '                                                                                     ',
  5561.     'LockedPage'    = l.page,
  5562.  
  5563.     'GroupID'    = p.gid,
  5564.     'GName'    = '                                ',
  5565.  
  5566.     'CPUUsage'    = p.cpu,
  5567.     'NT_Thread_#'    = p.kpid,
  5568.     'Memory_2K_Allocs'    = p.memusage,
  5569.     'PhysicalIO'    = p.physical_io,
  5570.     'HostProcess'    = p.hostprocess
  5571. into #info
  5572.  
  5573. from
  5574.     master..sysprocesses p,
  5575.     master..syslocks l,
  5576.     master..syslogins lo,
  5577.     master..sysdatabases d
  5578.  
  5579. where
  5580.     p.spid     *= l.spid and
  5581.     p.suid    = lo.suid and
  5582.     p.dbid    = d.dbid
  5583.  
  5584. /* ========================*/
  5585. /* flag blocking processes */    
  5586. /* ======================= */
  5587. update #info set Blocking = 1 where
  5588. ProcessID in (select Blockedby from #info where Blockedby > 0)
  5589.  
  5590. /* ============================*/
  5591. /* flag blocking process locks */    
  5592. /* ============================*/
  5593. Update #info set Blocking = Blocking + 100
  5594. where LockType >= 256
  5595.  
  5596. /* ===============================*/
  5597. /* flag transcient system objects */    
  5598. /* (syslocks/ sysprocesses/...    */
  5599. /* ===============================*/
  5600.  
  5601. Update #info set LKObj = (select name from spt_values where number = 0 and type = 'G')
  5602. where LKObjID = 0
  5603.  
  5604. /* =========================================== */
  5605. /* resolve all object names for each database  */
  5606. /* using LockedDBName, LKObjID                 */
  5607. /* =========================================== */
  5608.  
  5609. /* first we need a unique index to declare the cursor */
  5610. exec ('create unique index xxx on #info (ProcessID, LockType, LockedPage,LKObjID)')
  5611.  
  5612. /* =============================================*/
  5613. /* get list of locked object IDs */
  5614. /* =============================================*/
  5615.  
  5616. exec ('declare c1 cursor for select distinct LockedDBName = d.name, LKObjID , LKObjDBID from #info, master..sysdatabases d
  5617. where LKObjDBID = d.dbid  and LKObjID > 0 order by LockedDBName, LKObjID FOR READ ONLY ')
  5618.  
  5619. open c1
  5620.  
  5621. fetch c1 into @lkdbnm, @lkobjid, @lkdbid
  5622.  
  5623. while @@fetch_status >= 0
  5624.    begin
  5625.     /* set owner.name of locked objects in #info */
  5626.  
  5627.     select @stmt = 'Update #info set LKObj=u.name+''.''+o.name,'+
  5628.     'LKObjDB='''+@lkdbnm+
  5629.     ''' from '+@lkdbnm+'..sysobjects o,'+@lkdbnm+'..sysusers u '+
  5630.     'where o.id='+convert(char(10),@lkobjid)+
  5631.     ' and LKObjID=o.id' +
  5632.     ' and u.uid=o.uid and LKObjDBID=' + convert(char,@lkdbid)
  5633.     exec(@stmt )
  5634.  
  5635.     /* next please */
  5636.     fetch c1 into @lkdbnm, @lkobjid, @lkdbid
  5637.  
  5638.  
  5639.    end
  5640. deallocate c1
  5641.  
  5642. /* =============================================*/
  5643. /* resolve UserID, GroupID for all processes    */
  5644. /* get a list of each database we need to visit */
  5645. /* =============================================*/
  5646.  
  5647. exec ('declare c1 cursor for select distinct DBID, DbName from #info order by DBID FOR READ ONLY')
  5648.  
  5649. open c1
  5650.  
  5651. fetch c1 into  @UserDBID, @usrdbnm
  5652.  
  5653. while @@fetch_status >= 0
  5654.    begin
  5655.  
  5656.     /* set user/group in #info */
  5657.  
  5658.     select @stmt = 'Update #info set '+
  5659.     'GName=g.name,'+
  5660.     'UName=u.name '+
  5661.     'from '+@usrdbnm+'..sysusers u,'+
  5662.     @usrdbnm+'..sysusers g,#info '+
  5663.     'where u.uid=UserID ' +
  5664.     'and g.uid=GroupID and '+
  5665.     'DBID=' + RTRIM(convert(char(10),@UserDBID))
  5666.     exec(@stmt )
  5667.  
  5668.     /* next please */
  5669.     fetch c1 into  @UserDBID, @usrdbnm
  5670.  
  5671.    end
  5672. deallocate c1
  5673.  
  5674. /* ====== final fixups ====== */
  5675. /* Label SYSTEM processes as such */
  5676. Update #info set FullName = 'System' where ProcessID < 10
  5677.  
  5678. /* Construct fullname for user processes */
  5679. Update #info set FullName = LoginName where ProcessID >= 10
  5680.  
  5681. /* fully qualify existing object names  */
  5682. Update #info set
  5683. LKObj = LKObjDB +'.' + LKObj /* +'(id:' + RTRIM(Convert(char,LKObjID)) +')'*/
  5684. where LKObj > '' and LKObjDB > ''
  5685.  
  5686.  
  5687. /* ====== return the #info table ===== */
  5688. SELECT
  5689.  
  5690.     FullName , ProcessID,     Status,
  5691.     DName = substring(DbName,1,10),
  5692.     Command,Host, Application, Blockedby,LockType,LKObj,
  5693.     GName = substring(GName,1,10),
  5694.     CPUUsage, PhysicalIO, HostProcess,UName,Blocking
  5695.  
  5696. FROM #info
  5697. ORDER BY
  5698.     FullName,
  5699.     ProcessID
  5700.  
  5701. /* end of procedure */
  5702. return(0)
  5703. go
  5704.  
  5705. print ''
  5706. print 'Creating procedure sp_scan_xact.'
  5707. go
  5708. create procedure sp_scan_xact
  5709.     @commid    int = NULL
  5710. as
  5711. BEGIN
  5712.     IF    @commid = -1 or @commid is NULL
  5713.  
  5714.         SELECT commid,start,lastchange,totnum,outnum,
  5715.                status,applname,xactname
  5716.         FROM spt_committab
  5717.     ELSE
  5718.         SELECT commid,start,lastchange,totnum,outnum,
  5719.                status,applname,xactname
  5720.         FROM spt_committab
  5721.         WHERE @commid = commid
  5722. END
  5723. go
  5724.  
  5725. print ''
  5726. print 'Creating procedure sp_commonkey.'
  5727. go
  5728. create procedure sp_commonkey
  5729. @tabaname  varchar(92),        /* name of first table in the key */
  5730. @tabbname varchar(92),        /* name of second table in the key */
  5731. @col1a     varchar(30),     /* first column name of first table */
  5732. @col1b     varchar(30),     /* first column name of second table */
  5733. @col2a     varchar(30) = NULL,
  5734. @col2b     varchar(30) = NULL,
  5735. @col3a     varchar(30) = NULL,
  5736. @col3b     varchar(30) = NULL,
  5737. @col4a     varchar(30) = NULL,
  5738. @col4b     varchar(30) = NULL,
  5739. @col5a     varchar(30) = NULL,
  5740. @col5b     varchar(30) = NULL,
  5741. @col6a     varchar(30) = NULL,
  5742. @col6b     varchar(30) = NULL,
  5743. @col7a     varchar(30) = NULL,
  5744. @col7b     varchar(30) = NULL,
  5745. @col8a     varchar(30) = NULL,
  5746. @col8b     varchar(30) = NULL
  5747. as
  5748.  
  5749. declare @objida int        /* id of table we are doing */
  5750. declare @objidb int        /* id of table with primary key */
  5751. declare @uida smallint        /* owner of the first table */
  5752. declare @cnt    int        /* how many columns are in the key */
  5753.  
  5754. declare @key1a int        /* colids of the first table */
  5755. declare @key2a int
  5756. declare @key3a int
  5757. declare @key4a int
  5758. declare @key5a int
  5759. declare @key6a int
  5760. declare @key7a int
  5761. declare @key8a int
  5762.  
  5763. declare @key1b int        /* colids of the second table */
  5764. declare @key2b int
  5765. declare @key3b int
  5766. declare @key4b int
  5767. declare @key5b int
  5768. declare @key6b int
  5769. declare @key7b int
  5770. declare @key8b int
  5771.  
  5772. /*
  5773. **  Check to see that the tabnames are local.
  5774. */
  5775. if @tabaname like '%.%.%'
  5776.     and substring(@tabaname, 1, charindex('.', @tabaname) - 1) <> db_name()
  5777.     begin
  5778.         raiserror(15078,-1,-1)
  5779.         return (1)
  5780.     end
  5781.  
  5782. if @tabbname like '%.%.%'
  5783.     and substring(@tabbname, 1, charindex('.', @tabbname) - 1) <> db_name()
  5784.     begin
  5785.         raiserror(15078,-1,-1)
  5786.         return (1)
  5787.     end
  5788.  
  5789. /*
  5790. **  See if we can find the objects.  They must be system tables, user tables,
  5791. **  or views.  The low 4 bits of sysobjects.sysstat indicate what the
  5792. **  object type is -- it's more reliable than using sysobjects.type which
  5793. **  could change.
  5794. */
  5795. select @objida = id, @uida = uid
  5796.     from sysobjects
  5797.         where id = object_id(@tabaname)
  5798.             and (sysstat & 0xf = 1        /* system table */
  5799.                 or sysstat & 0xf = 2    /* view */
  5800.                 or sysstat & 0xf = 3)    /* user table */
  5801. /*
  5802. **  If either of the tables don't exist, quit.
  5803. */
  5804. if @objida is NULL
  5805.     begin
  5806.         raiserror(15112,-1,-1)
  5807.         return (1)
  5808.     end
  5809.  
  5810. select @objidb = id
  5811.     from sysobjects
  5812.         where id = object_id(@tabbname)
  5813.             and sysstat & 0xf in (1,2,3)
  5814.  
  5815. if @objidb is NULL
  5816.     begin
  5817.         raiserror(15113,-1,-1)
  5818.          return(1)
  5819.     end
  5820.  
  5821. /*
  5822. **  Only the owner of the table can define its common keys.
  5823. */
  5824. if @uida <> user_id()
  5825.     begin
  5826.         raiserror(15114,-1,-1)
  5827.         return (1)
  5828.     end
  5829.  
  5830. /*
  5831. **  Now check to see that the first key columns exist and have compatible types.
  5832. */
  5833. select @cnt = 1, @key1a = a.colid, @key1b = b.colid
  5834.     from syscolumns a, syscolumns b, master.dbo.spt_values y,
  5835.         master.dbo.spt_values z
  5836.         where a.name = @col1a
  5837.             and a.id = @objida
  5838.             and b.name = @col1b
  5839.             and b.id = @objidb
  5840.             and y.type = 'J'
  5841.             and a.type = y.low
  5842.             and z.type = 'J'
  5843.             and b.type = z.low
  5844.             and y.number = z.number
  5845. if @key1a is null
  5846.     begin
  5847.         raiserror(15115,-1,-1)
  5848.         return (1)
  5849.     end
  5850.  
  5851. if @col2a IS NOT NULL
  5852. begin
  5853.     select @cnt = @cnt + 1, @key2a = a.colid, @key2b = b.colid
  5854.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  5855.             master.dbo.spt_values z
  5856.             where a.name = @col2a
  5857.                 and a.id = @objida
  5858.                 and b.name = @col2b
  5859.                 and b.id = @objidb
  5860.                 and y.type = 'J'
  5861.                 and a.type = y.low
  5862.                 and z.type = 'J'
  5863.                 and b.type = z.low
  5864.                 and y.number = z.number
  5865.     if @key2a is null
  5866.         begin
  5867.             raiserror(15116,-1,-1)
  5868.             return (1)
  5869.         end
  5870. end
  5871. else goto keys_ok
  5872.  
  5873. if @col3a IS NOT NULL
  5874. begin
  5875.     select @cnt = @cnt + 1, @key3a = a.colid, @key3b = b.colid
  5876.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  5877.             master.dbo.spt_values z
  5878.             where a.name = @col3a
  5879.                 and a.id = @objida
  5880.                 and b.name = @col3b
  5881.                 and b.id = @objidb
  5882.                 and y.type = 'J'
  5883.                 and a.type = y.low
  5884.                 and z.type = 'J'
  5885.                 and b.type = z.low
  5886.                 and y.number = z.number
  5887.     if @key3a is null
  5888.         begin
  5889.             raiserror(15117,-1,-1)
  5890.             return (1)
  5891.         end
  5892. end
  5893. else goto keys_ok
  5894.  
  5895. if @col4a IS NOT NULL
  5896. begin
  5897.     select @cnt = @cnt + 1, @key4a = a.colid, @key4b = b.colid
  5898.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  5899.             master.dbo.spt_values z
  5900.             where a.name = @col4a
  5901.                 and a.id = @objida
  5902.                 and b.name = @col4b
  5903.                 and b.id = @objidb
  5904.                 and y.type = 'J'
  5905.                 and a.type = y.low
  5906.                 and z.type = 'J'
  5907.                 and b.type = z.low
  5908.                 and y.number = z.number
  5909.     if @key4a is null
  5910.         begin
  5911.             raiserror(15118,-1,-1)
  5912.             return (1)
  5913.         end
  5914. end
  5915. else goto keys_ok
  5916.  
  5917. if @col5a IS NOT NULL
  5918. begin
  5919.     select @cnt = @cnt + 1, @key5a = a.colid, @key5b = b.colid
  5920.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  5921.             master.dbo.spt_values z
  5922.             where a.name = @col5a
  5923.                 and a.id = @objida
  5924.                 and b.name = @col5b
  5925.                 and b.id = @objidb
  5926.                 and y.type = 'J'
  5927.                 and a.type = y.low
  5928.                 and z.type = 'J'
  5929.                 and b.type = z.low
  5930.                 and y.number = z.number
  5931.     if @key5a is null
  5932.         begin
  5933.             raiserror(15119,-1,-1)
  5934.             return (1)
  5935.         end
  5936. end
  5937. else goto keys_ok
  5938.  
  5939. if @col6a IS NOT NULL
  5940. begin
  5941.     select @cnt = @cnt + 1, @key6a = a.colid, @key6b = b.colid
  5942.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  5943.             master.dbo.spt_values z
  5944.             where a.name = @col6a
  5945.                 and a.id = @objida
  5946.                 and b.name = @col6b
  5947.                 and b.id = @objidb
  5948.                 and y.type = 'J'
  5949.                 and a.type = y.low
  5950.                 and z.type = 'J'
  5951.                 and b.type = z.low
  5952.                 and y.number = z.number
  5953.     if @key6a is null
  5954.         begin
  5955.             raiserror(15120,-1,-1)
  5956.             return (1)
  5957.         end
  5958. end
  5959. else goto keys_ok
  5960.  
  5961. if @col7a IS NOT NULL
  5962. begin
  5963.     select @cnt = @cnt + 1, @key7a = a.colid, @key7b = b.colid
  5964.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  5965.             master.dbo.spt_values z
  5966.             where a.name = @col7a
  5967.                 and a.id = @objida
  5968.                 and b.name = @col7b
  5969.                 and b.id = @objidb
  5970.                 and y.type = 'J'
  5971.                 and a.type = y.low
  5972.                 and z.type = 'J'
  5973.                 and b.type = z.low
  5974.                 and y.number = z.number
  5975.     if @key7a is null
  5976.         begin
  5977.             raiserror(15121,-1,-1)
  5978.             return (1)
  5979.         end
  5980. end
  5981. else goto keys_ok
  5982.  
  5983. if @col8a IS NOT NULL
  5984. begin
  5985.     select @cnt = @cnt + 1, @key8a = a.colid, @key8b = b.colid
  5986.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  5987.             master.dbo.spt_values z
  5988.             where a.name = @col8a
  5989.                 and a.id = @objida
  5990.                 and b.name = @col8b
  5991.                 and b.id = @objidb
  5992.                 and y.type = 'J'
  5993.                 and a.type = y.low
  5994.                 and z.type = 'J'
  5995.                 and b.type = z.low
  5996.                 and y.number = z.number
  5997.     if @key8a is null
  5998.         begin
  5999.             raiserror(15122,-1,-1)
  6000.             return (1)
  6001.         end
  6002. end
  6003.  
  6004. /*
  6005. **  If we made it this far then all the columns for the common key are ok.
  6006. **  Everything is consistent so add the common key to syskeys.
  6007. */
  6008. keys_ok:
  6009.  
  6010. insert syskeys (id, type, depid, keycnt, size, key1, key2, key3, key4, key5,
  6011.     key6, key7, key8, depkey1, depkey2, depkey3, depkey4, depkey5,
  6012.     depkey6, depkey7, depkey8)
  6013. values (@objida, 3, @objidb, @cnt, 0, @key1a, @key2a, @key3a, @key4a, @key5a,
  6014.     @key6a, @key7a, @key8a, @key1b, @key2b, @key3b, @key4b, @key5b,
  6015.     @key6b, @key7b, @key8b)
  6016.  
  6017. print 'New common key added.'
  6018.  
  6019. return (0)
  6020. go
  6021.  
  6022. print ''
  6023. print 'Creating procedure sp_configure.'
  6024. go
  6025. CREATE PROCEDURE sp_configure  --1995/10/26 14:17
  6026.  
  6027.     @configname   varchar(35) = NULL   -- option name to configure
  6028.    ,@configvalue  int         = NULL   -- new configuration value
  6029. as
  6030.  
  6031. declare
  6032.     @confignum                int   --Num of the opt to be configured
  6033.    ,@configcount              int   --Num of options like @configname
  6034. -- ,@value_in_sysconfigures   int   --For one option, its value bef Upd
  6035.    ,@show_advance             int   --Enable/supress actions on "advanced" opts
  6036.  
  6037. /*
  6038. **  Determine @maxnumber based on advance option in syscurconfigs.
  6039. */
  6040. if (select value from syscurconfigs where config = 518) = 1
  6041.    select @show_advance = 1   -- Display advanced options
  6042. else
  6043.    select @show_advance = 0   -- Don't display advanced options
  6044.  
  6045. /*
  6046. **  Make certain that max user info. reflects any addpak upgrades.
  6047. */
  6048. if (select high from master.dbo.spt_values where number=103 and type='C')
  6049.    <> @@max_connections
  6050.  
  6051.    update master.dbo.spt_values
  6052.       set high = @@max_connections
  6053.       where number = 103
  6054.          and type='C'
  6055.  
  6056. /*
  6057. **  If no option name is given, the procedure will just print out all the
  6058. **  options and their values.
  6059. */
  6060. if @configname is NULL
  6061.    begin
  6062.       select name, minimum = low, maximum = high,
  6063.          config_value = c.value,
  6064.          run_value = syscurconfigs.value
  6065.       from master.dbo.spt_values, sysconfigures c, syscurconfigs
  6066.       where type = 'C'
  6067.          and number = c.config
  6068.          and number = syscurconfigs.config
  6069.          and ((c.status/2) | @show_advance) & 1 = @show_advance
  6070.       order by lower(name)
  6071.  
  6072.       return (0)
  6073.    end
  6074.  
  6075. set nocount on
  6076.  
  6077. /*
  6078. **  Use @configname and try to find the right option.
  6079. **  If there isn't just one, print appropriate diagnostics and return.
  6080. */
  6081. select @configcount = count(*)
  6082.    from master.dbo.spt_values v ,sysconfigures c
  6083.    where v.name like '%' + @configname + '%' and v.type = 'C'
  6084.       and v.number = c.config
  6085.       and ((c.status/2) | @show_advance) & 1 = @show_advance
  6086.  
  6087. /*
  6088. **  If no option, show the user what the options are.
  6089. */
  6090. if @configcount = 0
  6091.    begin
  6092.       raiserror (15123,-1,-1)
  6093.  
  6094.       print ''
  6095.       print 'Valid configuration options are:'
  6096.  
  6097.       /*
  6098.       ** Show the user what the options are.
  6099.       */
  6100.       select name, minimum = low, maximum = high,
  6101.          config_value = c.value,
  6102.          run_value = syscurconfigs.value
  6103.       from master.dbo.spt_values, sysconfigures c, syscurconfigs
  6104.       where type = 'C'
  6105.          and number = c.config
  6106.          and number = syscurconfigs.config
  6107.          and ((c.status/2) | @show_advance) & 1 = @show_advance
  6108.  
  6109.       return (1)
  6110.    end
  6111.  
  6112. /*
  6113. **  If more than one option like @configname, show the duplicates and return.
  6114. */
  6115. if @configcount > 1
  6116.    begin
  6117.       raiserror (15124,-1,-1,@configname)
  6118.       print ''
  6119.  
  6120.       select duplicate_options = name
  6121.       from master.dbo.spt_values,sysconfigures c
  6122.       where name like '%' + @configname + '%'
  6123.          and type = 'C'
  6124.          and number = c.config
  6125.          and ((c.status/2) | @show_advance) & 1 = @show_advance
  6126.  
  6127.       return (1)
  6128.    end
  6129. else
  6130.    /* There must be exactly one, so get the full name. */
  6131.    select @configname = name --,@value_in_sysconfigures = c.value
  6132.       from master.dbo.spt_values,sysconfigures c
  6133.       where name like '%' + @configname + '%' and type = 'C'
  6134.          and number = c.config
  6135.          and ((c.status/2) | @show_advance) & 1 = @show_advance
  6136.  
  6137. /*
  6138. ** If @configvalue is NULL, just show the current state of the option.
  6139. */
  6140. if @configvalue is null
  6141. begin
  6142.    select name, minimum = low, maximum = high,
  6143.       config_value = c.value,
  6144.       run_value = syscurconfigs.value
  6145.    from master.dbo.spt_values, sysconfigures c, syscurconfigs
  6146.    where type = 'C'
  6147.       and number *= c.config
  6148.       and number *= syscurconfigs.config
  6149.       and name like '%' + @configname + '%'
  6150.       and ((c.status/2) | @show_advance) & 1 = @show_advance
  6151.    return (0)
  6152. end
  6153.  
  6154. /*
  6155. **  Only the SA can execute the update part of this procedure so check.
  6156. */
  6157. if suser_id() <> 1
  6158.    begin
  6159.       raiserror(15125,-1,-1)
  6160.       return (1)
  6161.    end
  6162.  
  6163. /*
  6164. **  Now get the configuration number.
  6165. */
  6166. select @confignum = number
  6167.    from master.dbo.spt_values,sysconfigures c
  6168.    where type = 'C'
  6169.       and (@configvalue between low and high or @configvalue = 0)
  6170.       and name like '%' + @configname + '%'
  6171.       and number = c.config
  6172.       and ((c.status/2) | @show_advance) & 1 = @show_advance
  6173.  
  6174. /*
  6175. **  If this is the number of devices configuration parameter,
  6176. **  we want to make sure that it's not being set to lower than the
  6177. **  number of devices in sysdevices.
  6178. */
  6179. if @confignum = 116
  6180. begin
  6181.    /*
  6182.    **  Get the max vdevno.
  6183.    */
  6184.    declare @maxvdevno int
  6185.    select @maxvdevno = max(convert(tinyint, substring(convert(binary(4),
  6186.       d.low), v.low, 1)))
  6187.    from sysdevices d, master.dbo.spt_values v
  6188.    where v.type = 'E'
  6189.       and v.number = 3
  6190.  
  6191.    /*
  6192.    **  If @configvalue = 0, then set it to the current number of devices.
  6193.    */
  6194.    if @configvalue = 0
  6195.    select @configvalue = @maxvdevno + 1
  6196.    if (select low from master.dbo.spt_values
  6197.          where type = 'C'
  6198.          and number = 116) > @configvalue
  6199.       begin
  6200.          select @configvalue = low
  6201.             from master.dbo.spt_values
  6202.             where type = 'C'
  6203.                and number = 116
  6204.       end
  6205.  
  6206.    if ((@maxvdevno + 1) > @configvalue)
  6207.       begin
  6208.          raiserror(15126,-1,-1)
  6209.          return (1)
  6210.       end
  6211. end
  6212.  
  6213. /*
  6214. **  If this is the number of default language, we want to make sure
  6215. **  that the new value is a valid language id in Syslanguages.
  6216. */
  6217. if @confignum = 124
  6218.    begin
  6219.    if not exists (select * from syslanguages
  6220.          where langid = @configvalue)
  6221.       begin
  6222.          /* 0 is default language, us_english */
  6223.          if @configvalue <> 0
  6224.             begin
  6225.                raiserror(15127,-1,-1)
  6226.                return (1)
  6227.             end
  6228.       end
  6229.    end
  6230.  
  6231. /*
  6232. **  If this is the number of kernel language, we want to make sure
  6233. **  that the new value is a valid language id in Syslanguages.
  6234. */
  6235. if @confignum = 132
  6236.    begin
  6237.    if not exists (select * from syslanguages
  6238.          where langid = @configvalue)
  6239.       begin
  6240.          /* 0 is default language, us_english */
  6241.          if @configvalue <> 0
  6242.             begin
  6243.                raiserror(15028,-1,-1)
  6244.                return (1)
  6245.             end
  6246.       end
  6247.    end
  6248.  
  6249. /*
  6250. **  "user options" should not try to set incompatible options/values.
  6251. */
  6252. if @confignum = 1534  --"user options"
  6253.    begin
  6254.  
  6255.    if (@configvalue & (1024+2048) = (1024+2048)) --ansi_null_default_on/off
  6256.       begin
  6257.       raiserror(15303,-1,-1,@configvalue)
  6258.       return (1)
  6259.       end
  6260.    end
  6261.  
  6262. /*
  6263. **  Although the @configname is good, @configvalue wasn't in range.
  6264. */
  6265. if @confignum is NULL
  6266.    begin
  6267.    raiserror(15129,-1,-1,@configvalue,@configname)
  6268.    return (1)
  6269.    end
  6270.  
  6271. /*
  6272. **  If we're in a transaction, disallow this since it might make recovery
  6273. **  impossible.
  6274. */
  6275. if @@trancount > 0
  6276.    begin
  6277.    raiserror(15002,-1,-1,'sp_configure')
  6278.    return (1)
  6279.    end
  6280.  
  6281. /*
  6282. **  Now update sysconfigures.
  6283. */
  6284. update sysconfigures set value = @configvalue
  6285.    where config = @confignum
  6286.  
  6287. /*
  6288. ** If this is memory parameter, we need to calculate a
  6289. ** new value for number of free buffers.
  6290. */
  6291. if @confignum = 104
  6292.    begin
  6293.    print ''
  6294.    print 'Recalculating free buffer setting.'
  6295.    update sysconfigures set value = @configvalue/20
  6296.       where config = 1515
  6297.    end
  6298.  
  6299. print 'Configuration option changed. Run the RECONFIGURE command to install.'
  6300.  
  6301. return (0)
  6302. go
  6303.  
  6304.  
  6305. print ''
  6306. print 'Creating procedure sp_change_configstatus.'
  6307. go
  6308. CREATE PROCEDURE sp_change_configstatus  --1995/10/16 20:27
  6309.  
  6310.     @pConfigNamePattern          varchar(35)    = '%'
  6311.    ,@pAction                     varchar(20)    = 'report_configs'
  6312. AS
  6313.  
  6314. /*****
  6315. --This sproc is NOT documented.
  6316.  
  6317. Available Actions:
  6318.   'off_advanced'   ,'on_advanced'   ,'report_configs'   ,'update_to_defaults'
  6319.  
  6320. exec sp_change_configstatus '%'                  ,'update_to_defaults'
  6321. exec sp_configure           'max worker threads' ,254
  6322. exec sp_change_configstatus '%working set%'      ,'off_advanced' --matches 1
  6323. exec sp_change_configstatus '%work%'        --second parm defaults to 'report_configs'
  6324.  
  6325.   *** Actual output.  ASTERISKS show types of "differences".  ***
  6326.  
  6327. Configuration option changed. Run the RECONFIGURE command to install.
  6328.  
  6329. ConfigName           Dynamic Advanced StagedValue CurrentValue
  6330. -------------------- ------- -------- ----------- -------------
  6331. max worker threads   yes     no       254         255         *
  6332. network packet size  yes     no       4096        4096
  6333. RA worker threads    no      no       3           3
  6334. set working set size no      no  *    0           0
  6335.  
  6336. (4 row(s) affected)
  6337. *****/
  6338.  
  6339. Set nocount       on
  6340. Set ansi_warnings off
  6341.  
  6342.  
  6343. Declare
  6344.     @RetCode                     int
  6345.    ,@vc1                         varchar(80)
  6346.    ,@vc2                         varchar(80)
  6347.    ,@CountStatusUpd              int
  6348.    ,@charMaxLenConfigName        varchar(11)
  6349.  
  6350. Declare
  6351.     @ConfigAllowUpdates          int
  6352.    ,@ConfigShowAdvanced          int
  6353.    ,@CountConfigNameMatches      int
  6354.  
  6355. Declare
  6356.     @CBit_Dynamic                smallint
  6357.    ,@CBit_Advanced               smallint
  6358.  
  6359. --------
  6360.  
  6361. Select
  6362.     @RetCode                     = 0
  6363.    ,@CountStatusUpd              = 0
  6364.    ,@CBit_Dynamic                = Power(2,0)  --  1=integer representation
  6365.    ,@CBit_Advanced               = Power(2,1)
  6366.  
  6367.  
  6368. ------------------  Edit input parm values  --------------------
  6369.  
  6370.  
  6371. IF (@pAction NOT IN  (
  6372.                       'off_advanced'
  6373.                      ,'on_advanced'
  6374.                      ,'report_configs'
  6375.                      ,'update_to_defaults'
  6376.                      )
  6377.       OR
  6378.  
  6379.     @pAction IS Null
  6380.    )
  6381.    begin
  6382.    RaisError(15304,-1,-1 ,@pAction)
  6383.  
  6384.    GOTO LABEL_86RETURN
  6385.  
  6386.    end
  6387.  
  6388.  
  6389. --------
  6390.  
  6391. IF (@pAction NOT LIKE 'report%')
  6392.    begin
  6393.  
  6394.    IF (suser_id() <> 1)  --SA
  6395.       begin
  6396.       RaisError(15305,-1,-1)
  6397.  
  6398.       GOTO LABEL_86RETURN
  6399.  
  6400.       end
  6401.  
  6402.    end
  6403.  
  6404.  
  6405.  
  6406. --------------------  How many config names match parm?  -------------------
  6407.  
  6408.  
  6409.  
  6410. -------- Using potential  report_  temp #table as counting mechanism too.
  6411.  
  6412. Create Table #tb1_ReportConfigs
  6413.    (
  6414.     zConfigNum          int
  6415.    ,zConfigName         varchar(35)
  6416.    ,zDynamic            char( 5)
  6417.    ,zAdvanced           char( 5)
  6418.    ,zStagedValue        char(11)
  6419.    ,zCurrentValue       char(13)
  6420.    )
  6421.  
  6422. Create Unique Clustered
  6423.    Index    ix1
  6424.    On       #tb1_ReportConfigs (zConfigName)
  6425.  
  6426.  
  6427.  
  6428. INSERT
  6429.       into      #tb1_ReportConfigs
  6430.          (
  6431.           zConfigNum
  6432.          ,zConfigName
  6433.          ,zDynamic
  6434.          ,zAdvanced
  6435.          ,zStagedValue
  6436.          ,zCurrentValue
  6437.          )
  6438.    SELECT
  6439.                 cf.config
  6440.                ,val.name
  6441.  
  6442.                ,CASE cf.status & @CBit_Dynamic
  6443.                   When 0 Then 'no'
  6444.                   Else        'yes'
  6445.                 END
  6446.  
  6447.                ,CASE cf.status & @CBit_Advanced
  6448.                   When 0 Then 'no'
  6449.                   Else        'yes'
  6450.                 END
  6451.  
  6452.                ,convert(varchar,cf.value)
  6453.                ,convert(varchar,cc.value)
  6454.       from
  6455.                 master.dbo.sysconfigures     cf
  6456.                ,master.dbo.syscurconfigs     cc
  6457.                ,master.dbo.spt_values        val
  6458.       where
  6459.                 val.type      = 'C'
  6460.       and
  6461.                 cf.config     = cc.config
  6462.       and       cf.config     = val.number
  6463.       and
  6464.                 val.name LIKE @pConfigNamePattern
  6465.  
  6466.  
  6467. Select @CountConfigNameMatches = @@rowcount
  6468.  
  6469.  
  6470.  
  6471. IF (@CountConfigNameMatches = 0)
  6472.    begin
  6473.    GOTO LABEL_76FINAL
  6474.    end
  6475.  
  6476.  
  6477.  
  6478. ------------  What are the empowering configs values?  ------------
  6479.  
  6480.  
  6481. SELECT
  6482.              @ConfigAllowUpdates       = cc.value
  6483.       from
  6484.              master.dbo.syscurconfigs  cc
  6485.             ,master.dbo.spt_values     val
  6486.       where
  6487.              cc.config  = val.number
  6488.       and    val.type   = 'C '
  6489.       and    val.name   = 'allow updates'
  6490.  
  6491.  
  6492.  
  6493. SELECT
  6494.              @ConfigShowAdvanced       = cc.value
  6495.       from
  6496.              master.dbo.syscurconfigs  cc
  6497.             ,master.dbo.spt_values     val
  6498.       where
  6499.              cc.config  = val.number
  6500.       and    val.type   = 'C '
  6501.       and    val.name   = 'show advanced option'
  6502.  
  6503.  
  6504.  
  6505. ------------  Just report the configs statuses and comparisons  ---------
  6506.  
  6507.  
  6508. IF (@pAction = 'report_configs')
  6509.    begin
  6510.  
  6511.  
  6512.    UPDATE
  6513.                 #tb1_ReportConfigs
  6514.          set
  6515.                 tb1.zAdvanced = substring(tb1.zAdvanced,1,4) + '*'
  6516.          from
  6517.                 #tb1_ReportConfigs           tb1
  6518.                ,master.dbo.sysconfigures     cf
  6519.                ,master.dbo.spt_values        val
  6520.          where
  6521.                 val.type      = 'C'
  6522.          and
  6523.                 cf.config     = tb1.zConfigNum
  6524.          and    cf.config     = val.number
  6525.          and
  6526.                 (@CBit_Advanced & cf.status)    <>
  6527.                 (@CBit_Advanced & val.status)
  6528.  
  6529.  
  6530.  
  6531.    UPDATE
  6532.                 #tb1_ReportConfigs
  6533.          set
  6534.                 tb1.zCurrentValue = substring(tb1.zCurrentValue,1,12) + '*'
  6535.          from
  6536.                 #tb1_ReportConfigs           tb1
  6537.                ,master.dbo.sysconfigures     cf
  6538.                ,master.dbo.syscurconfigs     cc
  6539.          where
  6540.                 cf.config     = tb1.zConfigNum
  6541.          and    cf.config     = cc.config
  6542.          and
  6543.                 cf.value     <> cc.value
  6544.  
  6545.  
  6546.  
  6547. --------  Optimize column widths.
  6548.  
  6549.  
  6550.    SELECT
  6551.                 @charMaxLenConfigName  =
  6552.                         convert( varchar,
  6553.                            isnull( max( datalength( zConfigName)),10)
  6554.                                )
  6555.          from
  6556.                 #tb1_ReportConfigs
  6557.  
  6558.  
  6559.  
  6560.    EXECUTE(
  6561.    '
  6562.    Set nocount off
  6563.  
  6564.  
  6565.    SELECT
  6566.                 ''ConfigName''     = substring(zConfigName,1,'
  6567.                                            + @charMaxLenConfigName + ')
  6568.  
  6569.                ,''Dynamic''        = zDynamic
  6570.                ,''Advanced''       = zAdvanced
  6571.  
  6572.                ,''StagedValue''    = zStagedValue
  6573.                ,''CurrentValue''   = zCurrentValue
  6574.          from
  6575.                 #tb1_ReportConfigs
  6576.          order by
  6577.                 ConfigName
  6578.  
  6579.    Set nocount on
  6580.    '
  6581.    )
  6582.  
  6583.  
  6584.    GOTO LABEL_76FINAL
  6585.  
  6586.    end
  6587.  
  6588.  
  6589.  
  6590. --------------------  Modify configs statuses  -----------------
  6591.  
  6592.  
  6593. IF (@pAction = 'off_advanced')
  6594.    begin
  6595.  
  6596.    IF (     @CountConfigNameMatches > 1
  6597.        AND  @ConfigAllowUpdates     = 0
  6598.        AND  @ConfigShowAdvanced     = 0
  6599.       )
  6600.       begin
  6601.       RaisError(15306,-1,-1)
  6602.  
  6603.       GOTO LABEL_86RETURN
  6604.  
  6605.       end
  6606.  
  6607.  
  6608.    Select
  6609.           @vc1 = 'cf.status & (~' + convert(varchar,@CBit_Advanced) + ')'
  6610.          ,@vc2 = '& ' + convert(varchar,@CBit_Advanced) + ' > 0'
  6611.    end
  6612.  
  6613.  
  6614. IF (@pAction = 'on_advanced')
  6615.    begin
  6616.    Select
  6617.           @vc1 = 'cf.status | ( ' + convert(varchar,@CBit_Advanced) + ')'
  6618.          ,@vc2 = '& ' + convert(varchar,@CBit_Advanced) + ' = 0'
  6619.    end
  6620.  
  6621.  
  6622. IF (@pAction = 'update_to_defaults')
  6623.    begin
  6624.    Select
  6625.           @vc1 = 'val.status'
  6626.          ,@vc2 = ' <> val.status'
  6627.    end
  6628.  
  6629.  
  6630. ---------------  Actual Upd
  6631.  
  6632.  
  6633. EXECUTE(
  6634. '
  6635. UPDATE
  6636.              master.dbo.sysconfigures
  6637.       set
  6638.              cf.status     = ' + @vc1 + '
  6639.       from
  6640.              master.dbo.sysconfigures     cf
  6641.             ,master.dbo.spt_values        val
  6642.       where
  6643.              val.type      = ''C ''
  6644.       and    val.number    = cf.config
  6645.       and    val.name   LIKE ''' + @pConfigNamePattern + '''
  6646.       and
  6647.              cf.status ' + @vc2 + '
  6648. '
  6649. )
  6650.  
  6651. Select @CountStatusUpd = @@rowcount
  6652.  
  6653.  
  6654.  
  6655. -----------------------  Finalization  -----------------------
  6656.  
  6657.  
  6658. LABEL_76FINAL:
  6659.  
  6660.  
  6661.  
  6662. LABEL_86RETURN:
  6663.  
  6664.  
  6665.  
  6666. IF (object_id('tempdb..#tb1_ReportConfigs') IS NOT Null)
  6667.             Drop Table #tb1_ReportConfigs
  6668.  
  6669.  
  6670. IF (@CountStatusUpd > 0)
  6671.    Select @RetCode = @RetCode | 1
  6672.  
  6673.  
  6674. Return @RetCode
  6675. go
  6676.  
  6677.  
  6678.  
  6679. print ''
  6680. print 'Creating procedure sp_dbinstall.'
  6681. go
  6682. create procedure sp_dbinstall --1995/09/25 16:42
  6683.  
  6684. @dbname        varchar(30) = null,    -- name of db
  6685. @logical    varchar(30) = null,    -- logical name of device
  6686. @physical    varchar(255) = null,    -- physical name of device
  6687. @size        int = null,        -- size of device in Meg.
  6688. @dev_type    varchar(6) = null,    -- Device can be 'system' or 'data'.
  6689. @location    varchar(255) = null    -- Disk location for writable
  6690.                     -- fragment.  Mandatory for
  6691.                     -- system device, optional for
  6692.                     -- data devices.
  6693.                     
  6694. as
  6695.         declare @vdevno int
  6696.     declare @dbid int
  6697.     declare @sysdb_version int
  6698.     declare @start int
  6699.  
  6700.     declare @filesize int
  6701.     declare @retcode int
  6702.     declare @lstart int
  6703.     declare @cmd varchar(255)
  6704.     declare @segmap int    
  6705.  
  6706.     /*
  6707.     ** Make sure all parameters were supplied, if not print a syntax diagram.
  6708.     */
  6709.     if    @dbname is null
  6710.         or @logical is null
  6711.         or @physical is null
  6712.         or @size is null
  6713.         or @dev_type is null
  6714.         begin
  6715.             raiserror(15130,-1,-1)
  6716.             return(1)
  6717.         end
  6718.  
  6719.     /* Check to see if a valid database name was supplied. */
  6720.     exec @retcode = sp_validname @dbname
  6721.     if @retcode <> 0
  6722.         return(1)
  6723.  
  6724.     /* Check to see if a valid device name was supplied. */
  6725.     exec @retcode = sp_validname @logical
  6726.     if @retcode <> 0
  6727.         return(1)
  6728.  
  6729.     select @dev_type=lower(@dev_type)
  6730.  
  6731.     /* Check to see if device type is valid. */
  6732.     if @dev_type not in ('system','data')
  6733.         begin
  6734.             raiserror(15048,-1,-1,@dev_type)
  6735.             return(1)
  6736.         end
  6737.  
  6738.     /*
  6739.         **  Check to see if we're defining the initial device or adding
  6740.     **  devices to complete an installation.
  6741.     */
  6742.  
  6743.     if @dev_type = 'system'
  6744.         begin
  6745.             /* We're creating the db, so make sure it doesn't already exist. */
  6746.             if exists (select * from sysdatabases where name = @dbname)
  6747.                 begin
  6748.                     raiserror(15049,-1,-1)
  6749.                     return(1)
  6750.                 end
  6751.  
  6752.             /* make sure that new location is specified. */
  6753.             if @location is null
  6754.                 begin
  6755.                     raiserror(15052,-1,-1)
  6756.                     return(1)
  6757.                 end
  6758.         end
  6759.     else
  6760.         begin
  6761.             /*
  6762.             ** We're appending data devices, so make sure db
  6763.             ** already exists.
  6764.             */
  6765.             if not exists (select * from sysdatabases where name = @dbname)
  6766.                 begin
  6767.                     raiserror(15050,-1,-1)
  6768.                     return(1)
  6769.                 end
  6770.         end
  6771.  
  6772.     /* Databases must occupy at least 1 meg on a device.
  6773.     ** Have to trust the user for just how much.
  6774.     */
  6775.     if @size < 1
  6776.         begin
  6777.             raiserror(15051,-1,-1)
  6778.             return(1)
  6779.         end
  6780.  
  6781.     /*
  6782.     ** Make sure that devices with the supplied logical or physical
  6783.     ** names don't already exist.
  6784.     */
  6785.     if exists (select * from sysdevices where name = @logical)
  6786.         begin
  6787.             raiserror(15026,-1,-1,@logical)
  6788.             return(1)
  6789.         end
  6790.  
  6791.  
  6792.     if exists (select * from sysdevices where phyname = isnull(@location,' o k'))
  6793.         begin
  6794.             raiserror(15030,-1,-1,@location)
  6795.             return(1)
  6796.         end
  6797.  
  6798.     /* Get the dbid. */
  6799.     if @dev_type = 'system'    /* Initial install, need to calculate one. */
  6800.         begin
  6801.             /* Get first available database number. */
  6802.  
  6803.                         select @dbid = min(dbid)+1
  6804.             from sysdatabases d1
  6805.             where dbid < 32767    /* Avoid arithmetic overflow if
  6806.                         ** dbid = max smallint exists. */
  6807.             and not exists
  6808.                 (select * from sysdatabases d2
  6809.                 where d2.dbid = d1.dbid+1)
  6810.         end
  6811.     else    /* Appending device frags. to existing db., get its dbid. */
  6812.         select @dbid = dbid from sysdatabases where name = @dbname
  6813.  
  6814.  
  6815.     dbcc getvalue('current_version')  --internal/system schema
  6816.     select @sysdb_version = @@error
  6817.  
  6818.  
  6819.     /* Get first available device number. */
  6820.     select @vdevno = null
  6821.     select @vdevno = (min(low)/0x01000000)+1
  6822.         from sysdevices d1
  6823.         where low/0x01000000 between 0 and 254
  6824.         and not exists
  6825.             (select * from sysdevices d2
  6826.                 where d2.low/0x01000000 = (d1.low/0x01000000)+1)
  6827.  
  6828.     if @vdevno is null
  6829.         begin
  6830.             raiserror(15054,-1,-1)
  6831.             return(1)
  6832.         end
  6833.  
  6834.     /* Calculate first virtual page number for device. */
  6835.     select  @start = 0x01000000 * @vdevno
  6836.  
  6837.     /* Get the file size. */
  6838.     exec('dbcc devcontrol('''+@physical+''',filesize) with no_infomsgs')
  6839.     select @filesize = @@error
  6840.     if @filesize = 0 /* => file can't be opened. */
  6841.         begin
  6842.             raiserror(15055,-1,-1,@physical)
  6843.             return(1)
  6844.         end
  6845.  
  6846.     if @location is not null
  6847.         begin
  6848.             select @cmd = 'copy '+@physical+' '+@location
  6849.             select @cmd = 'xp_cmdshell '''+@cmd+''''
  6850.             exec (@cmd)
  6851.             if @@error <> 0
  6852.                 begin
  6853.                     print 'Couldn''t move device file'
  6854.                     return(1)
  6855.                 end
  6856.             select @physical = @location
  6857.         end
  6858.  
  6859.     begin tran
  6860.  
  6861.         if @dev_type = 'system'        -- Don't mark system device as 'read only'
  6862.             insert sysdevices
  6863.                 (low,high,status,cntrltype,name,phyname,mirrorname)
  6864.                 values
  6865.                 (@start, @start+@filesize-1, 8194, 0, @logical, @physical, NULL)
  6866.         else    -- It must be a data fragment, so mark the device 'read only'
  6867.             insert sysdevices
  6868.                 (low,high,status,cntrltype,name,phyname,mirrorname)
  6869.                 values
  6870.                 (@start, @start+@filesize-1,12290, 0, @logical, @physical, NULL)
  6871.  
  6872.             if @@error <> 0
  6873.                 begin
  6874.                 raiserror(15056,-1,-1,'sysdevices')
  6875.                     goto failed
  6876.                 end
  6877.  
  6878.                 if @dev_type = 'system'    -- New db.
  6879.                         begin
  6880.                            select @lstart = 0
  6881.  
  6882.                                insert into sysdatabases
  6883.                     (name,dbid,suid,mode,status,version,logptr,crdate,dumptrdate,category)
  6884.                     values
  6885.                             (@dbname, @dbid, 1, 0, 512, @sysdb_version, 0, getdate(), getdate(), 0 )
  6886.  
  6887.                            if @@error <> 0
  6888.                                 begin
  6889.                                     raiserror(15056,-1,-1,'sysdatabases')
  6890.                                     goto failed
  6891.                                         end
  6892.  
  6893.                         end
  6894.                 else    /* We're appending, so get the last fragment and
  6895.                     ** go from there. */
  6896.                         select @lstart = lstart+size from sysusages
  6897.                     where dbid=@dbid
  6898.                 and lstart = (select max(lstart) from sysusages
  6899.                         where dbid=@dbid)
  6900.  
  6901.         /*
  6902.         ** If it's the data device, assume that it's static.
  6903.         ** Else, it is a system device and we must map the
  6904.         ** system and log segments to  it.
  6905.         */
  6906.         if @dev_type = 'data'
  6907.             select @segmap = 0    /* No allocations. */
  6908.         else
  6909.             /* It's the system device */
  6910.             select @segmap = 5    /* System + log */
  6911.  
  6912.         insert sysusages
  6913.             (dbid,segmap,lstart,size,vstart)
  6914.             values
  6915.             (@dbid, @segmap, @lstart, @size*512, @start )
  6916.             if @@error <> 0
  6917.                 begin
  6918.                     raiserror(15056,-1,-1,'sysusages')
  6919.                     goto failed
  6920.                 end
  6921.  
  6922.         dbcc dbrepair (@dbname,remap) with no_infomsgs
  6923.  
  6924.         /* If we made it to here, we're okay. */
  6925.  
  6926.         goto succeeded
  6927.  
  6928.         failed:
  6929.             begin
  6930.                 rollback tran
  6931.                 return(1)
  6932.             end
  6933.  
  6934.         succeeded:
  6935.  
  6936.     commit tran
  6937.  
  6938.     print ''
  6939.     if @dev_type = 'system'
  6940.         begin
  6941.                     print 'System device installed.'
  6942.             print 'Use sp_dbinstall to install data device(s).'
  6943.         end
  6944.     else
  6945.         begin
  6946.             print 'Data device installed.'
  6947.             print 'Use sp_dbinstall to install additional data device(s).  Or, if installation is complete, use sp_dboption to bring the database online.'
  6948.         end
  6949.  
  6950. return(0)
  6951. go
  6952.  
  6953.  
  6954. print ''
  6955. print 'Creating procedure sp_dbremove.'
  6956. go
  6957. create procedure sp_dbremove
  6958. @dbname varchar(30) = null,
  6959. @dropdev varchar(10) = null
  6960. as
  6961.  
  6962.     declare @dbid int
  6963.     declare @devname varchar(30)
  6964.     declare @pmsg varchar(255)
  6965.     declare @physname varchar(255)
  6966.  
  6967.     declare @cmd1 varchar(255)
  6968.     declare @cmd2 varchar(255)
  6969.     declare @cmd3 varchar(255)
  6970.  
  6971.     if @dbname is null
  6972.         begin
  6973.             raiserror(15131,-1,-1)
  6974.             return(1)
  6975.         end
  6976.  
  6977.     if lower(@dropdev) <> 'dropdev' and @dropdev is not null
  6978.         begin
  6979.             raiserror(15131,-1,-1)
  6980.             return(1)
  6981.         end
  6982.  
  6983.     /* Check to see if database exists. */
  6984.     select @dbid = null
  6985.     select @dbid = dbid from sysdatabases where name=@dbname
  6986.     if @dbid is null
  6987.         begin
  6988.             raiserror(15010,-1,-1,@dbname)
  6989.             return(1)
  6990.         end
  6991.  
  6992.     /* Make sure no one is in the db. */
  6993.     if (select count(*) from sysprocesses where dbid = @dbid) > 0
  6994.         begin
  6995.             raiserror(15069,-1,-1)
  6996.             return (1)
  6997.         end
  6998.  
  6999.     if lower(@dropdev) = 'dropdev'
  7000.         begin
  7001.             print 'Dropping any devices used only by this database.'
  7002.  
  7003.             select @cmd1 = 'declare c1 cursor for
  7004.                 select distinct d.name from sysdevices d,
  7005.                     master.dbo.sysusages u
  7006.                 where u.dbid = '+convert(varchar(5),@dbid)
  7007.  
  7008.             select @cmd2 = ' and u.segmap >= 0
  7009.                    and u.vstart between d.low and d.high
  7010.                    and d.status & 2 = 2    /* Physical devices only. */
  7011.                    and not exists
  7012.                        (select * from master.dbo.sysusages u2
  7013.                            where u2.dbid <> u.dbid'
  7014.                select @cmd3 =            ' and u2.vstart between d.low and d.high)'
  7015.             exec(@cmd1+@cmd2+@cmd3)
  7016.  
  7017.             open c1
  7018.             fetch c1 into @devname
  7019.  
  7020.             if @@fetch_status < 0
  7021.                 begin
  7022.                     print 'This database shares all of its devices with other databases.'
  7023.                     print '-- no devices will be dropped.'
  7024.                 end
  7025.  
  7026.             while @@fetch_status >= 0
  7027.                 begin
  7028.                     select @pmsg = 'Dropping device: '+@devname
  7029.                     /*
  7030.                     ** Get the physical file name before
  7031.                     ** delete the row from sysdevices.
  7032.                     */
  7033.                     select @physname = phyname
  7034.                         from sysdevices
  7035.                         where name = @devname
  7036.  
  7037.                     /*
  7038.                     ** Release file handle for physical device.
  7039.                     */
  7040.  
  7041.                     dbcc devcontrol(@devname,offline)
  7042.                                                 if @@error = 0
  7043.                                                         begin
  7044.                                             select @pmsg = 'File: '''+@physname+''' closed.'
  7045.                                             print @pmsg
  7046.                                                         end
  7047.  
  7048.                     delete from sysdevices where name = @devname
  7049.  
  7050.                     fetch c1 into @devname
  7051.                 end
  7052.  
  7053.             exec('deallocate c1')
  7054.         end
  7055.  
  7056.     update sysdatabases set status = 256 where dbid=@dbid
  7057.     dbcc dbrepair(@dbname,dropdb,noinit)
  7058.     print 'Database removed.'
  7059.  
  7060.     return(0)
  7061. go
  7062.  
  7063. print ''
  7064. print 'Creating procedure sp_devcreate'
  7065. go
  7066. create procedure sp_devcreate
  7067. @dbname varchar(30),
  7068. @logical varchar(30),
  7069. @physical varchar(255),
  7070. @size int
  7071. as
  7072.  
  7073. declare @retcode int,
  7074.     @vdevno int,
  7075.     @exec_str varchar(255),
  7076.     @size_in_blocks int
  7077.  
  7078. exec @retcode = sp_validname @logical
  7079. if @retcode <> 0
  7080.     return(1)
  7081.  
  7082. if @physical is null
  7083.     begin
  7084.         raiserror (15267,-1,-1,@logical)
  7085.         return(1)
  7086.     end
  7087.  
  7088. if @size is null
  7089.     begin
  7090.         raiserror (15268,-1,-1,@logical)
  7091.         return(1)
  7092.     end
  7093.  
  7094. if @size < 1
  7095.     begin
  7096.         raiserror (15262,-1,-1)
  7097.         return(1)
  7098.     end
  7099.  
  7100. /* Get next available device number for this segment. */
  7101. select @vdevno = null
  7102. select @vdevno = (min(low)/0x01000000)+1
  7103.     from sysdevices d1
  7104.     where low/0x01000000 between 0 and 254
  7105.         and not exists
  7106.             (select * from sysdevices d2
  7107.             where d2.low/0x01000000 =
  7108.                 (d1.low/0x01000000)+1)
  7109.  
  7110. if @vdevno is null or @@error <> 0
  7111.     begin
  7112.         raiserror(15054,-1,-1)
  7113.         exec sp_dbremove @dbname,dropdev
  7114.         return(1)
  7115.     end
  7116.  
  7117. select @size_in_blocks = @size * 512.
  7118.  
  7119. disk init
  7120.     name = @logical,
  7121.     physname = @physical,
  7122.     size = @size_in_blocks,
  7123.     vdevno = @vdevno
  7124.  
  7125. if @@error <> 0
  7126.     begin
  7127.         raiserror(15263,-1,-1,'data')
  7128.         exec sp_dbremove @dbname,dropdev
  7129.         return(1)
  7130.     end
  7131.  
  7132. select @exec_str = 'alter database '+@dbname+' on '+@logical+
  7133.             ' = '+convert(varchar(5),@size)
  7134. exec(@exec_str)
  7135.  
  7136. if @@error <> 0
  7137.     begin
  7138.         raiserror(15264,-1,-1,'data')
  7139.         exec sp_dbremove @dbname,dropdev
  7140.         return(1)
  7141.     end
  7142.  
  7143. /* Set sysusages.segmap to 'data' for data fragment. */
  7144. update sysusages set segmap = 2
  7145.     where vstart =
  7146.         (select low from sysdevices where name = @logical)
  7147.  
  7148. if @@error <> 0
  7149.     begin
  7150.         raiserror(15265,-1,-1)
  7151.         exec sp_dbremove @dbname,dropdev
  7152.         return(1)
  7153.     end
  7154.  
  7155. dbcc dbrepair (@dbname,remap) with no_infomsgs
  7156. go
  7157.  
  7158.  
  7159. print ''
  7160. print 'Creating procedure sp_coalesce_fragments.'
  7161. go
  7162. create procedure sp_coalesce_fragments  --1995/11/10 11:50
  7163.      @pDBNamePattern  varchar(44) = '%'
  7164. as
  7165.  
  7166. declare
  7167.     @c1_vstart int,
  7168.     @c1_size int,
  7169.     @c1_dbid smallint
  7170.  
  7171. declare
  7172.     @2size int,
  7173.     @2segmap int,
  7174.     @countusagesdel int,
  7175.     @_rowcount int
  7176.  
  7177. select    @countusagesdel = 0
  7178.  
  7179. if suser_id() <> 1
  7180.     begin
  7181.     raiserror(15003,-1,-1)  --must be SA
  7182.     return
  7183.     end
  7184.  
  7185. if @pDBNamePattern is null
  7186.     begin
  7187.     select @pDBNamePattern = ' n u l l'
  7188.     end
  7189.  
  7190. /*
  7191. ** Cursor to find a preceding contiguous fragment.
  7192. */
  7193. execute('declare c1 scroll cursor for
  7194.     select u1.vstart ,u1.size ,u1.dbid
  7195.     from master.dbo.sysusages u1
  7196.     where exists (select * from master.dbo.sysusages u2
  7197.             where u2.dbid = u1.dbid
  7198.             and u2.vstart = u1.vstart+u1.size
  7199.             and u2.lstart = u1.lstart+u1.size
  7200.             and u2.vstart between
  7201.                 (select d1.low
  7202.                     from master.dbo.sysdevices d1
  7203.                     where u1.vstart between
  7204.                         d1.low and d1.high
  7205.                     and d1.status&2=2)
  7206.             and
  7207.                 (select d2.high
  7208.                     from master.dbo.sysdevices d2
  7209.                     where u1.vstart between
  7210.                         d2.low and d2.high
  7211.                     and d2.status&2=2)
  7212.             )
  7213.     and db_name(u1.dbid) like ''' + @pDBNamePattern + '''
  7214.     and u1.vstart > 0'
  7215.     )
  7216.  
  7217. /*
  7218. ** Each loop iteration finds a sysusages row for which there is a
  7219. ** contiguous fragment at a higher vstart.   Then it gathers info on that
  7220. ** higher vstart row, and uses that info to delete the higher vstart
  7221. ** row and update the first row.
  7222. */
  7223. while 1=1
  7224.     begin
  7225.  
  7226.     open  c1
  7227.     fetch c1 into @c1_vstart,@c1_size ,@c1_dbid
  7228.  
  7229.     if @@fetch_status <> 0
  7230.         BREAK
  7231.  
  7232.  
  7233.  
  7234.     select @2size=null ,@2segmap=null
  7235.  
  7236.     select @2size=min(size) ,@2segmap=min(segmap)
  7237.           from  master.dbo.sysusages
  7238.           where vstart = @c1_vstart + @c1_size
  7239.           and   dbid   = @c1_dbid
  7240.  
  7241.     select @_rowcount = @@rowcount
  7242.  
  7243.     if (@2size is null  OR  @_rowcount <> 1)
  7244.         begin
  7245.         raiserror(15314,-1,-1,@c1_dbid,@c1_vstart) --corrupt sysusages
  7246.         BREAK
  7247.         end
  7248.  
  7249.  
  7250.     select @countusagesdel = @countusagesdel + 1
  7251.  
  7252.     delete from sysusages
  7253.           where vstart = @c1_vstart + @c1_size
  7254.           and   dbid   = @c1_dbid
  7255.  
  7256.     update sysusages
  7257.         set
  7258.             size   = size   + @2size,
  7259.             segmap = segmap | @2segmap
  7260.         where current of c1
  7261.  
  7262.  
  7263.     close c1  --force refreshing open
  7264.         
  7265.      end --of loop
  7266.  
  7267.  
  7268. raiserror(15315,-1,-1,@countusagesdel)
  7269.  
  7270. deallocate c1
  7271. go
  7272.  
  7273.  
  7274. print ''
  7275. print 'Creating procedure sp_create_removable.'
  7276. go
  7277. create procedure sp_create_removable
  7278.  
  7279. @dbname        varchar(30) = null,    /* name of db */
  7280. @syslogical    varchar(30) = null,    /* logical name of system device */
  7281. @sysphysical    varchar(255) = null,    /* physical name of system device */
  7282. @syssize    int = null,        /* size of sys device in Meg. */
  7283. @loglogical    varchar(30) = null,    /* logical name of log device */
  7284. @logphysical    varchar(255) = null,    /* physical name of log device */
  7285. @logsize    int = null,        /* size of log device in Meg. */
  7286. @datalogical1    varchar(30) = null,    /* logical name of data device */
  7287. @dataphysical1    varchar(255) = null,    /* physical name of data device */
  7288. @datasize1    int = null,        /* size of data device in Meg. */
  7289. @datalogical2    varchar(30) = null,    /* logical name of data device */
  7290. @dataphysical2    varchar(255) = null,    /* physical name of data device */
  7291. @datasize2    int = null,        /* size of data device in Meg. */
  7292. @datalogical3    varchar(30) = null,    /* logical name of data device */
  7293. @dataphysical3    varchar(255) = null,    /* physical name of data device */
  7294. @datasize3    int = null,        /* size of data device in Meg. */
  7295. @datalogical4    varchar(30) = null,    /* logical name of data device */
  7296. @dataphysical4    varchar(255) = null,    /* physical name of data device */
  7297. @datasize4    int = null,        /* size of data device in Meg. */
  7298. @datalogical5    varchar(30) = null,    /* logical name of data device */
  7299. @dataphysical5    varchar(255) = null,    /* physical name of data device */
  7300. @datasize5    int = null,        /* size of data device in Meg. */
  7301. @datalogical6    varchar(30) = null,    /* logical name of data device */
  7302. @dataphysical6    varchar(255) = null,    /* physical name of data device */
  7303. @datasize6    int = null,        /* size of data device in Meg. */
  7304. @datalogical7    varchar(30) = null,    /* logical name of data device */
  7305. @dataphysical7    varchar(255) = null,    /* physical name of data device */
  7306. @datasize7    int = null,        /* size of data device in Meg. */
  7307. @datalogical8    varchar(30) = null,    /* logical name of data device */
  7308. @dataphysical8    varchar(255) = null,    /* physical name of data device */
  7309. @datasize8    int = null,        /* size of data device in Meg. */
  7310. @datalogical9    varchar(30) = null,    /* logical name of data device */
  7311. @dataphysical9    varchar(255) = null,    /* physical name of data device */
  7312. @datasize9    int = null,        /* size of data device in Meg. */
  7313. @datalogical10    varchar(30) = null,    /* logical name of data device */
  7314. @dataphysical10    varchar(255) = null,    /* physical name of data device */
  7315. @datasize10    int = null,        /* size of data device in Meg. */
  7316. @datalogical11    varchar(30) = null,    /* logical name of data device */
  7317. @dataphysical11    varchar(255) = null,    /* physical name of data device */
  7318. @datasize11    int = null,        /* size of data device in Meg. */
  7319. @datalogical12    varchar(30) = null,    /* logical name of data device */
  7320. @dataphysical12    varchar(255) = null,    /* physical name of data device */
  7321. @datasize12    int = null,        /* size of data device in Meg. */
  7322. @datalogical13    varchar(30) = null,    /* logical name of data device */
  7323. @dataphysical13    varchar(255) = null,    /* physical name of data device */
  7324. @datasize13    int = null,        /* size of data device in Meg. */
  7325. @datalogical14    varchar(30) = null,    /* logical name of data device */
  7326. @dataphysical14    varchar(255) = null,    /* physical name of data device */
  7327. @datasize14    int = null,        /* size of data device in Meg. */
  7328. @datalogical15    varchar(30) = null,    /* logical name of data device */
  7329. @dataphysical15    varchar(255) = null,    /* physical name of data device */
  7330. @datasize15    int = null,        /* size of data device in Meg. */
  7331. @datalogical16    varchar(30) = null,    /* logical name of data device */
  7332. @dataphysical16 varchar(255) = null,    /* physical name of data device */
  7333. @datasize16    int = null        /* size of data device in Meg. */
  7334.     
  7335. as
  7336.  
  7337. declare @vdevno int,
  7338.     @size_in_blocks int,
  7339.     @retcode int,
  7340.     @exec_str varchar(255),
  7341.     @numdevs int
  7342.  
  7343. if suser_id() <> 1    -- Make sure that it's the SA executing this.
  7344.     begin
  7345.         raiserror(15003,-1,-1)
  7346.         return(1)    
  7347.     end
  7348.  
  7349. if @dbname is null
  7350.     or @syslogical is null
  7351.     or @sysphysical is null
  7352.     or @syssize is null
  7353.     or @loglogical is null
  7354.     or @logphysical is null
  7355.     or @logsize is null
  7356.     or @datalogical1 is null
  7357.     or @dataphysical1 is null
  7358.     or @datasize1 is null
  7359.         begin
  7360.             raiserror (15261,-1,-1)
  7361.             return (1)
  7362.         end
  7363.  
  7364. if exists (select * from sysdatabases where name = @dbname)
  7365.     begin
  7366.         raiserror(15032,-1,-1,@dbname)
  7367.         return(1)
  7368.     end
  7369.  
  7370. /* Check to verify that valid sizes were supplied for required devices. */
  7371. if @syssize < 1 or @logsize < 1 or @datasize1 < 1
  7372.     begin
  7373.         raiserror (15262,-1,-1)
  7374.         return(1)
  7375.     end
  7376.  
  7377. /* Check to see if a valid database name was supplied. */
  7378. exec @retcode = sp_validname @dbname
  7379. if @retcode <> 0
  7380.     return(1)
  7381.  
  7382. /* valid syslogical? */
  7383. exec @retcode = sp_validname @syslogical
  7384. if @retcode <> 0
  7385.     return(1)
  7386.  
  7387. /* valid loglogical? */
  7388. exec @retcode = sp_validname @loglogical
  7389. if @retcode <> 0
  7390.     return(1)
  7391.  
  7392. /* valid datalogical1? */
  7393. exec @retcode = sp_validname @datalogical1
  7394. if @retcode <> 0
  7395.     return(1)
  7396.  
  7397. /* Create the necessary devices. */
  7398.  
  7399. /* Get first available device number for the system device. */
  7400. select @vdevno = null
  7401. select @vdevno = (min(low)/0x01000000)+1
  7402.     from sysdevices d1
  7403.     where low/0x01000000 between 0 and 254
  7404.         and not exists
  7405.             (select * from sysdevices d2
  7406.             where d2.low/0x01000000 = (d1.low/0x01000000)+1)
  7407.  
  7408. if @vdevno is null or @@error <> 0
  7409.     begin
  7410.         raiserror(15054,-1,-1)
  7411.         return(1)
  7412.     end
  7413.  
  7414. select @size_in_blocks = @syssize * 512.
  7415.  
  7416. disk init
  7417.     name = @syslogical,
  7418.     physname = @sysphysical,
  7419.     size = @size_in_blocks,
  7420.     vdevno = @vdevno
  7421.  
  7422. if @@error <> 0
  7423.     begin
  7424.         raiserror(15263,-1,-1,'system')
  7425.         return(1)
  7426.     end
  7427.  
  7428. /* Create the database's system device segment. */
  7429. select @exec_str = 'create database '+ @dbname+' on '+@syslogical+
  7430.         ' = '+convert(varchar(5),@syssize)
  7431. exec(@exec_str)
  7432.  
  7433. if @@error <> 0
  7434.     begin
  7435.         raiserror(15264,-1,-1,'system')
  7436.         return(1)
  7437.     end
  7438.  
  7439. /* Get next available device number for the first data segment. */
  7440. select @vdevno = null
  7441. select @vdevno = (min(low)/0x01000000)+1
  7442.     from sysdevices d1
  7443.     where low/0x01000000 between 0 and 254
  7444.         and not exists
  7445.             (select * from sysdevices d2
  7446.             where d2.low/0x01000000 = (d1.low/0x01000000)+1)
  7447.  
  7448. if @vdevno is null or @@error <> 0
  7449.     begin
  7450.         raiserror(15054,-1,-1)
  7451.         exec sp_dbremove @dbname,dropdev
  7452.         return(1)
  7453.     end
  7454.  
  7455. select @size_in_blocks = @datasize1 * 512.
  7456.  
  7457. disk init
  7458.     name = @datalogical1,
  7459.     physname = @dataphysical1,
  7460.     size = @size_in_blocks,
  7461.     vdevno = @vdevno
  7462.  
  7463. if @@error <> 0
  7464.     begin
  7465.         raiserror(15263,-1,-1,'data')
  7466.         exec sp_dbremove @dbname,dropdev
  7467.         return(1)
  7468.     end
  7469.  
  7470. select @exec_str = 'alter database '+@dbname+' on '+@datalogical1+
  7471.             ' = '+convert(varchar(5),@datasize1)
  7472. exec(@exec_str)
  7473.  
  7474. if @@error <> 0
  7475.     begin
  7476.         raiserror(15264,-1,-1,'data')
  7477.         exec sp_dbremove @dbname,dropdev
  7478.         return(1)
  7479.     end
  7480.  
  7481. /* Set sysusages.segmap to 'data only' for data fragment. */
  7482. update sysusages set segmap = 2
  7483.     where vstart =
  7484.         (select low from sysdevices where name = @datalogical1)
  7485.  
  7486. if @@error <> 0
  7487.     begin
  7488.         raiserror(15265,-1,-1)
  7489.         exec sp_dbremove @dbname,dropdev
  7490.         return(1)
  7491.     end
  7492.  
  7493. dbcc dbrepair (@dbname,remap) with no_infomsgs
  7494.  
  7495. /* Check out optional data devices. */
  7496.  
  7497. if @datalogical2 is not null
  7498.     begin
  7499.         exec @retcode = sp_devcreate @dbname,@datalogical2,@dataphysical2,@datasize2
  7500.         if @retcode <> 0
  7501.             begin
  7502.                 raiserror(15269,-1,-1,@datalogical2)
  7503.                 exec sp_dbremove @dbname,dropdev
  7504.                 return(1)
  7505.             end
  7506.         select @numdevs = 2
  7507.     end
  7508. else goto no_more_devs
  7509.  
  7510. if @datalogical3 is not null
  7511.     begin
  7512.         exec @retcode = sp_devcreate @dbname,@datalogical3,@dataphysical3,@datasize3
  7513.         if @retcode <> 0
  7514.             begin
  7515.                 raiserror(15269,-1,-1,@datalogical3)
  7516.                 exec sp_dbremove @dbname,dropdev
  7517.                 return(1)
  7518.             end
  7519.         select @numdevs = @numdevs + 1
  7520.     end
  7521. else goto no_more_devs
  7522.  
  7523. if @datalogical4 is not null
  7524.     begin
  7525.         exec @retcode = sp_devcreate @dbname,@datalogical4,@dataphysical4,@datasize4
  7526.         if @retcode <> 0
  7527.             begin
  7528.                 raiserror(15269,-1,-1,@datalogical4)
  7529.                 exec sp_dbremove @dbname,dropdev
  7530.                 return(1)
  7531.             end
  7532.         select @numdevs = @numdevs + 1
  7533.     end
  7534. else goto no_more_devs
  7535.  
  7536. if @datalogical5 is not null
  7537.     begin
  7538.         exec @retcode = sp_devcreate @dbname,@datalogical5,@dataphysical5,@datasize5
  7539.         if @retcode <> 0
  7540.             begin
  7541.                 raiserror(15269,-1,-1,@datalogical5)
  7542.                 exec sp_dbremove @dbname,dropdev
  7543.                 return(1)
  7544.             end
  7545.         select @numdevs = @numdevs + 1
  7546.     end
  7547. else goto no_more_devs
  7548.  
  7549. if @datalogical6 is not null
  7550.     begin
  7551.         exec @retcode = sp_devcreate @dbname,@datalogical6,@dataphysical6,@datasize6
  7552.         if @retcode <> 0
  7553.             begin
  7554.                 raiserror(15269,-1,-1,@datalogical6)
  7555.                 exec sp_dbremove @dbname,dropdev
  7556.                 return(1)
  7557.             end
  7558.         select @numdevs = @numdevs + 1
  7559.     end
  7560. else goto no_more_devs
  7561.  
  7562. if @datalogical7 is not null
  7563.     begin
  7564.         exec @retcode = sp_devcreate @dbname,@datalogical7,@dataphysical7,@datasize7
  7565.         if @retcode <> 0
  7566.             begin
  7567.                 raiserror(15269,-1,-1,@datalogical7)
  7568.                 exec sp_dbremove @dbname,dropdev
  7569.                 return(1)
  7570.             end
  7571.         select @numdevs = @numdevs + 1
  7572.     end
  7573. else goto no_more_devs
  7574.  
  7575. if @datalogical8 is not null
  7576.     begin
  7577.         exec @retcode = sp_devcreate @dbname,@datalogical8,@dataphysical8,@datasize8
  7578.         if @retcode <> 0
  7579.             begin
  7580.                 raiserror(15269,-1,-1,@datalogical8)
  7581.                 exec sp_dbremove @dbname,dropdev
  7582.                 return(1)
  7583.             end
  7584.         select @numdevs = @numdevs + 1
  7585.     end
  7586. else goto no_more_devs
  7587.  
  7588. if @datalogical9 is not null
  7589.     begin
  7590.         exec @retcode = sp_devcreate @dbname,@datalogical9,@dataphysical9,@datasize9
  7591.         if @retcode <> 0
  7592.             begin
  7593.                 raiserror(15269,-1,-1,@datalogical9)
  7594.                 exec sp_dbremove @dbname,dropdev
  7595.                 return(1)
  7596.             end
  7597.         select @numdevs = @numdevs + 1
  7598.     end
  7599. else goto no_more_devs
  7600.  
  7601. if @datalogical10 is not null
  7602.     begin
  7603.         exec @retcode = sp_devcreate @dbname,@datalogical10,@dataphysical10,@datasize10
  7604.         if @retcode <> 0
  7605.             begin
  7606.                 raiserror(15269,-1,-1,@datalogical10)
  7607.                 exec sp_dbremove @dbname,dropdev
  7608.                 return(1)
  7609.             end
  7610.         select @numdevs = @numdevs + 1
  7611.     end
  7612. else goto no_more_devs
  7613.  
  7614. if @datalogical11 is not null
  7615.     begin
  7616.         exec @retcode = sp_devcreate @dbname,@datalogical11,@dataphysical11,@datasize11
  7617.         if @retcode <> 0
  7618.             begin
  7619.                 raiserror(15269,-1,-1,@datalogical11)
  7620.                 exec sp_dbremove @dbname,dropdev
  7621.                 return(1)
  7622.             end
  7623.         select @numdevs = @numdevs + 1
  7624.     end
  7625. else goto no_more_devs
  7626.  
  7627. if @datalogical12 is not null
  7628.     begin
  7629.         exec @retcode = sp_devcreate @dbname,@datalogical12,@dataphysical12,@datasize12
  7630.         if @retcode <> 0
  7631.             begin
  7632.                 raiserror(15269,-1,-1,@datalogical12)
  7633.                 exec sp_dbremove @dbname,dropdev
  7634.                 return(1)
  7635.             end
  7636.         select @numdevs = @numdevs + 1
  7637.     end
  7638. else goto no_more_devs
  7639.  
  7640. if @datalogical13 is not null
  7641.     begin
  7642.         exec @retcode = sp_devcreate @dbname,@datalogical13,@dataphysical13,@datasize13
  7643.         if @retcode <> 0
  7644.             begin
  7645.                 raiserror(15269,-1,-1,@datalogical13)
  7646.                 exec sp_dbremove @dbname,dropdev
  7647.                 return(1)
  7648.             end
  7649.         select @numdevs = @numdevs + 1
  7650.     end
  7651. else goto no_more_devs
  7652.  
  7653. if @datalogical14 is not null
  7654.     begin
  7655.         exec @retcode = sp_devcreate @dbname,@datalogical14,@dataphysical14,@datasize14
  7656.         if @retcode <> 0
  7657.             begin
  7658.                 raiserror(15269,-1,-1,@datalogical14)
  7659.                 exec sp_dbremove @dbname,dropdev
  7660.                 return(1)
  7661.             end
  7662.         select @numdevs = @numdevs + 1
  7663.     end
  7664. else goto no_more_devs
  7665.  
  7666. if @datalogical15 is not null
  7667.     begin
  7668.         exec @retcode = sp_devcreate @dbname,@datalogical15,@dataphysical15,@datasize15
  7669.         if @retcode <> 0
  7670.             begin
  7671.                 raiserror(15269,-1,-1,@datalogical15)
  7672.                 exec sp_dbremove @dbname,dropdev
  7673.                 return(1)
  7674.             end
  7675.         select @numdevs = @numdevs + 1
  7676.     end
  7677. else goto no_more_devs
  7678.  
  7679. if @datalogical16 is not null
  7680.     begin
  7681.         exec @retcode = sp_devcreate @dbname,@datalogical16,@dataphysical16,@datasize16
  7682.         if @retcode <> 0
  7683.             begin
  7684.                 raiserror(15269,-1,-1,@datalogical16)
  7685.                 exec sp_dbremove @dbname,dropdev
  7686.                 return(1)
  7687.             end
  7688.         select @numdevs = @numdevs + 1
  7689.     end
  7690.  
  7691. no_more_devs:
  7692.  
  7693. /* Get next available device number for log segment. */
  7694. select @vdevno = null
  7695. select @vdevno = (min(low)/0x01000000)+1
  7696.     from sysdevices d1
  7697.     where low/0x01000000 between 0 and 254
  7698.         and not exists
  7699.             (select * from sysdevices d2
  7700.             where d2.low/0x01000000 = (d1.low/0x01000000)+1)
  7701.  
  7702. if @vdevno is null or @@error <> 0
  7703.     begin
  7704.         raiserror(15054,-1,-1)
  7705.         exec sp_dbremove @dbname,dropdev
  7706.         return(1)
  7707.     end
  7708.  
  7709. select @size_in_blocks = @logsize * 512.
  7710.  
  7711. disk init
  7712.     name = @loglogical,
  7713.     physname = @logphysical,
  7714.     size = @size_in_blocks,
  7715.     vdevno = @vdevno
  7716.  
  7717. if @@error <> 0
  7718.     begin
  7719.         raiserror(15263,-1,-1,'log')
  7720.         exec sp_dbremove @dbname,dropdev
  7721.         return(1)
  7722.     end
  7723.  
  7724. select @exec_str = 'alter database '+@dbname+' on '+@loglogical+
  7725.             ' = '+convert(varchar(5),@logsize)
  7726. exec(@exec_str)
  7727.  
  7728. if @@error <> 0
  7729.     begin
  7730.         raiserror(15264,-1,-1,'log')
  7731.         exec sp_dbremove @dbname,dropdev
  7732.         return(1)
  7733.     end
  7734.  
  7735. /* Set sysusages.segmap to 'log' for log fragment. */
  7736. update sysusages set segmap = 4
  7737.     where vstart =
  7738.         (select low from sysdevices where name = @loglogical)
  7739.  
  7740. if @@error <> 0
  7741.     begin
  7742.         raiserror(15265,-1,-1)
  7743.         exec sp_dbremove @dbname,dropdev
  7744.         return(1)
  7745.     end
  7746.  
  7747. dbcc dbrepair (@dbname,remap) with no_infomsgs
  7748.  
  7749. /* Set sysusages.segmap to 'system' for system fragment. */
  7750. update sysusages set segmap = 1
  7751.     where vstart =
  7752.         (select low from sysdevices where name = @syslogical)
  7753.  
  7754. if @@error <> 0
  7755.     begin
  7756.         raiserror(15265,-1,-1)
  7757.         exec sp_dbremove @dbname,dropdev
  7758.         return(1)
  7759.     end
  7760.  
  7761. dbcc dbrepair (@dbname,remap) with no_infomsgs
  7762.  
  7763. return(0)
  7764.  
  7765. go
  7766.  
  7767. print ''
  7768. print 'Creating procedure sp_defaultdb.'
  7769. go
  7770. create procedure sp_defaultdb
  7771. @loginame varchar(30),            /* login name of the user */
  7772. @defdb varchar(30)             /* default db for the user */
  7773. as
  7774.  
  7775. declare @suid int        /* the suid to use to qualify the change */
  7776.  
  7777. /*
  7778. **  If we're in a transaction, disallow this since it might make recovery
  7779. **  impossible.
  7780. */
  7781. if @@trancount > 0
  7782.     begin
  7783.         raiserror(15002,-1,-1,'sp_defaultdb')
  7784.         return (1)
  7785.     end
  7786.  
  7787. /*
  7788. **  Check that the account exists.
  7789. */
  7790. if not exists (select * from syslogins where name = @loginame)
  7791.     begin
  7792.         raiserror(15007,-1,-1,@loginame)
  7793.         return (1)
  7794.     end
  7795.  
  7796. /*
  7797. **  Check that the database name is valid.
  7798. */
  7799. if not exists (select * from sysdatabases where name = @defdb)
  7800.     begin
  7801.         raiserror(15010,-1,-1,@defdb)
  7802.         return (1)
  7803.     end
  7804.  
  7805. /*
  7806. **  Both the owner of the account (@loginame) and the SA can run this
  7807. **  command.  If the SA is running it, set @suid to the suid of @loginame.
  7808. */
  7809. select @suid = suser_id()
  7810. if @suid = 1
  7811.     begin
  7812.         /*
  7813.         **  Get the suid for @loginame.  We know it exists because we
  7814.         **  checked above.
  7815.         */
  7816.         select @suid = suid from syslogins where name = @loginame
  7817.     end
  7818.  
  7819. /*
  7820. **  Change the database
  7821. */
  7822. update syslogins set dbname = @defdb
  7823.     where suid = @suid
  7824.     and name = @loginame
  7825.  
  7826. /*
  7827. **  If nothing got updated then it means that the the user tried to change
  7828. **  someone else's default.
  7829. */
  7830. if @@rowcount < 1
  7831.     begin
  7832.         raiserror(15132,-1,-1)
  7833.         return (1)
  7834.     end
  7835.  
  7836. print 'Default database changed.'
  7837.  
  7838. return (0)
  7839. go
  7840.  
  7841. print ''
  7842. print 'Creating procedure sp_depends.'
  7843. go
  7844. create procedure sp_depends
  7845. @objname varchar(92)        /* the object we want to check */
  7846. as
  7847.  
  7848. declare @objid int            /* the id of the object we want */
  7849. declare @found_some bit            /* flag for dependencies found */
  7850. declare @dbname varchar(30)
  7851.  
  7852. /*
  7853. **  Make sure the @objname is local to the current database.
  7854. */
  7855. if @objname like '%.%.%' and
  7856.     substring(@objname, 1, charindex('.', @objname) - 1) <> db_name()
  7857.     begin
  7858.         raiserror(15250,-1,-1)
  7859.         return (1)
  7860.     end
  7861.  
  7862. /*
  7863. **  See if @objname exists.
  7864. */
  7865. select @objid = object_id(@objname), @dbname=db_name()
  7866. if @objid is null
  7867.     begin
  7868.         raiserror(15009,-1,-1,@objname,@dbname)
  7869.         return (1)
  7870.     end
  7871.  
  7872. /*
  7873. **  Initialize @found_some to indicate that we haven't seen any dependencies.
  7874. */
  7875. select @found_some = 0
  7876.  
  7877. set nocount on
  7878.  
  7879. /*
  7880. **  Print out the particulars about the local dependencies.
  7881. */
  7882. if exists (select *
  7883.         from sysdepends
  7884.             where id = @objid)
  7885. begin
  7886.     print 'In the current database the specified object references the following:'
  7887.     select 'name' =    substring((s.name + '.' + o.name), 1, 40),
  7888.         type = substring(v.name, 1, 16),
  7889.         updated = substring(u.name, 1, 7),
  7890.         selected = substring(w.name, 1, 8)
  7891.             from sysobjects o, master.dbo.spt_values v, sysdepends d,
  7892.                 master.dbo.spt_values u, master.dbo.spt_values w,
  7893.                 sysusers s
  7894.             where o.id = d.depid
  7895.                 and o.sysstat & 0xf = v.number and v.type = 'O'
  7896.                 and u.type = 'B' and u.number = d.resultobj
  7897.                 and w.type = 'B' and w.number = d.readobj|d.selall
  7898.                 and d.id = @objid
  7899.                 and o.uid = s.uid
  7900.     select @found_some = 1
  7901. end
  7902.  
  7903. /*
  7904. **  Now check for things that depend on the object.
  7905. */
  7906. if exists (select *
  7907.         from sysdepends
  7908.             where depid = @objid)
  7909. begin
  7910.     print 'In the current database the specified object is referenced by the following:'
  7911.     select distinct 'name' = substring((s.name + '.' + o.name), 1, 40),
  7912.         type = substring(v.name, 1, 16)
  7913.             from sysobjects o, master.dbo.spt_values v, sysdepends d,
  7914.                 sysusers s
  7915.             where o.id = d.id
  7916.                 and o.sysstat & 0xf = v.number and v.type = 'O'
  7917.                 and d.depid = @objid
  7918.                 and o.uid = s.uid
  7919.     select @found_some = 1
  7920. end
  7921.  
  7922. /*
  7923. **  Did we find anything in sysdepends?
  7924. */
  7925. if @found_some = 0
  7926.     print 'Object doesn''t reference any object and no objects reference it.'
  7927.  
  7928. set nocount off
  7929.  
  7930. return (0)
  7931. go
  7932.  
  7933. print ''
  7934. print 'Creating procedure sp_devoption.'
  7935. go
  7936. create procedure sp_devoption
  7937. @devname varchar(30) = NULL,        -- device name to change
  7938. @optname varchar(20) = NULL,        -- option name to turn on/off
  7939. @optvalue varchar(10) = NULL,        -- true or false
  7940. @override varchar(8)=    NULL
  7941. as
  7942. declare @statvalue int
  7943. declare @optcount int
  7944.  
  7945. select @optname=lower(@optname)
  7946. select @optvalue=lower(@optvalue)
  7947. select @override=lower(@override)
  7948.  
  7949. /*
  7950. ** If no parameters were supplied, list settable options.
  7951. */
  7952. if @devname is null
  7953.      begin
  7954.         select 'Settable device options:' = name
  7955.             from master.dbo.spt_values
  7956.             where type = 'V'
  7957.                 and number in (4096,8192)
  7958.             order by name
  7959.         return (0)
  7960.     end
  7961.  
  7962. /*
  7963. ** Verify that device exists.
  7964. */
  7965. if not exists (select * from sysdevices where name=@devname)
  7966.     begin
  7967.         raiserror(15012,-1,-1,@devname)
  7968.         return (1)
  7969.     end
  7970.  
  7971. /*
  7972. ** If no option was supplied, display current settings.
  7973. */
  7974. if @optname is null
  7975.     begin
  7976.         select 'The following options are set:' = v.name
  7977.             from spt_values v, sysdevices d
  7978.             where d.name=@devname
  7979.                 and v.type = 'V'
  7980.                 and (v.number & d.status)=v.number
  7981.                 and v.number in (4096,8192)
  7982.         return(0)
  7983.     end
  7984.  
  7985. /*
  7986. ** Can't change settings for 'master' device.
  7987. */
  7988. if @devname = 'master'
  7989.     begin
  7990.         raiserror(15133,-1,-1)
  7991.         return (1)
  7992.     end
  7993.  
  7994. /*
  7995. **  Use @optname and try to find the right option.
  7996. **  If there isn't just one, print appropriate diagnostics and return.
  7997. */
  7998. select @statvalue = min(number), @optcount = count(*)
  7999.     from master.dbo.spt_values
  8000.     where lower(name) like '%' + @optname + '%'
  8001.         and type = 'V'
  8002.         and number in (4096,8192)
  8003.  
  8004. if @optcount = 0
  8005.     begin
  8006.         raiserror(15013,-1,-1,@optname)
  8007.         select 'Settable device options:' = name
  8008.             from master.dbo.spt_values
  8009.             where type = 'V'
  8010.                 and number in (4096,8192)
  8011.             order by name
  8012.         return (1)
  8013.     end
  8014.  
  8015. /*
  8016. **  If more than one option like @optname, show the duplicates and return.
  8017. */
  8018. if @optcount > 1
  8019. begin
  8020.     raiserror(15135,-1,-1,@optname)
  8021.     select duplicate_options = name
  8022.         from master.dbo.spt_values
  8023.         where lower(name) like '%' + @optname + '%'
  8024.             and type = 'V'
  8025.             and number in (4096,8192)
  8026.     return (1)
  8027. end
  8028.  
  8029. /*
  8030. **  Check optvalue.
  8031. */
  8032. if @optvalue not in ('true', 'false') or @optvalue is null
  8033.     begin
  8034.         raiserror(15136,-1,-1)
  8035.         return (1)
  8036.     end
  8037.  
  8038. /*
  8039. **  Check @override.
  8040. */
  8041. if @override <> 'override' and @override is not null
  8042.     begin
  8043.         raiserror(15281,-1,-1,@override)
  8044.         return(1)
  8045.     end
  8046.  
  8047. /*
  8048. **  Can only supply @override if setting 'read only' device option.
  8049. */
  8050. if @override is not null and not exists
  8051.     (select * from spt_values where type = 'V' and
  8052.         lower(name) like '%' + @optname + '%'
  8053.         and number = 4096)
  8054.     begin
  8055.         raiserror(15282,-1,-1)
  8056.         return(1)
  8057.     end
  8058.  
  8059. /*
  8060. **  Only the SA can execute the update part of this procedure.
  8061. */
  8062. if suser_id() <> 1
  8063.     begin
  8064.         raiserror(15137,-1,-1)
  8065.         return (1)
  8066.     end
  8067.  
  8068. /*
  8069. **  If we're in a transaction, disallow this since it might make recovery
  8070. **  impossible.
  8071. */
  8072.  
  8073. if @@trancount > 0
  8074.     begin
  8075.         raiserror(15002,-1,-1,'sp_devoption')
  8076.         return (1)
  8077.     end
  8078.  
  8079. /*
  8080. **  Get the number which is the bit value to set
  8081. */
  8082. select @statvalue = number
  8083.     from master.dbo.spt_values
  8084.     where lower(name) = @optname and type = 'V'
  8085.         and number in (4096,8192)
  8086.  
  8087. /*
  8088. ** If setting device to 'read only', make certain that all databases
  8089. ** on that device have been set to 'read only' or that user specified
  8090. ** override.
  8091. */
  8092. if @statvalue = 4096 and isnull(@override,'no override') <> 'override'
  8093.     and @optvalue='true'
  8094.     and exists (select * from sysdatabases d, sysusages u, sysdevices v
  8095.                     where  d.dbid = u.dbid
  8096.                     and u.vstart between v.low and v.high
  8097.                     and v.name = @devname
  8098.                     and (d.status&1024)=0)
  8099.     begin
  8100.         raiserror(15138,-1,-1)
  8101.         select distinct 'Writable database(s)' = d.name
  8102.             from sysdatabases d, sysusages u, sysdevices v
  8103.                 where  d.dbid = u.dbid
  8104.                 and u.vstart between v.low and v.high
  8105.                 and v.name = @devname
  8106.                 and (d.status&1024)=0
  8107.         return (1)
  8108.     end
  8109.  
  8110. if @optvalue='true'
  8111.     update sysdevices set status=status|@statvalue where name=@devname
  8112. else if lower(@optvalue)='false'
  8113.     update sysdevices set status=status & (~@statvalue) where name=@devname
  8114.  
  8115. print 'Device option set.'
  8116. return (0)
  8117. go
  8118.  
  8119. print ''
  8120. print 'Creating procedure sp_diskdefault.'
  8121. go
  8122. create procedure sp_diskdefault
  8123. @logicalname    varchar(30),        /* logical name of the device */
  8124. @defstatus    varchar(15)        /* turn on or off */
  8125. as
  8126.  
  8127. /*
  8128. **  If we're in a transaction, disallow this since it might make recovery
  8129. **  impossible.
  8130. */
  8131. if @@trancount > 0
  8132.     begin
  8133.            raiserror(15002,-1,-1,'sp_diskdefault')
  8134.        return (1)
  8135.     end
  8136.  
  8137. /*
  8138. **  Only the SA can run this sproc.
  8139. */
  8140. if suser_id() <> 1
  8141.     begin
  8142.         raiserror(15003,-1,-1)
  8143.         return (1)
  8144.     end
  8145.  
  8146. /*
  8147. **  Make sure that a device with @logicalname exists.
  8148. */
  8149. if not exists (select * from sysdevices where name = @logicalname)
  8150.     begin
  8151.         raiserror(15012,-1,-1,@logicalname)
  8152.         return (1)
  8153.     end
  8154.  
  8155. /*
  8156. **  Make sure that it is a database disk and not a dump device.
  8157. */
  8158. if exists (select * from sysdevices
  8159.         where name = @logicalname
  8160.             and status & 16 = 16)
  8161.     begin
  8162.         raiserror(15035,-1,-1,@logicalname)
  8163.         return (1)
  8164.     end
  8165.  
  8166. /*
  8167. **  Make sure that the database disk is NOT a RAM device.
  8168. */
  8169. if exists (select *
  8170.         from sysdevices
  8171.         where name = @logicalname
  8172.             and status & 2048 = 2048 )
  8173.     begin
  8174.         raiserror(15139,-1,-1)
  8175.         return (1)
  8176.     end
  8177.  
  8178. if @defstatus = 'defaulton'
  8179.     begin
  8180.         update sysdevices set status = status | 1
  8181.             where name = @logicalname
  8182.         return (0)
  8183.     end
  8184.  
  8185. if @defstatus = 'defaultoff'
  8186.     begin
  8187.         update sysdevices set status = status & ~1
  8188.             where name = @logicalname
  8189.         return (0)
  8190.     end
  8191.  
  8192. /*
  8193. **  @defstatus must be 'defaulton' or 'defaultoff'
  8194. */
  8195. raiserror(15140,-1,-1)
  8196.  
  8197. return (1)
  8198. go
  8199.  
  8200. dump tran master with no_log
  8201. go
  8202.  
  8203. print ''
  8204. print 'Creating procedure sp_dropalias.'
  8205. go
  8206. create procedure sp_dropalias
  8207. @loginame varchar(30)        /* account name of the user with the alias */
  8208. as
  8209.  
  8210. /*
  8211. **  You must be SA or the dbo to execute this sproc.
  8212. */
  8213. if suser_id() <> 1 and user_id() <> 1
  8214. begin
  8215.     raiserror(15000,-1,-1)
  8216.     return (1)
  8217. end
  8218.  
  8219. /*
  8220. **  Check to make sure that the @loginame has an account.
  8221. */
  8222. if (select suser_id(@loginame)) is null
  8223. begin
  8224.     raiserror(15007,-1,-1,@loginame)
  8225.     return (1)
  8226. end
  8227.  
  8228. /*
  8229. **  Delete the alias, if any, from sysalternates.
  8230. */
  8231. delete from sysalternates
  8232.     where suid = suser_id(@loginame)
  8233.  
  8234. /*
  8235. **  If nothing happened (rowcount = 0), there was no alias.
  8236. */
  8237. if @@rowcount > 0
  8238.     begin
  8239.         print 'Alias user dropped.'
  8240.         return (0)
  8241.     end
  8242. else
  8243.     begin
  8244.         raiserror(15134,-1,-1)
  8245.         return (1)
  8246.     end
  8247. go
  8248.  
  8249. print ''
  8250. print 'Creating procedure sp_dropdevice.'
  8251. go
  8252. create procedure sp_dropdevice
  8253. @logicalname    varchar(30),        -- logical name of the device
  8254. @delfile    varchar(7) = null    -- optional param. to delete disk file
  8255. as
  8256.  
  8257. declare @physname varchar(255)
  8258. declare @ctrltype smallint
  8259. declare @msg varchar(255)
  8260. declare @cmd varchar(255)
  8261.  
  8262. /*
  8263. ** See if user specified something for @delfile and, if so, validate it.
  8264. */
  8265. if @delfile is not null
  8266.     begin
  8267.         select @delfile = lower(@delfile)
  8268.  
  8269.         if @delfile <> 'delfile'
  8270.             begin
  8271.                 raiserror(15216,-1,-1,@delfile)
  8272.                 return(1)
  8273.             end
  8274.     end
  8275.  
  8276. /*
  8277. **  If we're in a transaction, disallow this since it might make recovery
  8278. **  impossible.
  8279. */
  8280. if @@trancount > 0
  8281.     begin
  8282.         raiserror(15002,-1,-1,'sp_dropdevice')
  8283.         return (1)
  8284.     end
  8285.  
  8286. /*
  8287. **  Only the system administrator (SA) can run this command.
  8288. **  Check to make sure the executor is the sa.
  8289. */
  8290. if suser_id() <> 1
  8291.     begin
  8292.         raiserror(15003,-1,-1)
  8293.         return (1)
  8294.     end
  8295.  
  8296. /*
  8297. **  Check and make sure that the device actually exists.
  8298. */
  8299. if not exists (select * from sysdevices where name = @logicalname)
  8300.     begin
  8301.         raiserror(15012,-1,-1,@logicalname)
  8302.         return (1)
  8303.     end
  8304.  
  8305. /*
  8306. **  Check and make sure that no database is using the device.
  8307. **  If so, print out who is using it and exit.
  8308. */
  8309. if exists (select *
  8310.     from sysdatabases s, sysusages u, sysdevices d,
  8311.         master.dbo.spt_values p
  8312.     where s.dbid = u.dbid
  8313.         and u.segmap >= 0
  8314.         and d.low <= u.size + u.vstart
  8315.         and d.high >= u.size + u.vstart - 1
  8316.         and d.status & 2 = 2
  8317.         and p.type = 'S'
  8318.         and d.name = @logicalname)
  8319. begin
  8320.     raiserror(15141,-1,-1)
  8321.  
  8322.     select distinct 'Device used by database(s):' = s.name
  8323.         from sysdatabases s, sysusages u, sysdevices d,
  8324.             master.dbo.spt_values p
  8325.         where s.dbid = u.dbid
  8326.             and u.segmap >= 0
  8327.             and d.low <= u.size + u.vstart
  8328.             and d.high >= u.size + u.vstart - 1
  8329.             and d.status & 2 = 2
  8330.             and p.type = 'S'
  8331.             and p.number >= 0
  8332.             and d.name = @logicalname
  8333.     order by s.name
  8334.  
  8335.     return (1)
  8336. end
  8337.  
  8338. select @physname = phyname,@ctrltype = cntrltype
  8339.         from sysdevices
  8340.         where name = @logicalname
  8341.  
  8342. if @ctrltype <> 6    -- Can't release file handle for 'pipe' device.
  8343.     begin
  8344.         /*
  8345.         ** Release file handle for physical devices.
  8346.         */
  8347.         dbcc devcontrol(@logicalname,offline)
  8348.  
  8349.         if @@error in (0,5154)    -- 5154 => Device is not open.
  8350.             begin
  8351.                 select @msg = 'File: '''+@physname+''' closed.'
  8352.                 print @msg
  8353.  
  8354.                 /*
  8355.                 ** Drop the device.
  8356.                 */
  8357.                 delete from sysdevices
  8358.                     where name = @logicalname
  8359.                 print 'Device dropped.'
  8360.  
  8361.                 if @delfile = 'delfile'
  8362.                     begin
  8363.                         select @cmd = 'del '+@physname
  8364.                         select @cmd = 'xp_cmdshell '''+@cmd+''''
  8365.                         exec (@cmd)
  8366.  
  8367.                         /* See if the delete was successful. */
  8368.                         exec('dbcc devcontrol(''' +
  8369.                             @physname +
  8370.                             ''',filesize) with no_infomsgs')
  8371.                         if @@error <> 0 /* => file can't be opened. */
  8372.                             begin
  8373.                                 print 'Couldn''t delete device file'
  8374.                                 return(1)
  8375.                             end
  8376.                         else
  8377.                             print 'Physical file deleted.'
  8378.                     end
  8379.             end
  8380.         else return(1)
  8381.     end
  8382.  
  8383. return (0)
  8384. go
  8385.  
  8386. print ''
  8387. print 'Creating procedure sp_dropextendedproc.'
  8388. go
  8389. create procedure sp_dropextendedproc
  8390. @functname varchar(30)        /* name of function */
  8391. as
  8392. /*
  8393. **  If we're in a transaction, disallow the dropping of the
  8394. **  extended stored procedure.
  8395. */
  8396. if @@trancount > 0
  8397.     begin
  8398.         raiserror(15002,-1,-1,'sp_dropextendedproc')
  8399.         return (1)
  8400.     end
  8401.  
  8402. /*
  8403. ** Drop the extended procedure mapping.
  8404. */
  8405. dbcc dropextendedproc( @functname )
  8406. return (0)
  8407. go
  8408.  
  8409. print ''
  8410. print 'Creating procedure sp_dropgroup.'
  8411. go
  8412. create procedure sp_dropgroup
  8413. @grpname varchar(30)        /* group to be dropped */
  8414. as
  8415.  
  8416. declare @gid int        /* group id of the group to be dropped */
  8417.  
  8418. /*
  8419. **  You must be SA or the dbo to execute this sproc.
  8420. */
  8421. if suser_id() <> 1 and user_id() <> 1
  8422.     begin
  8423.         raiserror(15000,-1,-1)
  8424.         return (1)
  8425.     end
  8426.  
  8427. /*
  8428. **  See if the group exists.
  8429. **  User ids are <= 16383 and group ids are > 16383.
  8430. */
  8431. select @gid = (select uid
  8432.     from sysusers
  8433.         where name = @grpname
  8434.             and (uid > 16383 or uid = 0))
  8435.  
  8436. if @gid is null
  8437.     begin
  8438.         raiserror(15014,-1,-1,@grpname)
  8439.         return (1)
  8440.     end
  8441.  
  8442. /*
  8443. **  Can't drop the group public.
  8444. */
  8445. if @gid = 0
  8446.     begin
  8447.         raiserror(15142,-1,-1)
  8448.         return (1)
  8449.     end
  8450.  
  8451. /*
  8452. **  Check to see that nobody is in the group.  If so, return.
  8453. */
  8454. if (select count(*) from sysusers where gid = @gid and uid <= 16383) <> 0
  8455.     begin
  8456.         raiserror(15144,-1,-1)
  8457.  
  8458.         /*
  8459.         **  Show who is in the group.
  8460.         */
  8461.         select name from sysusers
  8462.             where gid = @gid
  8463.             and uid <= 16383
  8464.  
  8465.         return (1)
  8466.     end
  8467.  
  8468. /*
  8469. **  Drop the group.
  8470. **  Also drop any references to the group in the sysprotects table.
  8471. */
  8472. begin transaction
  8473.  
  8474.     delete from sysusers
  8475.         where uid = @gid
  8476.  
  8477.     delete from sysprotects
  8478.         where uid = @gid
  8479.  
  8480. commit transaction
  8481.  
  8482. print 'Group has been dropped.'
  8483.  
  8484. return (0)
  8485. go
  8486.  
  8487. print ''
  8488. print 'Creating procedure sp_dropkey.'
  8489. go
  8490. create procedure sp_dropkey
  8491. @keytype varchar(10),             /* type of key to drop */
  8492. @tabname varchar(92),            /* table with the key */
  8493. @deptabname varchar(92) = null        /* dependent table */
  8494. as
  8495.  
  8496. declare @id int                /* id of @tabname */
  8497. declare @uid smallint            /* owner of @tabname */
  8498. declare @depid int            /* id of related table */
  8499. declare @depuid smallint        /* owner of @related table */
  8500. declare @dbname varchar(30)
  8501.  
  8502. /*
  8503. **  First make sure that the key type is ok.
  8504. */
  8505. if lower(@keytype) not in ('primary', 'foreign', 'common')
  8506.     begin
  8507.         raiserror(15145,-1,-1)
  8508.         return (1)
  8509.     end
  8510.  
  8511. /*
  8512. **  Check to see that the tabname is local.
  8513. */
  8514. if @tabname like '%.%.%'
  8515.     and substring(@tabname, 1, charindex('.', @tabname) - 1) <> db_name()
  8516.     begin
  8517.         raiserror(15078,-1,-1)
  8518.         return (1)
  8519.     end
  8520.  
  8521. if @deptabname like '%.%.%'
  8522.     and substring(@deptabname, 1, charindex('.', @deptabname) - 1) <> db_name()
  8523.     begin
  8524.         raiserror(15078,-1,-1)
  8525.         return (1)
  8526.     end
  8527.  
  8528. /*
  8529. **  Get the ids of the @tabname and @deptabname.
  8530. */
  8531. select @id = id, @depid = object_id(@deptabname), @uid = uid
  8532.         from sysobjects
  8533.             where id = object_id(@tabname)
  8534. if @id is null
  8535.     begin
  8536.         select @dbname = db_name()
  8537.         raiserror(15009,-1,-1,@tabname,@dbname)
  8538.         return (1)
  8539.     end
  8540.  
  8541. if @uid <> user_id()
  8542.     begin
  8543.         raiserror(15146,-1,-1)
  8544.         return (1)
  8545.     end
  8546.  
  8547. /*
  8548. **  If primary key, just drop it.
  8549. */
  8550. if lower(@keytype) = 'primary'
  8551.     begin
  8552.         delete from syskeys where id = @id and type = 1
  8553.  
  8554.         if @@rowcount = 0
  8555.             begin
  8556.                 raiserror(15147,-1,-1)
  8557.                 return (1)
  8558.             end
  8559.  
  8560.         else
  8561.             print 'Primary key for the table or view dropped.'
  8562.  
  8563.         /*
  8564.         **  Check to see if there are any foreign keys dependent on the
  8565.         **  primary key.  If so -- drop them.
  8566.         */
  8567.         delete from syskeys where depid = @id and type = 2
  8568.  
  8569.         if @@rowcount <> 0
  8570.             print 'Dependent foreign keys were also dropped.'
  8571.  
  8572.         return (0)
  8573.     end
  8574.  
  8575. /*
  8576. **  It's either a foreign or common key so we need to verify the
  8577. **  existence of the @deptabname.
  8578. */
  8579. if @depid is null
  8580.     begin
  8581.         /*
  8582.         **  Was the @deptabname supplied?
  8583.         */
  8584.         if @deptabname is null
  8585.             begin
  8586.                 raiserror(15148,-1,-1)
  8587.                 return (1)
  8588.             end
  8589.  
  8590.         /*
  8591.         **  It was supplied but it doesn't exist.
  8592.         */
  8593.         raiserror(15081,-1,-1)
  8594.         return (1)
  8595.     end
  8596.  
  8597.  
  8598. /*
  8599. **  If foreign key, get rid of it.
  8600. */
  8601. if lower(@keytype) = 'foreign'
  8602.     begin
  8603.         /*
  8604.         **  Get rid of the foreign key entry.
  8605.         */
  8606.         delete from syskeys
  8607.             where type = 2
  8608.             and id = @id
  8609.             and depid = @depid
  8610.  
  8611.         if @@rowcount = 0
  8612.             begin
  8613.                 raiserror(15149,-1,-1)
  8614.                 return (1)
  8615.             end
  8616.  
  8617.         print 'Foreign key dropped.'
  8618.  
  8619.         return (0)
  8620.     end
  8621.  
  8622. /*
  8623. **  Key type must be common so just get rid of the common keys
  8624. **  with the right ids and depids.  Since whenever a common key is defined
  8625. **  it is added to both of the tables involved, we'll get rid of both of
  8626. **  those entries.
  8627. */
  8628. delete from syskeys
  8629.     where type = 3
  8630.         and id = @id
  8631.         and depid = @depid
  8632.  
  8633. if @@rowcount = 0
  8634.     begin
  8635.         raiserror(15150,-1,-1)
  8636.         return (1)
  8637.     end
  8638.  
  8639. /*
  8640. **  Now get rid of the inverse common key entries.
  8641. */
  8642. delete from syskeys
  8643.     where type = 3
  8644.         and id = @depid
  8645.         and depid = @id
  8646.  
  8647. print 'Common keys dropped.'
  8648.  
  8649. return (0)
  8650. go
  8651.  
  8652. print ''
  8653. print 'Creating procedure sp_droplogin.'
  8654. go
  8655. create procedure sp_droplogin -- 1995/10/24 18:21 6.01.144
  8656.  
  8657. @loginame sysname        -- name of login to drop
  8658. as
  8659.  
  8660. set nocount on
  8661.  
  8662. declare @login_suid  smallint
  8663.        ,@char_login_suid  varchar(6)
  8664. declare @username sysname
  8665. declare @dbname    sysname
  8666.  
  8667. /*
  8668. **  If we're in a transaction, disallow this since it might make recovery
  8669. **  impossible.
  8670. */
  8671. if @@trancount > 0
  8672.     begin
  8673.         raiserror(15002,-1,-1,'sp_droplogin')
  8674.         return (1)
  8675.     end
  8676.  
  8677. /*
  8678. **  Only the system administrator (SA) can run this command.
  8679. **  Check to make sure the executor is the sa.
  8680. */
  8681. if suser_id() <> 1
  8682.     begin
  8683.         raiserror(15003,-1,-1)
  8684.         return (1)
  8685.     end
  8686.  
  8687. /*
  8688. **  If login exists, capture the corresponding suid.
  8689. */
  8690. select @login_suid = min(suid)
  8691.    from master..syslogins
  8692.    where name = @loginame
  8693.  
  8694. if @login_suid is null
  8695.    begin
  8696.    raiserror(15007,10,-1,@loginame)
  8697.    return(1)
  8698.    end
  8699.  
  8700. select @char_login_suid = convert(varchar,@login_suid)
  8701.  
  8702. /*
  8703. **  This work table will hold all problems found.
  8704. */
  8705. create table #db_list
  8706. (
  8707.     dbname sysname not null,
  8708.     user_name sysname null,
  8709.     map_type varchar (5) null
  8710. )
  8711.  
  8712. /*
  8713. **  Check to see if any databases are owned by the login.
  8714. */
  8715.  
  8716. insert into #db_list (dbname)
  8717.     select name from sysdatabases where suid = @login_suid
  8718.  
  8719. if @@rowcount <> 0
  8720.     begin
  8721.         raiserror(15174,-1,-1,@loginame)
  8722.         select 'Databases owned by login:' = dbname from #db_list
  8723.         return(1)
  8724.     end
  8725.  
  8726. /*
  8727. **  Check to see if the login is mapped to a user in any database.
  8728. */
  8729.  
  8730. declare db_name_cursor cursor for select name from sysdatabases
  8731. open db_name_cursor
  8732.  
  8733. fetch db_name_cursor into @dbname
  8734.  
  8735. while @@fetch_status >= 0
  8736.     begin
  8737.         exec ('use ' + @dbname + ' ' +
  8738.               'insert into #db_list (dbname,user_name,map_type)
  8739.             select '''+@dbname+''', name, ''user''
  8740.             from sysusers
  8741.             where suid = ' + @char_login_suid + '
  8742.             union
  8743.             select '''+@dbname+''',u.name,''alias''    
  8744.             from sysusers u, sysalternates a
  8745.             where ' + @char_login_suid + ' = a.suid
  8746.                 and a.altsuid = u.suid
  8747.             ')
  8748.  
  8749.         --In 6.5 DB context auto reverts back, immediately after dynam exec().
  8750.  
  8751.         fetch db_name_cursor into @dbname
  8752.     end
  8753.  
  8754. if (select count(*) from #db_list) <> 0
  8755.     begin
  8756.         raiserror(15175,-1,-1,@loginame)
  8757.  
  8758.         select
  8759.             'Database name:' = dbname,
  8760.             'User name:' = user_name,
  8761.             'Mapping type:' = map_type
  8762.         from #db_list
  8763.  
  8764.         deallocate db_name_cursor
  8765.  
  8766.         return (1)
  8767.     end
  8768.  
  8769.  
  8770. deallocate db_name_cursor
  8771.  
  8772. /*
  8773. ** Finally, check if the login owns tasks in msdb since we don't want the tasks to
  8774. ** get inadvertently re-assigned when a new login is created with the same suid.
  8775. */
  8776. if exists (select * from master.dbo.sysdatabases where name = 'msdb')
  8777. begin
  8778.     create table #retval (taskcount int not null)
  8779.     exec ('exec msdb.dbo.sp_MScheckforownedtasks ''#retval'', ''' + @loginame + '''')
  8780.     if exists (select taskcount from #retval where taskcount > 0)
  8781.     begin    
  8782.         declare @task_count int
  8783.         select @task_count = taskcount from #retval
  8784.         raiserror(14248, -1, -1, @task_count)
  8785.         return (1)
  8786.     end
  8787. end
  8788.  
  8789. /*
  8790. **  Delete the login, cascading to certain children first.
  8791. */
  8792. delete from sysremotelogins where suid = @login_suid
  8793. delete from syslogins       where suid = @login_suid
  8794.  
  8795. /*
  8796. ** Check @@rowcount when it works
  8797. */
  8798. if @@rowcount > 0
  8799.     begin
  8800.         raiserror('Login ''%s'' dropped (suid=%s).'
  8801.             ,1,1 ,@loginame ,@char_login_suid)
  8802.         return (0)
  8803.     end
  8804. else
  8805.     begin
  8806.         raiserror(15007,10,-1,@loginame)
  8807.         return (1)
  8808.     end
  8809. go
  8810.  
  8811.  
  8812. print ''
  8813. print 'Creating procedure sp_dropmessage.'
  8814. go
  8815. create procedure sp_dropmessage
  8816. @msgnum int = null,        -- Number of message to drop.
  8817. @lang varchar(30) = null    -- Language of message to drop (or 'ALL')
  8818. as
  8819. declare @retcode int
  8820. declare @langid smallint
  8821.  
  8822. /*
  8823. ** If no message id, show usage
  8824. */
  8825. if @msgnum is null
  8826.     begin
  8827.         raiserror(15177,-1,-1)
  8828.         return (1)
  8829.     end
  8830.  
  8831. /*
  8832. ** Message id must be > 50000
  8833. */
  8834. if @msgnum < 50001
  8835.     begin
  8836.         raiserror(15178,-1,-1)
  8837.         return(1)
  8838.     end
  8839.  
  8840. if (select count(*) from sysmessages where error=@msgnum) = 0
  8841.     begin
  8842.         raiserror(15179,-1,-1,@msgnum)
  8843.         return(1)
  8844.     end
  8845.  
  8846. /*
  8847. ** Verify the language
  8848. */
  8849. if @lang is null
  8850.     select @lang = @@language
  8851. if upper(@lang) <> 'ALL'
  8852. begin
  8853.     begin
  8854.         exec @retcode = sp_validlang @lang
  8855.         if @retcode <>  0
  8856.             return(1)
  8857.     end
  8858.     /*
  8859.     ** Get langid from syslanguages; us_english won't exist, so use 0.
  8860.     */
  8861.     select @langid = isnull((select langid from syslanguages where name = @lang),0)
  8862. end
  8863.  
  8864. /*
  8865. ** The us_english version must be the last one to be dropped
  8866. */
  8867. if (@langid = 0) and (select count(*) from sysmessages where error = @msgnum) > 1
  8868. begin
  8869.     raiserror(15280,-1,-1)
  8870.     return(1)
  8871. end
  8872.  
  8873. /*
  8874. **  Drop the message.
  8875. */
  8876. if upper(@lang) = 'ALL'
  8877.     delete from sysmessages where error = @msgnum
  8878. else
  8879.     delete from sysmessages where error = @msgnum and langid = @langid
  8880.  
  8881. print 'Message dropped.'
  8882. return (0)
  8883. go
  8884.  
  8885. print ''
  8886. print 'Creating procedure sp_droptype.'
  8887. go
  8888. create procedure sp_droptype
  8889. @typename varchar(30)            /* the user type to drop */
  8890. as
  8891.  
  8892. declare @typeid smallint        /* the typeid of the usertype to drop */
  8893.  
  8894. /*
  8895. **  Initialize @typeid so we can tell if we can't find it.
  8896. */
  8897. select @typeid = 0
  8898.  
  8899. /*
  8900. **  Find the user type with @typename.  It must be a user type (usertype > 99)
  8901. **  and it must be owned by the person (or dbo) running the procedure.
  8902. */
  8903. select @typeid = usertype
  8904.     from systypes
  8905.         where (uid = user_id() or user_id() = 1)
  8906.             and name = @typename
  8907.             and usertype > 99
  8908.  
  8909. if @typeid = 0
  8910.     begin
  8911.         raiserror(15105,-1,-1)
  8912.         return (1)
  8913.     end
  8914.  
  8915. /*
  8916. **  Check to see if the type is being used.  If it is, it can't be dropped.
  8917. */
  8918. if exists (select * from syscolumns where usertype = @typeid)
  8919.     begin
  8920.         raiserror(15180,-1,-1)
  8921.  
  8922.         /*
  8923.         **  Show where it's being used.
  8924.         */
  8925.         select object = o.name, type = o.type, owner = u.name,
  8926.             column = c.name, datatype = t.name
  8927.         from syscolumns c, systypes t, sysusers u, sysobjects o
  8928.         where c.usertype = @typeid
  8929.             and t.usertype = @typeid
  8930.             and o.uid = u.uid
  8931.             and c.id = o.id
  8932.         order by object, column
  8933.  
  8934.         return (1)
  8935.     end
  8936.  
  8937. /*
  8938. **  Everything is consistent so drop the type.
  8939. */
  8940. delete from systypes where usertype = @typeid
  8941.  
  8942. print 'Type has been dropped.'
  8943.  
  8944. return (0)
  8945. go
  8946.  
  8947. print ''
  8948. print 'Creating procedure sp_dropuser.'
  8949. go
  8950. create procedure sp_dropuser
  8951. @name_in_db varchar(30)            /* user name to drop */
  8952. as
  8953.  
  8954. declare @suid int                /* suid of the user */
  8955. declare @uid int                /* uid of the user */
  8956. declare @objectcount int        /* count of objects user owns */
  8957. declare @typecount int            /* count of types user owns */
  8958. declare    @userdropped int        /* flag to indicate user was dropped */
  8959. declare @privcount int                  /* count of occurrences as Grantor */
  8960.  
  8961. /*
  8962. **  You must be SA or the dbo to execute this sproc.
  8963. */
  8964. if suser_id() <> 1 and user_id() <> 1
  8965.     begin
  8966.         raiserror(15000,-1,-1)
  8967.         return (1)
  8968.     end
  8969.  
  8970. /*
  8971. **  See if the user exists in the database.
  8972. **  User ids are <= 16383 and group ids are > 16383.
  8973. */
  8974. select @uid = uid, @suid = suid
  8975.     from sysusers
  8976.         where name = @name_in_db
  8977.             and uid <= 16383 and uid > 0
  8978.  
  8979. /*
  8980. **  No such user so return.
  8981. */
  8982. if @uid is null
  8983.     begin
  8984.         raiserror(15008,-1,-1,@name_in_db)
  8985.         return (1)
  8986.     end
  8987.  
  8988. /*
  8989. **  Can't drop database owner.
  8990. */
  8991. if @uid = 1
  8992.     begin
  8993.         raiserror(15181,-1,-1)
  8994.         return (1)
  8995.     end
  8996.  
  8997. /*
  8998. **  Trouble if guest gets dropped from master or tempdb, so check.
  8999. */
  9000. if (@name_in_db = 'guest' and (db_id() = 1 or db_id() = 2))
  9001.     begin
  9002.         raiserror(15182,-1,-1)
  9003.         return(1)
  9004.     end
  9005.  
  9006. /*
  9007. **  If the user owns any objects or datatypes or is a grantor,
  9008. **  and we're not forcing the drop, return without doing anything.
  9009. */
  9010. select @objectcount = count(*)
  9011.        from sysobjects
  9012.            where uid = @uid
  9013. select @typecount = count(*)
  9014.     from systypes
  9015.         where uid = @uid
  9016. select @privcount = count(*)
  9017.     from sysprotects
  9018.     where grantor = @uid
  9019.  
  9020.  
  9021. if @objectcount > 0 or @typecount > 0 or @privcount > 0
  9022. begin
  9023.     if @objectcount > 0
  9024.         begin
  9025.             raiserror(15183,-1,-1)
  9026.             select name, type
  9027.                 from sysobjects
  9028.                     where uid = @uid
  9029.         end
  9030.  
  9031.     if @typecount > 0
  9032.         begin
  9033.             raiserror(15184,-1,-1)
  9034.             select user_type = a.name, physical_type = b.name
  9035.                 from systypes a, systypes b
  9036.                     where a.uid = @uid
  9037.                         and a.type = b.type
  9038.                         and b.usertype < 100
  9039.         end
  9040.  
  9041.     if @privcount > 0
  9042.         begin
  9043.             raiserror(15284,-1,-1)
  9044.             select 'Grantee'=user_name(uid) ,'Object'=object_name(id)
  9045.                 from sysprotects
  9046.                 where grantor = @uid
  9047.         end
  9048.  
  9049.     return (1)
  9050. end
  9051.  
  9052.  
  9053. /*
  9054. **  Drop the user.
  9055. **  Also drop any references to the user in the sysprotects table.
  9056. **  If anyone is aliased to the user, drop them also.
  9057. */
  9058. begin transaction
  9059.  
  9060.     delete from sysusers
  9061.         where suid = @suid
  9062.     select @userdropped = @@rowcount
  9063.  
  9064.     delete from sysprotects
  9065.         where uid = @uid
  9066.  
  9067.     /*
  9068.     **  Drop any dependent aliases.
  9069.     */
  9070.     if exists (select *
  9071.             from sysalternates
  9072.                 where altsuid = @suid)
  9073.     begin
  9074.         delete from sysalternates
  9075.             where altsuid = @suid
  9076.  
  9077.         print 'The dependent aliases were also dropped.'
  9078.     end
  9079.  
  9080. if @userdropped = 1
  9081.     commit transaction
  9082. else rollback transaction
  9083.  
  9084. print 'User has been dropped from current database.'
  9085.  
  9086. return (0)
  9087. go
  9088.  
  9089. dump tran master with no_log
  9090. go
  9091. print ''
  9092. print 'Creating procedure sp_dropremotelogin.'
  9093. go
  9094. create procedure sp_dropremotelogin
  9095. @remoteserver    varchar(30),        /* name of remote server */
  9096. @loginame varchar(30) = NULL,        /* user's remote name */
  9097. @remotename varchar(30) = NULL        /* user's local user name */
  9098. as
  9099.  
  9100. declare @suid    smallint
  9101.  
  9102. /*
  9103. **  If we're in a transaction, disallow this since it might make recovery
  9104. **  impossible.
  9105. */
  9106. if @@trancount > 0
  9107.     begin
  9108.         raiserror(15002,-1,-1,'sp_dropremotelogin')
  9109.         return (1)
  9110.     end
  9111.  
  9112. /*
  9113. **  If @loginame is NULL then we want to set @suid = -1. Otherwise get
  9114. **  it real value.
  9115. */
  9116. if @loginame is null
  9117.     select @suid = -1
  9118. else
  9119.     select @suid = suser_id(@loginame)
  9120.  
  9121. /*
  9122. **  Delete the remote login.
  9123. */
  9124. delete sysremotelogins
  9125.     from sysremotelogins l, sysservers s
  9126.     where l.remoteserverid = s.srvid
  9127.         and s.srvname = @remoteserver
  9128.         and l.remoteusername = @remotename
  9129.         and l.suid = @suid
  9130.  
  9131. /*
  9132. ** Check @@rowcount when it works
  9133. */
  9134. if @@rowcount > 0
  9135.     begin
  9136.         print 'Remote login dropped.'
  9137.         return (0)
  9138.     end
  9139. else
  9140.     begin
  9141.         raiserror(15185,-1,-1,@remotename,@loginame,@remoteserver)
  9142.         return (1)
  9143.     end
  9144. go
  9145.  
  9146. print ''
  9147. print 'Creating procedure sp_dropsegment.'
  9148. go
  9149. create procedure sp_dropsegment
  9150. @segname    varchar(30),        /* segment name */
  9151. @device        varchar(30) = null    /* device name */
  9152. as
  9153.  
  9154. declare @dbuid    smallint    /* id of the owner of the database */
  9155. declare @segbit    int        /* this is the bit to turn on in sysusages */
  9156. declare    @msg    varchar(200)
  9157. declare @dbname varchar(30)
  9158.  
  9159. /*
  9160. **  If we're in a transaction, disallow this since it might make recovery
  9161. **  impossible.
  9162. */
  9163. if @@trancount > 0
  9164.     begin
  9165.         raiserror(15002,-1,-1,'sp_dropsegment')
  9166.         return (1)
  9167.     end
  9168.  
  9169. /*
  9170. **  You must be SA or the dbo to execute this sproc.
  9171. */
  9172. if suser_id() <> 1 and user_id() <> 1
  9173.     begin
  9174.         raiserror(15000,-1,-1)
  9175.         return (1)
  9176.     end
  9177.  
  9178. /*
  9179. **  There are two drop cases:
  9180. **    1) dropping the segment
  9181. **    2) dropping a segment reference to a device
  9182. **  The sproc does things differently depending on which we're doing.
  9183. */
  9184.  
  9185. /*
  9186. **  Check to see if the segment exists.
  9187. */
  9188. if not exists (select * from syssegments where name = @segname)
  9189.     begin
  9190.         raiserror(15018,-1,-1,@segname)
  9191.         return (1)
  9192.     end
  9193.  
  9194. /*
  9195. **  Get the segment number of @segname.
  9196. */
  9197. select @segbit = segment
  9198.     from syssegments
  9199.         where name = @segname
  9200.  
  9201. /*
  9202. **  Now convert the segment number to the right bit for segmap.
  9203. */
  9204. if (@segbit < 31)
  9205.     select @segbit = power(2, @segbit)
  9206. else
  9207.     /*
  9208.     **  Since this is segment 31, power(2, 31) will overflow
  9209.     **  since segmap is an int.  We'll grab the machine-dependent
  9210.     **  bit mask from spt_values to clear the right bit.
  9211.     */
  9212.     select @segbit = low
  9213.         from master.dbo.spt_values
  9214.         where type = 'E'
  9215.             and number = 2
  9216.  
  9217. /*
  9218. **  Don't allow the segments 'default', 'system', or 'logsegment' to
  9219. **  be dropped completely.
  9220. */
  9221. if @segname in ('system', 'default', 'logsegment')
  9222.     begin
  9223.         if @device is null
  9224.             begin
  9225.                 raiserror(15186,-1,-1,@segname)
  9226.                 return (1)
  9227.             end
  9228.  
  9229.         /*
  9230.         **  For the case where we are dropping the logsegment from a
  9231.         **  device, the logic below works OK.  If this is the last
  9232.         **  device for the the segment, it won't let the segment be
  9233.         **  dropped.
  9234.         */
  9235.     end
  9236.  
  9237.  
  9238. /*
  9239. **  If we are dropping the segment, check to see that the segment isn't
  9240. **  being used by anyone.
  9241. */
  9242. if @device is null
  9243.     begin
  9244.         /*
  9245.         **  Check to see if the segment is being used.
  9246.         */
  9247.         if exists (select *
  9248.             from sysindexes i, syssegments s
  9249.                 where s.name = @segname
  9250.                     and i.segment = s.segment)
  9251.             begin
  9252.                 raiserror(15187,-1,-1,@segname)
  9253.                 return (1)
  9254.             end
  9255.     end
  9256.  
  9257. /*
  9258. **  If we are dropping the segment reference, check to see that arguments are
  9259. **  reasonable.
  9260. */
  9261. if @device IS NOT NULL
  9262. begin
  9263.     /*
  9264.     **  Now see if the database even uses the @device
  9265.     */
  9266.     if not exists (select *
  9267.             from sysusages u, sysdevices d
  9268.             where d.name = @device
  9269.                 and u.vstart between d.low and d.high
  9270.                 and u.dbid = db_id())
  9271.         begin
  9272.             select @dbname=db_name()
  9273.             raiserror(15073,-1,-1,@device,@dbname)
  9274.             return (1)
  9275.         end
  9276.  
  9277.     /*
  9278.     **  Now check that the segment references the device.
  9279.     */
  9280.     if not exists (select *
  9281.             from sysusages u, sysdevices d
  9282.             where u.segmap & @segbit = @segbit
  9283.                 and d.name = @device
  9284.                 and d.low <= u.size + u.vstart
  9285.                 and d.high >= u.size + u.vstart - 1
  9286.                 and u.dbid = db_id()
  9287.                 and d.status & 2 = 2)
  9288.         begin
  9289.             raiserror(15188,-1,-1,@segname,@device)
  9290.             return (1)
  9291.         end
  9292.  
  9293.     /*
  9294.     **  Now check to see if this is the last unique device reference for the
  9295.     **  segment.  If it is then we don't want to drop the reference.
  9296.     */
  9297.     select distinct d.name into #temptable
  9298.         from sysusages u, sysdevices d
  9299.         where u.segmap & @segbit = @segbit
  9300.             and d.low <= u.size + u.vstart
  9301.             and d.high >= u.size + u.vstart - 1
  9302.             and u.dbid = db_id()
  9303.             and d.status & 2 = 2
  9304.  
  9305.     if (select count(*) from #temptable) <= 1
  9306.         begin
  9307.             raiserror(15189,-1,-1,@segname)
  9308.             return (1)
  9309.         end
  9310.  
  9311.     drop table #temptable
  9312. end
  9313.  
  9314. /*
  9315. **  If we're dropping the segment, go ahead drop the segment and
  9316. **  clear its bit in sysusages.
  9317. */
  9318. if @device is null
  9319. begin
  9320.     /*
  9321.     **  NOTE: Don't update master..sysusages and syssegments as a xact since
  9322.     **      it could cause problems for recovery.
  9323.     */
  9324.  
  9325.     delete syssegments where name = @segname
  9326.  
  9327.     /*
  9328.     **  Now clear the segment from device in sysusages.
  9329.     */
  9330.     update sysusages set segmap = segmap & (~@segbit)
  9331.         from sysusages u, sysdevices d
  9332.         where d.low <= u.size + u.vstart
  9333.             and d.high >= u.size + u.vstart - 1
  9334.             and u.dbid = db_id()
  9335.             and d.status & 2 = 2
  9336. end
  9337.  
  9338. /*
  9339. **  We want to just clear the segment reference from the device.
  9340. */
  9341. else
  9342. begin
  9343.     update sysusages set segmap = segmap & (~@segbit)
  9344.         from sysusages u, sysdevices d
  9345.         where d.low <= u.size + u.vstart
  9346.             and d.high >= u.size + u.vstart - 1
  9347.             and u.dbid = db_id()
  9348.             and d.status & 2 = 2
  9349.             and d.name = @device
  9350.  
  9351. end
  9352.  
  9353. /*
  9354. **  Now we need to activate the new segment map.
  9355. */
  9356. select @dbname = db_name()
  9357. dbcc dbrepair (@dbname, remap)
  9358.  
  9359. if @device is null
  9360.     print 'Segment dropped.'
  9361. else print 'Segment reference to device dropped.'
  9362.  
  9363. /*
  9364. **  If there are no more segment references to the device,
  9365. **  print a warning.
  9366. */
  9367. if exists (select *
  9368.         from sysusages
  9369.             where segmap = 0
  9370.                 and dbid = db_id())
  9371. begin
  9372.     declare @nosegs    varchar(255),    /* list of unreferenced devices */
  9373.         @curdevice varchar(30),
  9374.         @i int
  9375.  
  9376.     select @curdevice = min(d.name)
  9377.         from sysusages u, sysdevices d
  9378.         where d.low <= u.size + u.vstart
  9379.             and d.high >= u.size + u.vstart - 1
  9380.             and u.dbid = db_id()
  9381.             and d.status & 2 = 2
  9382.             and segmap = 0
  9383.     select @nosegs = @curdevice, @i = 1
  9384.     while (@curdevice IS NOT NULL)
  9385.     begin
  9386.         select @curdevice = min(d.name)
  9387.             from sysusages u, sysdevices d
  9388.             where d.low <= u.size + u.vstart
  9389.                 and d.high >= u.size + u.vstart - 1
  9390.                 and u.dbid = db_id()
  9391.                 and d.status & 2 = 2
  9392.                 and segmap = 0
  9393.                 and d.name > @curdevice
  9394.         if @curdevice IS NOT NULL
  9395.         begin
  9396.             select @nosegs = @nosegs + ', ' + @curdevice
  9397.             select @i = @i + 1
  9398.         end
  9399.     end
  9400.  
  9401.     /*
  9402.     **  Get the device names.
  9403.     */
  9404.     select @msg =  'WARNING: There are no longer any segments referencing '
  9405.     if @i > 1
  9406.         select @msg = @msg + 'devices '''
  9407.     else select @msg = @msg + 'device '''
  9408.     select @msg = @msg + @nosegs + '''. '
  9409.     if @i > 1
  9410.         select @msg = @msg + 'These devices '
  9411.     else select @msg = @msg + 'This device '
  9412.     select @msg = @msg + 'will no longer be used for space allocation.'
  9413.     print @msg
  9414. end
  9415. return (0)
  9416. go
  9417.  
  9418. print ''
  9419. print 'Creating procedure sp_dropserver.'
  9420. go
  9421. create procedure sp_dropserver
  9422. @server    varchar(30),            /* server name */
  9423. @droplogins    char(10) = NULL        /* drop all related logins? */
  9424. as
  9425.  
  9426. declare    @msg varchar(200)
  9427. declare    @distributor varchar(30)
  9428. declare    @distribdb varchar(30)
  9429. declare    @distproc varchar(255)
  9430.  
  9431. /*
  9432. **  If we're in a transaction, disallow this since it might make recovery
  9433. **  impossible.
  9434. */
  9435. if @@trancount > 0
  9436.     begin
  9437.         raiserror(15002,-1,-1,'sp_dropserver')
  9438.         return (1)
  9439.     end
  9440.  
  9441. /*
  9442. **  Check to see if the server exists.
  9443. */
  9444. if not exists (select * from sysservers where srvname = @server)
  9445.     begin
  9446.         raiserror(15015,-1,-1,@server)
  9447.         return (1)
  9448.     end
  9449.  
  9450. /*
  9451. **  Check to see if there are any related logins in sysremotelogins.
  9452. */
  9453. if @droplogins is null
  9454.     begin
  9455.         if exists (select * from sysremotelogins l,
  9456.                 sysservers s
  9457.             where s.srvid = l.remoteserverid
  9458.                 and s.srvname = @server)
  9459.             begin
  9460.                 raiserror(15190,-1,-1,@server)
  9461.                 return (1)
  9462.             end
  9463.     end
  9464.  
  9465. /*
  9466. **  If @droplogins is true then drop any associated logins
  9467. */
  9468. else if lower(@droplogins) = 'droplogins'
  9469. begin
  9470.     begin transaction dropserver
  9471.  
  9472.         delete sysremotelogins
  9473.             from sysremotelogins l,
  9474.                 sysservers s
  9475.             where s.srvid = l.remoteserverid
  9476.                 and s.srvname = @server
  9477.         if @@rowcount > 0
  9478.         begin
  9479.             select @msg = 'Remote logins for remote server '''
  9480.                 + @server + ''' have been dropped.'
  9481.             print @msg
  9482.         end
  9483.  
  9484.         delete sysservers where srvname = @server
  9485.  
  9486.         print 'Server dropped.'
  9487.  
  9488.     commit transaction dropserver
  9489.  
  9490.     return (0)
  9491. end
  9492.  
  9493. /*
  9494. **  Bad argument to @droplogins.
  9495. */
  9496. else
  9497.     begin
  9498.         raiserror(15191,-1,-1)
  9499.         return (1)
  9500.     end
  9501.  
  9502. /*
  9503. ** Drop server information from distribution database MSsubscriber_info table
  9504. */
  9505. exec sp_helpdistributor @distributor = @distributor OUTPUT,
  9506.    @distribdb = @distribdb OUTPUT
  9507.  
  9508. if @distributor is not null and @distribdb is not null
  9509.   begin
  9510.      select @distproc = RTRIM(@distributor) + '.' + RTRIM(@distribdb) +
  9511.         '..sp_MSdrop_subscriber_info '
  9512.      exec @distproc @@SERVERNAME, @server
  9513.   end
  9514.  
  9515. /*
  9516. **  Drop the server.
  9517. */
  9518. delete sysservers where srvname = @server
  9519.  
  9520. print 'Server dropped.'
  9521.  
  9522. return (0)
  9523. go
  9524.  
  9525. print ''
  9526. print 'Creating procedure sp_extendsegment.'
  9527. go
  9528. create procedure sp_extendsegment
  9529. @segname varchar(30),    /* segment name */
  9530. @devname varchar(30)    /* device name to put segment on */
  9531. as
  9532.  
  9533. declare @dbuid  smallint        /* id of the owner of the database */
  9534. declare @segbit    int        /* this is the bit to turn on in sysusages */
  9535. declare    @msg    char(100)
  9536. declare @dbname varchar(30)
  9537. declare @retcode    int
  9538.  
  9539. /*
  9540. **  If we're in a transaction, disallow this since it might make recovery
  9541. **  impossible.
  9542. */
  9543. if @@trancount > 0
  9544.     begin
  9545.         raiserror(15002,-1,-1,'sp_extendsegment')
  9546.         return (1)
  9547.     end
  9548.  
  9549. /*
  9550. **  You must be SA or the dbo to execute this sproc.
  9551. */
  9552. if suser_id() <> 1 and user_id() <> 1
  9553.     begin
  9554.         raiserror(15000,-1,-1)
  9555.         return (1)
  9556.     end
  9557.  
  9558. /*
  9559. **  Check to see if the segment exists.
  9560. */
  9561. if not exists (select * from syssegments where name = @segname)
  9562.     begin
  9563.         raiserror(15018,-1,-1,@segname)
  9564.         return (1)
  9565.     end
  9566.  
  9567. /*
  9568. **  See if the device exists.
  9569. */
  9570. if not exists (select * from sysdevices where name like @devname)
  9571.     begin
  9572.         raiserror(15012,-1,-1,@devname)
  9573.         return (1)
  9574.     end
  9575.  
  9576. /*
  9577. **  Now see if the @dbname uses the @devname
  9578. */
  9579.  
  9580. if not exists (select * from sysusages u, sysdevices d
  9581.             where d.name = @devname
  9582.                 and u.vstart between d.low and d.high
  9583.                 and u.dbid = db_id())
  9584.     begin
  9585.         select @dbname=db_name()
  9586.         raiserror(15073,-1,-1,@devname,@dbname)
  9587.         return (1)
  9588.     end
  9589.  
  9590. /*
  9591. **  Check to see if the device is marked as a log device.
  9592. **  If so, print error.
  9593. */
  9594. if exists (select * from sysusages u, sysdevices d
  9595.         where d.name = @devname
  9596.             and u.vstart between d.low and d.high
  9597.             and u.dbid = db_id()
  9598.             and segmap = 4)
  9599.     begin
  9600.         raiserror(15074,-1,-1,@devname)
  9601.         return (1)
  9602.     end
  9603.  
  9604. /*
  9605. ** Check for valid identifier.
  9606. */
  9607. execute @retcode = sp_validname @segname
  9608. if @retcode <> 0
  9609.     return (1)
  9610.  
  9611. /*
  9612. **  Now go ahead and define the new segment and add it to the segmap
  9613. **  of sysusages.
  9614. **  NOTE: Don't update master..sysusages and syssegments as a xact since
  9615. **      it could cause problems for recovery.
  9616. */
  9617.  
  9618. /*
  9619. **  Get the segment number for @segname.
  9620. */
  9621. select @segbit = segment
  9622.     from syssegments
  9623.         where name = @segname
  9624.  
  9625. /*
  9626. **  If @segbit is 2 then it's the logsegment and the logsegment
  9627. **  doesn't share devices with other segments.  If this is the original
  9628. **  device, we must maintain a data segment since logical page 0
  9629. **  resides here, so exit.  If not, go ahead and make the change but
  9630. **  don't OR the @segbit in but just set segmap to 4.
  9631. */
  9632. if @segbit = 2
  9633. begin
  9634.     /*
  9635.     **  First check to see if this is the original device
  9636.     */
  9637.     if exists (select * from sysusages u, sysdevices d
  9638.             where d.name = @devname
  9639.                 and u.vstart between d.low and d.high
  9640.                 and u.dbid = db_id()
  9641.                 and lstart = 0)
  9642.         begin
  9643.             raiserror(15192,-1,-1)
  9644.             return (1)
  9645.         end
  9646.  
  9647.     else
  9648.         update sysusages set segmap = 4
  9649.             from sysusages u, sysdevices d
  9650.             where d.name = @devname
  9651.                 and u.vstart between d.low and d.high
  9652.                 and u.dbid = db_id()
  9653. end
  9654.  
  9655. else
  9656. begin
  9657.     if (@segbit < 31)
  9658.         select @segbit = power(2, @segbit)
  9659.     else
  9660.         /*
  9661.         **  Since this is segment 31, power(2, 31) will
  9662.         **  overflow since segmap is an int.  We'll grab the
  9663.         **  machine-dependent bit mask from spt_values to set
  9664.         **  the right bit.
  9665.         */
  9666.         select @segbit = low
  9667.             from master.dbo.spt_values
  9668.             where type = 'E'
  9669.                 and number = 2
  9670.     /*
  9671.     **  Add the segment to @devname in sysusages.
  9672.     */
  9673.     update sysusages set segmap = segmap | @segbit
  9674.             from sysusages u, sysdevices d
  9675.             where d.name = @devname
  9676.                 and u.vstart between d.low and d.high
  9677.                 and u.dbid = db_id()
  9678. end
  9679.  
  9680. /*
  9681. **  Now we need to activate the new segment map.
  9682. */
  9683. select @dbname = db_name()
  9684. dbcc dbrepair (@dbname, remap)
  9685. print 'Segment extended.'
  9686.  
  9687. /*
  9688. **  Get the segment number for @segname.
  9689. */
  9690. select @segbit = segment
  9691.     from syssegments
  9692.         where name = @segname
  9693.  
  9694. /*
  9695. **  If we are extending the logsegment, print out a message about what it
  9696. **  means to do so.
  9697. */
  9698. if @segbit = 2
  9699.     begin
  9700.         select @msg = 'Device ''' + @devname
  9701.             + ''' is now exclusively used by '''
  9702.             + @segname + '''.'
  9703.         print @msg
  9704.     end
  9705.  
  9706. return (0)
  9707. go
  9708.  
  9709. print ''
  9710. print 'Creating procedure sp_fixindex.'
  9711. go
  9712. create procedure sp_fixindex
  9713.         @dbname        varchar(30),
  9714.         @tabname    varchar(30),          /* system table name */
  9715.         @indid        int                    /* index id value    */
  9716. as
  9717.     /*
  9718.     **    Description:    allow the SA to force a drop and then a
  9719.     **            create index on system catalogs.
  9720.     **
  9721.     **    Usage:        sp_fixindex  database, systemcatalog, ind_id
  9722.     **
  9723.     **    Note:        before using this procedure the database has to
  9724.     **            be in single user mode. The sp_dboption has to
  9725.     **            be used for user databases, and update of
  9726.     **            sysdatabases for master.
  9727.     **
  9728.     */
  9729.  
  9730.     declare    @ramboix smallint            /* mask for rambo indx*/
  9731.     declare @badlist  varchar(255)   /* name list of all tables that should
  9732.                           not have any indexes on them */
  9733.     /*
  9734.     **    Initialize name lists. These will be used in catching
  9735.     **    any attempts to fix indexes on fake tables or tables
  9736.     **    that have no indexes on them.
  9737.     */
  9738.     select @badlist = 'syslocks, sysprocesses, syscurconfig,
  9739.                syssegments, syslogckp'
  9740.  
  9741.     /*
  9742.     **    Make sure we are 'fixing' a system catalog.
  9743.     */
  9744.     if @tabname NOT LIKE 'sys%'
  9745.         begin
  9746.             raiserror(15193,-1,-1)
  9747.             return (1)
  9748.         end
  9749.  
  9750.     /*
  9751.     **    Make sure that we are doing this on somenthing that
  9752.     **    has indexes (or real tables).
  9753.     */
  9754.     if @badlist LIKE  '%' + @tabname + '%'
  9755.         begin
  9756.             raiserror(15194,-1,-1)
  9757.             return (1)
  9758.         end
  9759.  
  9760.     /*
  9761.     **    At this point we are sure that the table has an index
  9762.     **    of requested type, so all there is to be done is to
  9763.     **    set the ramboix bit for this object unless we try to
  9764.     **    fix Sysobjects.
  9765.     */
  9766.     if @tabname <> 'sysobjects'
  9767.     begin
  9768.         /* Use decimal integer equivalent of hex 1000 to avoid
  9769.         ** byte order issues.
  9770.         */
  9771.         select @ramboix = 4096
  9772.         update sysobjects set sysstat = sysstat | @ramboix
  9773.         where name = @tabname
  9774.  
  9775.         checkpoint
  9776.     end
  9777.  
  9778.     /*
  9779.     **    Call dbcc to do the job.
  9780.     */
  9781.     dbcc dbrepair(@dbname, REPAIRINDEX, @tabname, @indid)
  9782.  
  9783.     /*
  9784.     **    Processing successfully done, so turn off the ramboix
  9785.     **    bit if not sysobjects, and tell the user that all is fine.
  9786.     */
  9787.     if @tabname <> 'sysobjects'
  9788.     begin
  9789.         update sysobjects set sysstat = sysstat & ~@ramboix
  9790.         where name = @tabname
  9791.  
  9792.         checkpoint
  9793.     end
  9794.  
  9795.     return (0)
  9796. go
  9797.  
  9798. print ''
  9799. print 'Creating procedure sp_foreignkey.'
  9800. go
  9801. create procedure sp_foreignkey
  9802. @tabname  varchar(92),        /* name of table that we are doing */
  9803. @pktabname varchar(92),        /* name of table with primary key */
  9804. @col1     varchar(30),         /* column name of table we are doing */
  9805. @col2     varchar(30) = NULL,
  9806. @col3     varchar(30) = NULL,
  9807. @col4     varchar(30) = NULL,
  9808. @col5     varchar(30) = NULL,
  9809. @col6     varchar(30) = NULL,
  9810. @col7     varchar(30) = NULL,
  9811. @col8     varchar(30) = NULL
  9812. as
  9813.  
  9814. declare @objida int    /* id of table we are doing */
  9815. declare @objidb int    /* id of table with primary key */
  9816. declare @uid smallint    /* id of owner of the table */
  9817. declare @cnt    int    /* how many columns are in foreign key */
  9818.  
  9819. declare @pkey1 int    /* colids of the foreign key */
  9820. declare @pkey2 int
  9821. declare @pkey3 int
  9822. declare @pkey4 int
  9823. declare @pkey5 int
  9824. declare @pkey6 int
  9825. declare @pkey7 int
  9826. declare @pkey8 int
  9827.  
  9828. declare @fkey1 int    /* colids of the primary key */
  9829. declare @fkey2 int
  9830. declare @fkey3 int
  9831. declare @fkey4 int
  9832. declare @fkey5 int
  9833. declare @fkey6 int
  9834. declare @fkey7 int
  9835. declare @fkey8 int
  9836.  
  9837. /*
  9838. **  Check to see that the tabname is local.
  9839. */
  9840. if @tabname like '%.%.%'
  9841.     and substring(@tabname, 1, charindex('.', @tabname) - 1) <> db_name()
  9842.     begin
  9843.         raiserror(15078,-1,-1)
  9844.         return (1)
  9845.     end
  9846.  
  9847. if @pktabname like '%.%.%'
  9848.     and substring(@pktabname, 1, charindex('.', @pktabname) - 1) <> db_name()
  9849.     begin
  9850.         raiserror(15078,-1,-1)
  9851.         return (1)
  9852.     end
  9853.  
  9854. /*
  9855. **  See if we can find the objects.  They must be a system table, user table,
  9856. **  or view.  The low 4 bits of sysobjects.sysstat indicate what the
  9857. **  object type is -- it's more reliable than using sysobjects.type which
  9858. **  could change.
  9859. */
  9860. select @objida = id, @uid = uid
  9861.     from sysobjects
  9862.         where id = object_id(@tabname)
  9863.             and (sysstat & 0xf = 1    /* system table */
  9864.                 or sysstat & 0xf = 2    /* view */
  9865.                 or sysstat & 0xf = 3)    /* user table */
  9866. /*
  9867. **  If either of the tables don't exist, quit.
  9868. */
  9869. if @objida is NULL
  9870.     begin
  9871.         raiserror(15151,-1,-1)
  9872.         return (1)
  9873.     end
  9874.  
  9875. select @objidb = id
  9876.     from sysobjects
  9877.         where id = object_id(@pktabname)
  9878.             and (sysstat & 0xf = 1
  9879.                 or sysstat & 0xf = 2
  9880.                 or sysstat & 0xf = 3)
  9881. if @objidb is NULL
  9882.     begin
  9883.         raiserror(15152,-1,-1)
  9884.         return (1)
  9885.     end
  9886.  
  9887. /*
  9888. **  Only the owner of the table can define its foreign keys.
  9889. */
  9890. if @uid <> user_id()
  9891.     begin
  9892.         raiserror(15153,-1,-1)
  9893.         return (1)
  9894.     end
  9895.  
  9896. /*
  9897. **  Now check to see that the foreign key columns exist.
  9898. */
  9899. select @cnt = 1, @fkey1 = colid
  9900.     from syscolumns
  9901.         where name = @col1
  9902.             and id = @objida
  9903. if @fkey1 is null
  9904.     begin
  9905.         raiserror(15154,-1,-1)
  9906.         return (1)
  9907.     end
  9908.  
  9909. if @col2 IS NOT NULL
  9910.     begin
  9911.         select @cnt = @cnt + 1, @fkey2 = colid
  9912.             from syscolumns
  9913.             where name = @col2
  9914.             and id = @objida
  9915.  
  9916.         if @fkey2 is NULL
  9917.             begin
  9918.                 raiserror(15155,-1,-1)
  9919.                 return (1)
  9920.             end
  9921.     end
  9922. else goto foreign_ok
  9923.  
  9924. if @col3 IS NOT NULL
  9925.     begin
  9926.         select @cnt = @cnt + 1, @fkey3 = colid
  9927.             from syscolumns
  9928.             where name = @col3
  9929.             and id = @objida
  9930.  
  9931.         if @fkey3 is NULL
  9932.             begin
  9933.                 raiserror(15156,-1,-1)
  9934.                 return (1)
  9935.             end
  9936.     end
  9937. else goto foreign_ok
  9938.  
  9939. if @col4 IS NOT NULL
  9940.     begin
  9941.         select @cnt = @cnt + 1, @fkey4 = colid
  9942.             from syscolumns
  9943.             where name = @col4
  9944.             and id = @objida
  9945.  
  9946.         if @fkey4 is NULL
  9947.             begin
  9948.                 raiserror(15157,-1,-1)
  9949.                 return (1)
  9950.             end
  9951.     end
  9952. else goto foreign_ok
  9953.  
  9954. if @col5 IS NOT NULL
  9955.     begin
  9956.         select @cnt = @cnt + 1, @fkey5 = colid
  9957.             from syscolumns
  9958.             where name = @col5
  9959.             and id = @objida
  9960.  
  9961.         if @fkey5 is NULL
  9962.             begin
  9963.                 raiserror(15158,-1,-1)
  9964.                 return (1)
  9965.             end
  9966.     end
  9967. else goto foreign_ok
  9968.  
  9969. if @col6 IS NOT NULL
  9970.     begin
  9971.         select @cnt = @cnt + 1, @fkey6 = colid
  9972.             from syscolumns
  9973.             where name = @col6
  9974.             and id = @objida
  9975.  
  9976.         if @fkey6 is NULL
  9977.             begin
  9978.                 raiserror(15159,-1,-1)
  9979.                 return (1)
  9980.             end
  9981.     end
  9982. else goto foreign_ok
  9983.  
  9984. if @col7 IS NOT NULL
  9985.     begin
  9986.         select @cnt = @cnt + 1, @fkey7 = colid
  9987.             from syscolumns
  9988.             where name = @col7
  9989.             and id = @objida
  9990.  
  9991.         if @fkey7 is NULL
  9992.             begin
  9993.                 raiserror(15160,-1,-1)
  9994.                 return (1)
  9995.             end
  9996.     end
  9997. else goto foreign_ok
  9998.  
  9999. if @col8 IS NOT NULL
  10000.     begin
  10001.         select @cnt = @cnt + 1, @fkey8 = colid
  10002.             from syscolumns
  10003.             where name = @col8
  10004.             and id = @objida
  10005.  
  10006.         if @fkey8 is NULL
  10007.             begin
  10008.                 raiserror(15161,-1,-1)
  10009.                 return (1)
  10010.             end
  10011.     end
  10012.  
  10013.  
  10014. /*
  10015. **  If we made it this far then all the columns for the foreign key are ok.
  10016. */
  10017. foreign_ok:
  10018.  
  10019. /*
  10020. **  Now let's check out the primary key that the foreign key is on.
  10021. **  There must be the same number of columns in the key and the
  10022. **  base types of the columns must agree.
  10023. */
  10024. select @pkey1 = key1, @pkey2 = key2, @pkey3 = key3, @pkey4 = key4,
  10025.     @pkey5 = key5, @pkey6 = key6, @pkey7 = key7, @pkey8 = key8
  10026.         from syskeys
  10027.     where id = @objidb
  10028.         and type = 1
  10029.         and keycnt = @cnt
  10030.  
  10031. /*
  10032. **  If @pkey1 is null then there is no such primary key or the number of
  10033. **  columns in the primary key are not the same as the number of columns
  10034. **  in the foreign key.
  10035. */
  10036. if @pkey1 is null
  10037. begin
  10038.     if exists (select * from syskeys where id = @objidb and type = 1)
  10039.         raiserror(15162,-1,-1)
  10040.     else
  10041.         raiserror(15163,-1,-1)
  10042.  
  10043.     return (1)
  10044. end
  10045.  
  10046. /*
  10047. **  Since we have the right number of columns in the foreign and primary keys,
  10048. **  check that their base datatypes agree.
  10049. */
  10050. if not exists (select *
  10051.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  10052.             master.dbo.spt_values z
  10053.         where a.colid = @fkey1
  10054.             and a.id = @objida
  10055.             and b.colid = @pkey1
  10056.             and b.id = @objidb
  10057.             and y.type = 'J'
  10058.             and a.type = y.low
  10059.             and z.type = 'J'
  10060.             and b.type = z.low
  10061.             and y.number = z.number)
  10062.     begin
  10063.         raiserror(15164,-1,-1)
  10064.         return (1)
  10065.     end
  10066.  
  10067. if @fkey2 IS NOT NULL and not exists (select *
  10068.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  10069.             master.dbo.spt_values z
  10070.         where a.colid = @fkey2
  10071.             and a.id = @objida
  10072.             and b.colid = @pkey2
  10073.             and b.id = @objidb
  10074.             and y.type = 'J'
  10075.             and a.type = y.low
  10076.             and z.type = 'J'
  10077.             and b.type = z.low
  10078.             and y.number = z.number)
  10079.     begin
  10080.         raiserror(15165,-1,-1)
  10081.         return (1)
  10082.     end
  10083. else goto doinsert
  10084.  
  10085. if @fkey3 IS NOT NULL and not exists (select *
  10086.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  10087.             master.dbo.spt_values z
  10088.         where a.colid = @fkey3
  10089.             and a.id = @objida
  10090.             and b.colid = @pkey3
  10091.             and b.id = @objidb
  10092.             and y.type = 'J'
  10093.             and a.type = y.low
  10094.             and z.type = 'J'
  10095.             and b.type = z.low
  10096.             and y.number = z.number)
  10097.     begin
  10098.         raiserror(15166,-1,-1)
  10099.         return (1)
  10100.     end
  10101. else goto doinsert
  10102.  
  10103. if @fkey4 IS NOT NULL and not exists (select *
  10104.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  10105.             master.dbo.spt_values z
  10106.         where a.colid = @fkey4
  10107.             and a.id = @objida
  10108.             and b.colid = @pkey4
  10109.             and b.id = @objidb
  10110.             and y.type = 'J'
  10111.             and a.type = y.low
  10112.             and z.type = 'J'
  10113.             and b.type = z.low
  10114.             and y.number = z.number)
  10115.     begin
  10116.         raiserror(15167,-1,-1)
  10117.         return (1)
  10118.     end
  10119.  
  10120. if @fkey5 IS NOT NULL and not exists (select *
  10121.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  10122.             master.dbo.spt_values z
  10123.         where a.colid = @fkey5
  10124.             and a.id = @objida
  10125.             and b.colid = @pkey5
  10126.             and b.id = @objidb
  10127.             and y.type = 'J'
  10128.             and a.type = y.low
  10129.             and z.type = 'J'
  10130.             and b.type = z.low
  10131.             and y.number = z.number)
  10132.     begin
  10133.         raiserror(15168,-1,-1)
  10134.         return (1)
  10135.     end
  10136. else goto doinsert
  10137.  
  10138. if @fkey6 IS NOT NULL and not exists (select *
  10139.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  10140.             master.dbo.spt_values z
  10141.         where a.colid = @fkey6
  10142.             and a.id = @objida
  10143.             and b.colid = @pkey6
  10144.             and b.id = @objidb
  10145.             and y.type = 'J'
  10146.             and a.type = y.low
  10147.             and z.type = 'J'
  10148.             and b.type = z.low
  10149.             and y.number = z.number)
  10150.     begin
  10151.         raiserror(15169,-1,-1)
  10152.         return (1)
  10153.     end
  10154. else goto doinsert
  10155.  
  10156. if @fkey7 IS NOT NULL and not exists (select *
  10157.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  10158.             master.dbo.spt_values z
  10159.         where a.colid = @fkey7
  10160.             and a.id = @objida
  10161.             and b.colid = @pkey7
  10162.             and b.id = @objidb
  10163.             and y.type = 'J'
  10164.             and a.type = y.low
  10165.             and z.type = 'J'
  10166.             and b.type = z.low
  10167.             and y.number = z.number)
  10168.     begin
  10169.         raiserror(15170,-1,-1)
  10170.         return (1)
  10171.     end
  10172. else goto doinsert
  10173.  
  10174. if @fkey8 IS NOT NULL and not exists (select *
  10175.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  10176.             master.dbo.spt_values z
  10177.         where a.colid = @fkey8
  10178.             and a.id = @objida
  10179.             and b.colid = @pkey8
  10180.             and b.id = @objidb
  10181.             and y.type = 'J'
  10182.             and a.type = y.low
  10183.             and z.type = 'J'
  10184.             and b.type = z.low
  10185.             and y.number = z.number)
  10186.     begin
  10187.         raiserror(15171,-1,-1)
  10188.         return (1)
  10189.     end
  10190.  
  10191. /*
  10192. **  Everything is consistent so add the foreign key to syskeys.
  10193. */
  10194. doinsert:
  10195.  
  10196. insert syskeys (id, type, depid, keycnt, size, key1, key2, key3, key4, key5,
  10197.     key6, key7, key8, depkey1, depkey2, depkey3, depkey4, depkey5,
  10198.     depkey6, depkey7, depkey8)
  10199. values (@objida, 2, @objidb, @cnt, 0, @fkey1, @fkey2, @fkey3, @fkey4, @fkey5,
  10200.     @fkey6, @fkey7, @fkey8, @pkey1, @pkey2, @pkey3, @pkey4, @pkey5,
  10201.     @pkey6, @pkey7, @pkey8)
  10202.  
  10203. print 'New foreign key added.'
  10204.  
  10205. return (0)
  10206. go
  10207.  
  10208.  
  10209. raiserror('
  10210. Creating procedure sp_help_setopts.',1,1)
  10211. go
  10212. CREATE PROCEDURE sp_help_setopts  --1995/11/15 17:32 Undoc in 6.5.
  10213.  
  10214.     @pSetOptNamePattern       varchar(35)    = '%'
  10215.    ,@pAction                  varchar(35)    = 'display_setopts'
  10216. AS
  10217.  
  10218. --Must capture about nocount before disturbing.
  10219. Declare @_Options_Orig int
  10220. Select  @_Options_Orig = @@options
  10221.  
  10222. --Most/All SETs auto revert to pre-sproc setting.
  10223. Set nocount on
  10224.  
  10225. Declare
  10226.     @CBit_Error                  int
  10227.    ,@CBit_AnyMatch               int
  10228.    ,@CBit_ExactOneMatch          int
  10229.    ,@CBit_AtLeastOneOn           int
  10230.    ,@CBit_AtLeastOneDiff         int
  10231.  
  10232. Declare
  10233.     @CBit_is_configable_setopt   int
  10234.  
  10235. Declare
  10236.     @RetCode                     int
  10237.    ,@_rowcount                   int
  10238.    ,@curconfigs_value            int
  10239.  
  10240. Declare
  10241.     @CurrentUser                 char(3)
  10242.    ,@SameAsConfig                char(9)
  10243.    ,@Bits                        int
  10244.  
  10245. Declare
  10246.     @c1name                      varchar(35)
  10247.    ,@c1number                    int
  10248.    ,@c1status                    int
  10249.  
  10250. Declare
  10251.     @charMaxLenSON               varchar(11)
  10252.  
  10253.  
  10254.  
  10255. ---------------------  Initial var values  -----------------
  10256.  
  10257. Select
  10258.     @RetCode                     = 0
  10259.  
  10260.    ,@CBit_Error                  = Power(2,0) --  1
  10261.    ,@CBit_AnyMatch               = Power(2,1) --  2
  10262.    ,@CBit_ExactOneMatch          = Power(2,2) --  4
  10263.    ,@CBit_AtLeastOneOn           = Power(2,3) --  8
  10264.    ,@CBit_AtLeastOneDiff         = Power(2,4) -- 16
  10265.  
  10266.    ,@CBit_is_configable_setopt   = 1  --spt_values.status
  10267.  
  10268.  
  10269.  
  10270. ----------------  Edit input parm values  ------------------
  10271.  
  10272.  
  10273. IF (@pSetOptNamePattern IS Null)
  10274.    begin
  10275.    RaisError(15311,-1,-1,'SetOptNamePattern')
  10276.    Select @RetCode = @CBit_Error
  10277.    GOTO LABEL_86RETURN
  10278.    end
  10279.  
  10280.  
  10281. --------
  10282.  
  10283. IF (@pAction IS Null)
  10284.    begin
  10285.    RaisError(15311,-1,-1,'Action')
  10286.    Select @RetCode = @CBit_Error
  10287.    GOTO LABEL_86RETURN
  10288.    end
  10289.  
  10290. IF (@pAction NOT IN  (
  10291.           'no_display'   ,'display_setopts'   ,'display_eventherc'
  10292.                      )
  10293.    )
  10294.    begin
  10295.    RaisError(15312,-1,-1,@pAction,'Action')
  10296.    Select @RetCode = @CBit_Error
  10297.    GOTO LABEL_86RETURN
  10298.    end
  10299.  
  10300.  
  10301.  
  10302. ----------  We will need the current "user options"  ------------
  10303. ----------  compound integer value.                  ------------
  10304.  
  10305.  
  10306. SELECT
  10307.              @curconfigs_value   = c.value
  10308.       from
  10309.              master.dbo.syscurconfigs  c
  10310.             ,master.dbo.spt_values     v
  10311.       where
  10312.              c.config   = v.number
  10313.       and    v.type     = 'C'
  10314.       and    v.name     = 'user options'  --1534 as of 1995/10
  10315.  
  10316.  
  10317.  
  10318. ---------------------  Create temp #table  -------------------
  10319.  
  10320.  
  10321. Create Table #tb1_sptv_setopts
  10322.    (
  10323.     SetOptName          varchar(35)    NOT Null  --See SET docu
  10324.    ,SetOptBitInt        int            NOT Null
  10325.    ,SetOptStatus        int                Null  --See spt_values
  10326.  
  10327.    ,Bits                int                Null
  10328.  
  10329.    ,SameAsConfig        char(9)            Null
  10330.    ,CurrentUser         char(3)            Null
  10331.    )
  10332.  
  10333.  
  10334. Create Unique Clustered
  10335.    Index ix1
  10336.    On    #tb1_sptv_setopts
  10337.       (
  10338.        SetOptName
  10339.       )
  10340.  
  10341.  
  10342.  
  10343. ---------------------  Populate #table  -------------------
  10344.  
  10345.  
  10346. INSERT
  10347.          into   #tb1_sptv_setopts
  10348.       (
  10349.                 SetOptName
  10350.                ,SetOptBitInt
  10351.                ,SetOptStatus
  10352.  
  10353.                ,Bits
  10354.  
  10355.                ,SameAsConfig
  10356.                ,CurrentUser
  10357.       )
  10358.    SELECT
  10359.                 name
  10360.                ,number
  10361.                ,status
  10362.  
  10363.                ,Null
  10364.  
  10365.                ,Null
  10366.                ,Null
  10367.       from
  10368.                 master.dbo.spt_values
  10369.       where
  10370.                 type    = 'SOP'
  10371.       and       number  > 0
  10372.       and       name LIKE @pSetOptNamePattern
  10373.       order by
  10374.                 name
  10375.  
  10376.  
  10377. Select @_rowcount = @@rowcount
  10378.  
  10379.  
  10380.  
  10381. ----------------  Determine some global RetCode bits  -------------
  10382.  
  10383.  
  10384. IF (@_rowcount > 0)
  10385.    Select @RetCode = @RetCode | @CBit_AnyMatch
  10386.  
  10387. IF (@_rowcount = 1)
  10388.    Select @RetCode = @RetCode | @CBit_ExactOneMatch
  10389.  
  10390.  
  10391.  
  10392. -------------  Declare looping cursor on #table  -------------
  10393.  
  10394. EXECUTE('
  10395. DECLARE Cursor1_Matches
  10396.    Cursor For
  10397. SELECT
  10398.              SetOptName
  10399.             ,SetOptBitInt
  10400.             ,SetOptStatus
  10401.       from
  10402.              #tb1_sptv_setopts
  10403. '
  10404. )
  10405.  
  10406. OPEN Cursor1_Matches
  10407.  
  10408.  
  10409.  
  10410. ---------------------------------------------------------------------
  10411. --             LOOP 1:  thru testable set options
  10412. ---------------------------------------------------------------------
  10413.  
  10414.  
  10415. -----------
  10416. WHILE (1=1)
  10417.    begin
  10418.  
  10419.  
  10420.    FETCH
  10421.              Next
  10422.       from
  10423.              Cursor1_Matches
  10424.       into
  10425.              @c1name
  10426.             ,@c1number
  10427.             ,@c1status
  10428.  
  10429.  
  10430.    IF (@@fetch_status <> 0)
  10431.       begin
  10432.       Deallocate Cursor1_Matches
  10433.       BREAK
  10434.       end
  10435.  
  10436.  
  10437.    Select
  10438.           @Bits         = 0
  10439.          ,@SameAsConfig = Null
  10440.  
  10441.  
  10442.  
  10443. ---------------  Determine bits for this row  --------------
  10444.  
  10445.  
  10446.    IF (@_Options_Orig & @c1number = 0)
  10447.       begin
  10448.       Select @CurrentUser = 'off'
  10449.       end
  10450.    ELSE
  10451.       begin
  10452.       Select @CurrentUser = 'on '
  10453.       Select @Bits      = @Bits    | @CBit_AtLeastOneOn
  10454.       Select @RetCode   = @RetCode | @CBit_AtLeastOneOn
  10455.       end
  10456.  
  10457.  
  10458. --------
  10459.  
  10460.    IF (@c1status & @CBit_is_configable_setopt = 0)
  10461.       begin
  10462.       Select @SameAsConfig = '.  '
  10463.       end
  10464.    ELSE
  10465.       begin
  10466.  
  10467.       IF (  (@c1number & @_Options_Orig)
  10468.                 =
  10469.             (@c1number & @curconfigs_value)
  10470.          )
  10471.          begin
  10472.          Select @SameAsConfig  = 'same'
  10473.          end
  10474.       ELSE
  10475.          begin
  10476.          Select @SameAsConfig  = 'DIFFERENT'
  10477.          Select @Bits      = @Bits    | @CBit_AtLeastOneDiff
  10478.          Select @RetCode   = @RetCode | @CBit_AtLeastOneDiff
  10479.          end
  10480.  
  10481.       end
  10482.  
  10483.  
  10484.  
  10485. -----------  Save comparison results in #table  -------------
  10486.  
  10487.  
  10488.    UPDATE
  10489.              #tb1_sptv_setopts
  10490.       set
  10491.              Bits           = @Bits
  10492.             ,CurrentUser    = @CurrentUser
  10493.             ,SameAsConfig   = @SameAsConfig
  10494.       where
  10495.              Current Of Cursor1_Matches
  10496.  
  10497.  
  10498.  
  10499.    end --loop 1
  10500.  
  10501.  
  10502.  
  10503. ---------------------------------------------------------------------
  10504. --             Printout/Display wanted?
  10505. ---------------------------------------------------------------------
  10506.  
  10507.  
  10508. IF (@pAction IN ('display_setopts' ,'display_eventherc'))
  10509.    begin
  10510.  
  10511.  
  10512.    SELECT
  10513.              @charMaxLenSON   =
  10514.                   convert( varchar
  10515.                           ,(isnull ( max ( datalength (SetOptName) ) ,13 )))
  10516.       from
  10517.              #tb1_sptv_setopts
  10518.  
  10519.  
  10520.    EXECUTE(
  10521.    '
  10522.    SELECT
  10523.                  SameAsConfig
  10524.  
  10525.                ,''SetOptionName''   =
  10526.                      substring(SetOptName,1,' + @charMaxLenSON + ')
  10527.  
  10528.                , CurrentUser
  10529.  
  10530.          from
  10531.                 #tb1_sptv_setopts
  10532.          order by
  10533.                 SetOptionName
  10534.    '
  10535.    )
  10536.  
  10537.  
  10538.    end
  10539.  
  10540.  
  10541.  
  10542. --------------------------  Finalization  -----------------------
  10543.  
  10544.  
  10545. LABEL_86RETURN:
  10546.  
  10547.  
  10548. IF (@pAction = 'display_eventherc')
  10549.    Raiserror('   (The return code = %d.)',1,1,@RetCode)
  10550.  
  10551.  
  10552. IF (object_id('tempdb..#tb1_sptv_setopts') IS NOT Null)
  10553.             Drop Table #tb1_sptv_setopts
  10554.  
  10555.  
  10556. RETURN @RetCode
  10557. go
  10558.  
  10559.  
  10560. print ''
  10561. print 'Creating procedure sp_helpconstraint.'
  10562. go
  10563. create procedure sp_helpconstraint --1995/12/05 08:40
  10564.     @objname varchar(92)             -- the table to check for constraints
  10565.    ,@nomsg   varchar(5) = 'msg'      -- 'nomsg' supresses printing of TBName (sp_help)
  10566. as
  10567.  
  10568. set nocount on
  10569.  
  10570. declare @objid    int           -- the object id of the table
  10571.        ,@indid    int           -- the index id of an index
  10572.        ,@cnstdes  varchar(255)  -- string to build up index desc
  10573.        ,@cnstname varchar(30)   -- name of const. currently under consideration
  10574.        ,@tptr     varbinary(16) -- pointer for building text strings.
  10575.        ,@i          int
  10576.        ,@thiskey    varchar(32)
  10577.        ,@cnstid     int
  10578.        ,@cnststatus int
  10579.        ,@numkeys    int
  10580.        ,@rkeyid     int
  10581.        ,@fkeyid     int
  10582.        ,@dbname     varchar(30)
  10583.  
  10584. declare
  10585.          @fkey1  int ,@fkey2  int ,@fkey3  int ,@fkey4  int ,@fkey5  int
  10586.         ,@fkey6  int ,@fkey7  int ,@fkey8  int ,@fkey9  int ,@fkey10 int
  10587.         ,@fkey11 int ,@fkey12 int ,@fkey13 int ,@fkey14 int ,@fkey15 int
  10588.         ,@fkey16 int
  10589.  
  10590. declare
  10591.          @rkey1  int ,@rkey2  int ,@rkey3  int ,@rkey4  int ,@rkey5  int
  10592.         ,@rkey6  int ,@rkey7  int ,@rkey8  int ,@rkey9  int ,@rkey10 int
  10593.         ,@rkey11 int ,@rkey12 int ,@rkey13 int ,@rkey14 int ,@rkey15 int
  10594.         ,@rkey16 int
  10595.  
  10596. declare
  10597.        @bitDisabled           integer
  10598.       ,@bitNotForReplication  integer
  10599. --------
  10600.  
  10601. select
  10602.        @bitDisabled           = 0x4000
  10603.       ,@bitNotForReplication  = 0x200000
  10604.  
  10605.  
  10606. ---- Check to see that the object names are local to the current database.
  10607.  
  10608. if      @objname like '%.%.%'
  10609.    and  substring(@objname, 1, charindex('.', @objname) - 1) <> db_name()
  10610.    begin
  10611.    raiserror(15250,-1,-1)
  10612.    return (1)
  10613.    end
  10614.  
  10615.  
  10616. ---- Check to see if the table exists and initialize @objid.
  10617.  
  10618. select @objid = object_id(@objname)
  10619.  
  10620.  
  10621. ---- Table does not exist so return.
  10622.  
  10623. if @objid is NULL
  10624.    begin
  10625.    select @dbname=db_name()
  10626.    raiserror(15009,-1,-1,@objname,@dbname)
  10627.    return (1)
  10628.    end
  10629.  
  10630.  
  10631. declare cnst_csr cursor for
  10632.      select   c.constid, c.status, o.name
  10633.         from  sysconstraints c, sysobjects o
  10634.         where c.id = @objid and o.id = c.constid
  10635.         for read only
  10636.  
  10637.  
  10638. ---- Now check out each constraint, figure out its type and keys and
  10639. ---- save the info in a temporary table that we'll print out at the end.
  10640.  
  10641. create table #spcnsttab
  10642. (
  10643.     rowid               int           NOT NULL  identity
  10644.    ,cnst_type           varchar(48)   NOT NULL   -- 30 for name + text for DEFAULT
  10645.    ,cnst_name           varchar(30)   NOT NULL
  10646.    ,cnst_nonblank_name  varchar(30)   NOT NULL
  10647.    ,cnst_status         integer           NULL
  10648.    ,cnst_keys           text              NULL
  10649. )
  10650.  
  10651. create table #spcnstkeys
  10652. (
  10653.     cnst_colid int NOT NULL
  10654. )
  10655.  
  10656. open cnst_csr
  10657.  
  10658. fetch cnst_csr into @cnstid, @cnststatus, @cnstname
  10659.  
  10660. while @@fetch_status >= 0
  10661.    begin
  10662.  
  10663.    if ((@cnststatus & 0xf) in (1,2)) -- primary key, unique
  10664.       begin
  10665.  
  10666.       if ((@cnststatus & 0xf) = 1)
  10667.          select @cnstdes = 'PRIMARY KEY'
  10668.       else
  10669.          select @cnstdes = 'UNIQUE'
  10670.  
  10671.       select   @indid = indid
  10672.          from  sysindexes, sysobjects
  10673.          where sysobjects.id = @cnstid
  10674.          and   sysindexes.name = sysobjects.name
  10675.  
  10676.       if (@indid > 1)
  10677.          select @cnstdes = @cnstdes + ' (non-clustered)'
  10678.       else
  10679.          select @cnstdes = @cnstdes + ' (clustered)'
  10680.  
  10681.       ---- First we'll figure out what the keys are.
  10682.  
  10683.       select @i = 1
  10684.  
  10685.       while (@i <= 16)
  10686.          begin
  10687.  
  10688.          select @thiskey = index_col(@objname, @indid, @i)
  10689.  
  10690.          if @thiskey is NULL
  10691.             goto keysdone
  10692.  
  10693.          if @i=1
  10694.             begin
  10695.             insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10696.                values (@cnstdes, @cnstname,@cnstname, @thiskey)
  10697.  
  10698.             select @tptr = textptr(cnst_keys) from #spcnsttab
  10699.             end
  10700.          else
  10701.             begin
  10702.             select @thiskey = ', ' + @thiskey
  10703.  
  10704.             if @tptr is not null
  10705.                updatetext #spcnsttab.cnst_keys @tptr null null @thiskey
  10706.             end
  10707.  
  10708.          select @i = @i + 1
  10709.          end --loop 16
  10710.  
  10711.  
  10712.          ---- When we get here we now have all the keys.
  10713.  
  10714. keysdone:
  10715.  
  10716.       end
  10717.    else   -- not pkey,ukey
  10718.  
  10719.       if ((@cnststatus & 0xf) = 3) /* foreign key */
  10720.          begin
  10721.          select @cnstdes = 'FOREIGN KEY'
  10722.  
  10723.          select
  10724.                 @fkeyid = fkeyid, @rkeyid = rkeyid,
  10725.                 @fkey1=fkey1, @fkey2=fkey2, @fkey3=fkey3,
  10726.                 @fkey4=fkey4, @fkey5=fkey5, @fkey6=fkey6,
  10727.                 @fkey7=fkey7, @fkey8=fkey8, @fkey9=fkey9,
  10728.                 @fkey10=fkey10, @fkey11=fkey11,
  10729.                 @fkey12=fkey12, @fkey13=fkey13,
  10730.                 @fkey14=fkey14, @fkey15=fkey15,
  10731.                 @fkey16=fkey16,
  10732.                 @rkey1=rkey1, @rkey2=rkey2, @rkey3=rkey3,
  10733.                 @rkey4=rkey4, @rkey5=rkey5, @rkey6=rkey6,
  10734.                 @rkey7=rkey7, @rkey8=rkey8, @rkey9=rkey9,
  10735.                 @rkey10=rkey10, @rkey11=rkey11,
  10736.                 @rkey12=rkey12, @rkey13=rkey13,
  10737.                 @rkey14=rkey14, @rkey15=rkey15,
  10738.                 @rkey16=rkey16
  10739.             from  sysreferences
  10740.             where constid = @cnstid
  10741.  
  10742.          insert into #spcnstkeys values(@fkey1)
  10743.          insert into #spcnstkeys values(@fkey2)
  10744.          insert into #spcnstkeys values(@fkey3)
  10745.          insert into #spcnstkeys values(@fkey4)
  10746.          insert into #spcnstkeys values(@fkey5)
  10747.          insert into #spcnstkeys values(@fkey6)
  10748.          insert into #spcnstkeys values(@fkey7)
  10749.          insert into #spcnstkeys values(@fkey8)
  10750.          insert into #spcnstkeys values(@fkey9)
  10751.          insert into #spcnstkeys values(@fkey10)
  10752.          insert into #spcnstkeys values(@fkey11)
  10753.          insert into #spcnstkeys values(@fkey12)
  10754.          insert into #spcnstkeys values(@fkey13)
  10755.          insert into #spcnstkeys values(@fkey14)
  10756.          insert into #spcnstkeys values(@fkey15)
  10757.          insert into #spcnstkeys values(@fkey16)
  10758.  
  10759.          delete from #spcnstkeys where cnst_colid = 0
  10760.  
  10761.          ---- Need a unique index so we can use a cursor.
  10762.  
  10763.          create unique index ind1 on #spcnstkeys(cnst_colid)
  10764.  
  10765.          execute('declare fkey_curs cursor for
  10766.                      select cnst_colid from #spcnstkeys
  10767.                      for read only')
  10768.  
  10769.          open fkey_curs
  10770.  
  10771.          fetch fkey_curs into @i
  10772.  
  10773.          select @numkeys=1
  10774.  
  10775.          while @@fetch_status >= 0
  10776.             begin
  10777.             select @thiskey = col_name(@fkeyid, @i)
  10778.  
  10779.             ---- No comma for fist key column.
  10780.  
  10781.             if @numkeys = 1
  10782.                begin
  10783.                insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10784.                   values (@cnstdes, @cnstname,@cnstname, @thiskey)
  10785.  
  10786.                select @tptr = textptr(cnst_keys) from #spcnsttab
  10787.                end
  10788.             else
  10789.                begin
  10790.                select @thiskey = ', ' + @thiskey
  10791.  
  10792.                if @tptr is not null
  10793.                   updatetext #spcnsttab.cnst_keys @tptr null null @thiskey
  10794.                end
  10795.  
  10796.             select @numkeys=@numkeys+1
  10797.  
  10798.             fetch fkey_curs into @i
  10799.             end --loop key fetch
  10800.  
  10801.  
  10802.          ---- When we get here we now have all the keys.
  10803.  
  10804.          truncate table #spcnstkeys
  10805.  
  10806.          drop index #spcnstkeys.ind1
  10807.  
  10808.          deallocate fkey_curs
  10809.  
  10810.          insert into #spcnstkeys values(@rkey1)
  10811.          insert into #spcnstkeys values(@rkey2)
  10812.          insert into #spcnstkeys values(@rkey3)
  10813.          insert into #spcnstkeys values(@rkey4)
  10814.          insert into #spcnstkeys values(@rkey5)
  10815.          insert into #spcnstkeys values(@rkey6)
  10816.          insert into #spcnstkeys values(@rkey7)
  10817.          insert into #spcnstkeys values(@rkey8)
  10818.          insert into #spcnstkeys values(@rkey9)
  10819.          insert into #spcnstkeys values(@rkey10)
  10820.          insert into #spcnstkeys values(@rkey11)
  10821.          insert into #spcnstkeys values(@rkey12)
  10822.          insert into #spcnstkeys values(@rkey13)
  10823.          insert into #spcnstkeys values(@rkey14)
  10824.          insert into #spcnstkeys values(@rkey15)
  10825.          insert into #spcnstkeys values(@rkey16)
  10826.  
  10827.          delete from #spcnstkeys where cnst_colid = 0
  10828.  
  10829.          ---- Need a unique index so we can use a cursor.
  10830.  
  10831.          create unique index ind1 on #spcnstkeys(cnst_colid)
  10832.  
  10833.          insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10834.             select
  10835.                       ' ' ,' ' ,@cnstname
  10836.                      ,'REFERENCES ' + rtrim(db_name(rkeydbid))
  10837.                            + '.' + rtrim(
  10838.                   (select user_name(uid) from sysobjects where id = @rkeyid
  10839.                   )
  10840.                                         )
  10841.                            + '.'+object_name(@rkeyid) + ' ('
  10842.                from  sysreferences
  10843.                where constid = @cnstid
  10844.  
  10845.          select @tptr = textptr(cnst_keys) from #spcnsttab
  10846.  
  10847.          execute('declare rkey_curs cursor for
  10848.                      select cnst_colid from #spcnstkeys
  10849.                      for read only')
  10850.  
  10851.          open rkey_curs
  10852.  
  10853.          fetch rkey_curs into @i
  10854.  
  10855.          select @numkeys=1
  10856.  
  10857.          while @@fetch_status >= 0
  10858.             begin
  10859.             select @thiskey = col_name(@rkeyid, @i)
  10860.  
  10861.             ---- No comma for first key column.
  10862.  
  10863.             if @numkeys <> 1
  10864.                select @thiskey = ', ' + @thiskey
  10865.  
  10866.             if @tptr is not null
  10867.                updatetext #spcnsttab.cnst_keys @tptr null null @thiskey
  10868.  
  10869.             select @numkeys=@numkeys+1
  10870.  
  10871.             fetch rkey_curs into @i
  10872.             end --loop
  10873.  
  10874.  
  10875.          ---- When we get here we now have all the keys.
  10876.  
  10877.          if @tptr is not null
  10878.             updatetext #spcnsttab.cnst_keys @tptr null null ')'
  10879.  
  10880.          truncate table #spcnstkeys
  10881.  
  10882.          drop index #spcnstkeys.ind1
  10883.  
  10884.          deallocate rkey_curs
  10885.          end
  10886.       else
  10887.          if ((@cnststatus & 0xf) = 4)    -- check constraint
  10888.             begin
  10889.             select @i = 1
  10890.  
  10891.             select @cnstdes = text from syscomments
  10892.                where id = @cnstid and colid = @i
  10893.  
  10894.             while @cnstdes is not null
  10895.                begin
  10896.  
  10897.                if @i=1
  10898.                   begin
  10899.                   -- Get Table Check constraint
  10900.                   insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10901.                      select   'CHECK Table Level ',@cnstname,@cnstname,' '
  10902.                         from  sysconstraints
  10903.                         where colid = 0 and constid = @cnstid
  10904.  
  10905.                   -- Column Level Check
  10906.                   insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10907.                      select 'CHECK on column ' + col_name(id, colid)
  10908.                            ,@cnstname,@cnstname,' '
  10909.                         from  sysconstraints
  10910.                         where colid > 0 and constid = @cnstid
  10911.  
  10912.                   select @tptr = textptr(cnst_keys) from #spcnsttab
  10913.  
  10914.                   if @tptr is not null
  10915.                   updatetext #spcnsttab.cnst_keys @tptr 0 null null
  10916.                   end
  10917.                else
  10918.                   begin
  10919.  
  10920.                   if @tptr is not null
  10921.                      updatetext #spcnsttab.cnst_keys @tptr null null @cnstdes
  10922.                   end
  10923.  
  10924.                select @cnstdes = null
  10925.  
  10926.                select @cnstdes = text from syscomments
  10927.                   where id = @cnstid and colid = @i
  10928.  
  10929.                select @i = @i + 1
  10930.                end
  10931.             end
  10932.          else
  10933.             if ((@cnststatus & 0xf) = 5)    -- default
  10934.                begin
  10935.                select @i = 1
  10936.  
  10937.                select @cnstdes = text from syscomments
  10938.                   where id = @cnstid and colid = @i
  10939.  
  10940.                while @cnstdes is not null
  10941.                   begin
  10942.  
  10943.                   if @i=1
  10944.                      begin
  10945.                      insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10946.                         select 'DEFAULT on column ' + col_name(id, colid)
  10947.                               ,@cnstname,@cnstname,' '
  10948.                            from  sysconstraints
  10949.                            where colid > 0 and constid = @cnstid
  10950.  
  10951.                      select @tptr = textptr(cnst_keys) from #spcnsttab
  10952.  
  10953.                      if @tptr is not null
  10954.                         updatetext #spcnsttab.cnst_keys @tptr 0 null null
  10955.                      end
  10956.                   else
  10957.                      begin
  10958.                      if @tptr is not null
  10959.                         updatetext #spcnsttab.cnst_keys @tptr null null @cnstdes
  10960.                      end
  10961.  
  10962.                   select @cnstdes = null
  10963.  
  10964.                   select @cnstdes = text from syscomments
  10965.                      where id = @cnstid and colid = @i
  10966.  
  10967.                   select @i = @i + 1
  10968.                   end
  10969.                end
  10970.             else
  10971.                insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10972.                   values
  10973.                      ('*** INVALID TYPE FOUND IN SYSCONSTRAINTS ***'
  10974.                      ,'ERROR','ERROR','ERROR')
  10975.  
  10976.             fetch cnst_csr into @cnstid, @cnststatus, @cnstname
  10977.         end --of major loop
  10978.  
  10979.  
  10980.         ---- Find any rules or defaults bound by the sp_bind... method.
  10981.  
  10982.         insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10983.            select 'RULE (bound with sp_bindrule)'
  10984.                  ,object_name(c.domain),object_name(c.domain)
  10985.                  ,text
  10986.               from  syscolumns c,syscomments m
  10987.               where c.id = @objid
  10988.                 and m.id = c.domain
  10989.                 and c.domain not in
  10990.                         (select constid from sysconstraints)
  10991.  
  10992.         insert into #spcnsttab (cnst_type,cnst_name,cnst_nonblank_name,cnst_keys)
  10993.            select 'DEFAULT (bound with sp_bindefault)'
  10994.                  ,object_name(c.cdefault),object_name(c.cdefault)
  10995.                  ,text
  10996.               from syscolumns c,syscomments m
  10997.               where c.id = @objid
  10998.                 and m.id = c.cdefault
  10999.                 and c.cdefault not in
  11000.                         (select constid from sysconstraints)
  11001.  
  11002.  
  11003.         ---- constraint status (type included)
  11004.  
  11005.         update #spcnsttab
  11006.                 set   cnst_status = cs.status
  11007.                 from  #spcnsttab tt1 ,sysconstraints cs
  11008.                 where tt1.cnst_name=object_name(cs.constid)
  11009.  
  11010.         update #spcnsttab
  11011.                 set   cnst_status = 0
  11012.                 where cnst_status is null
  11013.  
  11014.  
  11015.         if @nomsg <> 'nomsg'
  11016.            begin
  11017.            select 'Object Name' = @objname
  11018.            print ''
  11019.            end
  11020.  
  11021.  
  11022.         ---- Now print out the contents of the temporary index table.
  11023.  
  11024.         if (select count(*) from #spcnsttab) <> 0
  11025.  
  11026.            select
  11027.                    'constraint_type' = cnst_type
  11028.                   ,'constraint_name' = cnst_name
  11029.  
  11030.                   ,'status_enabled'      = -- 3=fkey ,4=check
  11031.                      CASE
  11032.                         When cnst_name = ' ' Then ' '
  11033.                         When cnst_status & 0xf in (3,4) and
  11034.                              cnst_status & @bitDisabled > 0 and
  11035.                              cnst_name <> ' '
  11036.                            Then    'Disabled'
  11037.                         When cnst_status & 0xf in (3,4) and
  11038.                              cnst_status & @bitDisabled = 0 and
  11039.                              cnst_name <> ' '
  11040.                            Then    'Enabled'
  11041.                         Else       '(n/a)'
  11042.                      END
  11043.  
  11044.                   ,'status_for_replication'  =
  11045.                      CASE
  11046.                         When cnst_name = ' ' Then ' '
  11047.                         When cnst_status & 0xf in (3,4) and
  11048.                              cnst_status & @bitNotForReplication > 0 and
  11049.                              cnst_name <> ' '
  11050.                            Then    'Not_For_Replication'
  11051.                         When cnst_status & 0xf in (3,4) and
  11052.                              cnst_status & @bitNotForReplication = 0 and
  11053.                              cnst_name <> ' '
  11054.                            Then    'Is_For_Replication'
  11055.                         Else       '(n/a)'
  11056.                      END
  11057.  
  11058.                   ,'constraint_keys' = cnst_keys
  11059.                 from      #spcnsttab
  11060.                 order by  cnst_nonblank_name ,cnst_name desc
  11061.  
  11062.         else
  11063.            print 'No constraints have been defined for this object.'
  11064.  
  11065.         print ''
  11066.  
  11067.         if (select count(*) from sysreferences where rkeyid = @objid) <> 0
  11068.  
  11069.            select
  11070.                    'Table is referenced by ' =
  11071.                         db_name(r.fkeydbid) + '.'
  11072.                      +  rtrim(
  11073.                (select user_name(o.uid) from sysobjects o
  11074.                   where o.id = r.fkeyid
  11075.                )
  11076.                              )
  11077.                      + '.' + object_name(r.fkeyid)
  11078.                      + ': ' + object_name(r.constid)
  11079.                from      sysreferences r
  11080.                where     r.rkeyid = @objid
  11081.                order by  1
  11082.         else
  11083.            print 'No foreign keys reference this table.'
  11084.  
  11085. deallocate cnst_csr
  11086. return (0)
  11087. go
  11088.  
  11089. dump tran master with no_log
  11090. go
  11091.  
  11092. print ''
  11093. print 'Creating procedure sp_helpdb.'
  11094. go
  11095. create procedure sp_helpdb
  11096. @dbname varchar(30) = NULL            /* database name to change */
  11097. as
  11098.  
  11099. declare @showdev    bit
  11100. declare @allopts    int
  11101.  
  11102. set nocount on
  11103.  
  11104. /*
  11105. **  If no database name given, get 'em all.
  11106. */
  11107. if @dbname is null
  11108.     select @dbname = '%', @showdev = 0
  11109. else select @showdev = 1
  11110.  
  11111. /*
  11112. **  See if the database exists
  11113. */
  11114. if not exists (select * from sysdatabases where name like @dbname)
  11115.     begin
  11116.         raiserror(15010,-1,-1,@dbname)
  11117.         return (1)
  11118.     end
  11119.  
  11120. /*
  11121. ** Get bitmap of all options that can be set by sp_dboption.
  11122. */
  11123. select @allopts=number from master.dbo.spt_values
  11124.     where type = 'D' and name = 'ALL SETTABLE OPTIONS'
  11125.  
  11126. /*
  11127. **  Since we examine the status bits in sysdatabase and turn them
  11128. **  into english, we need a temporary table to build the descriptions.
  11129. */
  11130. create table #spdbdesc
  11131. (
  11132.     dbid    smallint    null,
  11133.     dbdesc    varchar(175)    null
  11134. )
  11135.  
  11136. /*
  11137. **  Initialize #spdbdesc from sysdatabases
  11138. */
  11139. insert into #spdbdesc (dbid)
  11140.         select dbid from sysdatabases
  11141.             where name like @dbname
  11142.  
  11143. /*
  11144. **  Now for each dbid in #spdbdesc, build the database status
  11145. **  description.
  11146. */
  11147. declare @curdbid smallint    /* the one we're currently working on */
  11148. declare @dbdesc varchar(175)    /* the total description for the db */
  11149. declare @bitdesc varchar(35)    /* the bit description for the db */
  11150.  
  11151. /*
  11152. **  Set @curdbid to the first dbid.
  11153. */
  11154. select @curdbid = min(dbid) from #spdbdesc
  11155.  
  11156. while @curdbid IS NOT NULL
  11157. begin
  11158.     /*
  11159.     **  Initialize @dbdesc.
  11160.     */
  11161.     select @dbdesc = ''
  11162.  
  11163.     /*
  11164.     ** First check bits in sysdatabases.status.
  11165.     */
  11166.  
  11167.     /*
  11168.     **  Check select into/bulk copy bit (4)
  11169.     */
  11170.     select @bitdesc = null
  11171.     select @bitdesc = v.name
  11172.         from master.dbo.spt_values v, sysdatabases d
  11173.         where d.dbid = @curdbid
  11174.             and v.type = 'D'
  11175.             and d.status & v.number = 4
  11176.             and v.number <> @allopts       /* all options */
  11177.     if @bitdesc IS NOT NULL
  11178.     begin
  11179.         if @dbdesc <> ''
  11180.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11181.         else select @dbdesc = @bitdesc
  11182.     end
  11183.  
  11184.     /*
  11185.     **  Check truncate log on checkpoint bit (8)
  11186.     */
  11187.     select @bitdesc = null
  11188.     select @bitdesc = v.name
  11189.         from master.dbo.spt_values v, sysdatabases d
  11190.         where d.dbid = @curdbid
  11191.             and v.type = 'D'
  11192.             and d.status & v.number = 8
  11193.             and v.number <> @allopts       /* all options */
  11194.     if @bitdesc IS NOT NULL
  11195.     begin
  11196.         if @dbdesc <> ''
  11197.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11198.         else select @dbdesc = @bitdesc
  11199.     end
  11200.  
  11201.     /*
  11202.     **  Check no checkpoint on recovery bit (16)
  11203.     */
  11204.     select @bitdesc = null
  11205.     select @bitdesc = v.name
  11206.         from master.dbo.spt_values v, sysdatabases d
  11207.         where d.dbid = @curdbid
  11208.             and v.type = 'D'
  11209.             and d.status & v.number = 16
  11210.             and v.number <> @allopts /* all options */
  11211.     if @bitdesc IS NOT NULL
  11212.     begin
  11213.         if @dbdesc <> ''
  11214.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11215.         else select @dbdesc = @bitdesc
  11216.     end
  11217.  
  11218.     /*
  11219.     **  Check don't recover bit (32)
  11220.     */
  11221.     select @bitdesc = null
  11222.     select @bitdesc = v.name
  11223.         from master.dbo.spt_values v, sysdatabases d
  11224.         where d.dbid = @curdbid
  11225.             and v.type = 'D'
  11226.             and d.status & v.number = 32
  11227.             and v.number <> @allopts       /* all options */
  11228.     if @bitdesc IS NOT NULL
  11229.     begin
  11230.         if @dbdesc <> ''
  11231.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11232.         else select @dbdesc = @bitdesc
  11233.     end
  11234.  
  11235.     /*
  11236.     **  Check not recovered only bit (256)
  11237.     */
  11238.     select @bitdesc = null
  11239.     select @bitdesc = v.name
  11240.         from master.dbo.spt_values v, sysdatabases d
  11241.         where d.dbid = @curdbid
  11242.             and v.type = 'D'
  11243.             and d.status & v.number = 256
  11244.             and v.number <> @allopts       /* all options */
  11245.     if @bitdesc IS NOT NULL
  11246.     begin
  11247.         if @dbdesc <> ''
  11248.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11249.         else select @dbdesc = @bitdesc
  11250.     end
  11251.  
  11252.     /*
  11253.     **  Check offline bit (512)
  11254.     */
  11255.     select @bitdesc = null
  11256.     select @bitdesc = v.name
  11257.         from master.dbo.spt_values v, sysdatabases d
  11258.         where d.dbid = @curdbid
  11259.             and v.type = 'D'
  11260.             and d.status & v.number = 512
  11261.             and v.number <> @allopts       /* all options */
  11262.     if @bitdesc IS NOT NULL
  11263.     begin
  11264.         if @dbdesc <> ''
  11265.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11266.         else select @dbdesc = @bitdesc
  11267.     end
  11268.  
  11269.     /*
  11270.     **  Check read only bit (1024)
  11271.     */
  11272.     select @bitdesc = null
  11273.     select @bitdesc = v.name
  11274.         from master.dbo.spt_values v, sysdatabases d
  11275.         where d.dbid = @curdbid
  11276.             and v.type = 'D'
  11277.             and d.status & v.number = 1024
  11278.             and v.number <> @allopts       /* all options */
  11279.     if @bitdesc IS NOT NULL
  11280.     begin
  11281.         if @dbdesc <> ''
  11282.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11283.         else select @dbdesc = @bitdesc
  11284.     end
  11285.  
  11286.     /*
  11287.     **  Check dbo only bit (2048)
  11288.     */
  11289.     select @bitdesc = null
  11290.     select @bitdesc = v.name
  11291.         from master.dbo.spt_values v, sysdatabases d
  11292.         where d.dbid = @curdbid
  11293.             and v.type = 'D'
  11294.             and d.status & v.number = 2048
  11295.             and v.number <> @allopts       /* all options */
  11296.     if @bitdesc IS NOT NULL
  11297.     begin
  11298.         if @dbdesc <> ''
  11299.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11300.         else select @dbdesc = @bitdesc
  11301.     end
  11302.  
  11303.     /*
  11304.     **  Check single user bit (4096)
  11305.     */
  11306.     select @bitdesc = null
  11307.     select @bitdesc = v.name
  11308.         from master.dbo.spt_values v, sysdatabases d
  11309.         where d.dbid = @curdbid
  11310.             and v.type = 'D'
  11311.             and d.status & v.number = 4096
  11312.             and v.number <> @allopts       /* all options */
  11313.     if @bitdesc IS NOT NULL
  11314.     begin
  11315.         if @dbdesc <> ''
  11316.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11317.         else select @dbdesc = @bitdesc
  11318.     end
  11319.  
  11320.     /*
  11321.     **  Check ANSI NULL default bit (16384)
  11322.     */
  11323.     select @bitdesc = null
  11324.     select @bitdesc = v.name
  11325.         from master.dbo.spt_values v, sysdatabases d
  11326.         where d.dbid = @curdbid
  11327.             and v.type = 'D'
  11328.             and d.status & v.number = 16384
  11329.             and v.number <> @allopts       /* all options */
  11330.     if @bitdesc IS NOT NULL
  11331.     begin
  11332.         if @dbdesc <> ''
  11333.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11334.         else select @dbdesc = @bitdesc
  11335.     end
  11336.  
  11337.     /*
  11338.     ** Now check bits in sysdatabases.category.
  11339.     */
  11340.  
  11341.     /*
  11342.     **  Check published bit (65536)
  11343.     */
  11344.     select @bitdesc = null
  11345.     select @bitdesc = v.name
  11346.         from master.dbo.spt_values v, sysdatabases d
  11347.         where d.dbid = @curdbid
  11348.             and v.type = 'D'
  11349.             and d.category & (v.number/0x10000) = 1
  11350.             and v.number <> @allopts       /* all options */
  11351.     if @bitdesc IS NOT NULL
  11352.     begin
  11353.         if @dbdesc <> ''
  11354.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11355.         else select @dbdesc = @bitdesc
  11356.     end
  11357.  
  11358.  
  11359.     /*
  11360.     **  Check subscribed bit (131072)
  11361.     */
  11362.     select @bitdesc = null
  11363.     select @bitdesc = v.name
  11364.         from master.dbo.spt_values v, sysdatabases d
  11365.         where d.dbid = @curdbid
  11366.             and v.type = 'D'
  11367.             and d.category & (v.number/0x10000) = 2
  11368.             and v.number <> @allopts       /* all options */
  11369.     if @bitdesc IS NOT NULL
  11370.     begin
  11371.         if @dbdesc <> ''
  11372.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  11373.         else select @dbdesc = @bitdesc
  11374.     end
  11375.  
  11376.     /*
  11377.     **  If no flags are set, say so.
  11378.     */
  11379.     if @dbdesc = ''
  11380.         select @dbdesc = 'no options set'
  11381.  
  11382.     /*
  11383.     **  Save the description.
  11384.     */
  11385.     update #spdbdesc set dbdesc = @dbdesc
  11386.         from #spdbdesc
  11387.             where dbid = @curdbid
  11388.  
  11389.     /*
  11390.     **  Now get the next, if any dbid.
  11391.     */
  11392.     select @curdbid = min(dbid) from #spdbdesc where dbid > @curdbid
  11393. end
  11394.  
  11395. /*
  11396. **  Now #spdbdesc is complete so we can print out the db info
  11397. */
  11398. select name = substring(d.name, 1, 24),
  11399.     db_size = str(sum(convert(dec(15),u.size))*
  11400.         (select low from master.dbo.spt_values
  11401.             where type = 'E' and number = 1)
  11402.              / 1048576,10,2)+ ' MB',
  11403.     owner = substring(l.name, 1, 24),
  11404.     dbid = d.dbid,
  11405.     created = convert(char(11), d.crdate),
  11406.     status = s.dbdesc
  11407. from sysdatabases d, syslogins l, sysusages u, #spdbdesc s
  11408. where d.dbid = s.dbid
  11409.     and d.suid = l.suid
  11410.     and s.dbid = u.dbid
  11411. group by d.name,l.name,d.dbid,d.crdate,s.dbdesc
  11412. order by d.name
  11413.  
  11414. /*
  11415. **  If we are looking at one database, show its device allocation.
  11416. */
  11417. if @showdev = 1
  11418. begin
  11419.     print ''
  11420.     select device_fragments = v.name, size =
  11421.         str((select low from master.dbo.spt_values
  11422.             where type = 'E'
  11423.                 and number = 1)
  11424.             * convert(dec(15), u.size)/ 1048576,10,2) +' MB',
  11425.         usage = t.name
  11426.     from sysdatabases d, sysusages u, sysdevices v,
  11427.         master.dbo.spt_values t
  11428.     where d.dbid = u.dbid
  11429.         and u.vstart between v.low and v.high
  11430.         and v.status & 2 = 2
  11431.         and d.name = @dbname
  11432.         and t.type = 'S'
  11433.         and u.segmap & 7 = t.number
  11434.     order by 1
  11435.  
  11436.  
  11437.     /*
  11438.     **  If there is only one database and we are in it, show the
  11439.     **  segments.
  11440.     */
  11441.     if exists (select * from #spdbdesc where db_id() = dbid)
  11442.     begin
  11443.         declare @curdevice    varchar(30),
  11444.             @curseg        smallint,
  11445.             @segbit        int
  11446.  
  11447.         delete from #spdbdesc
  11448.  
  11449.         select @curdevice = min(d.name)
  11450.             from  sysusages u, sysdevices d
  11451.             where u.dbid = db_id()
  11452.                 and u.vstart between d.low and d.high
  11453.                 and d.status & 2 = 2
  11454.  
  11455.         while @curdevice IS NOT NULL
  11456.         begin
  11457.             /*
  11458.             ** We need an inner loop here to go through
  11459.             **  all the possible segments.
  11460.             */
  11461.             select @curseg = min(segment) from syssegments
  11462.  
  11463.             while (@curseg IS NOT NULL)
  11464.             begin
  11465.                 if (@curseg < 31)
  11466.                     select @segbit = power(2, @curseg)
  11467.                 else select @segbit = low
  11468.                     from master.dbo.spt_values
  11469.                     where type = 'E'
  11470.                         and number = 2
  11471.                 insert into #spdbdesc
  11472.                     select @curseg, @curdevice
  11473.                         from sysusages u,
  11474.                             sysdevices d
  11475.                     where u.segmap & @segbit = @segbit
  11476.                         and u.vstart between d.low and d.high
  11477.                         and u.dbid = db_id()
  11478.                         and d.status & 2 = 2
  11479.                         and d.name = @curdevice
  11480.                 select @curseg = min(segment)
  11481.                     from syssegments
  11482.                     where segment > @curseg
  11483.             end
  11484.  
  11485.             select @curdevice = min(d.name)
  11486.                 from  sysusages u, sysdevices d
  11487.                 where u.dbid = db_id()
  11488.                     and u.vstart between d.low and d.high
  11489.                     and d.status & 2 = 2
  11490.                     and d.name > @curdevice
  11491.         end
  11492.  
  11493.         /*
  11494.         **  One last check for any devices that have no segments.
  11495.         */
  11496.         insert into #spdbdesc
  11497.             select null, d.name
  11498.             from sysusages u, sysdevices d
  11499.             where u.segmap = 0
  11500.                 and u.vstart between d.low and d.high
  11501.                 and u.dbid = db_id()
  11502.                 and d.status & 2 = 2
  11503.  
  11504.         print ''
  11505.  
  11506.         select distinct device = substring(dbdesc, 1, 30),
  11507.             segment = isnull(name, ' -- unused by any segments --')
  11508.         from #spdbdesc, syssegments
  11509.             where dbid *= segment
  11510.         order by 1, 2
  11511.     end
  11512.  
  11513. end
  11514. return (0)
  11515. go
  11516.  
  11517.  
  11518. print ''
  11519. print 'Creating procedure sp_help_revdatabase.'
  11520. go
  11521. CREATE PROCEDURE sp_help_revdatabase  --1995/11/20 07:53
  11522.  
  11523.        @pDBNamePattern     varchar (44)   = '%'   -- LIKE pattern
  11524. AS
  11525.  
  11526. /****************************************************************
  11527.       This SP reverse generates CREATE & ALTER DB statements.
  11528. The output statements are in the sequence necessary to facilitate
  11529. the LOADing of a DUMP DATABASE output file onto a different
  11530. DB and possibly a different SV too.
  11531.       Perhaps sp_coalesce_fragments could be safely incorporated,
  11532. but for now we are keeping it simple.
  11533. ****************************************************************/
  11534.  
  11535. SET nocount on
  11536.  
  11537. -----------------  declares  ------------------
  11538.  
  11539. DECLARE
  11540.        @vc80a                 varchar (80)
  11541.       ,@vc255a                varchar (255)
  11542.       ,@int1                  int
  11543.       ,@NowDateTm             datetime
  11544.       ,@CountDBs              int
  11545.       ,@Loop22Count           int
  11546.       ,@G_O                   varchar (2)
  11547.       ,@TrueFalse             varchar (5)
  11548.       ,@CommentThisDBOption   char (1)
  11549.       ,@EOLWinNT              varchar (2)
  11550.       ,@OrigDBName            varchar (30)
  11551.  
  11552. DECLARE
  11553.        @cu33OptName           varchar (35)
  11554.       ,@cu33OptNumber         int
  11555.  
  11556. DECLARE
  11557.        @cu11DBName            varchar (30)
  11558.       ,@cu11DBId              smallint
  11559.       ,@cu11DBStatus          smallint
  11560.       ,@cu11DBSUID            smallint
  11561.  
  11562. DECLARE
  11563.        @cu22DBName            varchar (30)
  11564.       ,@cu22DBId              smallint
  11565.       ,@cu22DVName            varchar (30)
  11566.       ,@cu22FragSizePages     int
  11567.       ,@cu22FragSizeMb        varchar (15)
  11568.       ,@cu22SegMap            int
  11569.       ,@cu22LStart            int
  11570.  
  11571. DECLARE
  11572.        @LoginName             varchar (30)
  11573.       ,@LoginDBName           varchar (30)
  11574.       ,@LoginLanguage         varchar (30)
  11575.  
  11576. DECLARE
  11577.        @SPTValAllSettableOptions    int
  11578.       ,@SPTValDataAndLog            int
  11579.       ,@SPTValPageSize              int
  11580.       ,@SPTValLogOnly               int
  11581.       ,@cSPTValAllSettableOptions   varchar (15)
  11582.       ,@cSPTValDataAndLog           varchar (15)
  11583.       ,@cSPTValPageSize             varchar (15)
  11584.       ,@cSPTValLogOnly              varchar (15)
  11585.       ,@DefaultSortOrderId          int
  11586.       ,@OneMb                       numeric(9,1)
  11587.       ,@cOneMb                      varchar (15)
  11588.  
  11589.  
  11590. ----------------  initial values  -------------------
  11591.  
  11592. Select
  11593.        @NowDateTm       = Getdate()
  11594.       ,@OneMb           = 1048576.0
  11595.       ,@G_O             = 'g' + 'o'
  11596.       ,@CountDBs        = 0
  11597.       ,@EOLWinNT        = 0x0D0A
  11598.       ,@OrigDBName      = Db_name()
  11599.  
  11600.  
  11601. Select
  11602.        @cOneMb          = Convert(varchar,@OneMb)
  11603.  
  11604.  
  11605.  
  11606. /*********************************************************************
  11607.  *
  11608.  *                Initialization
  11609.  *
  11610.  ********************************************************************/
  11611.  
  11612.  
  11613. Print  @EOLWinNT
  11614.  
  11615.  
  11616. ----------------  code page and sort order config  ---------------
  11617.  
  11618.  
  11619. SELECT
  11620.              @DefaultSortOrderId    = c.value
  11621.       From
  11622.              master..syscurconfigs  c
  11623.       Where
  11624.              lower(c.comment)       = 'default sortorder id'
  11625.  
  11626.  
  11627.  
  11628.  
  11629. ---------------------  Selects, cursor for spt_values  -----------
  11630.  
  11631.  
  11632. SELECT
  11633.              @SPTValAllSettableOptions    = v.number
  11634.             ,@cSPTValAllSettableOptions   = Convert(varchar,v.number)
  11635.       From
  11636.              master..spt_values     v
  11637.       Where
  11638.              v.type                 = 'D'
  11639.       And    v.name                 = 'ALL SETTABLE OPTIONS'
  11640.  
  11641.  
  11642.  
  11643.  
  11644. SELECT
  11645.              @SPTValPageSize        = v.low
  11646.             ,@cSPTValPageSize       = Convert(varchar,v.low)
  11647.       From
  11648.              master..spt_values     v
  11649.       Where
  11650.              v.type                 = 'E'
  11651.       And    v.name                 = 'WINDOWS/NT'
  11652.  
  11653.  
  11654.  
  11655.  
  11656. SELECT
  11657.              @SPTValDataAndLog      = v.number
  11658.             ,@cSPTValDataAndLog     = Convert(varchar,v.number)
  11659.       From
  11660.              master..spt_values     v
  11661.       Where
  11662.              v.type                 = 'S'
  11663.       And    v.name                 = 'data and log'
  11664.  
  11665.  
  11666.  
  11667.  
  11668. SELECT
  11669.              @SPTValLogOnly         = v.number
  11670.             ,@cSPTValLogOnly        = Convert(varchar,v.number)
  11671.       From
  11672.              master..spt_values     v
  11673.       Where
  11674.              v.type                 = 'S'
  11675.       And    v.name                 = 'log only'
  11676.  
  11677.  
  11678.  
  11679.  
  11680. --  cursor
  11681.  
  11682.  
  11683. EXECUTE(
  11684. '
  11685. DECLARE cursor_33SPTValDBOpts
  11686.    Insensitive
  11687.    Cursor For
  11688.    SELECT
  11689.              v.name
  11690.             ,v.number
  11691.       From
  11692.              master..spt_values   v
  11693. '+'
  11694.       Where
  11695.              v.type    = ''D''
  11696.       And    v.number <> ' + @cSPTValAllSettableOptions + '
  11697.       And    v.number >  0
  11698.       And    v.number  & ' + @cSPTValAllSettableOptions + ' = Abs(v.number)
  11699.       Order By
  11700.              v.name
  11701.  
  11702.    For Read Only
  11703. '
  11704. )
  11705.  
  11706.  
  11707.  
  11708.  
  11709. --------------------  Cursor for DB names  -------------------
  11710.  
  11711.  
  11712.  
  11713. EXECUTE(
  11714. '
  11715. DECLARE cursor_11DBNames
  11716.    Insensitive
  11717.    Cursor For
  11718. '+'
  11719.    SELECT
  11720.              d.name
  11721.             ,d.dbid
  11722.             ,d.status
  11723.             ,d.suid
  11724.       From
  11725.              master..sysdatabases   d
  11726. '+'
  11727.       Where
  11728.              d.name        LIKE ''' + @pDBNamePattern + '''
  11729.       Order By
  11730.              d.name
  11731.  
  11732.    For Read Only
  11733. '
  11734. )
  11735.  
  11736.  
  11737.  
  11738.  
  11739. /****************************************************************
  11740.  *
  11741.  *                MainLine
  11742.  *
  11743.  ***************************************************************/
  11744.  
  11745.  
  11746.  
  11747. OPEN cursor_11DBNames
  11748.  
  11749.  
  11750. ----------------------------------------------------------------
  11751. --              LOOP 11:  thru DBs
  11752. ----------------------------------------------------------------
  11753.  
  11754.  
  11755. WHILE (11=11)
  11756.    Begin
  11757.  
  11758.  
  11759.    FETCH
  11760.              Next
  11761.       From
  11762.              cursor_11DBNames
  11763.       Into
  11764.              @cu11DBName
  11765.             ,@cu11DBId
  11766.             ,@cu11DBStatus
  11767.             ,@cu11DBSUID
  11768.  
  11769.  
  11770.    IF (@@fetch_status < 0)
  11771.       begin
  11772.       CLOSE cursor_11DBNames
  11773.  
  11774.       BREAK
  11775.       end
  11776.  
  11777.  
  11778.    Select @CountDBs = @CountDBs + 1
  11779.  
  11780.  
  11781.  
  11782. ----------------------  Print the headers  ----------------------
  11783.  
  11784.    Print  @EOLWinNT
  11785.    Print  '/********1*********2*********3*********4*********5*********6**'
  11786.  
  11787.    Select @vc80a = 'Reverse generated at '
  11788.             +   Substring(convert(varchar,@NowDateTm,111),1 ,10) + ' '
  11789.             +   Substring(convert(varchar,@NowDateTm,113),12,13)
  11790.    Print  @vc80a
  11791.  
  11792.    Print  @EOLWinNT
  11793.    Print  'Server / Database / Default sortorder ID :'
  11794.  
  11795.    Select @vc80a = @@servername + ' / '
  11796.             +   @cu11DBName + ' / '
  11797.             +   Convert(varchar,@DefaultSortOrderId)
  11798.    Print  @vc80a
  11799.  
  11800.    SELECT
  11801.          'DBName'   =db_name(ug.dbid)
  11802.         ,'FromLPage'=ug.lstart
  11803.         ,'ToLPage'  =ug.lstart + ug.size - 1
  11804.         ,ug.segmap
  11805.     from
  11806.          master.dbo.sysusages ug
  11807.     where
  11808.          ug.dbid = db_id(@cu11DBName)
  11809.     order by
  11810.          DBName ,FromLPage
  11811.  
  11812.    Print  @vc80a
  11813.    Print  @EOLWinNT
  11814.    Select @vc255a = @@version
  11815.    Select @int1 = CharIndex(char(10),@vc255a)
  11816.    Select @vc255a = '@@version:  '  +  Substring(@vc255a ,1 ,@int1 - 1)
  11817.    Print  @vc255a
  11818.  
  11819.    Print  '*********1*********2*********3*********4*********5*********6**/'
  11820.    Print  @G_O
  11821.  
  11822.    Print  @EOLWinNT
  11823.    Print  'USE master'
  11824.    Print  @G_O
  11825.  
  11826.  
  11827.  
  11828. ----------------------  Refresh DV usage fragment cursor  --------------
  11829.  
  11830.  
  11831.  
  11832.    Select @vc255a = Convert(varchar,@cu11DBId)
  11833.  
  11834.  
  11835.  
  11836.  
  11837.    EXECUTE(
  11838.    '
  11839.    DECLARE cursor_22DVUsageFrags
  11840.       Insensitive
  11841.       Cursor For
  11842.    '+'
  11843.    SELECT
  11844.              db.name
  11845.             ,db.dbid
  11846.             ,dv.name
  11847.             ,ug.size
  11848.  
  11849.                -- (numPages * bytesPerPage) / 1 Mb power of 2
  11850.  
  11851.             ,Str( (Convert(numeric(25,0),ug.size)  * ' +
  11852.                      @cSPTValPageSize +  ') / '  + @cOneMb + ' ,13  ,1)
  11853.  
  11854.             ,ug.segmap
  11855.             ,ug.lstart
  11856.       From
  11857.              master..sysdatabases   db
  11858.             ,master..sysusages      ug
  11859.             ,master..sysdevices     dv
  11860.             ,master..spt_values     va
  11861.       Where
  11862.              db.dbid     = ug.dbid
  11863.       And    dv.low     <= ug.size + ug.vstart
  11864.       And    dv.high    >= ug.size + ug.vstart - 1
  11865.       And    db.dbid     = ' + @vc255a + '
  11866.       And    va.type = ''S''
  11867.       And    ug.segmap & ' + @cSPTValDataAndLog + ' =
  11868.                              va.number  --1,2,4 & 7 always 1,2,4
  11869.       And    dv.status & 2 > 0
  11870.       Order By
  11871.              ug.lstart  Asc
  11872.  
  11873.    For Read Only
  11874.    '
  11875.    )
  11876.  
  11877.  
  11878.  
  11879. ----------------------------------------------------------------
  11880. --              LOOP 22:  thru DV frags
  11881. ----------------------------------------------------------------
  11882.  
  11883.  
  11884.    Print  @EOLWinNT
  11885.    Print  '-----------------  Space and Log allocations  ---------------'
  11886.    Print  @EOLWinNT
  11887.  
  11888.  
  11889.  
  11890.    Select @Loop22Count = 0
  11891.  
  11892.    OPEN cursor_22DVUsageFrags
  11893.  
  11894.  
  11895.  
  11896.    WHILE (22=22)
  11897.       Begin
  11898.  
  11899.  
  11900.       FETCH
  11901.              Next
  11902.          From
  11903.              cursor_22DVUsageFrags
  11904.          Into
  11905.              @cu22DBName
  11906.             ,@cu22DBId
  11907.             ,@cu22DVName
  11908.             ,@cu22FragSizePages
  11909.             ,@cu22FragSizeMb
  11910.             ,@cu22SegMap
  11911.             ,@cu22LStart
  11912.  
  11913.  
  11914.       IF (@@fetch_status < 0)
  11915.          begin
  11916.          DEALLOCATE cursor_22DVUsageFrags
  11917.  
  11918.          BREAK
  11919.          end
  11920.  
  11921.  
  11922.       Select @cu22FragSizeMb = Rtrim(Ltrim(@cu22FragSizeMb))
  11923.  
  11924.  
  11925.  
  11926. ---------------------  massage the fragemnt size  -------------------
  11927.  
  11928.  
  11929.       IF (     (Right(@cu22FragSizeMb,2) >= '.1')
  11930.          AND   (Right(@cu22FragSizeMb,2) <= '.9')
  11931.          )
  11932.          begin   -- thus not .0
  11933.  
  11934.  
  11935.          Select @cu22FragSizeMb =
  11936.                      Convert(varchar
  11937.                             ,(Convert(numeric(12,1) ,@cu22FragSizeMb) +
  11938.                               Convert(numeric( 3,1) ,0.9) -- Adding 0.9!
  11939.                              )
  11940.                             )
  11941.  
  11942.  
  11943.          Select @cu22FragSizeMb = Rtrim(Ltrim(@cu22FragSizeMb))
  11944.  
  11945.  
  11946.          Select @cu22FragSizeMb = Substring(@cu22FragSizeMb
  11947.                                            ,1
  11948.                                            ,Datalength(@cu22FragSizeMb)-2
  11949.                                            )
  11950.                                 + '.0'
  11951.  
  11952.          Print  @EOLWinNT
  11953.          Print  @EOLWinNT
  11954.  
  11955.          Print '/***'
  11956.          Raiserror(15316,-1,-1)  --Frag in Mb rounded up from size in pages.
  11957.          Print '***/'
  11958.  
  11959.          Print  @G_O
  11960.          Print  @EOLWinNT
  11961.          end
  11962.  
  11963.  
  11964.  
  11965. -----------------------  first iteration for this DB?  -------------
  11966.  
  11967.  
  11968.  
  11969.       Select @Loop22Count = @Loop22Count + 1
  11970.  
  11971.  
  11972.       Print  @EOLWinNT
  11973.  
  11974.  
  11975.       IF (@Loop22Count = 1)
  11976.          begin
  11977.          Select @vc80a = 'CREATE  '
  11978.          end
  11979.       ELSE
  11980.          begin
  11981.          Select @vc80a = 'ALTER   '
  11982.          end
  11983.  
  11984.  
  11985.       Select @vc80a = @vc80a + 'Database  ' + @cu22DBName
  11986.       Print  @vc80a
  11987.  
  11988.       Select @vc80a = ' '
  11989.  
  11990.  
  11991.  
  11992. ---------------------  is this a special system DB?  ----------------
  11993.  
  11994.  
  11995.       IF (     @cu22DBName     IN ('master','model','msdb'
  11996.                                -- ,'pubs'
  11997.                                   ,'tempdb')
  11998.       -- AND   @Loop22Count   =  1
  11999.          )
  12000.          begin
  12001.          Raiserror(15313,-1,-1,@cu22DBName)
  12002.          end
  12003.  
  12004.  
  12005.       Select @int1 = Datalength(@cu22FragSizeMb)
  12006.       Select @cu22FragSizeMb = Substring(@cu22FragSizeMb,1,@int1-2)
  12007.  
  12008.  
  12009.       Select @vc80a = @vc80a + '      on  ' + @cu22DVName + '  =  '
  12010.                         +  Ltrim(Rtrim(@cu22FragSizeMb))
  12011.                         +  '  -- ' + Convert(varchar,@cu22FragSizePages)
  12012.                         +  '  of two Kb pages'
  12013.       Print  @vc80a
  12014.  
  12015.  
  12016.       Print  @G_O
  12017.  
  12018.  
  12019.  
  12020. --------------------  is this a log fragment?  --------------------
  12021.  
  12022.  
  12023.       IF (@cu22SegMap = @SPTValLogOnly)
  12024.          begin
  12025.  
  12026.          Select @vc80a = 'EXECute sp_logdevice '
  12027.                            +  @cu22DBName + ' ,'
  12028.                            +  @cu22DVName
  12029.          Print  @vc80a
  12030.          Print  @G_O
  12031.          end
  12032.  
  12033.  
  12034.  
  12035. --------------------  make pretty  -------------------------
  12036.  
  12037.  
  12038.       IF (@Loop22Count = 1)
  12039.          begin
  12040.          Print  @EOLWinNT
  12041.          Print  @EOLWinNT
  12042.          end
  12043.  
  12044.  
  12045.  
  12046.       End  -- loop 22
  12047.  
  12048.  
  12049.  
  12050.  
  12051. ----------------------------------------------------------------
  12052. --              LOOP 33:  thru DB options
  12053. ----------------------------------------------------------------
  12054.  
  12055.  
  12056.  
  12057.    Print  @EOLWinNT
  12058.    Print  '---------------------  DB Options  -------------------'
  12059.    Print  @EOLWinNT
  12060.  
  12061.  
  12062.  
  12063.    OPEN cursor_33SPTValDBOpts
  12064.  
  12065.  
  12066.  
  12067.    WHILE (33=33)
  12068.       Begin
  12069.  
  12070.  
  12071.       FETCH
  12072.              Next
  12073.          From
  12074.              cursor_33SPTValDBOpts
  12075.          Into
  12076.              @cu33OptName
  12077.             ,@cu33OptNumber
  12078.  
  12079.  
  12080.       IF (@@fetch_status < 0)
  12081.          begin
  12082.          CLOSE cursor_33SPTValDBOpts
  12083.  
  12084.          BREAK
  12085.          end
  12086.  
  12087.  
  12088.  
  12089.  
  12090.       IF (@cu33OptNumber & @cu11DBStatus = @cu33OptNumber)
  12091.          begin
  12092.          Select @TrueFalse = 'TRUE'
  12093.          end
  12094.       ELSE
  12095.          begin
  12096.          Select @TrueFalse = 'false'
  12097.          end
  12098.  
  12099.  
  12100.  
  12101.       Print  @EOLWinNT
  12102.  
  12103.  
  12104.       IF (@cu33OptName IN (
  12105.              'ANSI null default'
  12106.             ,'dbo use only'
  12107.             ,'no chkpt on recovery'
  12108.             ,'read only'
  12109.             ,'select into/bulkcopy'
  12110.             ,'single user'
  12111.             ,'trunc. log on chkpt.'
  12112.                          )
  12113.          )
  12114.          begin
  12115.          Select @CommentThisDBOption = 'N'
  12116.          end
  12117.       ELSE
  12118.          begin
  12119.          Select @CommentThisDBOption = 'Y'
  12120.          end
  12121.  
  12122.  
  12123.       IF (@CommentThisDBOption = 'Y')
  12124.          begin
  12125.          Print '/***'
  12126.          end
  12127.  
  12128.  
  12129.  
  12130.       Select @vc255a =
  12131.          'EXECute sp_dboption  ' + @cu11DBName + ' ,''' + @cu33OptName + ''''
  12132.       Print  @vc255a
  12133.  
  12134.  
  12135.       Select @vc255a = Space(21 + Datalength(@cu11DBName))
  12136.                        +  ' , '  + @TrueFalse
  12137.       Print  @vc255a
  12138.  
  12139.  
  12140.  
  12141.       IF (@CommentThisDBOption = 'Y')
  12142.          begin
  12143.          Print '***/'
  12144.          end
  12145.  
  12146.  
  12147. --    Print  @G_O
  12148.  
  12149.  
  12150.       End  -- loop 33
  12151.  
  12152.  
  12153.    Print  @EOLWinNT
  12154.    Print  @G_O
  12155.  
  12156.  
  12157.  
  12158. -----------------------  dbo login  ----------------------------
  12159.  
  12160.  
  12161.  
  12162.    SELECT
  12163.        @LoginName       = Null
  12164.       ,@LoginDBName     = Null
  12165.       ,@LoginLanguage   = Null
  12166.  
  12167.  
  12168.  
  12169.    Select @vc255a = Null
  12170.  
  12171.  
  12172.  
  12173.  
  12174.    SELECT
  12175.              @LoginName       = l.name
  12176.             ,@LoginDBName     = l.dbname
  12177.             ,@LoginLanguage   = l.language
  12178.       From
  12179.              master..sysdatabases   d
  12180.             ,master..syslogins      l
  12181.       Where
  12182.              d.suid     = l.suid
  12183.       And    d.dbid     = @cu11DBId
  12184.  
  12185.  
  12186.  
  12187.  
  12188.  
  12189.    IF (     @LoginName         is Null
  12190.       OR    @LoginName         =  ''
  12191.       OR    Lower(@LoginName)  =  'sa'
  12192.       )
  12193.       begin
  12194.  
  12195.       Print  @EOLWinNT
  12196.       Print  '--------------------  sa  is  dbo  ---------------------'
  12197.       Print  @EOLWinNT
  12198.  
  12199.       Goto LABEL_91SAISDBO
  12200.       end
  12201.  
  12202.  
  12203.  
  12204.    Print  @EOLWinNT
  12205.    Print  '---------------------  DBO Login  --------------------'
  12206.    Print  @EOLWinNT
  12207.  
  12208.  
  12209.  
  12210.  
  12211.    SELECT @vc255a =
  12212.                'EXECute  sp_addlogin  ' +  @LoginName
  12213.             +  char(13) + char(10)
  12214.             +  '   ,Null  ,'
  12215.             +  Isnull(@LoginDBName,'Null')  +  '  ,'
  12216.             +  Isnull(@LoginLanguage,'Null')
  12217.  
  12218.  
  12219.  
  12220.    Print  @EOLWinNT
  12221.    Print  @EOLWinNT
  12222.    Print  @EOLWinNT
  12223.  
  12224.    Print  @vc255a
  12225.    Print  @G_O
  12226.  
  12227.    Print  @EOLWinNT
  12228.    Select @vc255a = 'USE ' + @cu11DBName
  12229.    Print  @vc255a
  12230.    Print  @G_O
  12231.  
  12232.    Print  @EOLWinNT
  12233.    Select @vc255a = 'EXECute sp_changedbowner '  +  @LoginName
  12234.    Print  @vc255a
  12235.    Print  @G_O
  12236.  
  12237.    Print  @EOLWinNT
  12238.    Print  'USE master'
  12239.    Print  @G_O
  12240.  
  12241.  
  12242.  
  12243.  
  12244. LABEL_91SAISDBO:
  12245.  
  12246.  
  12247.  
  12248.    Print  @EOLWinNT
  12249.    Print  @G_O
  12250.    Print  '---'
  12251.    Print  @EOLWinNT
  12252.    Print  @EOLWinNT
  12253.  
  12254.  
  12255.    End  -- loop 11
  12256.  
  12257.  
  12258.  
  12259.  
  12260. ---------------------------  Finalization  -----------------------
  12261.  
  12262.  
  12263. DEALLOCATE cursor_33SPTValDBOpts
  12264. DEALLOCATE cursor_11DBNames
  12265. -- DEALLOCATE cursor_22DVUsageFrags
  12266.  
  12267. EXECUTE('USE ' + @OrigDBName)  --For 6.0 db resumption.
  12268.  
  12269. RETURN @CountDBs
  12270. go
  12271.  
  12272.  
  12273.  
  12274.  
  12275. print ''
  12276. print 'Creating procedure sp_helpdevice.'
  12277. go
  12278. create procedure sp_helpdevice
  12279. @devname varchar(30) = '%'        /* device to check out */
  12280. as
  12281.  
  12282. /*
  12283. **  See if the device exists.
  12284. */
  12285. if not exists (select * from sysdevices where name like @devname)
  12286.     begin
  12287.         raiserror(15012,-1,-1,@devname)
  12288.         return (1)
  12289.     end
  12290.  
  12291. /*
  12292. **  Create a temporary table where we can build up a translation of
  12293. **  the device status bits.
  12294. */
  12295. create table #spdevtab
  12296. (
  12297.     name varchar(30)        NOT NULL,
  12298.     statusdesc varchar(255)    null
  12299. )
  12300.  
  12301. set nocount on
  12302.  
  12303. /*
  12304. **  Initialize the temporary table with the names of the devices.
  12305. */
  12306. insert into #spdevtab (name)
  12307.     select name
  12308.         from sysdevices
  12309.         where name like @devname
  12310.  
  12311.  
  12312. /*
  12313. **  Now figure out what kind of controller type it is.
  12314. **
  12315. **  cntrltype =            0    special (data disk)
  12316. **                2    disk (dump)
  12317. **                3-4    floppy (dump)
  12318. **                5    tape
  12319. **                6    pipe
  12320. **                7    cdrom
  12321. */
  12322. update #spdevtab
  12323.     set statusdesc = 'special'
  12324.         from sysdevices d, #spdevtab
  12325.             where d.cntrltype = 0
  12326.                 and #spdevtab.name = d.name
  12327. update #spdevtab
  12328.     set statusdesc = 'disk'
  12329.         from sysdevices d, #spdevtab
  12330.             where d.cntrltype = 2
  12331.                 and #spdevtab.name = d.name
  12332. update #spdevtab
  12333.     set statusdesc = 'diskette'
  12334.         from sysdevices d, #spdevtab
  12335.             where d.cntrltype between 3 and 4
  12336.                 and #spdevtab.name = d.name
  12337.  
  12338. update #spdevtab
  12339.     set statusdesc = 'pipe'
  12340.         from sysdevices d, #spdevtab
  12341.             where d.cntrltype = 6
  12342.                 and #spdevtab.name = d.name
  12343. update #spdevtab
  12344.     set statusdesc = 'cdrom'
  12345.         from sysdevices d, #spdevtab
  12346.             where d.cntrltype = 7
  12347.                 and #spdevtab.name = d.name
  12348. /*
  12349. **  If a floppy dump device, also figure out the floppy capacity which
  12350. **    is listed in sysdevices.high in number of 62k blocks.
  12351. */
  12352. update #spdevtab
  12353.     set statusdesc = statusdesc + ', '
  12354.         + ltrim(str(((d.high * 63488.0) / 1000000.0), 5,1))
  12355.         + ' MB'
  12356.     from sysdevices d, #spdevtab
  12357.         where d.cntrltype in (3,4)
  12358.             and d.high > 0
  12359.             and #spdevtab.name = d.name
  12360.  
  12361. /*
  12362. **  If a tape device, also figure out the tape capacity which is listed
  12363. **  in sysdevices.high in number of 62k blocks.
  12364. */
  12365. update #spdevtab
  12366.     set statusdesc = statusdesc + ', ' + convert(varchar(10),
  12367.         round((d.high * convert(float, 63488)) / 1048576, 0))
  12368.         + ' MB'
  12369.     from sysdevices d, #spdevtab
  12370.         where d.cntrltype = 5
  12371.             and d.high > 0
  12372.             and #spdevtab.name = d.name
  12373.  
  12374. update #spdevtab
  12375.     set statusdesc = 'UNKNOWN DEVICE'
  12376.         from sysdevices d, #spdevtab
  12377.             where d.cntrltype >= 8
  12378.                 and #spdevtab.name = d.name
  12379.  
  12380. /*
  12381. **  Now check out the status bits and turn them into english.
  12382. **  The mirror status bits are between 32 and 512.
  12383. */
  12384. if exists (select * from sysdevices d, master.dbo.spt_values v, #spdevtab
  12385.         where v.type = 'V' and v.number > -1
  12386.             and d.status & 992 <> 0        /* 992 = (32+64+128+256+512) */
  12387.             and #spdevtab.name = d.name)
  12388. begin
  12389.     /*
  12390.     **  Check to see if the mirror is enabled. (512 bit in status)
  12391.     */
  12392.     update #spdevtab
  12393.         set statusdesc = statusdesc + ', MIRROR ENABLED'
  12394.         from sysdevices d, #spdevtab
  12395.         where d.status & 512 = 512
  12396.             and #spdevtab.name = d.name
  12397.  
  12398.     update #spdevtab
  12399.         set statusdesc = statusdesc + ', MIRROR DISABLED'
  12400.         from sysdevices d, #spdevtab
  12401.         where d.status & 512 <> 512
  12402.             and d.status & 480 <> 0        /* 480 = sum of bits */
  12403.             and #spdevtab.name = d.name    /* from 32 - 256     */
  12404.  
  12405.     /* add mirror name */
  12406.     update #spdevtab
  12407.         set statusdesc = statusdesc + ', mirrored on ''' + d.mirrorname
  12408.             + ''''
  12409.         from sysdevices d, #spdevtab
  12410.         where #spdevtab.name = d.name
  12411.             and d.status & 992 <> 0        /* 992 = sum of bits from 32 - 512 */
  12412. end
  12413.  
  12414. /*
  12415. **  Check to see if there is a mirrorname entry but mirroring not enabled.
  12416. **  If so, then one side of the mirror is off-line.
  12417. */
  12418. else if exists (select *
  12419.     from sysdevices d, #spdevtab
  12420.     where #spdevtab.name = d.name
  12421.         and d.mirrorname IS NOT NULL)
  12422. begin
  12423.     /*
  12424.     **  Figure out which side of the mirror is disabled.
  12425.     **  If 256 is on then phyname is disabled and mirrorname is enabled.
  12426.     */
  12427.     update #spdevtab set statusdesc = 'only device ''' + d.mirrorname
  12428.             + ''' of mirror is enabled -- device '''
  12429.             + d.phyname + ''' is disabled'
  12430.         from sysdevices d, master.dbo.spt_values v, #spdevtab
  12431.         where v.type = 'V' and v.number > -1
  12432.             and d.status & v.number = 256
  12433.             and #spdevtab.name = d.name
  12434.  
  12435.     update #spdevtab set statusdesc = 'only device ''' + d.phyname
  12436.             + ''' of mirror is enabled -- device '''
  12437.             + d.mirrorname + ''' is disabled'
  12438.         from sysdevices d, sysdevices e, master.dbo.spt_values v,
  12439.             #spdevtab
  12440.         where v.type = 'V' and v.number > -1
  12441.             and d.status & v.number = 64
  12442.             and #spdevtab.name = d.name
  12443.             and e.status & 256 <> 256
  12444.             and #spdevtab.name = e.name
  12445. end
  12446.  
  12447. /*
  12448. **  Status of 32 is 'serial writes' for mirrored disks.
  12449. */
  12450. update #spdevtab set statusdesc = statusdesc + ', ' + rtrim(v.name)
  12451.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12452.     where v.type = 'V' and v.number > -1
  12453.         and d.status & v.number = 32
  12454.         and #spdevtab.name = d.name
  12455.  
  12456. update #spdevtab set statusdesc = statusdesc + ', nonserial writes'
  12457.     from sysdevices d, #spdevtab
  12458.     where d.status & 960 <> 0        /* Sum of bits from 64 to 512 */
  12459.         and d.status & 32 <> 32
  12460.         and #spdevtab.name = d.name
  12461.  
  12462. /*
  12463. **  Status of 128 is 'reads mirrored' for mirrored disks.
  12464. */
  12465. update #spdevtab set statusdesc = statusdesc + ', ' + rtrim(v.name)
  12466.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12467.     where v.type = 'V' and v.number > -1
  12468.         and d.status & v.number = 128
  12469.         and #spdevtab.name = d.name
  12470.  
  12471. /*
  12472. **  Now check out the status bits and turn them into english.
  12473. **  Status of 16 is a dump device.
  12474. */
  12475. update #spdevtab set statusdesc = statusdesc + ', ' + rtrim(v.name)
  12476.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12477.     where v.type = 'V' and v.number > -1
  12478.         and d.status & v.number = 16
  12479.         and #spdevtab.name = d.name
  12480.  
  12481. /*
  12482. **  Status of 1 is a default disk.
  12483. */
  12484. update #spdevtab set statusdesc = statusdesc + ', ' + rtrim(v.name)
  12485.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12486.     where v.type = 'V' and v.number > -1
  12487.         and d.status & v.number = 1
  12488.         and #spdevtab.name = d.name
  12489.  
  12490. /*
  12491. **  Status of 2 is a physical disk.
  12492. */
  12493. update #spdevtab
  12494.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + rtrim(v.name)
  12495.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12496.     where v.type = 'V' and v.number > -1
  12497.         and d.status & v.number = 2
  12498.         and #spdevtab.name = d.name
  12499.  
  12500. /*
  12501. **  Add in its size in MB.
  12502. */
  12503. update #spdevtab
  12504.     set statusdesc = statusdesc + ', ' + convert(varchar(10),
  12505.         round(((d.high - d.low)
  12506.             * convert(float, v.low)) / 1048576, 0)) + ' MB'
  12507.     from sysdevices d, #spdevtab, master.dbo.spt_values v
  12508.     where d.status & 2 = 2
  12509.         and #spdevtab.name = d.name
  12510.         and v.number = 1
  12511.         and v.type = 'E'
  12512.  
  12513. /*
  12514. **  Status of 4 is a logical disk.
  12515. */
  12516. update #spdevtab
  12517.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + rtrim(v.name)
  12518.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12519.     where v.type = 'V' and v.number > -1
  12520.         and d.status & v.number = 4
  12521.         and #spdevtab.name = d.name
  12522.  
  12523. /*
  12524. **  Status of 8 is a skip tape header.
  12525. */
  12526. update #spdevtab
  12527.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + rtrim(v.name)
  12528.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12529.     where v.type = 'V' and v.number > -1
  12530.         and d.status & v.number = 8
  12531.         and #spdevtab.name = d.name
  12532. /*
  12533. **  Status of 4096 is read only.
  12534. */
  12535. update #spdevtab
  12536.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + rtrim(v.name)
  12537.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12538.     where v.type = 'V' and v.number > -1
  12539.         and d.status & v.number = 4096
  12540.         and #spdevtab.name = d.name
  12541. /*
  12542. **  Status of 8192 is deferred.
  12543. */
  12544. update #spdevtab
  12545.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + (v.name)
  12546.     from sysdevices d, master.dbo.spt_values v, #spdevtab
  12547.     where v.type = 'V' and v.number > -1
  12548.         and d.status & v.number = 8192
  12549.         and #spdevtab.name = d.name
  12550.  
  12551. set nocount off
  12552.  
  12553. /*
  12554. **  The device number is in the high byte of sysdevices.low so
  12555. **  spt_values tells us which byte to pick out.
  12556. */
  12557. select device_name = d.name, physical_name = substring(d.phyname, 1, 46),
  12558.     description = #spdevtab.statusdesc,
  12559.     d.status, d.cntrltype,
  12560.     device_number = convert(tinyint, substring(convert(binary(4), d.low),
  12561.         v.low, 1)),
  12562.     d.low, d.high
  12563.     from sysdevices d, #spdevtab, master.dbo.spt_values v
  12564.     where d.name = #spdevtab.name
  12565.         and v.type = 'E'
  12566.         and v.number = 3
  12567.  
  12568. return(0)
  12569. go
  12570.  
  12571. print ''
  12572. print 'Creating procedure sp_helpextendedproc.'
  12573. go
  12574. create procedure sp_helpextendedproc
  12575. @funcname varchar(30) = NULL
  12576. as
  12577.  
  12578. set nocount on
  12579.  
  12580. /*
  12581. **  If no function name given, get 'em all.
  12582. */
  12583. if @funcname is null
  12584.     select @funcname = '%'
  12585.  
  12586. /*
  12587. **  Make sure the function name exists
  12588. */
  12589. if not exists (select * from master.dbo.sysobjects
  12590.         where type = 'X '
  12591.           and name like @funcname)
  12592. begin
  12593.     if @funcname <> '%'
  12594.         begin
  12595.             raiserror(15019,-1,-1,@funcname)
  12596.             return (1)
  12597.         end
  12598.     else
  12599.         begin
  12600.             print 'No extended stored procedures exist.'
  12601.             return (0)
  12602.         end
  12603.  
  12604. end
  12605.  
  12606. /*
  12607. **  Now print out the function name info
  12608. */
  12609. select distinct name = o.name, dll = substring(c.text,1,30)
  12610.     from master.dbo.sysobjects o, master.dbo.syscomments c
  12611.     where o.id = c.id
  12612.         and o.name like @funcname
  12613.         and o.type = 'X '
  12614.     order by o.name
  12615.  
  12616. return (0)
  12617. go
  12618.  
  12619. print ''
  12620. print 'Creating procedure sp_helpgroup.'
  12621. go
  12622. create procedure sp_helpgroup
  12623. @grpname varchar(30) = NULL        /* group name of interest */
  12624. as
  12625.  
  12626. /*
  12627. **  If no group name given, list all the groups.
  12628. **  User ids are <= 16383 and group ids are > 16383 or = 0.
  12629. */
  12630. if @grpname is null
  12631. begin
  12632.     select Group_name = name, Group_id = gid
  12633.         from sysusers
  12634.             where (uid > 16383 or uid = 0)
  12635.         order by name
  12636.  
  12637.     return (0)
  12638. end
  12639.  
  12640. /*
  12641. **  Check to see if group exists.
  12642. */
  12643. if not exists (select * from sysusers where name = @grpname
  12644.         and (uid > 16383 or uid = 0))
  12645.     begin
  12646.         raiserror(15014,-1,-1,@grpname)
  12647.         return (1)
  12648.     end
  12649.  
  12650. /*
  12651. **  List the particulars for the group.
  12652. */
  12653. select Group_name = substring(g.name, 1, 25), Group_id = g.gid,
  12654.     Users_in_group = substring(u.name, 1, 25), Userid = u.uid
  12655.         from sysusers u, sysusers g
  12656.             where g.name like @grpname
  12657.             and g.uid = u.gid
  12658.             and (g.uid > 16383 or g.uid = 0)
  12659.             and u.uid <> u.gid
  12660.         order by g.name, u.name
  12661.  
  12662. return (0)
  12663. go
  12664.  
  12665.  
  12666. print ''
  12667. print 'Creating procedure sp_helplog.'
  12668. go
  12669. create procedure sp_helplog
  12670. as
  12671. declare @firstpage int,
  12672.     @devname varchar(255),
  12673.     @msg varchar(255)
  12674.  
  12675.  
  12676. /* Get the first page of the log from sysindexes */
  12677. select @firstpage = first
  12678.     from sysindexes
  12679.         where id = 8
  12680.  
  12681. /*
  12682. **  Get the name of the device which contains the first page of the log.
  12683. **  The device number is in the high byte of d.low and u.vstart and which is the
  12684. **  high byte is defined in spt_values.
  12685. */
  12686. select @devname = d.name
  12687.     from sysdevices d, sysusages u, master.dbo.spt_values v
  12688.     where (d.status & 2 = 2 or d.status & 4 = 4)
  12689.         and @firstpage >= u.lstart
  12690.         and @firstpage < u.lstart + u.size - 1
  12691.         and convert(tinyint, substring(convert(binary(4), d.low),
  12692.             v.low, 1))
  12693.           = convert(tinyint, substring(convert(binary(4), u.vstart),
  12694.                v.low, 1))
  12695.         and v.type = 'E'
  12696.         and v.number = 3
  12697.         and u.dbid = db_id()
  12698.  
  12699. /* Print out the name of the device which contains the first page of the log */
  12700. select @msg = 'In database ''' + (select db_name())
  12701.     + ''', the log starts on device ''' + @devname + '''.'
  12702.  
  12703. print @msg
  12704.  
  12705. return (0)
  12706. go
  12707.  
  12708.  
  12709.  
  12710. print ''
  12711. print 'Creating procedure sp_helplogins.'
  12712. go
  12713. CREATE PROCEDURE sp_helplogins  --1995/11/20 16:50
  12714.  
  12715.     @pLoginNamePattern     varchar(55)    = '%'
  12716. AS
  12717.  
  12718. Set nocount on
  12719.  
  12720. Declare
  12721.        @RetCode                        int
  12722.       ,@CountSkipPossUsers             int
  12723.       ,@Int1                           int
  12724.  
  12725. Declare
  12726.        @c10DBName                      varchar(30)
  12727.       ,@c10DBStatus                    smallint
  12728.       ,@c10DBSUID                      smallint
  12729.  
  12730. Declare
  12731.        @charMaxLenLoginName            varchar(11)
  12732.       ,@charMaxLenDBName               varchar(11)
  12733.       ,@charMaxLenUserName             varchar(11)
  12734.       ,@charMaxLenLangName             varchar(11)
  12735.  
  12736. Declare
  12737.        @DBOptLoading                   int   --0x0020      32  "DoNotRecover"
  12738.       ,@DBOptPreRecovery               int   --0x0040      64
  12739.       ,@DBOptRecovering                int   --0x0080     128
  12740.  
  12741.       ,@DBOptSuspect                   int   --0x0100     256  ("not recovered")
  12742.       ,@DBOptOffline                   int   --0x0200     512
  12743.       ,@DBOptDBOUseOnly                int   --0x0800    2048
  12744.  
  12745.       ,@DBOptSingleUser                int   --0x1000    4096
  12746.  
  12747.  
  12748. ----------------  Initial data values  -------------------
  12749.  
  12750. Select
  12751.        @RetCode                        = 0  -- 0=good ,1=bad
  12752.       ,@CountSkipPossUsers             = 0
  12753.  
  12754.  
  12755. ----------------  Only SA can run this  -------------------
  12756.  
  12757.  
  12758. IF (suser_id() <> 1)  --SA, else risk errors in DB's lacking GUEST.
  12759.    begin
  12760.    RaisError(15003,-1,-1)
  12761.    Select @RetCode = 1
  12762.    GOTO LABEL_86RETURN
  12763.    end
  12764.  
  12765.  
  12766. ---------------  Edit input parm values  ---------------
  12767.  
  12768.  
  12769. IF (      @pLoginNamePattern IS Null)
  12770.    Select @pLoginNamePattern  = '%'
  12771.  
  12772.  
  12773. -------------  create work holding tables  ----------------
  12774.  
  12775.  
  12776. CREATE Table #tb2_PlainLogins
  12777.    (
  12778.     LoginName                       varchar(30)    NOT Null
  12779.    ,SUID                            char(6)        NOT Null
  12780.    ,DefDBName                       varchar(30)    NOT Null
  12781.    ,DefLangName                     varchar(30)        Null
  12782.    ,AUser                           char(5)            Null
  12783.    ,ARemote                         char(7)            Null
  12784.    )
  12785.  
  12786.  
  12787. CREATE Table #tb1_UA
  12788.    (
  12789.     LoginName                       varchar(30)    NOT Null
  12790.    ,DBName                          varchar(30)    NOT Null
  12791.    ,UserName                        varchar(30)    NOT Null
  12792.    ,UserOrAlias                     char(5)        NOT Null
  12793.    )
  12794.  
  12795.  
  12796. ----------------------  spt_values  ----------------
  12797.  
  12798.  
  12799. -------- 'D'
  12800.  
  12801. SELECT       @DBOptLoading       = number
  12802.       from   master.dbo.spt_values
  12803.       where  type                = 'D'
  12804.       and    name                = 'loading'
  12805.  
  12806. SELECT       @DBOptPreRecovery   = number
  12807.       from   master.dbo.spt_values
  12808.       where  type                = 'D'
  12809.       and    name                = 'pre recovery'
  12810.  
  12811. SELECT       @DBOptRecovering    = number
  12812.       from   master.dbo.spt_values
  12813.       where  type                = 'D'
  12814.       and    name                = 'recovering'
  12815.  
  12816. SELECT       @DBOptSuspect       = number
  12817.       from   master.dbo.spt_values
  12818.       where  type                = 'D'
  12819.       and    name                = 'not recovered'
  12820.  
  12821. SELECT       @DBOptOffline       = number
  12822.       from   master.dbo.spt_values
  12823.       where  type                = 'D'
  12824.       and    name                = 'offline'
  12825.  
  12826. SELECT       @DBOptDBOUseOnly    = number
  12827.       from   master.dbo.spt_values
  12828.       where  type                = 'D'
  12829.       and    name                = 'dbo use only'
  12830.  
  12831. SELECT       @DBOptSingleUser    = number
  12832.       from   master.dbo.spt_values
  12833.       where  type                = 'D'
  12834.       and    name                = 'single user'
  12835.  
  12836.  
  12837.  
  12838. ---------------  Cursor, for DBNames  -------------------
  12839.  
  12840.  
  12841. DECLARE cursor10_DB
  12842.    Insensitive
  12843.    Cursor For
  12844. SELECT
  12845.              name ,status ,suid
  12846.       from
  12847.              master.dbo.sysdatabases
  12848.  
  12849.  
  12850.  
  12851. OPEN cursor10_DB
  12852.  
  12853.  
  12854. -----------------  LOOP 10:  thru Databases  ------------------
  12855.  
  12856.  
  12857. --------------
  12858. WHILE (10 = 10
  12859.       )
  12860.    begin    --LOOP 10: thru Databases
  12861.  
  12862.  
  12863.    FETCH
  12864.              Next
  12865.       from
  12866.              cursor10_DB
  12867.       into
  12868.              @c10DBName
  12869.             ,@c10DBStatus
  12870.             ,@c10DBSUID
  12871.  
  12872.  
  12873.    IF (@@fetch_status <> 0)
  12874.       begin
  12875.       Deallocate cursor10_DB
  12876.       BREAK
  12877.       end
  12878.  
  12879.  
  12880. --------------------  Okay if we peek inside this DB now?
  12881.  
  12882.  
  12883.    IF (     @c10DBStatus & @DBOptDBOUseOnly  > 0
  12884.        AND  @c10DBSUID                      <> suser_id()
  12885.       )
  12886.       begin
  12887.       Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  12888.       CONTINUE
  12889.       end
  12890.  
  12891.  
  12892.    IF (@c10DBStatus & @DBOptSingleUser  > 0)
  12893.       begin
  12894.  
  12895.       SELECT    @Int1 = count(*)
  12896.          from   master.dbo.sysprocesses
  12897.          where  spid <> @@spid
  12898.          and    dbid  = db_id(@c10DBName)
  12899.  
  12900.       IF (@Int1 > 0)
  12901.          begin
  12902.          Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  12903.          CONTINUE
  12904.          end
  12905.       end
  12906.  
  12907.  
  12908.    IF (@c10DBStatus &
  12909.          (
  12910.            @DBOptLoading
  12911.          | @DBOptRecovering
  12912.          | @DBOptSuspect
  12913.          | @DBOptPreRecovery
  12914.          )
  12915.                > 0
  12916.       )
  12917.       begin
  12918.       Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  12919.       CONTINUE
  12920.       end
  12921.  
  12922.  
  12923.    IF (@c10DBStatus &
  12924.          (
  12925.            @DBOptOffline
  12926.          )
  12927.                > 0
  12928.       )
  12929.       begin
  12930.       --Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  12931.       CONTINUE
  12932.       end
  12933.  
  12934.  
  12935. ---------------------  Add the User info to holding table.
  12936.  
  12937.  
  12938.    EXECUTE(
  12939.    '
  12940.    INSERT    #tb1_UA
  12941.             (
  12942.              DBName
  12943.             ,LoginName
  12944.             ,UserName
  12945.             ,UserOrAlias
  12946.             )
  12947.       Select
  12948.              ''' + @c10DBName + '''
  12949.             ,l.name
  12950.             ,u.name
  12951.             ,''User''
  12952.          from
  12953.              ' + @c10DBName + '.dbo.sysusers       u
  12954.             ,master.dbo.syslogins                  l
  12955.          where
  12956.              u.suid  = l.suid
  12957.          and
  12958.              l.name LIKE ''' + @pLoginNamePattern + '''
  12959.  
  12960.       UNION
  12961.  
  12962.       Select
  12963.  
  12964.              ''' + @c10DBName + '''
  12965.             ,l.name
  12966.             ,u.name
  12967.             ,''Alias''
  12968.          from
  12969.              ' + @c10DBName + '.dbo.sysalternates  a
  12970.             ,' + @c10DBName + '.dbo.sysusers       u
  12971.             ,master.dbo.syslogins                  l
  12972.          where
  12973.              a.suid     = l.suid
  12974.          and a.altsuid  = u.suid
  12975.          and
  12976.              l.name LIKE ''' + @pLoginNamePattern + '''
  12977.    '
  12978.    )
  12979.  
  12980.  
  12981.    end --loop 10
  12982.  
  12983.  
  12984.  
  12985. ---------------  Populate plain logins work table  ---------------
  12986.  
  12987.  
  12988. INSERT       #tb2_PlainLogins
  12989.             (
  12990.              LoginName
  12991.             ,SUID
  12992.             ,DefDBName
  12993.             ,DefLangName
  12994.             ,AUser
  12995.             ,ARemote
  12996.             )
  12997.    SELECT
  12998.              name
  12999.             ,convert(char(6),suid)
  13000.             ,dbname
  13001.             ,isnull(language,'us_english')
  13002.             ,Null
  13003.             ,Null
  13004.       from
  13005.              master.dbo.syslogins
  13006.       where
  13007.              name LIKE @pLoginNamePattern
  13008.  
  13009.  
  13010. -- AUser
  13011.  
  13012. UPDATE       #tb2_PlainLogins
  13013.       set
  13014.              tb2.AUser  = 'yes'
  13015.       from
  13016.              #tb2_PlainLogins    tb2
  13017.             ,#tb1_UA             tb1
  13018.       where
  13019.              tb2.LoginName     = tb1.LoginName
  13020.       and    tb2.AUser        IS Null
  13021.  
  13022.  
  13023.  
  13024. UPDATE       #tb2_PlainLogins
  13025.       set
  13026.              AUser    =
  13027.                   CASE @CountSkipPossUsers
  13028.                      When  0  Then  'NO'
  13029.                      Else           '?'
  13030.                   END
  13031.       where
  13032.              AUser   IS Null
  13033.  
  13034.  
  13035. -- ARemote
  13036.  
  13037. UPDATE       #tb2_PlainLogins
  13038.       set
  13039.              tb2.ARemote   = 'YES'
  13040.       from
  13041.              #tb2_PlainLogins             tb2
  13042.             ,master.dbo.sysremotelogins   rl
  13043.       where
  13044.              convert(smallint,tb2.SUID)   = rl.suid
  13045.       and    tb2.ARemote                 IS Null
  13046.  
  13047.  
  13048.  
  13049. UPDATE       #tb2_PlainLogins
  13050.       set
  13051.              ARemote  = 'no'
  13052.       where
  13053.              ARemote IS Null
  13054.  
  13055.  
  13056.  
  13057. ------------  Optimize widths for plain Logins report  ----------
  13058.  
  13059.  
  13060. SELECT
  13061.              @charMaxLenLoginName      =
  13062.                   convert ( varchar
  13063.                            ,isnull ( max(datalength(LoginName)) ,9)
  13064.                           )
  13065.             ,@charMaxLenDBName         =
  13066.                   convert ( varchar
  13067.                            ,isnull ( max(datalength(DefDBName)) ,9)
  13068.                           )
  13069.             ,@charMaxLenLangName   =
  13070.                   convert ( varchar
  13071.                            ,isnull ( max(datalength(DefLangName)) ,11)
  13072.                           )
  13073.       from
  13074.              #tb2_PlainLogins
  13075.  
  13076.  
  13077.  
  13078. ----------------  Print out plain Logins report  -------------
  13079.  
  13080. /*** Message Handlers get confused.
  13081. Raiserror('
  13082.  
  13083. ...Logins...
  13084. ' ,1,1)
  13085. ***/
  13086.  
  13087. EXECUTE(
  13088. '
  13089. Set nocount off
  13090.  
  13091.  
  13092. SELECT
  13093.           ''LoginName''       = substring (LoginName     ,1 ,'
  13094.                                        + @charMaxLenLoginName   + ')
  13095.  
  13096.          ,SUID
  13097.  
  13098.          ,''DefDBName''       = substring (DefDBName     ,1 ,'
  13099.                                        + @charMaxLenDBName      + ')
  13100.  
  13101.          ,''DefLangName''     = substring (DefLangName   ,1 ,'
  13102.                                        + @charMaxLenLangName    + ')
  13103.  
  13104.          ,AUser
  13105.          ,ARemote
  13106.    from
  13107.           #tb2_PlainLogins
  13108.    order by
  13109.           LoginName
  13110.  
  13111.  
  13112. Set nocount on
  13113. '
  13114. )
  13115.  
  13116.  
  13117.  
  13118. ------------  Optimize UA report column display widths  -----------
  13119.  
  13120.  
  13121. SELECT
  13122.              @charMaxLenLoginName   =
  13123.                   convert ( varchar
  13124.                            ,isnull ( max(datalength(LoginName)) ,9)
  13125.                           )
  13126.             ,@charMaxLenDBName      =
  13127.                   convert ( varchar
  13128.                            ,isnull ( max(datalength(DBName)) ,6)
  13129.                           )
  13130.             ,@charMaxLenUserName    =
  13131.                   convert ( varchar
  13132.                            ,isnull ( max(datalength(UserName)) ,8)
  13133.                           )
  13134.       from
  13135.              #tb1_UA
  13136.  
  13137.  
  13138.  
  13139. ------------  Print out the UserOrAlias report  ------------
  13140.  
  13141. /***
  13142. Raiserror('
  13143. ...Logins-to-Users...
  13144. ' ,1,1)
  13145. ***/
  13146.  
  13147. EXECUTE(
  13148. '
  13149. Set nocount off
  13150.  
  13151.  
  13152. SELECT
  13153.           ''LoginName''    = substring (LoginName  ,1 ,'
  13154.                                        + @charMaxLenLoginName  + ')
  13155.  
  13156.          ,''DBName''       = substring (DBName     ,1 ,'
  13157.                                        + @charMaxLenDBName     + ')
  13158.  
  13159.          ,''UserName''     = substring (UserName   ,1 ,'
  13160.                                        + @charMaxLenUserName   + ')
  13161.  
  13162.          ,UserOrAlias
  13163.    from
  13164.           #tb1_UA
  13165.    order by
  13166.           1 ,2 ,3
  13167.  
  13168.  
  13169. Set nocount on
  13170. '
  13171. )
  13172.  
  13173.  
  13174. -----------------------  Finalization  --------------------
  13175.  
  13176.  
  13177. IF (object_id('tempdb..#tb2_PlainLogins') IS NOT Null)
  13178.             DROP Table #tb2_PlainLogins
  13179.  
  13180. IF (object_id('tempdb..#tb1_UA') IS NOT Null)
  13181.             DROP Table #tb1_UA
  13182.  
  13183.  
  13184. LABEL_86RETURN:
  13185.  
  13186. Return @RetCode
  13187. go
  13188.  
  13189.  
  13190.  
  13191. print ''
  13192. print 'Creating procedure sp_helpindex.'
  13193. go
  13194. create procedure sp_helpindex
  13195. @objname varchar(92)        /* the table to check for indexes */
  13196. as
  13197.  
  13198. declare @objid int        /* the object id of the table */
  13199. declare @indid int        /* the index id of an index */
  13200. declare @keys varchar(200)    /* string to build up index key in */
  13201. declare @inddesc varchar(68)    /* string to build up index desc in */
  13202. declare @dbname varchar(30)
  13203.  
  13204. /*
  13205. **  Check to see that the object names are local to the current database.
  13206. */
  13207. if @objname like '%.%.%' and
  13208.     substring(@objname, 1, charindex('.', @objname) - 1) <> db_name()
  13209.     begin
  13210.         raiserror(15250,-1,-1)
  13211.         return (1)
  13212.     end
  13213.  
  13214. /*
  13215. **  Check to see the the table exists and initialize @objid.
  13216. */
  13217. select @objid = object_id(@objname)
  13218.  
  13219. /*
  13220. **  Table doesn't exist so return.
  13221. */
  13222. if @objid is NULL
  13223.     begin
  13224.         select @dbname=db_name()
  13225.         raiserror(15009,-1,-1,@objname,@dbname)
  13226.         return (1)
  13227.     end
  13228.  
  13229. /*
  13230. **  See if the object has any indexes.
  13231. **  Since there may be more than one entry in sysindexes for the object,
  13232. **  this select will set @indid to the index id of the first index.
  13233. */
  13234. select @indid = min(indid) from sysindexes
  13235.     where id = @objid
  13236.         and indid > 0
  13237.         and indid < 255
  13238.  
  13239. /*
  13240. **  If no indexes, return.
  13241. */
  13242. if @indid is NULL
  13243.     begin
  13244.         print 'Object does not have any indexes.'
  13245.         return (0)
  13246.     end
  13247.  
  13248. set nocount on
  13249.  
  13250. /*
  13251. **  Now check out each index, figure out its type and keys and
  13252. **  save the info in a temporary table that we'll print out at the end.
  13253. */
  13254. create table #spindtab
  13255. (
  13256.     index_name        varchar(30)    NOT NULL,
  13257.     index_keys        varchar(255)    NOT NULL,
  13258.     index_description    varchar(68)    NOT NULL
  13259. )
  13260.  
  13261. while @indid IS NOT NULL
  13262. begin
  13263.  
  13264.     /*
  13265.     **  First we'll figure out what the keys are.
  13266.     */
  13267.     declare @i int
  13268.     declare @thiskey varchar(30)
  13269.     declare @lastindid int
  13270.  
  13271.     select @i = 1
  13272.  
  13273.     while @i <= 16
  13274.     begin
  13275.         select @thiskey = index_col(@objname, @indid, @i)
  13276.  
  13277.         if @thiskey is null
  13278.             goto keysdone
  13279.  
  13280.         if @i = 1
  13281.             select @keys = index_col(@objname, @indid, @i)
  13282.         else
  13283.             select @keys = @keys + ', '+index_col(@objname, @indid, @i)
  13284.  
  13285.         /*
  13286.         **  Increment @i so it will check for the next key.
  13287.         */
  13288.         select @i = @i + 1
  13289.  
  13290.     end
  13291.  
  13292.  
  13293.     /*
  13294.     **  When we get here we now have all the keys.
  13295.     */
  13296.     keysdone:
  13297.  
  13298.     /*
  13299.     **  Initialize the index description by figuring out if it's a
  13300.     **  clustered or nonclustered index.
  13301.     */
  13302.     if @indid = 1
  13303.         select @inddesc = 'clustered'
  13304.  
  13305.     if @indid > 1
  13306.         select @inddesc = 'nonclustered'
  13307.  
  13308.     /*
  13309.     **  Now we'll check out the status bits for this index and
  13310.     **  build an english description from them.
  13311.     */
  13312.  
  13313.     /*
  13314.     **  See if the index is ignore_dupkey (0x01).
  13315.     */
  13316.     if exists (select *
  13317.         from master.dbo.spt_values v, sysindexes i
  13318.         where i.status & v.number = v.number
  13319.             and v.type = 'I'
  13320.             and v.number = 1
  13321.             and i.id = @objid
  13322.             and i.indid = @indid)
  13323.  
  13324.         select @inddesc = @inddesc + ', ' + v.name
  13325.         from master.dbo.spt_values v, sysindexes i
  13326.         where i.status & v.number = v.number
  13327.             and v.type = 'I'
  13328.             and v.number = 1
  13329.             and i.id = @objid
  13330.             and i.indid = @indid
  13331.  
  13332.     /*
  13333.     **  See if the index is unique (0x02).
  13334.     */
  13335.     if exists (select *
  13336.         from master.dbo.spt_values v, sysindexes i
  13337.         where i.status & v.number = v.number
  13338.             and v.type = 'I'
  13339.             and v.number = 2
  13340.             and i.id = @objid
  13341.             and i.indid = @indid)
  13342.  
  13343.         select @inddesc = @inddesc + ', ' + v.name
  13344.         from master.dbo.spt_values v, sysindexes i
  13345.         where i.status & v.number = v.number
  13346.             and v.type = 'I'
  13347.             and v.number = 2
  13348.             and i.id = @objid
  13349.             and i.indid = @indid
  13350.  
  13351.     /*
  13352.     **  See if the index is ignore_dup_row (0x04).
  13353.     */
  13354.     if exists (select *
  13355.         from master.dbo.spt_values v, sysindexes i
  13356.         where i.status & v.number = v.number
  13357.             and v.type = 'I'
  13358.             and v.number = 4
  13359.             and i.id = @objid
  13360.             and i.indid = @indid)
  13361.  
  13362.         select @inddesc = @inddesc + ', ' + v.name
  13363.         from master.dbo.spt_values v, sysindexes i
  13364.         where i.status & v.number = v.number
  13365.             and v.type = 'I'
  13366.             and v.number = 4
  13367.             and i.id = @objid
  13368.             and i.indid = @indid
  13369.  
  13370.     /*
  13371.     **  See if the index is allow_dup_row (0x40).
  13372.     */
  13373.     if exists (select *
  13374.         from master.dbo.spt_values v, sysindexes i
  13375.         where i.status & v.number = v.number
  13376.             and v.type = 'I'
  13377.             and v.number = 64
  13378.             and i.id = @objid
  13379.             and i.indid = @indid)
  13380.  
  13381.         select @inddesc = @inddesc + ', ' + v.name
  13382.         from master.dbo.spt_values v, sysindexes i
  13383.         where i.status & v.number = v.number
  13384.             and v.type = 'I'
  13385.             and v.number = 64
  13386.             and i.id = @objid
  13387.             and i.indid = @indid
  13388.  
  13389.     /*
  13390.     ** See if the index is primary key constraint (0x800).
  13391.     */
  13392.     if exists (select *
  13393.         from master.dbo.spt_values v, sysindexes i
  13394.         where i.status & v.number = v.number
  13395.             and v.type = 'I'
  13396.             and v.number = 2048
  13397.              and i.id = @objid
  13398.              and i.indid = @indid)
  13399.  
  13400.             select @inddesc = @inddesc + ', ' + v.name
  13401.                 from master.dbo.spt_values v, sysindexes i
  13402.                 where i.status & v.number = v.number
  13403.                     and v.type = 'I'
  13404.                     and v.number = 2048
  13405.                     and i.id = @objid
  13406.                     and i.indid = @indid
  13407.  
  13408.     /*
  13409.     **  See if the index is unique key constraint (0x1000).
  13410.      */
  13411.     if exists (select * from master.dbo.spt_values v, sysindexes i
  13412.             where i.status & v.number = v.number
  13413.             and v.type = 'I'
  13414.             and v.number = 4096
  13415.             and i.id = @objid
  13416.              and i.indid = @indid)
  13417.  
  13418.             select @inddesc = @inddesc + ', ' + v.name
  13419.                 from master.dbo.spt_values v, sysindexes i
  13420.                 where i.status & v.number = v.number
  13421.                     and v.type = 'I'
  13422.                     and v.number = 2048
  13423.                     and i.id = @objid
  13424.                     and i.indid = @indid
  13425.  
  13426.     /*
  13427.     **  Add the location of the data.
  13428.     */
  13429.  
  13430.     select @inddesc = @inddesc + ' located on ' + s.name
  13431.         from syssegments s, sysindexes i
  13432.         where s.segment = i.segment
  13433.             and i.id = @objid
  13434.             and i.indid = @indid
  13435.  
  13436.     /*
  13437.     **  Now we have the whole description for the index so we'll add
  13438.     **  the goods to the temporary table.
  13439.     */
  13440.     insert into #spindtab
  13441.         select name, @keys, @inddesc
  13442.             from sysindexes
  13443.             where id = @objid
  13444.                 and indid = @indid
  13445.     /*
  13446.     **  Now move @indid to the next index.
  13447.     */
  13448.     select @lastindid = @indid
  13449.     select @indid = NULL
  13450.     select @indid = min(indid)
  13451.         from sysindexes
  13452.         where id = @objid
  13453.             and indid > @lastindid
  13454.             and indid < 255
  13455. end
  13456.  
  13457. /*
  13458. **  Now print out the contents of the temporary index table.
  13459. */
  13460. select index_name = substring(index_name, 1, 20),
  13461.     index_description = substring(index_description, 1, 56),
  13462.     index_keys = index_keys from #spindtab
  13463.  
  13464. set nocount off
  13465.  
  13466. return (0)
  13467. go
  13468.  
  13469. print ''
  13470. print 'Creating procedure sp_helpjoins.'
  13471. go
  13472. create procedure sp_helpjoins
  13473. @lefttab varchar(92),            /* name of first table to join */
  13474. @righttab varchar(92)            /* name of first table to join */
  13475. as
  13476.  
  13477. declare @leftid int            /* id of first table */
  13478. declare @rightid int            /* id of second table */
  13479. declare @foundit bit            /* flag to indicate joins found */
  13480.  
  13481. /*
  13482. **  This procedure returns any foreign or common joins.
  13483. **  If none exists, then it returns any joins that have the same usertype.
  13484. **  If none exists, it returns any joins that have the same physical type.
  13485. */
  13486.  
  13487. /*
  13488. **  Make sure the @objname is local to the current database.
  13489. */
  13490. if (@lefttab like '%.%.%' and
  13491.     substring(@lefttab, 1, charindex('.', @lefttab) - 1) <> db_name())
  13492. OR
  13493.     (@righttab like '%.%.%' and
  13494.     substring(@righttab, 1, charindex('.', @righttab) - 1) <> db_name())
  13495.         begin
  13496.             raiserror(15250,-1,-1)
  13497.             return (1)
  13498.         end
  13499.  
  13500. /*
  13501. **  See if we can find the objects.  They must be a system table, user table,
  13502. **  or view.  The low 4 bits of sysobjects.sysstat indicate what the
  13503. **  object type is -- it's more reliable than using sysobjects.type which
  13504. **  could change.
  13505. */
  13506. select @leftid = id
  13507.     from sysobjects
  13508.         where id = object_id(@lefttab)
  13509.             and (sysstat & 0xf = 1        /* system table */
  13510.                 or sysstat & 0xf = 2    /* view */
  13511.                 or sysstat & 0xf = 3)    /* user table */
  13512. select @rightid = id
  13513.     from sysobjects
  13514.         where id = object_id(@righttab)
  13515.             and (sysstat & 0xf = 1        /* system table */
  13516.                 or sysstat & 0xf = 2    /* view */
  13517.                 or sysstat & 0xf = 3)    /* user table */
  13518.  
  13519. /*
  13520. **  If either of the tables don't exist, quit.
  13521. */
  13522. if @leftid is NULL
  13523.     begin
  13524.         raiserror(15195,-1,-1)
  13525.         return (1)
  13526.     end
  13527. if @rightid is NULL
  13528.     begin
  13529.         raiserror(15196,-1,-1)
  13530.         return (1)
  13531.     end
  13532.  
  13533. create table #hjtab
  13534. (
  13535.     a1    varchar(30) NOT NULL,
  13536.     a2    varchar(30) NOT NULL,
  13537.     b1    varchar(30) null,
  13538.     b2    varchar(30) null,
  13539.     c1    varchar(30) null,
  13540.     c2    varchar(30) null,
  13541.     d1    varchar(30) null,
  13542.     d2    varchar(30) null,
  13543.     e1    varchar(30) null,
  13544.     e2    varchar(30) null,
  13545.     f1    varchar(30) null,
  13546.     f2    varchar(30) null,
  13547.     g1    varchar(30) null,
  13548.     g2    varchar(30) null,
  13549.     h1    varchar(30) null,
  13550.     h2    varchar(30) null
  13551. )
  13552.  
  13553. /*
  13554. **  Look for foreign key joins.
  13555. */
  13556. select @foundit = 0
  13557. if exists (select *
  13558.         from syskeys
  13559.             where type = 2
  13560.                 and id = @leftid
  13561.                 and depid = @rightid)
  13562. begin
  13563.     insert into #hjtab
  13564.     select distinct first_pair = col_name(id, key1), col_name(depid, depkey1),
  13565.         second_pair = col_name(id, key2), col_name(depid, depkey2),
  13566.         third_pair = col_name(id, key3), col_name(depid, depkey3),
  13567.         fourth_pair = col_name(id, key4), col_name(depid, depkey4),
  13568.         fifth_pair = col_name(id, key5), col_name(depid, depkey5),
  13569.         sixth_pair = col_name(id, key6), col_name(depid, depkey6),
  13570.         seventh_pair = col_name(id, key7), col_name(depid, depkey7),
  13571.         eighth_pair = col_name(id, key8), col_name(depid, depkey8)
  13572.     from syskeys
  13573.         where type = 2
  13574.             and id = @leftid
  13575.             and depid = @rightid
  13576.  
  13577.     select @foundit = 1
  13578. end
  13579.  
  13580. if exists (select *
  13581.         from syskeys
  13582.             where type = 2
  13583.                 and id = @rightid
  13584.                 and depid = @leftid)
  13585. begin
  13586.     insert into #hjtab
  13587.     select distinct first_pair = col_name(depid, depkey1), col_name(id, key1),
  13588.         second_pair = col_name(depid, depkey2), col_name(id, key2),
  13589.         third_pair = col_name(depid, depkey3), col_name(id, key3),
  13590.         fourth_pair = col_name(depid, depkey4), col_name(id, key4),
  13591.         fifth_pair = col_name(depid, depkey5), col_name(id, key5),
  13592.         sixth_pair = col_name(depid, depkey6), col_name(id, key6),
  13593.         seventh_pair = col_name(depid, depkey7), col_name(id, key7),
  13594.         eighth_pair = col_name(depid, depkey8), col_name(id, key8)
  13595.     from syskeys
  13596.         where type = 2
  13597.             and id = @rightid
  13598.             and depid = @leftid
  13599.  
  13600.     select @foundit = 1
  13601. end
  13602.  
  13603. /*
  13604. **  Look for common key joins.
  13605. */
  13606. if exists (select *
  13607.         from syskeys
  13608.             where type = 3
  13609.                 and id = @leftid
  13610.                 and depid = @rightid)
  13611. begin
  13612.     insert into #hjtab
  13613.     select distinct first_pair = col_name(id, key1), col_name(depid, depkey1),
  13614.         second_pair = col_name(id, key2), col_name(depid, depkey2),
  13615.         third_pair = col_name(id, key3), col_name(depid, depkey3),
  13616.         fourth_pair = col_name(id, key4), col_name(depid, depkey4),
  13617.         fifth_pair = col_name(id, key5), col_name(depid, depkey5),
  13618.         sixth_pair = col_name(id, key6), col_name(depid, depkey6),
  13619.         seventh_pair = col_name(id, key7), col_name(depid, depkey7),
  13620.         eighth_pair = col_name(id, key8), col_name(depid, depkey8)
  13621.     from syskeys
  13622.         where type = 3
  13623.             and id = @leftid
  13624.             and depid = @rightid
  13625.  
  13626.     select @foundit = 1
  13627. end
  13628.  
  13629. if exists (select *
  13630.         from syskeys
  13631.             where type = 3
  13632.                 and id = @rightid
  13633.                 and depid = @leftid)
  13634. begin
  13635.     insert into #hjtab
  13636.     select distinct first_pair = col_name(depid, depkey1), col_name(id, key1),
  13637.         second_pair = col_name(depid, depkey2), col_name(id, key2),
  13638.         third_pair = col_name(depid, depkey3), col_name(id, key3),
  13639.         fourth_pair = col_name(depid, depkey4), col_name(id, key4),
  13640.         fifth_pair = col_name(depid, depkey5), col_name(id, key5),
  13641.         sixth_pair = col_name(depid, depkey6), col_name(id, key6),
  13642.         seventh_pair = col_name(depid, depkey7), col_name(id, key7),
  13643.         eighth_pair = col_name(depid, depkey8), col_name(id, key8)
  13644.     from syskeys
  13645.         where type = 3
  13646.             and id = @rightid
  13647.             and depid = @leftid
  13648.  
  13649.     select @foundit = 1
  13650. end
  13651.  
  13652. /*
  13653. **  We got a foreignkey and we didn't get a common key.
  13654. */
  13655. if @foundit = 1
  13656.     begin
  13657.         select distinct * from #hjtab
  13658.  
  13659.         drop table #hjtab
  13660.  
  13661.         return (0)
  13662.     end
  13663.  
  13664. /*
  13665. **  We didn't find any defined joins so we'll look for common user types.
  13666. */
  13667. if exists (select *
  13668.         from syscolumns a, syscolumns b
  13669.             where a.id = @leftid
  13670.                 and b.id = @rightid
  13671.                 and a.usertype = b.usertype
  13672.                 and a.usertype > 99)
  13673. begin
  13674.     select distinct first_pair = col_name(a.id, a.colid),
  13675.         col_name(b.id, b.colid)
  13676.     from syscolumns a, syscolumns b
  13677.         where a.id = @leftid
  13678.             and b.id = @rightid
  13679.             and a.usertype = b.usertype
  13680.             and a.usertype > 99
  13681.     order by first_pair
  13682.  
  13683.     /*
  13684.     **  If we found something, we can stop.
  13685.     */
  13686.     if @@rowcount > 0
  13687.         return (0)
  13688. end
  13689.  
  13690. /*
  13691. **  We couldn't find anything so far so we'll see if we have anything
  13692. **  that just shares the same physical type.
  13693. */
  13694. if exists (select *
  13695.         from syscolumns a, syscolumns b, master.dbo.spt_values y,
  13696.             master.dbo.spt_values z
  13697.         where a.id = @leftid
  13698.             and b.id = @rightid
  13699.             and a.id <> b.id
  13700.             and a.name = b.name
  13701.             and y.type = 'J'
  13702.             and a.type = y.low
  13703.             and z.type = 'J'
  13704.             and b.type = z.low
  13705.             and y.number = z.number)
  13706. begin
  13707.     select distinct first_pair = col_name(a.id, a.colid),
  13708.         col_name(b.id, b.colid)
  13709.     from syscolumns a, syscolumns b, master.dbo.spt_values y,
  13710.         master.dbo.spt_values z
  13711.     where a.id = @leftid
  13712.         and b.id = @rightid
  13713.         and a.id <> b.id
  13714.         and a.name = b.name
  13715.         and y.type = 'J'
  13716.         and a.type = y.low
  13717.         and z.type = 'J'
  13718.         and b.type = z.low
  13719.         and y.number = z.number
  13720.     order by first_pair
  13721.  
  13722. end
  13723.  
  13724. return (0)
  13725. go
  13726.  
  13727. print ''
  13728. print 'Creating procedure sp_helpkey.'
  13729. go
  13730. create procedure sp_helpkey
  13731. @tabname varchar(92) = null,    /* table or view we want to check */
  13732. @nomsg varchar(5) = 'msg'    /* option param. to suppress printing
  13733.                 ** of suggestion to also use
  13734.                 ** sp_helpconstraint to view additional
  13735.                 ** constraints. */
  13736. as
  13737.  
  13738. declare    @tabid    int    /* id of table or view we want to check */
  13739. declare @dbname varchar(30)
  13740.  
  13741. /*
  13742. **  Check to see that the object names are local to the current database.
  13743. */
  13744. if @tabname like '%.%.%' and
  13745.     substring(@tabname, 1, charindex('.', @tabname) - 1) <> db_name()
  13746.     begin
  13747.         raiserror(15078,-1,-1)
  13748.         return (1)
  13749.     end
  13750.  
  13751. /*
  13752. **  If @tabname is null, show all the keys.
  13753. */
  13754. print ''
  13755.  
  13756. if @tabname is null
  13757. begin
  13758.     select keytype = substring(v.name, 1, 10), object = object_name(k.id),
  13759.         related_object = isnull(object_name(k.depid), ' -- none --'),
  13760.         object_keys = substring(col_name(k.id, key1) + ', '
  13761.             + isnull(col_name(k.id, key2), '*') + ', '
  13762.             + isnull(col_name(k.id, key3), '*') + ', '
  13763.             + isnull(col_name(k.id, key4), '*') + ', '
  13764.             + isnull(col_name(k.id, key5), '*') + ', '
  13765.             + isnull(col_name(k.id, key6), '*') + ', '
  13766.             + isnull(col_name(k.id, key7), '*') + ', '
  13767.             + isnull(col_name(k.id, key8), '*'), 1, 70),
  13768.         related_keys = substring(isnull(col_name(k.depid, depkey1), '*')
  13769.             + ', '
  13770.             + isnull(col_name(k.depid, depkey2), '*') + ', '
  13771.             + isnull(col_name(k.depid, depkey3), '*') + ', '
  13772.             + isnull(col_name(k.depid, depkey4), '*') + ', '
  13773.             + isnull(col_name(k.depid, depkey5), '*') + ', '
  13774.             + isnull(col_name(k.depid, depkey6), '*') + ', '
  13775.             + isnull(col_name(k.depid, depkey7), '*') + ', '
  13776.             + isnull(col_name(k.depid, depkey8), '*'), 1, 70)
  13777.     from syskeys k, master.dbo.spt_values v
  13778.     where k.type = v.number
  13779.         and v.type = 'K'
  13780.     order by object, keytype, related_object
  13781.  
  13782.     return (0)
  13783. end
  13784.  
  13785. /*
  13786. **  We're looking for a particular table or view.
  13787. */
  13788. else
  13789. begin
  13790.     /*
  13791.     **  Make sure the table or view exists.
  13792.     */
  13793.     select @tabid = object_id(@tabname)
  13794.  
  13795.     if @tabid is null
  13796.         begin
  13797.             select @dbname=db_name()
  13798.             raiserror(15009,-1,-1,@tabname,@dbname)
  13799.             return (1)
  13800.         end
  13801.  
  13802.     /*
  13803.     **  See if any keys exist.
  13804.     */
  13805.     if not exists (select *
  13806.             from syskeys
  13807.             where id = @tabid or depid = @tabid)
  13808.         begin
  13809.             if @nomsg <> 'nomsg'
  13810.                 begin
  13811.                     print 'No keys were defined for this object using sp_primarykey,'
  13812.                     print 'sp_foreignkey or sp_commonkey.  Please use sp_helpconstraint'
  13813.                     print 'to list any ''system enforced'' keys.'
  13814.                 end
  13815.  
  13816.             return (0)
  13817.         end
  13818.  
  13819.     select keytype = substring(v.name, 1, 10), object = object_name(k.id),
  13820.         related_object = isnull(object_name(k.depid), ' -- none --'),
  13821.         object_keys = substring(col_name(k.id, key1) + ', '
  13822.             + isnull(col_name(k.id, key2), '*') + ', '
  13823.             + isnull(col_name(k.id, key3), '*') + ', '
  13824.             + isnull(col_name(k.id, key4), '*') + ', '
  13825.             + isnull(col_name(k.id, key5), '*') + ', '
  13826.             + isnull(col_name(k.id, key6), '*') + ', '
  13827.             + isnull(col_name(k.id, key7), '*') + ', '
  13828.             + isnull(col_name(k.id, key8), '*'), 1, 70),
  13829.         related_keys = substring(isnull(col_name(k.depid, depkey1), '*')
  13830.             + ', '
  13831.             + isnull(col_name(k.depid, depkey2), '*') + ', '
  13832.             + isnull(col_name(k.depid, depkey3), '*') + ', '
  13833.             + isnull(col_name(k.depid, depkey4), '*') + ', '
  13834.             + isnull(col_name(k.depid, depkey5), '*') + ', '
  13835.             + isnull(col_name(k.depid, depkey6), '*') + ', '
  13836.             + isnull(col_name(k.depid, depkey7), '*') + ', '
  13837.             + isnull(col_name(k.depid, depkey8), '*'), 1, 70)
  13838.     from syskeys k, master.dbo.spt_values v
  13839.     where k.type = v.number
  13840.         and v.type = 'K'
  13841.         and (k.id = @tabid or k.depid = @tabid)
  13842.     order by object, keytype, related_object
  13843.  
  13844.     return (0)
  13845. end
  13846. go
  13847.  
  13848. print ''
  13849. print 'Creating procedure sp_objectsegment.'
  13850. go
  13851. create procedure sp_objectsegment
  13852. @objid    int
  13853. as
  13854.     /*
  13855.     ** Print out the object's data segment if applicable.
  13856.     */
  13857.  
  13858.     if exists (select * from sysobjects
  13859.             where id = @objid
  13860.             and sysstat & 0xf in (1,3))    -- system table or user table.
  13861.         begin
  13862.             select Data_located_on_segment = s.name
  13863.             from syssegments s, sysindexes i
  13864.             where i.id = @objid
  13865.                 and i.indid < 2
  13866.                 and i.segment = s.segment
  13867.         end
  13868.  
  13869.     /*
  13870.     **  It's not a table so segment is not applicable.
  13871.     */
  13872.     else
  13873.         select Data_located_on_segment = 'not applicable'
  13874.  
  13875. return (0)
  13876. go
  13877.  
  13878.  
  13879. print ''
  13880. print 'Creating procedure sp_help.'
  13881. go
  13882. create procedure sp_help  -- 1995/09/13 18:23
  13883.     @objname varchar(92) = NULL      /* object name we're after */
  13884. as
  13885.  
  13886. declare @objid int         /* id of the object */
  13887. declare @sysstat smallint     /* the type of the object */
  13888. declare @dbname varchar(30)
  13889. declare @colname varchar(30)
  13890.  
  13891. set nocount on
  13892.  
  13893. /*
  13894. **  If no @objname given, give a little info about all objects.
  13895. */
  13896. if @objname is null
  13897. begin
  13898.    select Name = o.name,
  13899.       Owner = user_name(uid),
  13900.       Object_type = v.name + x.name
  13901.    from sysobjects o, master.dbo.spt_values v, master.dbo.spt_values x
  13902.    where o.sysstat & 0xf = v.number
  13903.       and v.type = 'O'
  13904.       and x.type = 'R'
  13905.       and o.userstat & -32768 = x.number
  13906.    order by Object_type desc, Name asc
  13907.  
  13908.    print ''
  13909.  
  13910.    select User_type = s.name,
  13911.           'Storage_type' = st.name,
  13912.           'Length' = s.length,
  13913.           'Prec' =
  13914.          case when s.type in  -- Prec. only valid for numerics.
  13915.          (38,48,52,55,56,59,60,62,63,106,108,109,110,122)
  13916.          then convert(varchar(4),s.prec)
  13917.          else ' '
  13918.          end,
  13919.           'Scale' =
  13920.          case when s.type in  -- Scale only valid for numerics.
  13921.          (38,48,52,55,56,59,60,62,63,106,108,109,110,122)
  13922.          then convert(varchar(4),s.scale)
  13923.          else ' '
  13924.          end,
  13925.           'Nullable' = (select name from spt_values
  13926.             where number = convert(int,s.allownulls)
  13927.             and type = 'B'),
  13928.           'Default_name' = isnull(object_name(s.tdefault),
  13929.          (select name from master.dbo.spt_values
  13930.             where number = 2 and type = 'B')),
  13931.           'Rule_name' = isnull(object_name(s.domain),
  13932.          (select name from master.dbo.spt_values
  13933.             where number = 2 and type = 'B'))
  13934.    from systypes s, systypes st
  13935.    where s.type = st.type
  13936.       and s.usertype > 99
  13937.       and st.usertype <= 99
  13938.       and st.usertype <> 18 /* ignore sysname */
  13939.    order by s.name
  13940.  
  13941.    return(0)
  13942. end
  13943.  
  13944. /*
  13945. **  Make sure the @objname is local to the current database.
  13946. */
  13947. if @objname like '%.%.%' and
  13948.    substring(@objname, 1, charindex('.', @objname) - 1) <> db_name()
  13949.    begin
  13950.       raiserror(15250,-1,-1)
  13951.       return(1)
  13952.    end
  13953.  
  13954. /*
  13955. **  Now check to see if the @objname is in sysobjects.  It has to be either
  13956. **  in sysobjects or systypes.
  13957. */
  13958. select @objid = id, @sysstat = sysstat from sysobjects
  13959.    where id = object_id(@objname)
  13960.  
  13961. /*
  13962. **  It wasn't in sysobjects so we'll check in systypes.
  13963. */
  13964. if @objid is null
  13965. begin
  13966.    select @objid = usertype from systypes where name = @objname
  13967.  
  13968.    /*
  13969.    **  Time to give up -- @objname is not in sysobjects or systypes.
  13970.    */
  13971.    if @objid is null
  13972.       begin
  13973.          select @dbname=db_name()
  13974.          raiserror(15009,-1,-1,@objname,@dbname)
  13975.          return(1)
  13976.       end
  13977.  
  13978.    /*
  13979.    ** Print help about a data type.  Prec and scale only valid
  13980.    ** for numerics.
  13981.    */
  13982.  
  13983.    if (select type from systypes
  13984.       where usertype = @objid) in
  13985.          (38,48,52,55,56,59,60,62,63,106,108,109,110,122)
  13986.  
  13987.       select Type_name = s.name,
  13988.          Storage_type = st.name,
  13989.          Length = s.length,
  13990.          Prec = s.prec,
  13991.          Scale = s.scale,
  13992.          'Nullable' = (select name from master.dbo.spt_values
  13993.                where number =
  13994.                   convert(int,s.allownulls)
  13995.                   and type = 'B'),
  13996.          Default_name = isnull(object_name(s.tdefault),
  13997.             (select name from master.dbo.spt_values
  13998.                where number = 2 and type = 'B')),
  13999.          Rule_name = isnull(object_name(s.domain),
  14000.             (select name from master.dbo.spt_values
  14001.                where number = 2 and type = 'B'))
  14002.       from systypes s, systypes st
  14003.       where s.usertype = @objid
  14004.          and s.type = st.type
  14005.          and st.usertype <> 18 /* ignore sysname */
  14006.          and st.usertype < 100
  14007.    else
  14008.       select Type_name = s.name,
  14009.          Storage_type = st.name,
  14010.          Length = s.length,
  14011.          Prec = '',
  14012.          Scale = '',
  14013.          'Nullable' = (select name from master.dbo.spt_values
  14014.                where number =
  14015.                   convert(int,s.allownulls)
  14016.                   and type = 'B'),
  14017.          Default_name = isnull(object_name(s.tdefault),
  14018.             (select name from master.dbo.spt_values
  14019.                where number = 2 and type = 'B')),
  14020.          Rule_name =
  14021.             isnull(object_name(s.domain),
  14022.             (select name from master.dbo.spt_values
  14023.                where number = 2 and type = 'B'))
  14024.       from systypes s, systypes st
  14025.       where s.usertype = @objid
  14026.          and s.type = st.type
  14027.          and st.usertype <> 18 /* ignore sysname */
  14028.          and st.usertype < 100
  14029.  
  14030.  
  14031.    return(0)
  14032. end
  14033.  
  14034. /*
  14035. **  It's in sysobjects so print out the information.
  14036. */
  14037. select Name = o.name,
  14038.    Owner = user_name(uid),
  14039.    Type = v.name + x.name,
  14040.    When_created = o.crdate
  14041. from sysobjects o, master.dbo.spt_values v, master.dbo.spt_values x
  14042. where o.id = @objid
  14043.    and o.sysstat & 0xf = v.number
  14044.    and v.type = 'O'
  14045.    and x.type = 'R'
  14046.    and o.userstat & -32768 = x.number
  14047.  
  14048. print ''
  14049. execute sp_objectsegment @objid
  14050.  
  14051. /*
  14052. **  If the object is a system table, view, or user table, we want to check
  14053. **  out the object's columns here.
  14054. */
  14055.  
  14056. if @sysstat & 0xf in (1, 2, 3)   -- system table, view, or user table.
  14057. begin
  14058.  
  14059.    create table #sphelptab
  14060.    (
  14061.       col_name char (30)   NULL,
  14062.       col_type char (30)   NULL,
  14063.       col_len     tinyint     NULL,
  14064.       col_prec char (5) NULL,
  14065.       col_scale   char (5) NULL,
  14066.       col_status  tinyint     NULL,
  14067.       colid    tinyint     NULL,
  14068.       type_systemdata  tinyint  NULL
  14069.    )
  14070.  
  14071.    insert into #sphelptab
  14072.       select c.name, t.name, c.length, convert(char(5),c.prec),
  14073.          convert(char(5),c.scale), c.status,
  14074.          c.colid, t.type
  14075.       from syscolumns c, systypes t
  14076.       where c.id = @objid
  14077.          and c.usertype *= t.usertype
  14078.  
  14079.    /*
  14080.    ** Don't display precision and scale for datatypes
  14081.    ** for which they not applicable.
  14082.    */
  14083.    update #sphelptab
  14084.       set col_prec = '', col_scale = ''
  14085.       where col_type in
  14086.          (select name from systypes where type not in
  14087.          (38,48,52,55,56,59,60,62,63,106,108,109,110,122))
  14088.  
  14089.    print ''
  14090.    select Column_name = col_name,
  14091.           Type = col_type,
  14092.           Length = col_len,
  14093.           Prec = col_prec,
  14094.           Scale = col_scale,
  14095.  
  14096.           Nullable = case when (col_status & 8) = 0 then
  14097.             (select name from master.dbo.spt_values
  14098.                where number = 0
  14099.                   and type = 'B')
  14100.             else
  14101.             (select name from master.dbo.spt_values
  14102.                where number = 1
  14103.                   and type = 'B')
  14104.             end,
  14105.  
  14106.           TrimTrailingBlanks =  -- Blanks; or 0x00 bytes for varbinary
  14107.                CASE
  14108.                   When (type_systemdata NOT IN (45,47,39,37))
  14109.                      Then '(n/a)'
  14110.                   When (col_status & 0x10) > 0
  14111.                      Then (Select   name
  14112.                               from  master.dbo.spt_values
  14113.                               where number = 0 and type = 'B')
  14114.                   Else
  14115.                           (Select   name
  14116.                               from  master.dbo.spt_values
  14117.                               where number = 1 and type = 'B')
  14118.                END,
  14119.  
  14120.           FixedLenNullInSource =
  14121.                CASE
  14122.                   When (type_systemdata NOT IN (45,47,39,37))
  14123.                      Then '(n/a)'
  14124.                   When (col_status & 0x20) = 0
  14125.                      Then (Select   name
  14126.                               from  master.dbo.spt_values
  14127.                               where number = 0 and type = 'B')
  14128.                   Else
  14129.                           (Select   name
  14130.                               from  master.dbo.spt_values
  14131.                               where number = 1 and type = 'B')
  14132.                END
  14133.  
  14134.    from #sphelptab
  14135.    order by colid
  14136.  
  14137.    -- See if there is an identity column.
  14138.  
  14139.    print ''
  14140.    select @colname = null
  14141.    select @colname = col_name from #sphelptab
  14142.       where (col_status & 128) = 128
  14143.  
  14144.    select 'Identity' = isnull(@colname,'No identity column defined.'),
  14145.           'Seed' = ident_seed(@objname),
  14146.           'Increment' = ident_incr(@objname)
  14147.  
  14148. end
  14149.  
  14150. /*
  14151. **  For procedures, the parameters of the procedures are stored in syscolumns.
  14152. */
  14153. if @sysstat & 0xf = 4   -- stored procedure
  14154. begin
  14155.    /*
  14156.    **  Does the sproc have any parameters?
  14157.    */
  14158.    if exists (select * from syscolumns c, systypes t
  14159.          where c.id = @objid
  14160.             and c.usertype *= t.usertype)
  14161.    begin
  14162.       print ''
  14163.       select Parameter_name = c.name,
  14164.          Type = t.name,
  14165.          Length = c.length,
  14166.          Prec = c.prec,
  14167.          Scale = c.scale,
  14168.          Param_order=c.colid
  14169.       from syscolumns c, systypes t
  14170.       where c.id = @objid
  14171.          and c.usertype *= t.usertype
  14172.    end
  14173. end
  14174.  
  14175. /*
  14176. **  If the object is a table, check out the indexes.
  14177. */
  14178. if @sysstat & 0xf in (1, 3)   -- system table or user table
  14179.    begin
  14180.       print ''
  14181.       execute sp_helpindex @objname
  14182.    end
  14183.  
  14184. /*
  14185. **  If the object is a table or view, check out the constraints.
  14186. */
  14187. if @sysstat & 0xf in (1, 2, 3)   -- system table, view, or user table
  14188.    begin
  14189.       print ''
  14190.       execute sp_helpconstraint @objname,'nomsg'
  14191.    end
  14192.  
  14193. return (0)
  14194. go
  14195.  
  14196.  
  14197. print ''
  14198. print 'Creating procedure sp_a_count_bits_on.'
  14199. go
  14200. CREATE Procedure sp_a_count_bits_on --1995/10/01 21:04
  14201.  
  14202. /**
  14203. Originally written 1995/10/01 for sp_helprotect.
  14204. Count of ON bits is RETURNed.
  14205. **/
  14206.  
  14207.     @p_int                       int
  14208.  
  14209.    ,@p_num_bits_want_counted     smallint    = 32 --  1 thru 32 are valid.
  14210. AS
  14211.  
  14212. Set nocount on
  14213.  
  14214. Declare
  14215.     @one_bit_int_value           int
  14216.    ,@count_on_bits               smallint
  14217.    ,@count_bits                  smallint
  14218.    ,@test_bit_int_value          int
  14219.    ,@two_byte_int                int
  14220.    ,@b4_p_int                    binary(4)
  14221.    ,@pos_b4                      smallint
  14222.    ,@bits_counted_previously     smallint
  14223.    ,@bits_counted_on_previously  smallint
  14224.  
  14225.  
  14226. -----------------  Edit input parms  --------------------
  14227.  
  14228.  
  14229. IF (@p_int IS Null)
  14230.    RETURN 0
  14231.  
  14232. Select @b4_p_int = convert(binary(4),@p_int)
  14233.  
  14234.  
  14235.  
  14236. IF (     isnull(@p_num_bits_want_counted,0) <  1
  14237.     OR   isnull(@p_num_bits_want_counted,0) > 32
  14238.    )
  14239.    RETURN 0
  14240.  
  14241.  
  14242.  
  14243. ------------------  Mainline  -----------------------------
  14244.  
  14245.  
  14246. ----------------  LOOP 10:  Halves of datatype INTEGER  ---
  14247.  
  14248.  
  14249. Select
  14250.        @bits_counted_previously     = 0
  14251.       ,@bits_counted_on_previously  = 0
  14252.  
  14253. Select @pos_b4 = 3
  14254.  
  14255.  
  14256.  
  14257.  
  14258. WHILE (@pos_b4 >= 1
  14259.       )
  14260.    begin --loop 10
  14261.  
  14262.  
  14263.    Select @two_byte_int = convert(int,substring(@b4_p_int,@pos_b4,2))
  14264.  
  14265.  
  14266.  
  14267. ----------------  LOOP 20:  Individual bit tests  -----------
  14268.  
  14269.  
  14270.    Select
  14271.        @test_bit_int_value    = 1
  14272.       ,@count_bits            = 0
  14273.       ,@count_on_bits         = 0
  14274.  
  14275.  
  14276.  
  14277.    WHILE (     @count_bits                              < 16
  14278.           AND  (@bits_counted_previously + @count_bits) <
  14279.                                            @p_num_bits_want_counted
  14280.          )
  14281.       begin --loop 20
  14282.  
  14283.       Select @count_bits = @count_bits + 1
  14284.  
  14285.       Select @one_bit_int_value = @two_byte_int & @test_bit_int_value
  14286.  
  14287.  
  14288.       if (@one_bit_int_value > 0)
  14289.          Select @count_on_bits = @count_on_bits + 1
  14290.  
  14291.  
  14292.       select @test_bit_int_value = @test_bit_int_value * 2
  14293.  
  14294.       end --loop 20
  14295.  
  14296.  
  14297.  
  14298.  
  14299.    Select @bits_counted_previously =
  14300.           @bits_counted_previously + @count_bits
  14301.  
  14302.    Select @bits_counted_on_previously =
  14303.           @bits_counted_on_previously + @count_on_bits
  14304.  
  14305.  
  14306.    Select @pos_b4 = @pos_b4 - 2
  14307.  
  14308.  
  14309.    end --loop 10
  14310.  
  14311.  
  14312.  
  14313. -----------------  Finalization  ---------------------------
  14314.  
  14315.  
  14316. RETURN @bits_counted_on_previously
  14317. go
  14318.  
  14319.  
  14320. print ''
  14321. print 'Creating procedure sp_helprotect.'
  14322. go
  14323. CREATE PROCEDURE sp_helprotect -- 1995/10/06 19:03
  14324.  
  14325.     @pOwnerObjectStatementName   character varying(99)  = '%'
  14326.    ,@pGranteeName                character varying(66)  = '%'
  14327.    ,@pGrantorName                character varying(66)  = '%'
  14328.    ,@pGeneralPermissionType      character varying(10)  = 'o s'
  14329. AS
  14330.  
  14331. /********
  14332.       Explanation of the parms...
  14333.       ---------------------------
  14334.  
  14335. @pOwnerObjectStatementName:  Name of [Owner.]Object and Statement; meaning
  14336.                              for sysprotects.id and sysprotects.action at the
  14337.                              same time; thus see parm @pGeneralPermissionType.
  14338.    Examples-   'user2.tb%'  , 'create%'
  14339.  
  14340.  
  14341. @pGranteeName:  Name of the grantee (for sysprotects.uid).
  14342.    Examples-   'user2'
  14343.  
  14344.  
  14345. @pGrantorName:  Name of the grantor (for sysprotects.grantor).
  14346.    Examples-   '[^d]%' --Would prevent report rows which would
  14347.                        --  have 'dbo' as grantor.
  14348.  
  14349. @pGeneralPermissionType:  O=Object, S=Statement; include all which apply.
  14350.    Examples-   'o'  , ',s'  , 'os'  , 'so'  , 's o'  , 's,o'
  14351. ********/
  14352.  
  14353.  
  14354. Set nocount on
  14355.  
  14356. Declare
  14357.        @RetCode               integer
  14358.       ,@High2Int              integer
  14359.       ,@High4Int              integer
  14360.       ,@Int1                  integer
  14361.       ,@Int2                  integer
  14362.       ,@Int3                  integer
  14363.       ,@Int4                  integer
  14364.  
  14365. Declare
  14366.        @full_len_need_sysprots_cols    integer
  14367.       ,@num_col_bits_on                integer
  14368.  
  14369. Declare
  14370.        @Tinyint1              tinyint
  14371.  
  14372. Declare
  14373.        @charMaxLenOwner       character varying(11)
  14374.       ,@charMaxLenObject      character varying(11)
  14375.       ,@charMaxLenGrantee     character varying(11)
  14376.       ,@charMaxLenGrantor     character varying(11)
  14377.       ,@charMaxLenAction      character varying(11)
  14378.       ,@charMaxLenColumnName  character varying(11)
  14379.  
  14380. Declare
  14381.        @OrderBy               character varying(255)
  14382.  
  14383.       ,@OwnerName             character varying(66)
  14384.       ,@ObjectStatementName   character varying(66)
  14385.  
  14386.       ,@VarBinFront           varbinary(32)
  14387.       ,@VarBinBack            varbinary(32)
  14388.       ,@Bin1                 varbinary(1)
  14389.  
  14390. Declare
  14391.        @c1pkid                integer
  14392.       ,@c1id                  integer
  14393.       ,@c1uid                 smallint
  14394.       ,@c1action              tinyint
  14395.       ,@c1protecttype         tinyint
  14396.       ,@c1columns             varbinary(32)
  14397.       ,@c1grantor             smallint
  14398.  
  14399. Declare
  14400.        @t1_all_col_bits_on             tinyint
  14401.       ,@t1_columns_orig_datalength     smallint
  14402.       ,@t1_columns_flip_datalength     smallint
  14403.       ,@t1_columns_flipped             varbinary(32)
  14404.       ,@t1_columns_orig                varbinary(32)
  14405.       ,@t1_max_colid                   smallint
  14406.       ,@t1_type1code                   char(6)
  14407.       ,@t1_objtype                     char(2)
  14408.       ,@t1_new_bit_on                  tinyint
  14409.  
  14410.  
  14411.  
  14412. ----------------------------------------------------------------------------
  14413. --
  14414. --             Initialization
  14415. --
  14416. ----------------------------------------------------------------------------
  14417.  
  14418.  
  14419. Select
  14420.        @RetCode               = 0            -- 0=good ,1=bad
  14421.       ,@High2Int              =      32767
  14422.       ,@High4Int              = 2147483647
  14423.  
  14424.  
  14425. -----------------------  Input parm edits  ---------------------
  14426.  
  14427.  
  14428. Select @pGeneralPermissionType = upper( isnull(@pGeneralPermissionType,'?') )
  14429.  
  14430. IF (     charindex('O',@pGeneralPermissionType) <= 0
  14431.     AND  charindex('S',@pGeneralPermissionType) <= 0
  14432.    )
  14433.    begin
  14434.    RaisError(15300,-1,-1 ,@pGeneralPermissionType,'o,s')
  14435.    Select @RetCode = 1
  14436.    GOTO LABEL_86RETURN
  14437.    end
  14438.  
  14439.  
  14440. --------
  14441.  
  14442.  
  14443. IF (     @pOwnerObjectStatementName IS Null
  14444.     OR   @pGranteeName              IS Null
  14445.     OR   @pGrantorName              IS Null
  14446.    )
  14447.    begin
  14448.    RaisError(15008,-1,-1)  --No nulls allowed, use '%' instead.
  14449.    Select @RetCode = 1
  14450.    GOTO LABEL_86RETURN
  14451.    end
  14452.  
  14453.  
  14454. --------  Derive OwnerName
  14455.  
  14456.  
  14457. IF (@pOwnerObjectStatementName LIKE '%.%.%')
  14458.    begin
  14459.    RaisError(15009,-1,-1)  --Do not qualify with DB name.
  14460.    Select @RetCode = 1
  14461.    GOTO LABEL_86RETURN
  14462.    end
  14463.  
  14464.  
  14465.  
  14466.  
  14467. IF (@pOwnerObjectStatementName LIKE '%.%')
  14468.  
  14469.    Select
  14470.           @OwnerName    =
  14471.                substring ( @pOwnerObjectStatementName
  14472.                           ,1
  14473.                           ,charindex('.' ,@pOwnerObjectStatementName) - 1
  14474.                          )
  14475.          ,@ObjectStatementName   =
  14476.                substring ( @pOwnerObjectStatementName
  14477.                           ,charindex('.' ,@pOwnerObjectStatementName) + 1
  14478.                           ,Datalength(@pOwnerObjectStatementName)
  14479.                          )
  14480. ELSE
  14481.  
  14482.    Select
  14483.           @OwnerName             = '%'
  14484.          ,@ObjectStatementName   = @pOwnerObjectStatementName
  14485.  
  14486.  
  14487.  
  14488. ----------------------------------------------------------------------------
  14489. --
  14490. --             MainLine:  Phase 10
  14491. --
  14492. ----------------------------------------------------------------------------
  14493.  
  14494.  
  14495.  
  14496. --------------  create a fixed copy of sysprotects for processing  --------
  14497.  
  14498.  
  14499. -- Simpler when bit 0 is OFF, because other ON bits really mean ON.
  14500.  
  14501.  
  14502. CREATE Table #t1_Prots
  14503.    (
  14504.     pkid                int               not null    identity(1,1)
  14505.    ,type1code           char(6)           not null
  14506.    ,status              smallint          not null -- 0=unprocessed
  14507.    ,objtype             char(2)               null
  14508.  
  14509.    ,id                  int                   null
  14510.    ,uid                 smallint              null
  14511.    ,action              tinyint               null
  14512.    ,protecttype         tinyint               null
  14513.    ,grantor             smallint              null
  14514.    ,columns_orig        varbinary(32)         null
  14515.  
  14516.    ,columns_flipped     varbinary(32)         null
  14517.    ,max_colid           smallint              null
  14518.    ,all_col_bits_on     tinyint               null
  14519.    ,new_bit_on          tinyint               null  -- 1=yes on
  14520.    )
  14521.  
  14522.  
  14523.  
  14524. CREATE Unique    Clustered Index ix1 on #t1_Prots (pkid)
  14525. CREATE Unique Nonclustered Index ix2 on #t1_Prots (id,uid,action,grantor)
  14526.  
  14527.  
  14528.  
  14529.  
  14530. -- Will loop through OFF=ON rows to finish the copy of sysprotects.
  14531. -- For these rows, ON=ON only for the 0x01 bit.
  14532.  
  14533. DECLARE Cursor1_Prots
  14534.    Insensitive
  14535.    Cursor For
  14536. SELECT
  14537.              id
  14538.             ,uid
  14539.             ,action
  14540.             ,protecttype
  14541.             ,columns
  14542.             ,grantor
  14543.       from
  14544.              sysprotects
  14545.  
  14546.  
  14547.  
  14548. OPEN Cursor1_Prots
  14549.  
  14550.  
  14551.  
  14552. ---------------
  14553. WHILE (110=110)
  14554.    begin
  14555.  
  14556.  
  14557.    FETCH
  14558.              Next
  14559.       from
  14560.              Cursor1_Prots
  14561.       into
  14562.              @c1id
  14563.             ,@c1uid
  14564.             ,@c1action
  14565.             ,@c1protecttype
  14566.             ,@c1columns
  14567.             ,@c1grantor
  14568.  
  14569.  
  14570.  
  14571.    IF (@@fetch_status <> 0)
  14572.       begin
  14573.       Deallocate Cursor1_Prots
  14574.       BREAK
  14575.       end
  14576.  
  14577.  
  14578.    Select
  14579.           @t1_type1code               = Null
  14580.          ,@t1_columns_orig            = @c1columns
  14581.          ,@t1_columns_orig_datalength = datalength(@c1columns) --Null if null.
  14582.          ,@t1_max_colid               = Null
  14583.          ,@t1_all_col_bits_on         = Null
  14584.          ,@t1_new_bit_on              = Null
  14585.          ,@t1_type1code               = '1Regul'
  14586.          ,@t1_objtype                 = Null
  14587.  
  14588.  
  14589.    SELECT
  14590.              @t1_objtype   = ob.type
  14591.       from
  14592.              sysobjects    ob
  14593.       where
  14594.              ob.id         = @c1id
  14595.  
  14596.  
  14597.  
  14598.  
  14599. ---------------  Handle the simple cases first.
  14600.  
  14601.  
  14602.    IF (@c1columns IS Null)
  14603.       begin
  14604.       Select @t1_type1code       = '2Simpl'
  14605.             ,@t1_columns_flipped = @c1columns
  14606.       GOTO LABEL_49INSERT1
  14607.       end
  14608.  
  14609.  
  14610.  
  14611. ---------------------  Upcoming steps...  ------------------
  14612.  
  14613.  
  14614. --Pad columns bits variable to full needed length.
  14615. --Flip most bits in columns bits var, so ON=ON consistently.
  14616. --Count ON bits in columns bits var, compare to max syscolumns colid.
  14617. --Insert #t2
  14618.  
  14619.  
  14620.  
  14621. ------------------------------------------------------------------------
  14622. --------------  Must first append some 0x00 paddings perhaps  ----------
  14623.  
  14624.  
  14625.    SELECT
  14626.              @t1_max_colid = max(colid)  --Cannot come back Null this time.
  14627.       from
  14628.              syscolumns
  14629.       where
  14630.              id    = @c1id
  14631.  
  14632.  
  14633.  
  14634. --As needed, later add 1 bitcount for the All/New 0x01 "zero" bit
  14635. --   of the first sysprotects.columns bytes.
  14636.  
  14637.  
  14638.    Select @full_len_need_sysprots_cols =
  14639.           (@t1_max_colid + 1) / 8       --8 bits per byte; trunc not round
  14640.  
  14641.  
  14642.    IF ((@t1_max_colid + 1) % 8 > 0)
  14643.       Select @full_len_need_sysprots_cols =
  14644.              @full_len_need_sysprots_cols + 1
  14645.  
  14646.  
  14647.    --------------------------------------
  14648.    WHILE (datalength(@c1columns) < @full_len_need_sysprots_cols
  14649.          )
  14650.       begin                      --Pad the columns bits variable.
  14651.  
  14652.       Select @c1columns = @c1columns + 0x00 --convert(binary(1),0x00) is trimmed
  14653.  
  14654.       end --loop to pad
  14655.  
  14656.  
  14657.    Select @t1_columns_flip_datalength = datalength(@c1columns)
  14658.  
  14659.  
  14660.  
  14661.  
  14662. ------------------------------------------------------------------------
  14663. -----------------  Flip most bits, so never OFF=ON anymore  ------------
  14664.  
  14665.  
  14666.  
  14667. --Bit operators do not work against binarys, so use int.
  14668.  
  14669.  
  14670.  
  14671.    Select @Int1 = convert(int,substring(@c1columns,1,1))
  14672.  
  14673.    IF (@Int1 & 1 = 0
  14674.       )
  14675.       begin
  14676.       Select @t1_new_bit_on = 0
  14677.  
  14678.       GOTO LABEL_73BITONMEANSON  --ON already means ON consistently
  14679.  
  14680.       end
  14681.    ELSE
  14682.       Select @t1_new_bit_on = 1
  14683.  
  14684.    IF (@t1_objtype = 'V ')
  14685.       begin
  14686.       Select @t1_new_bit_on = 0
  14687.  
  14688.       Select @Int1 = @Int1 & ~1  --Views cannot get "New" columns.
  14689.       Select @Bin1 = convert(binary(1),@Int1)  --Len 1 not trimmed.
  14690.       Select @c1columns = @Bin1 +
  14691.                           substring(@c1columns,2,@t1_columns_flip_datalength-1)
  14692.       end
  14693.  
  14694.  
  14695.  
  14696.  
  14697.  
  14698.    Select @Int1 = 0  --Position in substring
  14699.  
  14700.  
  14701. --Proper for Revoke rows as well as for Grant rows.
  14702.    ------------------------------------
  14703.    WHILE (@t1_columns_flip_datalength > @Int1
  14704.          )
  14705.       begin  --Total length > current byte position, more Flipping.
  14706.  
  14707.  
  14708.       Select @Int1 = @Int1 + 1  --increment pos
  14709.  
  14710.  
  14711.       IF (1 = @Int1)
  14712.          begin
  14713.          Select @VarBinFront = Null
  14714.          Select @Bin1        = substring(@c1columns ,@Int1   ,1)
  14715.          Select @VarBinBack  = substring(@c1columns ,@Int1+1
  14716.                                         ,@t1_columns_flip_datalength-@Int1)
  14717.          end
  14718.  
  14719.  
  14720.       IF (     1                           < @Int1
  14721.           AND  @t1_columns_flip_datalength > @Int1
  14722.          )
  14723.          begin
  14724.          Select @VarBinFront = substring(@c1columns ,1       ,@Int1-1)
  14725.          Select @Bin1        = substring(@c1columns ,@Int1   ,1)
  14726.          Select @VarBinBack  = substring(@c1columns ,@Int1+1
  14727.                                         ,@t1_columns_flip_datalength-@Int1)
  14728.          end
  14729.  
  14730.  
  14731.       IF (@t1_columns_flip_datalength = @Int1)
  14732.          begin
  14733.          Select @VarBinFront = substring(@c1columns ,1       ,@Int1-1)
  14734.          Select @Bin1        = substring(@c1columns ,@Int1   ,1)
  14735.          Select @VarBinBack  = Null
  14736.          end
  14737.  
  14738.  
  14739.  
  14740.       Select @Int3 = convert(int,@Bin1)
  14741.  
  14742.  
  14743.  
  14744.       IF (     @Int1     = 1  --Byte containing the All/NewCols bit (0x01)
  14745.           AND  @Int3 & 1 > 0  --NewCols bit on
  14746.          )
  14747.          Select @Int3 = @Int3 & (~1)  --Flip (here Turn off) the 0x01 bit
  14748.  
  14749.  
  14750.  
  14751.       --Flip all the bits (so 0x01 bit return to its initial setting).
  14752.       Select @Int3 = ~@Int3
  14753.  
  14754.       Select @Bin1      = convert(binary(1),@Int3)
  14755.  
  14756.       Select @c1columns = @VarBinFront + @Bin1 + @VarBinBack
  14757.  
  14758.  
  14759.       end  --loop to flip most bits
  14760.  
  14761.  
  14762.  
  14763. LABEL_73BITONMEANSON:
  14764.  
  14765.  
  14766.  
  14767. ------------------------------------------------------------------------------
  14768. -----------  Determine whether all current columns are individually ON!  -----
  14769.  
  14770.  
  14771.  
  14772. LABEL_42LOOP110EACHBIT:
  14773.  
  14774.  
  14775.  
  14776.    Select
  14777.        @Int1                     = 0  --POSition
  14778.       ,@num_col_bits_on          = 0
  14779.  
  14780.  
  14781.  
  14782.    WHILE (37=37)
  14783.       begin
  14784.  
  14785.       Select @Int1 = @Int1 + 1
  14786.  
  14787.       IF (@Int1 > @full_len_need_sysprots_cols)
  14788.          BREAK
  14789.  
  14790.  
  14791.       Select @Int2 = convert( int ,substring(@c1columns ,@Int1 ,1) )
  14792.  
  14793.  
  14794.  
  14795.       IF (@Int1 <= (@t1_max_colid + 1) / 8    --truncated, not rounded
  14796.          )
  14797.          Select @Int4 = 8  --num of Bits want tested in this byte/number
  14798.       ELSE
  14799.          Select @Int4 = (@t1_max_colid + 1) % 8
  14800.  
  14801.  
  14802.  
  14803.       Execute @Int3 =  sp_a_count_bits_on  @Int2 ,@Int4
  14804.  
  14805.  
  14806.       IF (     @Int1       = 1
  14807.           AND  @Int2 & 1   > 0
  14808.          )
  14809.          Select @Int3 = @Int3 - 1  --Do not count "New" bit.
  14810.  
  14811.  
  14812.       Select @num_col_bits_on = @num_col_bits_on + @Int3
  14813.  
  14814.  
  14815.       end --loop 37
  14816.  
  14817.  
  14818.  
  14819.  
  14820.    IF (@t1_max_colid = @num_col_bits_on)   --  @ < @  impossible
  14821.       Select @t1_all_col_bits_on = 1
  14822.    ELSE
  14823.       Select @t1_all_col_bits_on = 0
  14824.  
  14825.  
  14826.  
  14827.  
  14828. -------------------------------------------------------------------------
  14829. ----------------  Finally, Ins modified copy of sysprotects row  --------
  14830.  
  14831.  
  14832.  
  14833. LABEL_49INSERT1:
  14834.  
  14835.  
  14836.  
  14837.    INSERT
  14838.              #t1_Prots
  14839.          (
  14840.            --pkid,
  14841.              type1code
  14842.             ,status
  14843.             ,objtype
  14844.             ,id
  14845.             ,uid
  14846.             ,action
  14847.             ,protecttype
  14848.             ,grantor
  14849.             ,columns_orig
  14850.             ,columns_flipped
  14851.             ,max_colid
  14852.             ,all_col_bits_on
  14853.             ,new_bit_on
  14854.          )
  14855.       Values
  14856.          (
  14857.              --identity,
  14858.              @t1_type1code
  14859.             ,0
  14860.             ,@t1_objtype
  14861.             ,@c1id
  14862.             ,@c1uid
  14863.             ,@c1action
  14864.             ,@c1protecttype
  14865.             ,@c1grantor
  14866.             ,@t1_columns_orig
  14867.             ,@c1columns
  14868.             ,@t1_max_colid
  14869.             ,@t1_all_col_bits_on
  14870.             ,@t1_new_bit_on
  14871.          )
  14872.  
  14873.  
  14874.    end  --loop 110
  14875.  
  14876.  
  14877.  
  14878.  
  14879. ----------------------------------------------------------------------------
  14880. --
  14881. --             MainLine:  Phase 20
  14882. --
  14883. ----------------------------------------------------------------------------
  14884.  
  14885.  
  14886.  
  14887. ------------------  create smart temporary holding table  --------------
  14888.  
  14889.  
  14890. CREATE TABLE #t2_SmartProts    --The z's avoid label/colname sorting conflicts
  14891.    (
  14892.     zPKId               int            NOT Null    Identity(1,1)
  14893.    ,zType2Code          char(6)        NOT Null
  14894.    ,zStatus             smallint       NOT Null
  14895.    ,zOwnerName          varchar(30)    NOT Null
  14896.    ,zObjectName         varchar(30)    NOT Null
  14897.    ,zGranteeName        varchar(30)    NOT Null
  14898.    ,zGrantorName        varchar(30)    NOT Null
  14899.    ,zProtectTypeNum     tinyint        NOT Null --Revoke rows have effects.
  14900.    ,zProtectTypeName    char(10)           Null
  14901.    ,zProtectCategory    char(2)            Null
  14902.    ,zWGO                char(3)            Null
  14903.    ,zActionNum          tinyint        NOT Null
  14904.    ,zActionName         varchar(20)        Null
  14905.    ,zActionCategory     char(2)            Null
  14906.    ,zColumnName         varchar(30)    NOT Null
  14907.    ,zColId              smallint           Null
  14908.    )
  14909.  
  14910.  
  14911. CREATE Unique Clustered
  14912.    INDEX    ix1
  14913.    ON       #t2_SmartProts
  14914.       (zPKId)
  14915.  
  14916.  
  14917.  
  14918. ---------------------  Populate the holding table  -----------------------
  14919.  
  14920.  
  14921. --------  Only non objects  ---
  14922.  
  14923.  
  14924. IF (charindex('S',@pGeneralPermissionType) <= 0)
  14925.    GOTO LABEL_1NOOBJ
  14926.  
  14927.  
  14928.  
  14929. INSERT
  14930.       into   #t2_SmartProts
  14931.    (
  14932.   --zPKId,
  14933.     zType2Code
  14934.    ,zStatus
  14935.    ,zOwnerName
  14936.    ,zObjectName
  14937.    ,zGranteeName
  14938.    ,zGrantorName
  14939.    ,zProtectTypeNum
  14940.    ,zProtectTypeName
  14941.    ,zProtectCategory
  14942.    ,zWGO
  14943.    ,zActionNum
  14944.    ,zActionName
  14945.    ,zActionCategory
  14946.    ,zColumnName
  14947.    ,zColId
  14948.    )
  14949.    SELECT
  14950.            --identity,
  14951.              '1NOOBJ'
  14952.             ,0
  14953.             ,'.'
  14954.             ,'.'
  14955.             ,usr2.name
  14956.             ,usr3.name
  14957.  
  14958.             ,prot1.protecttype
  14959.             ,Null
  14960.             ,Null
  14961.  
  14962.             ,Null
  14963.  
  14964.             ,prot1.action
  14965.             ,Null
  14966.             ,Null
  14967.  
  14968.             ,'.'
  14969.             ,Null
  14970.       from
  14971.              #t1_Prots              prot1
  14972.             ,sysusers               usr2
  14973.             ,sysusers               usr3
  14974.             ,master.dbo.spt_values  val1
  14975.       where
  14976.              prot1.columns_orig IS Null
  14977.       and    prot1.objtype      IS Null
  14978.       and
  14979.              usr2.uid      =  prot1.uid
  14980.       and    usr3.uid      =  prot1.grantor
  14981.       and
  14982.              usr2.name  LIKE  @pGranteeName
  14983.       and    usr3.name  LIKE  @pGrantorName
  14984.       and
  14985.              val1.number   =  prot1.action
  14986.       and    val1.type     = 'T'
  14987.       and
  14988.              val1.name  LIKE  @ObjectStatementName
  14989.       and
  14990.              prot1.id      = 0
  14991.       and
  14992.              prot1.status  = 0
  14993.  
  14994.  
  14995.  
  14996.  
  14997. UPDATE
  14998.              #t1_Prots
  14999.    set
  15000.              prot1.status  = prot1.status + Power(2,1)
  15001.    from
  15002.              #t1_Prots              prot1
  15003.             ,sysusers               usr2
  15004.             ,sysusers               usr3
  15005.             ,master.dbo.spt_values  val1
  15006.       where
  15007.              prot1.columns_orig IS Null
  15008.       and    prot1.objtype      IS Null
  15009.       and
  15010.              usr2.uid      =  prot1.uid
  15011.       and    usr3.uid      =  prot1.grantor
  15012.       and
  15013.              usr2.name  LIKE  @pGranteeName
  15014.       and    usr3.name  LIKE  @pGrantorName
  15015.       and
  15016.              val1.number   =  prot1.action
  15017.       and    val1.type     = 'T'
  15018.       and
  15019.              val1.name  LIKE  @ObjectStatementName
  15020.       and
  15021.              prot1.id      = 0
  15022.       and
  15023.              prot1.status  = 0
  15024.  
  15025.  
  15026.  
  15027. LABEL_1NOOBJ:
  15028.  
  15029.  
  15030.  
  15031.  
  15032. -----------  Only objects, and only null columns  ---------
  15033.  
  15034.  
  15035.  
  15036. IF (charindex('O',@pGeneralPermissionType) <= 0)
  15037.    GOTO LABEL_2OBNUL
  15038.  
  15039.  
  15040.  
  15041. INSERT
  15042.       into   #t2_SmartProts
  15043.    (
  15044.   --zPKId,
  15045.     zType2Code
  15046.    ,zStatus
  15047.    ,zOwnerName
  15048.    ,zObjectName
  15049.    ,zGranteeName
  15050.    ,zGrantorName
  15051.    ,zProtectTypeNum
  15052.    ,zProtectTypeName
  15053.    ,zProtectCategory
  15054.    ,zWGO
  15055.    ,zActionNum
  15056.    ,zActionName
  15057.    ,zActionCategory
  15058.    ,zColumnName
  15059.    ,zColId
  15060.    )
  15061.    SELECT
  15062.            --identity,
  15063.              '2OBNUL'
  15064.             ,0
  15065.             ,usr1.name
  15066.             ,obj1.name
  15067.             ,usr2.name
  15068.             ,usr3.name
  15069.  
  15070.             ,prot1.protecttype
  15071.             ,Null
  15072.             ,Null
  15073.  
  15074.             ,Null
  15075.  
  15076.             ,prot1.action
  15077.             ,Null
  15078.             ,Null
  15079.  
  15080.             ,'.'
  15081.  
  15082.             ,Null
  15083.       from
  15084.              #t1_Prots              prot1
  15085.             ,sysobjects             obj1
  15086.             ,sysusers               usr1  --obj owner
  15087.             ,sysusers               usr2  --grantee
  15088.             ,sysusers               usr3  --grantor
  15089.       where
  15090.              prot1.id         = obj1.id
  15091.       and    prot1.objtype    = obj1.type
  15092.       and
  15093.              obj1.type       IN ('X ' ,'P ' ,'U ' ,'S ' ,'V ')
  15094.       and
  15095.              usr1.uid      =  obj1.uid
  15096.       and    usr2.uid      =  prot1.uid
  15097.       and    usr3.uid      =  prot1.grantor
  15098.       and
  15099.              usr1.name  LIKE  @OwnerName
  15100.       and    obj1.name  LIKE  @ObjectStatementName
  15101.       and    usr2.name  LIKE  @pGranteeName
  15102.       and    usr3.name  LIKE  @pGrantorName
  15103.       and
  15104.              prot1.columns_orig IS Null
  15105.       and
  15106.              prot1.status  = 0
  15107.  
  15108.  
  15109.  
  15110.  
  15111.  
  15112. UPDATE
  15113.              #t1_Prots
  15114.    set
  15115.              prot1.status  = prot1.status + Power(2,2)
  15116.       from
  15117.              #t1_Prots              prot1
  15118.             ,sysobjects             obj1
  15119.             ,sysusers               usr1  --obj owner
  15120.             ,sysusers               usr2  --grantee
  15121.             ,sysusers               usr3  --grantor
  15122.       where
  15123.              prot1.id         = obj1.id
  15124.       and    prot1.objtype    = obj1.type
  15125.       and
  15126.              obj1.type       IN ('X ' ,'P ' ,'U ' ,'S ' ,'V ')
  15127.       and
  15128.              usr1.uid      =  obj1.uid
  15129.       and    usr2.uid      =  prot1.uid
  15130.       and    usr3.uid      =  prot1.grantor
  15131.       and
  15132.              usr1.name  LIKE  @OwnerName
  15133.       and    obj1.name  LIKE  @ObjectStatementName
  15134.       and    usr2.name  LIKE  @pGranteeName
  15135.       and    usr3.name  LIKE  @pGrantorName
  15136.       and
  15137.              prot1.columns_orig IS Null
  15138.       and
  15139.              prot1.status  = 0
  15140.  
  15141.  
  15142.  
  15143.  
  15144. LABEL_2OBNUL:
  15145.  
  15146.  
  15147.  
  15148.  
  15149. ---------------------  Only tables where both All & New  -----------
  15150.  
  15151.  
  15152.  
  15153. IF (charindex('O',@pGeneralPermissionType) <= 0)
  15154.    GOTO LABEL_3TBAN
  15155.  
  15156.  
  15157.  
  15158. INSERT
  15159.       into   #t2_SmartProts
  15160.    (
  15161.   --zPKId,
  15162.     zType2Code
  15163.    ,zStatus
  15164.    ,zOwnerName
  15165.    ,zObjectName
  15166.    ,zGranteeName
  15167.    ,zGrantorName
  15168.    ,zProtectTypeNum
  15169.    ,zProtectTypeName
  15170.    ,zProtectCategory
  15171.    ,zWGO
  15172.    ,zActionNum
  15173.    ,zActionName
  15174.    ,zActionCategory
  15175.    ,zColumnName
  15176.    ,zColId
  15177.    )
  15178.    SELECT
  15179.            --identity,
  15180.              '3TBAN '
  15181.             ,0
  15182.             ,usr1.name
  15183.             ,obj1.name
  15184.             ,usr2.name
  15185.             ,usr3.name
  15186.  
  15187.             ,prot1.protecttype
  15188.             ,Null
  15189.             ,Null
  15190.  
  15191.             ,Null
  15192.  
  15193.             ,prot1.action
  15194.             ,Null
  15195.             ,Null
  15196.  
  15197.             ,'(All+New)'
  15198.             ,Null
  15199.       from
  15200.              #t1_Prots              prot1
  15201.             ,sysobjects             obj1
  15202.             ,sysusers               usr1  --obj owner
  15203.             ,sysusers               usr2  --grantee
  15204.             ,sysusers               usr3  --grantor
  15205.       where
  15206.              prot1.id         = obj1.id
  15207.       and    prot1.objtype    = obj1.type
  15208.       and
  15209.              obj1.type       IN ('S ' ,'U ')
  15210.       and
  15211.              usr1.uid         =  obj1.uid
  15212.       and    usr2.uid         =  prot1.uid
  15213.       and    usr3.uid         =  prot1.grantor
  15214.       and
  15215.              usr1.name     LIKE  @OwnerName
  15216.       and    obj1.name     LIKE  @ObjectStatementName
  15217.       and    usr2.name     LIKE  @pGranteeName
  15218.       and    usr3.name     LIKE  @pGrantorName
  15219.       and
  15220.              prot1.all_col_bits_on  = 1
  15221.       and    prot1.new_bit_on       = 1
  15222.       and
  15223.              prot1.status     = 0
  15224.  
  15225.  
  15226.  
  15227.  
  15228. UPDATE
  15229.              #t1_Prots
  15230.    set
  15231.              prot1.status  = prot1.status + Power(2,3)
  15232.       from
  15233.              #t1_Prots              prot1
  15234.             ,sysobjects             obj1
  15235.             ,sysusers               usr1  --obj owner
  15236.             ,sysusers               usr2  --grantee
  15237.             ,sysusers               usr3  --grantor
  15238.       where
  15239.              prot1.id         = obj1.id
  15240.       and    prot1.objtype    = obj1.type
  15241.       and
  15242.              obj1.type       IN ('S ' ,'U ')
  15243.       and
  15244.              usr1.uid         =  obj1.uid
  15245.       and    usr2.uid         =  prot1.uid
  15246.       and    usr3.uid         =  prot1.grantor
  15247.       and
  15248.              usr1.name     LIKE  @OwnerName
  15249.       and    obj1.name     LIKE  @ObjectStatementName
  15250.       and    usr2.name     LIKE  @pGranteeName
  15251.       and    usr3.name     LIKE  @pGrantorName
  15252.       and
  15253.              prot1.all_col_bits_on  = 1
  15254.       and    prot1.new_bit_on       = 1
  15255.       and
  15256.              prot1.status     = 0
  15257.  
  15258.  
  15259.  
  15260. /********
  15261. sysprotects.columns  and  spt_values.type='P':
  15262.  
  15263. NUMBER=ColId  ,LOW=SubstringPosOfByte  ,HIGH=Power(2,0-7 bit pos)
  15264.  
  15265.       NUMBER=0 detects 0x01 bit.   The 0x01 bit being on means New
  15266. columns will automatically be picked up.   And if sysprotects.columns
  15267. equals 0x01 entirely, then All Current and New columns are included.
  15268. Note that for Ins/Del Null should be treated as =0x01.
  15269.       In the first post-6.0 release the bit on/off meanings have reversed,
  15270. except for the 0x01 bit.
  15271.  
  15272.       Note that in MS SQL 6.0 and back, when the 0x01 bit was on
  15273. in sysprotects.columns, that no other bits were ever on or mattered.
  15274. After 6.0 the 0x01 can be on with a mixture of other bits which matter.
  15275. ********/
  15276.  
  15277.  
  15278.  
  15279. LABEL_3TBAN:
  15280.  
  15281.  
  15282.  
  15283.  
  15284. -----------------  TBs & VWs where only All columns (not New)  -----------
  15285.  
  15286.  
  15287.  
  15288. IF (charindex('O',@pGeneralPermissionType) <= 0)
  15289.    GOTO LABEL_4TBVWA
  15290.  
  15291.  
  15292.  
  15293. INSERT
  15294.       into   #t2_SmartProts
  15295.    (
  15296.   --zPKId,
  15297.     zType2Code
  15298.    ,zStatus
  15299.    ,zOwnerName
  15300.    ,zObjectName
  15301.    ,zGranteeName
  15302.    ,zGrantorName
  15303.    ,zProtectTypeNum
  15304.    ,zProtectTypeName
  15305.    ,zProtectCategory
  15306.    ,zWGO
  15307.    ,zActionNum
  15308.    ,zActionName
  15309.    ,zActionCategory
  15310.    ,zColumnName
  15311.    ,zColId
  15312.    )
  15313.    SELECT
  15314.            --identity,
  15315.              '4TBVWA'
  15316.             ,0
  15317.             ,usr1.name
  15318.             ,obj1.name
  15319.             ,usr2.name
  15320.             ,usr3.name
  15321.  
  15322.             ,prot1.protecttype
  15323.             ,Null
  15324.             ,Null
  15325.  
  15326.             ,Null
  15327.  
  15328.             ,prot1.action
  15329.             ,Null
  15330.             ,Null
  15331.  
  15332.             ,'(All)'
  15333.             ,Null
  15334.       from
  15335.              #t1_Prots              prot1
  15336.             ,sysobjects             obj1
  15337.             ,sysusers               usr1  --obj owner
  15338.             ,sysusers               usr2  --grantee
  15339.             ,sysusers               usr3  --grantor
  15340.       where
  15341.              prot1.id         = obj1.id
  15342.       and    prot1.objtype    = obj1.type
  15343.       and
  15344.              obj1.type       IN ('S ' ,'U ' ,'V ')
  15345.       and
  15346.              usr1.uid         =  obj1.uid
  15347.       and    usr2.uid         =  prot1.uid
  15348.       and    usr3.uid         =  prot1.grantor
  15349.       and
  15350.              usr1.name     LIKE  @OwnerName
  15351.       and    obj1.name     LIKE  @ObjectStatementName
  15352.       and    usr2.name     LIKE  @pGranteeName
  15353.       and    usr3.name     LIKE  @pGrantorName
  15354.       and
  15355.              prot1.all_col_bits_on  = 1
  15356.       and    prot1.new_bit_on       = 0
  15357.       and
  15358.              prot1.status     = 0
  15359.  
  15360.  
  15361.  
  15362.  
  15363. UPDATE
  15364.              #t1_Prots
  15365.    set
  15366.              prot1.status  = prot1.status + Power(2,4)
  15367.       from
  15368.              #t1_Prots              prot1
  15369.             ,sysobjects             obj1
  15370.             ,sysusers               usr1  --obj owner
  15371.             ,sysusers               usr2  --grantee
  15372.             ,sysusers               usr3  --grantor
  15373.       where
  15374.              prot1.id         = obj1.id
  15375.       and    prot1.objtype    = obj1.type
  15376.       and
  15377.              obj1.type       IN ('S ' ,'U ' ,'V ')
  15378.       and
  15379.              usr1.uid         =  obj1.uid
  15380.       and    usr2.uid         =  prot1.uid
  15381.       and    usr3.uid         =  prot1.grantor
  15382.       and
  15383.              usr1.name     LIKE  @OwnerName
  15384.       and    obj1.name     LIKE  @ObjectStatementName
  15385.       and    usr2.name     LIKE  @pGranteeName
  15386.       and    usr3.name     LIKE  @pGrantorName
  15387.       and
  15388.              prot1.all_col_bits_on  = 1
  15389.       and    prot1.new_bit_on       = 0
  15390.       and
  15391.              prot1.status     = 0
  15392.  
  15393.  
  15394.  
  15395.  
  15396. LABEL_4TBVWA:
  15397.  
  15398.  
  15399.  
  15400.  
  15401. --------  TBs & VWs where not all columns were granted (avoid New)  ---------
  15402.  
  15403.  
  15404.  
  15405. IF (charindex('O',@pGeneralPermissionType) <= 0)
  15406.    GOTO LABEL_5TBVWC
  15407.  
  15408.  
  15409.  
  15410. INSERT
  15411.       into   #t2_SmartProts
  15412.    (
  15413.   --zPKId,
  15414.     zType2Code
  15415.    ,zStatus
  15416.    ,zOwnerName
  15417.    ,zObjectName
  15418.    ,zGranteeName
  15419.    ,zGrantorName
  15420.    ,zProtectTypeNum
  15421.    ,zProtectTypeName
  15422.    ,zProtectCategory
  15423.    ,zWGO
  15424.    ,zActionNum
  15425.    ,zActionName
  15426.    ,zActionCategory
  15427.    ,zColumnName
  15428.    ,zColId
  15429.    )
  15430.    SELECT
  15431.            --identity,
  15432.              '5TBVWC'
  15433.             ,0
  15434.             ,usr1.name
  15435.             ,obj1.name
  15436.             ,usr2.name
  15437.             ,usr3.name
  15438.  
  15439.             ,prot1.protecttype
  15440.             ,Null
  15441.             ,Null
  15442.  
  15443.             ,Null
  15444.  
  15445.             ,prot1.action
  15446.             ,Null
  15447.             ,Null
  15448.  
  15449.             ,col_name ( prot1.id ,val1.number )
  15450.             ,val1.number
  15451.       from
  15452.              #t1_Prots              prot1
  15453.             ,sysobjects             obj1
  15454.             ,sysusers               usr1  --obj owner
  15455.             ,sysusers               usr2  --grantee
  15456.             ,sysusers               usr3  --grantor
  15457.             ,master.dbo.spt_values  val1
  15458.       where
  15459.              prot1.id         = obj1.id
  15460.       and    prot1.objtype    = obj1.type
  15461.       and
  15462.              obj1.type       IN ('S ' ,'U ' ,'V ')
  15463.       and
  15464.              usr1.uid      =  obj1.uid
  15465.       and    usr2.uid      =  prot1.uid
  15466.       and    usr3.uid      =  prot1.grantor
  15467.       and
  15468.              usr1.name  LIKE  @OwnerName
  15469.       and    obj1.name  LIKE  @ObjectStatementName
  15470.       and    usr2.name  LIKE  @pGranteeName
  15471.       and    usr3.name  LIKE  @pGrantorName
  15472.       and
  15473.              prot1.all_col_bits_on = 0
  15474.       and
  15475.              val1.type        = 'P'
  15476.       and
  15477.              val1.number BETWEEN 1 AND prot1.max_colid
  15478.       and
  15479.              val1.low        <= Datalength(prot1.columns_flipped)
  15480.       and
  15481.              val1.high  &
  15482.                convert(int, substring(prot1.columns_flipped ,val1.low ,1) )
  15483.                         <> 0
  15484.       and    prot1.status     = 0
  15485.  
  15486.  
  15487.  
  15488.  
  15489. UPDATE
  15490.              #t1_Prots
  15491.    set
  15492.              prot1.status  = prot1.status + Power(2,5)
  15493.       from
  15494.              #t1_Prots              prot1
  15495.             ,sysobjects             obj1
  15496.             ,sysusers               usr1  --obj owner
  15497.             ,sysusers               usr2  --grantee
  15498.             ,sysusers               usr3  --grantor
  15499.             ,master.dbo.spt_values  val1
  15500.       where
  15501.              prot1.id         = obj1.id
  15502.       and    prot1.objtype    = obj1.type
  15503.       and
  15504.              obj1.type       IN ('S ' ,'U ' ,'V ')
  15505.       and
  15506.              usr1.uid      =  obj1.uid
  15507.       and    usr2.uid      =  prot1.uid
  15508.       and    usr3.uid      =  prot1.grantor
  15509.       and
  15510.              usr1.name  LIKE  @OwnerName
  15511.       and    obj1.name  LIKE  @ObjectStatementName
  15512.       and    usr2.name  LIKE  @pGranteeName
  15513.       and    usr3.name  LIKE  @pGrantorName
  15514.       and
  15515.              prot1.all_col_bits_on = 0
  15516.       and
  15517.              val1.type        = 'P'
  15518.       and
  15519.              val1.number BETWEEN 1 AND prot1.max_colid
  15520.       and
  15521.              val1.low        <= Datalength(prot1.columns_flipped)
  15522.       and
  15523.              val1.high  &
  15524.                convert(int, substring(prot1.columns_flipped ,val1.low ,1) )
  15525.                         <> 0
  15526.       and    prot1.status     = 0
  15527.  
  15528.  
  15529.  
  15530.  
  15531. LABEL_5TBVWC:
  15532.  
  15533.  
  15534.  
  15535. ----------  Only tables where only New columns are authorized!  ---------
  15536.  
  15537.  
  15538.  
  15539. IF (charindex('O',@pGeneralPermissionType) <= 0)
  15540.    GOTO LABEL_6TBNEW
  15541.  
  15542.  
  15543.  
  15544. INSERT
  15545.       into   #t2_SmartProts
  15546.    (
  15547.   --zPKId,
  15548.     zType2Code
  15549.    ,zStatus
  15550.    ,zOwnerName
  15551.    ,zObjectName
  15552.    ,zGranteeName
  15553.    ,zGrantorName
  15554.    ,zProtectTypeNum
  15555.    ,zProtectTypeName
  15556.    ,zProtectCategory
  15557.    ,zWGO
  15558.    ,zActionNum
  15559.    ,zActionName
  15560.    ,zActionCategory
  15561.    ,zColumnName
  15562.    ,zColId
  15563.    )
  15564.    SELECT
  15565.            --identity,
  15566.              '6TBNEW'
  15567.             ,0
  15568.             ,usr1.name
  15569.             ,obj1.name
  15570.             ,usr2.name
  15571.             ,usr3.name
  15572.  
  15573.             ,prot1.protecttype
  15574.             ,Null
  15575.             ,Null
  15576.  
  15577.             ,Null
  15578.  
  15579.             ,prot1.action
  15580.             ,Null
  15581.             ,Null
  15582.  
  15583.             ,'(New)'
  15584.             ,Null
  15585.       from
  15586.              #t1_Prots              prot1
  15587.             ,sysobjects             obj1
  15588.             ,sysusers               usr1  --obj owner
  15589.             ,sysusers               usr2  --grantee
  15590.             ,sysusers               usr3  --grantor
  15591.       where
  15592.              prot1.id         = obj1.id
  15593.       and    prot1.objtype    = obj1.type
  15594.       and
  15595.              obj1.type       IN ('S ' ,'U ')
  15596.       and
  15597.              usr1.uid         =  obj1.uid
  15598.       and    usr2.uid         =  prot1.uid
  15599.       and    usr3.uid         =  prot1.grantor
  15600.       and
  15601.              usr1.name     LIKE  @OwnerName
  15602.       and    obj1.name     LIKE  @ObjectStatementName
  15603.       and    usr2.name     LIKE  @pGranteeName
  15604.       and    usr3.name     LIKE  @pGrantorName
  15605.       and
  15606.              prot1.all_col_bits_on  = 0
  15607.       and    prot1.new_bit_on       = 1
  15608.       and
  15609.              prot1.status     IN (0,32)  --Some rows processed twice.
  15610.  
  15611.  
  15612.  
  15613.  
  15614. UPDATE
  15615.              #t1_Prots
  15616.    set
  15617.              prot1.status  = prot1.status + Power(2,6)
  15618.       from
  15619.              #t1_Prots              prot1
  15620.             ,sysobjects             obj1
  15621.             ,sysusers               usr1  --obj owner
  15622.             ,sysusers               usr2  --grantee
  15623.             ,sysusers               usr3  --grantor
  15624.       where
  15625.              prot1.id         = obj1.id
  15626.       and    prot1.objtype    = obj1.type
  15627.       and
  15628.              obj1.type       IN ('S ' ,'U ')
  15629.       and
  15630.              usr1.uid         =  obj1.uid
  15631.       and    usr2.uid         =  prot1.uid
  15632.       and    usr3.uid         =  prot1.grantor
  15633.       and
  15634.              usr1.name     LIKE  @OwnerName
  15635.       and    obj1.name     LIKE  @ObjectStatementName
  15636.       and    usr2.name     LIKE  @pGranteeName
  15637.       and    usr3.name     LIKE  @pGrantorName
  15638.       and
  15639.              prot1.all_col_bits_on  = 0
  15640.       and    prot1.new_bit_on       = 1
  15641.       and
  15642.              prot1.status     IN (0,32)  --Some rows processed twice.
  15643.  
  15644.  
  15645.  
  15646.  
  15647. LABEL_6TBNEW:
  15648.  
  15649.  
  15650.  
  15651. ----------------------------------------------------------------------------
  15652. --
  15653. --             MainLine:  Phase 30
  15654. --
  15655. ----------------------------------------------------------------------------
  15656.  
  15657.  
  15658.  
  15659. ----------------  Translations on the held data  --------------------
  15660.  
  15661.  
  15662. UPDATE
  15663.              #t2_SmartProts
  15664.       set
  15665.              zProtectTypeName = val2.name
  15666.  
  15667.             ,zProtectCategory =
  15668.                CASE
  15669.                   When zProtectTypeNum IN (204,205) Then 'Gr' --Grant
  15670.                   When zProtectTypeNum IN (206    ) Then 'Re' --Revoke
  15671.                   Else                   '??'
  15672.                END
  15673.  
  15674.             ,zWGO             =
  15675.                CASE zProtectTypeNum
  15676.                   When 204 Then 'YES'
  15677.                   When 205 Then 'no'
  15678.                   When 206 Then '.'
  15679.                   Else          '??'
  15680.                 END
  15681.  
  15682.             ,zActionName      = val1.name
  15683.  
  15684.             ,zActionCategory  =
  15685.                CASE
  15686.                   When zActionNum IN ( 26, 57,193,195,196,197,224,228,235)
  15687.                                                     Then 'Ob' --Object
  15688.                   When zActionNum IN (198,203,207,222,233,236) Then 'St' --Statement
  15689.                   Else                   '??'
  15690.                END
  15691.  
  15692.             ,zColId        = isnull ( zColId , -123 )
  15693.       from
  15694.              #t2_SmartProts         tbz
  15695.             ,master.dbo.spt_values  val1
  15696.             ,master.dbo.spt_values  val2
  15697.       where
  15698.              val1.number   = tbz.zActionNum
  15699.       and    val1.type     = 'T'
  15700.       and
  15701.              val2.number   = tbz.zProtectTypeNum
  15702.       and    val2.type     = 'T' --T is overloaded.
  15703.  
  15704.  
  15705.  
  15706.  
  15707. -----------------  Dynamically tailor the report sorted order  ---------
  15708.  
  15709.  
  15710. --Specialized sort sequences not really needed in this app.
  15711.  
  15712. Select @OrderBy = '
  15713.   zActionCategory
  15714.  ,Owner            ,Object
  15715.  ,Grantee          ,Grantor
  15716.  ,zProtectCategory ,ProtectType
  15717.  ,Action
  15718. '
  15719.  
  15720.  
  15721.  
  15722. -----------------  Calculate dynamic display col widths  ---------------
  15723.  
  15724.  
  15725. SELECT
  15726.              @charMaxLenOwner       =
  15727.                   convert ( varchar
  15728.                            ,isnull ( max(datalength(zOwnerName)) ,5)
  15729.                           )
  15730.             ,@charMaxLenObject      =
  15731.                   convert ( varchar
  15732.                            ,isnull ( max(datalength(zObjectName)) ,6)
  15733.                           )
  15734.             ,@charMaxLenGrantee     =
  15735.                   convert ( varchar
  15736.                            ,isnull ( max(datalength(zGranteeName)) ,7)
  15737.                           )
  15738.             ,@charMaxLenGrantor     =
  15739.                   convert ( varchar
  15740.                            ,isnull ( max(datalength(zGrantorName)) ,7)
  15741.                           )
  15742.             ,@charMaxLenAction      =
  15743.                   convert ( varchar
  15744.                            ,isnull ( max(datalength(zActionName)) ,6)
  15745.                           )
  15746.             ,@charMaxLenColumnName  =
  15747.                   convert ( varchar
  15748.                            ,isnull ( max(datalength(zColumnName)) ,6)
  15749.                           )
  15750.       from
  15751.              #t2_SmartProts
  15752.  
  15753.  
  15754.  
  15755. --------------------  Output the report  -----------------------
  15756.  
  15757.  
  15758. EXECUTE(
  15759. '
  15760. Set nocount off
  15761.  
  15762.  
  15763. SELECT
  15764.           ''Owner''       = substring (zOwnerName   ,1 ,'
  15765.                                        + @charMaxLenOwner   + ')
  15766.  
  15767.          ,''Object''      = substring (zObjectName  ,1 ,'
  15768.                                        + @charMaxLenObject  + ')
  15769.  
  15770.          ,''Grantee''     = substring (zGranteeName ,1 ,'
  15771.                                        + @charMaxLenGrantee + ')
  15772.  
  15773.          ,''Grantor''     = substring (zGrantorName ,1 ,'
  15774.                                        + @charMaxLenGrantor + ')
  15775.  
  15776.       -- ,''WGO''         = zWGO
  15777.  
  15778.          ,''ProtectType'' = zProtectTypeName
  15779.  
  15780.          ,''Action''      = substring (zActionName ,1 ,'
  15781.                                        + @charMaxLenAction + ')
  15782.  
  15783.          ,''Column''      = substring (zColumnName ,1 ,'
  15784.                                        + @charMaxLenColumnName + ')
  15785.    from
  15786.           #t2_SmartProts
  15787.    order by
  15788.           ' + @OrderBy + '
  15789.          ,zColId  --Multiple  -123s  ( <0 )  possible
  15790.          ,zColumnName
  15791.  
  15792.  
  15793. Set nocount on
  15794. '
  15795. )
  15796.  
  15797.  
  15798.  
  15799. ----------------------------------------------------------------------------
  15800. --
  15801. --             Finalization
  15802. --
  15803. ----------------------------------------------------------------------------
  15804.  
  15805.  
  15806. LABEL_86RETURN:
  15807.  
  15808.  
  15809.  
  15810. IF (object_id('tempdb..#t1_Prots') IS NOT Null)
  15811.             DROP TABLE #t1_Prots
  15812.  
  15813. IF (object_id('tempdb..#t2_SmartProts') IS NOT Null)
  15814.             DROP TABLE #t2_SmartProts
  15815.  
  15816. Return @RetCode
  15817. go
  15818.  
  15819.  
  15820.  
  15821. print ''
  15822. print 'Creating procedure sp_helptext.'
  15823. go
  15824. create procedure sp_helptext
  15825. @objname varchar(92)
  15826. as
  15827. declare @dbname varchar(30)
  15828.  
  15829. set nocount on
  15830.  
  15831. /*
  15832. **  Make sure the @objname is local to the current database.
  15833. */
  15834. if (@objname like '%.%.%' and
  15835.         substring(@objname, 1, charindex('.', @objname) - 1) <> db_name() )
  15836.         begin
  15837.                 raiserror(15250,-1,-1)
  15838.                 return (1)
  15839.         end
  15840.  
  15841. /*
  15842. **  See if @objname exists.
  15843. */
  15844. if (object_id(@objname) is null)
  15845.         begin
  15846.         select @dbname = db_name()
  15847.         raiserror(15009,-1,-1,@objname,@dbname)
  15848.                 return (1)
  15849.         end
  15850.  
  15851. /*
  15852. **  Find out how many lines of text are coming back,
  15853. **  and return if there are none.
  15854. */
  15855. if (select count(*) from syscomments where id = object_id(@objname)) = 0
  15856.         begin
  15857.                 raiserror(15197,-1,-1,@objname)
  15858.                 return (1)
  15859.         end
  15860.  
  15861. if (select count(*) from syscomments where id = object_id(@objname)
  15862.     and texttype & 4 = 0) = 0
  15863.         begin
  15864.                 print 'The object''s comments have been encrypted.'
  15865.                 return (0)
  15866.         end
  15867.  
  15868. /*
  15869. **  Else get the text.
  15870. */
  15871. select text from syscomments where id = object_id(@objname)
  15872.  
  15873. return (0)
  15874. go
  15875.  
  15876.  
  15877.  
  15878. --Running this create AFTER create sp_helpgroup.
  15879. print ''
  15880. print 'Creating procedure sp_helpuser.'
  15881. go
  15882. CREATE PROCEDURE sp_helpuser  --1995/10/17 16:21
  15883.  
  15884.     @pName_UGA       varchar(30)    = NULL --User,Group,Alias
  15885. AS
  15886.  
  15887. Set nocount on
  15888.  
  15889.  
  15890. Declare
  15891.     @RetCode               int
  15892.    ,@_rowcount             int
  15893.  
  15894. Declare
  15895.     @charMaxLen_UsName     varchar(11)
  15896.    ,@charMaxLen_GrName     varchar(11)
  15897.    ,@charMaxLen_LoName     varchar(11)
  15898.    ,@charMaxLen_DbName     varchar(11)
  15899.  
  15900. Declare
  15901.     @Name1Type             char(2)
  15902.    ,@CMaxUsUID             smallint
  15903.  
  15904. --------
  15905.  
  15906. Select
  15907.     @RetCode               = 0
  15908.    ,@Name1Type             = Null
  15909.    ,@CMaxUsUID             = 16383
  15910.  
  15911. Raiserror('',1,1)
  15912.  
  15913.  
  15914. -----------------------  create holding table  --------------------
  15915.  
  15916.  
  15917. Create Table #tb1_uga
  15918.    (
  15919.     zUserName        varchar(30)        Null
  15920.    ,zGroupName       varchar(30)        Null
  15921.    ,zLoginName       varchar(30)        Null
  15922.    ,zDefDBName       varchar(30)        Null
  15923.    ,zUID             smallint           Null
  15924.    ,zSUID            smallint           Null
  15925.    )
  15926.  
  15927.  
  15928.  
  15929. -------------  What type of value (U,G,A) was input?  --------------
  15930.  
  15931.  
  15932. -------- NULL
  15933.  
  15934. IF (@pName_UGA IS Null)
  15935.    begin
  15936.  
  15937.    Select @Name1Type = '-'
  15938.  
  15939.  
  15940.    INSERT
  15941.          into   #tb1_uga
  15942.                (
  15943.                 zUserName
  15944.                ,zGroupName
  15945.                ,zLoginName
  15946.                ,zDefDBName
  15947.                ,zUID
  15948.                ,zSUID
  15949.                )
  15950.       SELECT
  15951.                    usu.name
  15952.                   ,usg.name
  15953.                   ,lo.name
  15954.                   ,lo.dbname
  15955.                   ,usu.uid
  15956.                   ,usu.suid
  15957.          from
  15958.                    sysusers               usu
  15959.                   ,sysusers               usg
  15960.                   ,master.dbo.syslogins   lo
  15961.          where
  15962.                    usu.suid   *= lo.suid
  15963.          and       usu.gid    *= usg.uid
  15964.          and
  15965.                    usg.uid     > @CMaxUsUID
  15966.          and
  15967.                    usu.uid    <= @CMaxUsUID
  15968.          and       usu.uid    >  0
  15969.  
  15970.  
  15971.  
  15972.    GOTO LABEL_25NAME1TYPEKNOWN
  15973.  
  15974.    end
  15975.  
  15976.  
  15977. -------- USER
  15978.  
  15979. INSERT
  15980.          into   #tb1_uga
  15981.                (
  15982.                 zUserName
  15983.                ,zGroupName
  15984.                ,zLoginName
  15985.                ,zDefDBName
  15986.                ,zUID
  15987.                ,zSUID
  15988.                )
  15989.       SELECT
  15990.                    usu.name
  15991.                   ,usg.name
  15992.                   ,lo.name
  15993.                   ,lo.dbname
  15994.                   ,usu.uid
  15995.                   ,usu.suid
  15996.          from
  15997.                    sysusers               usu
  15998.                   ,sysusers               usg
  15999.                   ,master.dbo.syslogins   lo
  16000.          where
  16001.                    usu.suid   *= lo.suid
  16002.          and       usu.gid    *= usg.uid
  16003.          and
  16004.                    usg.uid     > @CMaxUsUID
  16005.          and
  16006.                    usu.uid    <= @CMaxUsUID
  16007.          and       usu.uid    >  0
  16008.          and
  16009.                    usu.name    = @pName_UGA
  16010.  
  16011.  
  16012. Select @_rowcount = @@rowcount
  16013.  
  16014.  
  16015. IF (@_rowcount > 0)
  16016.    begin
  16017.    Select @Name1Type = 'US'
  16018.  
  16019.    GOTO LABEL_25NAME1TYPEKNOWN
  16020.  
  16021.    end
  16022.  
  16023.  
  16024. -------- ALIAS
  16025.  
  16026. INSERT
  16027.          into   #tb1_uga
  16028.                (
  16029.                 zUserName
  16030.                ,zGroupName
  16031.                ,zLoginName
  16032.                ,zDefDBName
  16033.                ,zUID
  16034.                ,zSUID
  16035.                )
  16036.       SELECT
  16037.                    usu.name
  16038.                   ,usg.name
  16039.                   ,lo.name
  16040.                   ,lo.dbname
  16041.                   ,usu.uid
  16042.                   ,usu.suid
  16043.          from
  16044.                    sysusers               usu
  16045.                   ,sysusers               usg
  16046.                   ,master.dbo.syslogins   lo
  16047.                   ,sysalternates          al
  16048.          where
  16049.                    usu.suid   *= lo.suid
  16050.          and       usu.gid    *= usg.uid
  16051.          and
  16052.                    usg.uid     > @CMaxUsUID
  16053.          and
  16054.                    usu.uid    <= @CMaxUsUID
  16055.          and       usu.uid    >  0
  16056.          and
  16057.                    al.suid     = suser_id(@pName_UGA)
  16058.          and       al.altsuid  = usu.suid
  16059.  
  16060.  
  16061. Select @_rowcount = @@rowcount
  16062.  
  16063.  
  16064. IF (@_rowcount > 0)
  16065.    begin
  16066.    Select @Name1Type = 'AL'
  16067.  
  16068.    GOTO LABEL_25NAME1TYPEKNOWN
  16069.  
  16070.    end
  16071.  
  16072.  
  16073. -------- GROUP
  16074.  
  16075. IF EXISTS
  16076.       (SELECT * FROM sysusers
  16077.          WHERE  name = @pName_UGA
  16078.          AND   (uid > @CMaxUsUID  OR  uid = 0)
  16079.       )
  16080.    begin
  16081.    Select @Name1Type = 'GR'
  16082.  
  16083.    Execute sp_helpgroup @pName_UGA
  16084.  
  16085.    GOTO LABEL_75FINAL  --Done
  16086.  
  16087.    end
  16088.  
  16089.  
  16090. -------- Error
  16091.  
  16092. Raiserror(15198,-1,-1 ,@pName_UGA)  --Input Name is unfound
  16093. Select @RetCode = @RetCode | 1
  16094.  
  16095. GOTO LABEL_75FINAL
  16096.  
  16097.  
  16098.  
  16099. --------
  16100.  
  16101.  
  16102. LABEL_25NAME1TYPEKNOWN:
  16103.  
  16104.  
  16105.  
  16106. -----------------------  Printout the report  -------------------------
  16107.  
  16108.  
  16109. IF (@Name1Type IN ('AL'))
  16110.    begin
  16111.    Raiserror(15307,-1,-1 ,@pName_UGA)  --Explanation of output
  16112.    end
  16113.  
  16114.  
  16115.  
  16116. -------- Preparations for dynamic exec
  16117.  
  16118. SELECT
  16119.           @charMaxLen_UsName  = convert( varchar,
  16120.                   isnull( max( datalength( zUserName)),8))
  16121.  
  16122.          ,@charMaxLen_GrName  = convert( varchar,
  16123.                   isnull( max( datalength( zGroupName)),9))
  16124.  
  16125.          ,@charMaxLen_LoName  = convert( varchar,
  16126.                   isnull( max( datalength( zLoginName)),9))
  16127.  
  16128.          ,@charMaxLen_DbName  = convert( varchar,
  16129.                   isnull( max( datalength( zDefDBName)),9))
  16130.    from
  16131.           #tb1_uga
  16132.  
  16133.  
  16134. -------- Dynamic EXEC() to printout report
  16135.  
  16136.  
  16137. EXECUTE(
  16138. '
  16139. SELECT
  16140.              ''UserName''  =
  16141.                      substring(zUserName ,1,' + @charMaxLen_UsName + ')
  16142.  
  16143.             ,''GroupName'' =
  16144.                      substring(zGroupName,1,' + @charMaxLen_GrName + ')
  16145.  
  16146.             ,''LoginName'' =
  16147.                      substring(zLoginName,1,' + @charMaxLen_LoName + ')
  16148.  
  16149.             ,''DefDBName'' =
  16150.                      substring(zDefDBName,1,' + @charMaxLen_DbName + ')
  16151.  
  16152.             ,''UserID''    = convert(char(6),zUID)
  16153.  
  16154.             ,''SUserID''   = convert(char(7),zSUID)
  16155.       from
  16156.              #tb1_uga
  16157.       order by
  16158.              1
  16159. '
  16160. )
  16161.  
  16162.  
  16163.  
  16164. -----------------------  A little extra nice-to-have
  16165.  
  16166.  
  16167. IF (@Name1Type IN ('-','US'))
  16168.    begin
  16169.  
  16170.    IF EXISTS (SELECT * FROM #tb1_uga tb1 ,sysalternates al
  16171.                        WHERE tb1.zSUID = al.altsuid
  16172.              )
  16173.       begin
  16174.  
  16175.       Raiserror(15308,-1,-1)  --Explanation of output
  16176.  
  16177.  
  16178.       SELECT   'LoginName' = suser_name(al.suid)
  16179.               ,'UserNameAliasedTo' = tb1.zUserName
  16180.          from  #tb1_uga tb1 ,sysalternates al
  16181.          where tb1.zSUID   = al.altsuid
  16182.          order by 1
  16183.  
  16184.       end
  16185.    end
  16186.  
  16187.  
  16188.  
  16189. -----------------------  Finalization  ----------------------
  16190.  
  16191.  
  16192. LABEL_75FINAL:
  16193.  
  16194.  
  16195. IF (object_id('tempdb..#tb1_uga') IS Null)
  16196.             Drop Table #tb1_uga
  16197.  
  16198. Raiserror('',1,1)
  16199.  
  16200. RETURN @RetCode
  16201. go
  16202.  
  16203.  
  16204. print ''
  16205. print 'Creating procedure sp_lock.'
  16206. go
  16207. create procedure sp_lock
  16208. @spid1 int = NULL,        /* server process id to check for locks */
  16209. @spid2 int = NULL        /* other process id to check for locks */
  16210. as
  16211.  
  16212. /*
  16213. **  Show the locks for both parameters.
  16214. */
  16215. if @spid1 is not NULL
  16216. begin
  16217.     select spid, locktype = name, table_id = id, page,
  16218.         dbname = substring(db_name(dbid), 1, 15)
  16219.         from syslocks, master.dbo.spt_values v
  16220.         where syslocks.type = v.number
  16221.             and v.type = 'L'
  16222.             and spid in (@spid1, @spid2)
  16223. end
  16224.  
  16225. /*
  16226. **  No parameters, so show all the locks.
  16227. */
  16228. else
  16229. begin
  16230.     select spid, locktype = name, table_id = id, page,
  16231.         dbname = substring(db_name(dbid), 1, 15)
  16232.     from syslocks, master.dbo.spt_values v
  16233.     where syslocks.type = v.number
  16234.         and v.type = 'L'
  16235.     order by spid, dbname, table_id, locktype, page
  16236. end
  16237.  
  16238. return (0)
  16239. go
  16240.  
  16241.  
  16242. print ''
  16243. print 'Creating procedure sp_lock2.'
  16244. go
  16245. CREATE PROCEDURE sp_lock2  --1995/11/20 07:19
  16246.  
  16247.     @pSPID1    integer = NULL
  16248.    ,@pSPID2    integer = NULL  --A second spid can be given also.
  16249. as
  16250. --Concerned in 6.5 that temp #tables accumulate if @@trancount>0.
  16251.  
  16252. Set nocount on
  16253.  
  16254. Declare
  16255.        @RetCode                  integer
  16256.       ,@SUID                     smallint
  16257.       ,@cu111_DBName             character varying(30)
  16258.       ,@OrigDBName               character varying(30)
  16259.  
  16260. Declare
  16261.        @charMaxLenLockTypeName   character varying(10)
  16262.       ,@charMaxLenTBName         character varying(10)
  16263.       ,@charMaxLenDBName         character varying(10)
  16264.       ,@charMaxLenOwner          character varying(10)
  16265.  
  16266. --------
  16267.  
  16268. Select
  16269.        @RetCode     = 0  -- 0=good ,1=bad
  16270.       ,@SUID        = suser_id()
  16271.       ,@OrigDBName  = db_name()
  16272.  
  16273. -------------  Capture raw lock info  ----------------
  16274.  
  16275. CREATE TABLE #Lock
  16276.    (
  16277.     TableId         int             Null
  16278.    ,DBName          varchar(30)     Null
  16279.    ,Page            int             Null
  16280.  
  16281.    ,LockTypeId      smallint        Null
  16282.    ,LockTypeName    varchar(35)     Null
  16283.    ,SPID            smallint        Null
  16284.  
  16285.    ,OwnerName       varchar(30)     Null
  16286.    ,TableName       varchar(30)     Null
  16287.    )
  16288.  
  16289.  
  16290. INSERT
  16291.       into   #Lock
  16292.    SELECT
  16293.              l.id
  16294.             ,db_name(dbid)
  16295.             ,l.page
  16296.  
  16297.             ,l.type
  16298.             ,Null
  16299.             ,l.spid
  16300.  
  16301.             ,'-'
  16302.             ,'-'
  16303.       from
  16304.              master.dbo.syslocks    l
  16305.       where
  16306.             (
  16307.              (     @pSPID1 IS NOT Null
  16308.               AND  l.spid  IN (@pSPID1 ,@pSPID2)
  16309.              )
  16310.             OR
  16311.              (     @pSPID1 IS     Null
  16312.              )
  16313.             )
  16314.  
  16315.  
  16316.  
  16317. UPDATE --Delayed until here to avoid reporting on self (spt_values).
  16318.                #Lock
  16319.       set
  16320.                LockTypeName    = v.name
  16321.       from
  16322.                #Lock                  tb2
  16323.               ,master.dbo.spt_values  v
  16324.       where
  16325.                tb2.LockTypeId  = v.number
  16326.         and    v.type          = 'L'
  16327.  
  16328.  
  16329. --------------  This phase will convert IDs to Names  --------------
  16330.  
  16331.  
  16332. EXECUTE(
  16333. '
  16334. DECLARE Cursor111_LockDB
  16335.    Insensitive
  16336.    Cursor
  16337. For
  16338. SELECT
  16339.       DISTINCT
  16340.              DBName
  16341.       from
  16342.              #Lock
  16343. '
  16344. )
  16345.  
  16346.  
  16347. OPEN Cursor111_LockDB
  16348.  
  16349.  
  16350. WHILE (111=111)   -----------  LOOP 111: thru DBNames  ------------
  16351.    begin
  16352.  
  16353.  
  16354.    FETCH
  16355.                 NEXT
  16356.          from
  16357.                 Cursor111_LockDB
  16358.          into
  16359.                 @cu111_DBName
  16360.  
  16361.  
  16362.    IF (@@fetch_status <> 0)
  16363.       begin
  16364.       Deallocate Cursor111_LockDB
  16365.       BREAK
  16366.       end
  16367.  
  16368.  
  16369.    IF (     @SUID         = 1
  16370.       or    @cu111_DBName IN ('tempdb' ,'master',@OrigDBName)
  16371.       or    @cu111_DBName = (SELECT   dbname
  16372.                                from  master.dbo.syslogins
  16373.                                where suid=@SUID)
  16374.       or    @SUID         = (SELECT   suid
  16375.                                from  master.dbo.sysdatabases
  16376.                                where name=@cu111_DBName)
  16377.       )
  16378.       begin --USE will not error.  sysdb.status bit for GUEST?
  16379.  
  16380.  
  16381.       EXECUTE(
  16382.       '
  16383.       USE ' + @cu111_DBName + '
  16384.  
  16385.       UPDATE
  16386.                 #Lock
  16387.          set
  16388.                 TableName  = object_name(tb2.TableId)
  16389.                ,OwnerName  = user_name(o.uid)
  16390.          from
  16391.                 #Lock      tb2
  16392.                ,sysobjects o
  16393.          where
  16394.                 tb2.TableId   = o.id
  16395.          and    tb2.DBName    = ''' + @cu111_DBName + '''
  16396.       '
  16397.       )
  16398.  
  16399.       end
  16400.  
  16401.  
  16402.    end  --loop 111
  16403.  
  16404.  
  16405. -------------------  Shorten those pesky temp #tb names  ------------
  16406.  
  16407. UPDATE
  16408.              #Lock
  16409.       set
  16410.              TableName = substring(TableName,1
  16411.                                ,patindex('%[_][_]%',TableName)-1) + '-'
  16412.       where
  16413.              TableName LIKE '#%[_][_]%'  --Start of system assigned portion.
  16414.  
  16415. /***
  16416. -------------------  special case  ----------------------
  16417.  
  16418. UPDATE
  16419.              #Lock
  16420.       set
  16421.              TableName  =  '(work)'  --Little white lie; syslogs?
  16422.             ,OwnerName  =  '(n/a)'
  16423.       where
  16424.              TableId    =  0
  16425.       and    TableName  =  '-'
  16426. ***/
  16427. ----------------  Prepare dynamic column widths  ------------------
  16428.  
  16429. SELECT
  16430.              @charMaxLenLockTypeName =
  16431.                   convert( varchar
  16432.                           ,isnull( max( datalength(LockTypeName)) ,8)
  16433.                          )
  16434.             ,@charMaxLenTBName       =
  16435.                   convert( varchar
  16436.                           ,isnull( max( datalength(TableName)) ,6)
  16437.                          )
  16438.             ,@charMaxLenDBName       =
  16439.                   convert( varchar
  16440.                           ,isnull( max( datalength(DBName)) ,6)
  16441.                          )
  16442.             ,@charMaxLenOwner        =
  16443.                   convert( varchar
  16444.                           ,isnull( max( datalength(OwnerName)) ,5)
  16445.                          )
  16446.       from
  16447.              #Lock
  16448.  
  16449. ----------------  Output the report  --------------------
  16450.  
  16451. EXECUTE(
  16452. '
  16453. SELECT
  16454.              SPID
  16455.             ,LockType  = substring(LockTypeName,1,' + @charMaxLenLockTypeName + ')
  16456.             ,TableId
  16457.             ,Page
  16458.             ,DBName    = substring(DBName,1,' + @charMaxLenDBName + ')
  16459.             ,TableName = substring(TableName,1,' + @charMaxLenTBName + ')
  16460.             ,Owner     = substring(OwnerName,1,' + @charMaxLenOwner + ')
  16461.       from
  16462.              #Lock
  16463.       order by
  16464.              SPID ,DBName ,Owner ,TableName ,TableId ,LockType ,Page
  16465. '
  16466. )
  16467.  
  16468. -----------------  Finalization  ------------------
  16469.  
  16470.  
  16471. LABEL_86RETURN:
  16472.  
  16473.  
  16474. EXECUTE('USE ' + @OrigDBName) --So this will work on 6.0 too.
  16475.  
  16476. IF (object_id('tempdb..#Lock') IS NOT Null)
  16477.             Drop table #Lock
  16478.  
  16479. Return @RetCode
  16480. go
  16481.  
  16482.  
  16483.  
  16484. print ''
  16485. print 'Creating procedure sp_lockinfo.'
  16486. go
  16487. create procedure sp_lockinfo
  16488. as
  16489. /* ====================================================*/
  16490. /* sp_processinfo - returns detailed lock              */
  16491. /* information for the server                          */
  16492. /* Microsoft SQL Server - copyright 94                 */
  16493. /* ====================================================*/
  16494.  
  16495. declare @lkdbnm varchar(32)
  16496. declare @lkdbid smallint
  16497. declare @lkobjid int
  16498. declare @UserDBID smallint
  16499. declare @usrdbnm varchar(32)
  16500. declare @User_ID smallint
  16501. declare @grpid smallint
  16502. declare @stmt varchar(255)
  16503.  
  16504. /* ===========================================================*/
  16505. /* build temp table with processes and their associated locks */
  16506. /* ===========================================================*/
  16507.  
  16508. select  distinct
  16509.  
  16510.     'FullName'    = '                                               ',
  16511.     'LoginName'    = lo.name,
  16512.     'UserID'    = p.uid,
  16513.     'UName'    = '                                ',
  16514.  
  16515.     'ProcessID'    = p.spid,
  16516.     'Status'    = p.status,
  16517.     'DBID'        = p.dbid,
  16518.     'DbName'    = d.name,    
  16519.     'Command'    = p.cmd,
  16520.     'Host'        = p.hostname,
  16521.     'Application'    = p.program_name,    
  16522.     'Blocking'    = 0,
  16523.     'Blockedby'    = p.blocked,
  16524.  
  16525.     'LockType'    = l.type,
  16526.     'LKObjDBID'    = l.dbid,    
  16527.     'LKObjDB'    = '                                ',
  16528.     'LKObjID'    = l.id,
  16529.     'LKObj'        = '                                                                                     ',
  16530.     'LockedPage'    = l.page,
  16531.  
  16532.     'GroupID'    = p.gid,
  16533.     'GName'    = '                                ',
  16534.  
  16535.     'CPUUsage'    = p.cpu,
  16536.     'NT_Thread_#'    = p.kpid,
  16537.     'Memory_2K_Allocs'    = p.memusage,
  16538.     'PhysicalIO'    = p.physical_io,
  16539.     'HostProcess'    = p.hostprocess
  16540. into #info
  16541.  
  16542. from
  16543.     master..sysprocesses p,
  16544.     master..syslocks l,
  16545.     master..syslogins lo,
  16546.     master..sysdatabases d
  16547.  
  16548. where
  16549.     p.spid     = l.spid and
  16550.     p.suid    = lo.suid and
  16551.     p.dbid    = d.dbid
  16552.  
  16553. /* ========================*/
  16554. /* flag blocking processes */    
  16555. /* ======================= */
  16556. update #info set Blocking = 1 where
  16557. ProcessID in (select Blockedby from #info where Blockedby > 0)
  16558.  
  16559. /* ============================*/
  16560. /* flag blocking process locks */    
  16561. /* ============================*/
  16562. Update #info set Blocking = Blocking + 100
  16563. where LockType >= 256
  16564.  
  16565. /* ===============================*/
  16566. /* flag transcient system objects */    
  16567. /* (syslocks/ sysprocesses/...    */
  16568. /* ===============================*/
  16569.  
  16570. Update #info set LKObj = 'SQL Server Internal Table'
  16571. where LKObjID = 0
  16572.  
  16573. /* =========================================== */
  16574. /* resolve all object names for each database  */
  16575. /* using LockedDBName, LKObjID                 */
  16576. /* =========================================== */
  16577.  
  16578. /* first we need a unique index to declare the cursor */
  16579. exec ('create unique index xxx on #info (ProcessID, LockType, LockedPage,LKObjID)')
  16580.  
  16581. /* =============================================*/
  16582. /* get list of locked object IDs */
  16583. /* =============================================*/
  16584.  
  16585. exec ('declare c1 cursor for select distinct LockedDBName = d.name, LKObjID , LKObjDBID from #info, master..sysdatabases d
  16586. where LKObjDBID = d.dbid  and LKObjID > 0 order by LockedDBName, LKObjID FOR READ ONLY ')
  16587.  
  16588. open c1
  16589.  
  16590. fetch c1 into @lkdbnm, @lkobjid, @lkdbid
  16591.  
  16592. while @@fetch_status >= 0
  16593.    begin
  16594.     /* set owner.name of locked objects in #info */
  16595.  
  16596.     select @stmt = 'Update #info set LKObj=u.name+''.''+o.name,'+
  16597.     'LKObjDB='''+@lkdbnm+
  16598.     ''' from '+@lkdbnm+'..sysobjects o,'+@lkdbnm+'..sysusers u '+
  16599.     'where o.id='+convert(char(10),@lkobjid)+
  16600.     ' and LKObjID=o.id' +
  16601.     ' and u.uid=o.uid and LKObjDBID=' + convert(char,@lkdbid)
  16602.     exec(@stmt )
  16603.  
  16604.     /* next please */
  16605.     fetch c1 into @lkdbnm, @lkobjid, @lkdbid
  16606.  
  16607.  
  16608.    end
  16609. deallocate c1
  16610.  
  16611. /* =============================================*/
  16612. /* resolve UserID, GroupID for all processes    */
  16613. /* get a list of each database we need to visit */
  16614. /* =============================================*/
  16615.  
  16616. exec ('declare c1 cursor for select distinct DBID, DbName from #info order by DBID FOR READ ONLY')
  16617.  
  16618. open c1
  16619.  
  16620. fetch c1 into  @UserDBID, @usrdbnm
  16621.  
  16622. while @@fetch_status >= 0
  16623.    begin
  16624.  
  16625.     /* set user/group in #info */
  16626.  
  16627.     select @stmt = 'Update #info set '+
  16628.     'GName=g.name,'+
  16629.     'UName=u.name '+
  16630.     'from '+@usrdbnm+'..sysusers u,'+
  16631.     @usrdbnm+'..sysusers g,#info '+
  16632.     'where u.uid=UserID ' +
  16633.     'and g.uid=GroupID and '+
  16634.     'DBID=' + RTRIM(convert(char(10),@UserDBID))
  16635.     exec(@stmt )
  16636.  
  16637.     /* next please */
  16638.     fetch c1 into  @UserDBID, @usrdbnm
  16639.  
  16640.    end
  16641. deallocate c1
  16642.  
  16643. /* ====== final fixups ====== */
  16644. /* Label SYSTEM processes as such */
  16645. Update #info set FullName = 'System' where ProcessID < 10
  16646.  
  16647. /* Construct fullname for user processes */
  16648. Update #info set FullName = LoginName where ProcessID >= 10
  16649.  
  16650. /* fully qualify existing object names  */
  16651. Update #info set
  16652. LKObj = LKObjDB +'.' + LKObj /* +'(id:' + RTRIM(Convert(char,LKObjID)) +')'*/
  16653. where LKObj > '' and LKObjDB > ''
  16654.  
  16655.  
  16656. /* ====== return the #info table ===== */
  16657. SELECT
  16658.  
  16659.     FullName , ProcessID,     Status,
  16660.     DName = substring(DbName,1,10),
  16661.     Command,Host, Application, Blockedby,LockType,LKObj,
  16662.     GName = substring(GName,1,10),
  16663.     CPUUsage, PhysicalIO, HostProcess
  16664.     ,UName,Blocking    /* added CLK 11/11/94 */
  16665.  
  16666. FROM #info
  16667. ORDER BY
  16668.     LKObj,
  16669.     ProcessID
  16670.  
  16671. /* end of procedure */
  16672. return(0)
  16673. go
  16674.  
  16675. print ''
  16676. print 'Creating procedure sp_logdevice.'
  16677. go
  16678. create procedure sp_logdevice  --1995/11/11 16:45
  16679. @dbname    varchar(30),        /* database name that has the syslogs */
  16680. @devname    varchar(30)    /* device name to put syslogs on */
  16681. as
  16682.  
  16683. declare @dbid    smallint    /* dbid of the database to be changed */
  16684. declare @dbuid    smallint    /* id of the owner of the database */
  16685. declare @logbit    int        /* this is the bit to turn on in sysusages */
  16686. declare @sum_rowcount int    /* used to determine no action needed */
  16687.  
  16688. select @logbit = 4        /* bit 3 is the one to turn on */
  16689. select @sum_rowcount = 0
  16690.  
  16691. /*
  16692. **  Verify the database name and get the @dbid and @dbuid
  16693. */
  16694. select @dbid = dbid, @dbuid = suid
  16695.     from sysdatabases
  16696.         where name = @dbname
  16697.  
  16698. /*
  16699. **  If @dbname not found, say so.
  16700. */
  16701. if @dbid is null
  16702. begin
  16703.     raiserror(15010,-1,-1,@dbname)
  16704.     return (1)
  16705. end
  16706.  
  16707. /*
  16708. **  See if the device exists.
  16709. */
  16710. if not exists (select * from sysdevices where name like @devname)
  16711.     begin
  16712.         raiserror(15012,-1,-1,@devname)
  16713.         return (1)
  16714.     end
  16715.  
  16716. /*
  16717. **  You must be SA or the dbo to execute this sproc.
  16718. */
  16719. if suser_id() <> 1 and suser_id() <> @dbuid
  16720.     begin
  16721.         raiserror(15199,-1,-1)
  16722.         return (1)
  16723.     end
  16724.  
  16725. /*
  16726. **  Now see if the @dbname uses the @devname
  16727. */
  16728. if not exists (select * from sysusages u, sysdevices d
  16729.         where d.name = @devname
  16730.             and u.vstart between d.low and d.high
  16731.             and u.dbid = @dbid)
  16732.     begin
  16733.         raiserror(15073,-1,-1,@devname,@dbname)
  16734.         return (1)
  16735.     end
  16736.  
  16737. /*
  16738. **  Check to see if the user specified that the original device be used
  16739. **  as dedicated log which would necessitate mixing fragment usage on
  16740. **  the device.
  16741. */
  16742. if exists (select * from sysusages u, sysdevices d
  16743.         where d.name = @devname
  16744.             and u.vstart between d.low and d.high
  16745.             and u.dbid = @dbid
  16746.             and lstart = 0)
  16747.     begin
  16748.     raiserror(15320,-1,-1,@dbname,@devname) --lpage 0 never log only
  16749.     return (1)
  16750.     end
  16751.  
  16752. /*
  16753. **  clear the bit from any database segments that aren't already log only
  16754. */
  16755. update sysusages
  16756.     set   segmap  = segmap & ~@logbit
  16757.     from  sysusages
  16758.     where dbid    = @dbid
  16759.     and   segmap <> @logbit
  16760.     and   segmap  & @logbit > 0
  16761.  
  16762. select @sum_rowcount = @sum_rowcount + @@rowcount
  16763.  
  16764. /*
  16765. **  Now set the segments on @devname as log-only.
  16766. */
  16767. update sysusages
  16768.     set   segmap = @logbit
  16769.     from  sysusages u, sysdevices d
  16770.     where d.name = @devname
  16771.     and   u.dbid = @dbid
  16772.     and   u.vstart between d.low and d.high
  16773.     and   u.segmap <> @logbit
  16774.  
  16775. select @sum_rowcount = @sum_rowcount + @@rowcount
  16776.  
  16777.  
  16778. --Any action needed?
  16779. if @sum_rowcount = 0
  16780.     begin
  16781.     raiserror(15317,-1,-1,@dbname,@devname) --okay no action
  16782.     return (0)
  16783.     end
  16784.  
  16785. /*
  16786. **  Now we need to activate the new segment map.
  16787. */
  16788. dbcc dbrepair (@dbname, remap)
  16789.  
  16790. if @@error=0
  16791.     begin
  16792.     raiserror(15318,-1,-1,@dbname,@devname)
  16793.     end
  16794. else
  16795.     begin
  16796.     raiserror(15319,-1,-1,@dbname,@devname)
  16797.     return (1)
  16798.     end
  16799.  
  16800. return (0)
  16801. go
  16802.  
  16803.  
  16804. print ''
  16805. print 'Creating procedure sp_lookup.'
  16806. go
  16807. create procedure sp_lookup
  16808. @typearg int,
  16809. @owname    varchar(30) = '%', /* owner of the desired objects (except indexes) */
  16810. @obname    varchar(30) = '%', /* name of the desired objects (including indexes) */
  16811. @indtab    varchar(30) = '%', /* table associated with the desired index */
  16812. @indown varchar(30) = '%'  /* owner of the desired index */
  16813. as
  16814.     create table #ddtab
  16815.     (
  16816.         name    varchar(30)    NOT NULL,
  16817.         owner    varchar(30)    NOT NULL,
  16818.         type    int        NOT NULL,
  16819.         indtab    varchar(30)    NOT NULL
  16820.     )
  16821.  
  16822. declare @table    int
  16823. declare @view    int
  16824. declare @index    int
  16825. declare @sproc    int
  16826. declare @trgr    int
  16827. declare @dflt    int
  16828. declare @rule    int
  16829. declare @dtype    int
  16830. declare @db    int
  16831. declare @report int
  16832.  
  16833. select @table = 1, @view = 2, @index = 4, @sproc = 8, @trgr = 16, @dflt = 32,
  16834.     @rule = 64, @dtype = 128, @db = 256, @report = 512
  16835.  
  16836. if (@typearg & @table = @table)
  16837.     insert into #ddtab
  16838.         select name, user_name(uid), @table, '' from dbo.sysobjects
  16839.             where name like @obname
  16840.                 and user_name(uid) like @owname
  16841.                 and (sysstat & 0xf = 1    /* system table */
  16842.                   or sysstat & 0xf = 3)    /* user table */
  16843.  
  16844.  
  16845. if (@typearg & @view = @view)
  16846.     insert into #ddtab
  16847.         select name, user_name(uid), @view, '' from dbo.sysobjects
  16848.             where name like @obname
  16849.                 and user_name(uid) like @owname
  16850.                   and sysstat & 0xf = 2        /* view */
  16851.  
  16852. if (@typearg & @index = @index)
  16853.     insert into #ddtab
  16854.         select i.name, user_name(o.uid), @index, o.name
  16855.             from dbo.sysindexes i, dbo.sysobjects o
  16856.                 where i.name like @obname
  16857.                     and i.indid > 0
  16858.                     and i.id = o.id
  16859.                     and user_name(o.uid) like @indown
  16860.                     and o.name = object_name(o.id)
  16861.                     and o.name like @indtab
  16862.  
  16863. if (@typearg & @report = @report)
  16864.     insert into #ddtab
  16865.         select name, user_name(uid), @report, '' from dbo.sysobjects
  16866.             where name like @obname
  16867.                 and user_name(uid) like @owname
  16868.                 and sysstat & 0xf = 4        /* sproc */
  16869.                 and userstat & -32768 = -32768    /* report */
  16870.  
  16871. if (@typearg & @sproc = @sproc)
  16872. begin
  16873.     /*
  16874.     **  If we also wanted reports, don't pick up reports again as sprocs.
  16875.     */
  16876.     if (@typearg & @report = @report)
  16877.     begin
  16878.         insert into #ddtab
  16879.             select name, user_name(uid), @sproc, '' from dbo.sysobjects
  16880.              where name like @obname
  16881.                 and user_name(uid) like @owname
  16882.                 and sysstat & 0xf = 4    /* stored procedure */
  16883.                 and userstat & -32768 <> -32768    /* report */
  16884.     end
  16885.     else
  16886.     begin
  16887.         insert into #ddtab
  16888.             select name, user_name(uid), @sproc, '' from dbo.sysobjects
  16889.              where name like @obname
  16890.                 and user_name(uid) like @owname
  16891.                 and sysstat & 0xf = 4    /* stored procedure */
  16892.     end
  16893. end
  16894.  
  16895. if (@typearg & @trgr = @trgr)
  16896.     insert into #ddtab
  16897.         select name, user_name(uid), @trgr, '' from dbo.sysobjects
  16898.             where name like @obname
  16899.                 and user_name(uid) like @owname
  16900.                   and sysstat & 0xf = 8    /* trigger */
  16901.  
  16902. if (@typearg & @dflt = @dflt)
  16903.     insert into #ddtab
  16904.         select name, user_name(uid), @dflt, '' from dbo.sysobjects
  16905.              where name like @obname
  16906.                  and user_name(uid) like @owname
  16907.                  and sysstat & 0xf = 6        /* default */
  16908.  
  16909. if (@typearg & @rule = @rule)
  16910.     insert into #ddtab
  16911.         select name, user_name(uid), @rule, '' from dbo.sysobjects
  16912.              where name like @obname
  16913.                  and user_name(uid) like @owname
  16914.                  and sysstat & 0xf = 7        /* rule */
  16915.  
  16916. if (@typearg & @dtype = @dtype)
  16917.     insert into #ddtab
  16918.         select name, user_name(uid), @dtype, '' from dbo.systypes
  16919.             where name like @obname
  16920.                 and user_name(uid) like @owname
  16921.  
  16922. if (@typearg & @db = @db)
  16923.     insert into #ddtab
  16924.         select name, suser_name(suid), @db, ''
  16925.             from sysdatabases
  16926.                 where (name like @obname)
  16927.                     and suser_name(suid) like @owname
  16928.  
  16929. select * from #ddtab order by name
  16930. return (0)
  16931. go
  16932.  
  16933. print ''
  16934. print 'Creating procedure sp_helpremotelogin.'
  16935. go
  16936. create procedure sp_helpremotelogin
  16937. @remoteserver varchar(30) = NULL,    /* remote server name */
  16938. @remotename varchar(30) = NULL        /* remote login name */
  16939. as
  16940.  
  16941. set nocount on
  16942.  
  16943. /*
  16944. **  If no server given, get 'em all.
  16945. */
  16946. if @remoteserver is null
  16947.     select @remoteserver = '%'
  16948. else
  16949.     if not exists (select *
  16950.         from sysservers s, sysremotelogins r
  16951.         where s.srvid = r.remoteserverid
  16952.             and s.srvname like @remoteserver
  16953.             and s.srvid > 0)
  16954.         begin
  16955.             if @remoteserver = '%'
  16956.                 begin
  16957.                     raiserror(15200,-1,-1)
  16958.                     return (1)
  16959.                 end
  16960.  
  16961.             raiserror(15201,-1,-1,@remoteserver)
  16962.             return (1)
  16963.         end
  16964.  
  16965. /*
  16966. **  If no remotename given, get 'em all.
  16967. */
  16968. if @remotename is null
  16969.     begin
  16970.         select @remotename = '%'
  16971.     end
  16972. else
  16973.     begin
  16974.         if not exists (select * from sysremotelogins
  16975.             where isnull(remoteusername, '') like @remotename)
  16976.  
  16977.             begin
  16978.                 if @remotename = '%'
  16979.                     begin
  16980.                         raiserror(15202,-1,-1)
  16981.                         return (1)
  16982.                     end
  16983.  
  16984.                 raiserror(15203,-1,-1,@remotename)
  16985.                 return (1)
  16986.             end
  16987.     end
  16988.  
  16989. /*
  16990. **  Check for empty results.
  16991. */
  16992. if not exists (select *
  16993.         from sysremotelogins r, sysservers s
  16994.         where isnull(r.remoteusername, '') like @remotename
  16995.             and s.srvid = r.remoteserverid
  16996.             and s.srvname like @remoteserver)
  16997.     begin
  16998.         if ((@remoteserver = '%') and (@remotename = '%'))
  16999.             raiserror(15202,-1,-1)
  17000.         else
  17001.             raiserror(15204,-1,-1,@remotename,@remoteserver)
  17002.  
  17003.         return (1)
  17004.     end
  17005.  
  17006. /*
  17007. **  Select the information.
  17008. */
  17009. select server = substring(s.srvname, 1, 22),
  17010.     local_user_name =
  17011.         substring(isnull(suser_name(r.suid), '** use local name **'), 1, 22),
  17012.     remote_user_name =
  17013.         substring(isnull(r.remoteusername, '** mapped locally **'), 1, 22),
  17014.     options = substring(v.name, 1, 9)
  17015.         from sysservers s, sysremotelogins r,
  17016.             master.dbo.spt_values v
  17017.     where s.srvid = r.remoteserverid
  17018.         and s.srvname like @remoteserver
  17019.         and s.srvid > 0
  17020.         and isnull(r.remoteusername, '') like @remotename
  17021.         and v.type = 'F'
  17022.         and v.number = r.status
  17023. order by server, remote_user_name
  17024.  
  17025. return (0)
  17026. go
  17027.  
  17028. print ''
  17029. print 'Creating procedure sp_helpsegment.'
  17030. go
  17031. create procedure sp_helpsegment
  17032. @segname varchar(30) = NULL        /* segment name */
  17033. as
  17034.  
  17035. declare    @segbit    int    /* this is the bit version of the segment # */
  17036. declare    @segment int    /* the segment number of the segment */
  17037.  
  17038. set nocount on
  17039.  
  17040. /*
  17041. **  If no segment name given, get 'em all.
  17042. */
  17043. if @segname is null
  17044.     begin
  17045.         select * from syssegments
  17046.         return (0)
  17047.     end
  17048.  
  17049. /*
  17050. **  Make sure the segment exists
  17051. */
  17052. if not exists (select * from syssegments where name = @segname)
  17053.     begin
  17054.         raiserror(15018,-1,-1,@segname)
  17055.         return (1)
  17056.     end
  17057.  
  17058. /*
  17059. **  Show the syssegment entry, then the fragments and size it is on,
  17060. **  then any dependent objects in the database.
  17061. */
  17062. select * from syssegments where name = @segname
  17063.  
  17064. /*
  17065. **  Set the bit position for the segment.
  17066. */
  17067. select @segment = segment from syssegments where name = @segname
  17068.  
  17069. /*
  17070. **  Now set the segments on @devname sysusages.
  17071. */
  17072. if (@segment < 31)
  17073.     select @segbit = power(2, @segment)
  17074. else
  17075.     /*
  17076.     **  Since this is segment 31, power(2, 31) will overflow
  17077.     **  since segmap is an int.  We'll grab the machine-dependent
  17078.     **  bit mask from spt_values to set the right bit.
  17079.     */
  17080.     select @segbit = low
  17081.         from master.dbo.spt_values
  17082.         where type = 'E'
  17083.             and number = 2
  17084.  
  17085. select device = d.name, size = convert(varchar(20),
  17086.         round((u.size * convert(float, v.low)) / 1048576, 0)) + 'MB'
  17087.     from sysusages u, sysdevices d, master.dbo.spt_values v
  17088.     where u.segmap & @segbit = @segbit
  17089.         and d.low <= u.size + u.vstart
  17090.         and d.high >= u.size + u.vstart - 1
  17091.         and u.dbid = db_id()
  17092.         and d.status & 2 = 2
  17093.         and v.number = 1
  17094.         and v.type = 'E'
  17095.  
  17096. if exists (select * from sysindexes i, syssegments s
  17097.         where s.name = @segname
  17098.             and s.segment = i.segment)
  17099.  
  17100.     select table_name = object_name(i.id), index_name = i.name, i.indid
  17101.         from sysindexes i, syssegments s
  17102.         where s.name = @segname
  17103.             and s.segment = i.segment
  17104.         order by table_name, indid
  17105.  
  17106. return (0)
  17107. go
  17108.  
  17109. print ''
  17110. print 'Creating procedure sp_helpsort.'
  17111. go
  17112. create procedure sp_helpsort
  17113. AS
  17114. set nocount on
  17115.  
  17116. declare @sortid tinyint, @charid tinyint, @status tinyint
  17117. declare @image binary(1)
  17118. declare @count int, @end_flag int
  17119.  
  17120. declare @string varchar(66)
  17121. create table #helpsort3 (string varchar(66)    NOT NULL)
  17122.  
  17123. /*
  17124. ** Get the sortorder ID, character set ID, and status
  17125. */
  17126. select @sortid = id, @charid = csid, @image = convert(binary(1), definition)
  17127.     from syscharsets, syscurconfigs
  17128.     where id = value and config = 1123
  17129.  
  17130. /*
  17131. ** Get the name and description of the character set and sort order
  17132. */
  17133. if (@sortid is null)
  17134.  BEGIN
  17135.     select @sortid = 0, @charid = 0, @status = 0
  17136.     insert #helpsort3 values ('Character Set = 0, ascii_8')
  17137.     insert #helpsort3 values ('    8-bit ASCII Character Set - System Default')
  17138.     insert #helpsort3 values ('Sort Order = 0, bin_ascii_8')
  17139.     insert #helpsort3 values ('    Binary Ordering - System Default')
  17140.  END
  17141. else
  17142.  BEGIN
  17143.     select @status = convert(tinyint, @image)
  17144.  
  17145.     select @string = 'Character Set = ' + convert(varchar(4), id) + ', ' + name
  17146.         from syscharsets
  17147.         where id = @charid and type = 1001
  17148.  
  17149.     insert into #helpsort3 values (@string)
  17150.  
  17151.     select @count = 1
  17152.     select @end_flag = 1
  17153.  
  17154.     while (@end_flag <> 0)
  17155.     begin
  17156.         select @string = substring(description, @count, 62)
  17157.             from syscharsets
  17158.             where id = @charid and type = 1001
  17159.         select @end_flag = isnull(ascii(@string), 0)
  17160.  
  17161.         if (@end_flag <> 0)
  17162.         begin
  17163.             select @string = '    ' + @string
  17164.             insert #helpsort3 values (@string)
  17165.         end
  17166.         select @count = @count + 62
  17167.     end
  17168.  
  17169.     select @string = 'Sort Order = ' + convert(varchar(4), id) + ', ' + name
  17170.         from syscharsets
  17171.         where id = @sortid and type = 2001
  17172.  
  17173.     insert into #helpsort3 values (@string)
  17174.  
  17175.     select @count = 1
  17176.     select @end_flag = 1
  17177.  
  17178.     while (@end_flag <> 0)
  17179.     begin
  17180.         select @string = substring(description, @count, 62)
  17181.             from syscharsets
  17182.             where id = @sortid and type = 2001
  17183.         select @end_flag = isnull(ascii(@string), 0)
  17184.  
  17185.         if (@end_flag <> 0)
  17186.         begin
  17187.             select @string = '    ' + @string
  17188.             insert #helpsort3 values (@string)
  17189.         end
  17190.  
  17191.         select @count = @count + 62
  17192.     end
  17193. END
  17194.  
  17195. select 'Sort Order Description' = string from #helpsort3
  17196.  
  17197. /*
  17198. ** Build the sorted list of characters for this sort order.
  17199. ** If it's not stored in spt_values yet, then put the results in there.
  17200. */
  17201. if not exists (select * from master.dbo.spt_values
  17202.         where type = 'Z'
  17203.             and high = @sortid)
  17204. BEGIN
  17205.  
  17206.     create table #helpsort1 (char_val char(1) NOT NULL)
  17207.  
  17208.  
  17209.  
  17210.     if @charid = 0       /*    ascii_8 has valid values from 32 to 126 */
  17211.     begin
  17212.             select @count = 32
  17213.             while @count <= 126
  17214.             begin
  17215.                 insert #helpsort1 (char_val)
  17216.                     values (char(@count))
  17217.                 select @count = @count + 1
  17218.             end
  17219.     end
  17220.  
  17221.     if @charid = 1      /*     iso_1 has values from 32 to 126, 160 to 255 */
  17222.     begin
  17223.             select @count = 32
  17224.             while @count <= 126
  17225.             begin
  17226.                 insert #helpsort1 (char_val)
  17227.                     values (char(@count))
  17228.                 select @count = @count + 1
  17229.             end
  17230.  
  17231.             select @count = 160
  17232.             while @count <= 255
  17233.             begin
  17234.                    insert #helpsort1 (char_val)
  17235.                         values (char(@count))
  17236.                     select @count = @count + 1
  17237.             end
  17238.     end
  17239.  
  17240.     if @charid = 2      /*     cp850 has valid values from 0 to 255 */
  17241.     begin
  17242.             select @count = 32
  17243.             while @count <= 255
  17244.             begin
  17245.                 insert #helpsort1 (char_val)
  17246.                     values (char(@count))
  17247.                 select @count = @count + 1
  17248.             end
  17249.     end
  17250.  
  17251.     if @charid = 3      /*     cp437 has valid values from 0 to 255 */
  17252.     begin
  17253.             select @count =32
  17254.             while @count <= 255
  17255.             begin
  17256.                 insert #helpsort1 (char_val)
  17257.                     values (char(@count))
  17258.                 select @count = @count + 1
  17259.             end
  17260.     end
  17261.  
  17262.     if @charid = 4
  17263.         begin
  17264.                 select @count =32
  17265.                 while @count <= 255
  17266.                 begin
  17267.                         insert #helpsort1 (char_val)
  17268.                                 values (char(@count))
  17269.                         select @count = @count + 1
  17270.                 end
  17271.  
  17272.                 /* Remove unwanted values */
  17273.  
  17274.                 delete #helpsort1 where ascii(char_val) in (127, 128, 129, 131, 136, 144, 152)
  17275.  
  17276.         end
  17277.  
  17278.     if @charid = 5
  17279.         begin
  17280.                 select @count =32
  17281.                 while @count <= 255
  17282.                 begin
  17283.                         insert #helpsort1 (char_val)
  17284.                                 values (char(@count))
  17285.                         select @count = @count + 1
  17286.                 end
  17287.  
  17288.                 /* Remove unwanted values */
  17289.  
  17290.                 delete #helpsort1 where ascii(char_val) in (127, 136, 152)
  17291.  
  17292.         end
  17293.  
  17294.     if @charid = 6
  17295.         begin
  17296.                 select @count =32
  17297.                 while @count <= 255
  17298.                 begin
  17299.                         insert #helpsort1 (char_val)
  17300.                                 values (char(@count))
  17301.                         select @count = @count + 1
  17302.                 end
  17303.  
  17304.                 /* Remove unwanted values */
  17305.  
  17306.                 delete #helpsort1 where ascii(char_val) in (128, 129, 136, 138, 140, 141, 142, 143, 144, 152, 154, 156, 157, 158, 159)
  17307.  
  17308.         end
  17309.  
  17310.     if @charid = 7
  17311.         begin
  17312.                 select @count =32
  17313.                 while @count <= 255
  17314.                 begin
  17315.                         insert #helpsort1 (char_val)
  17316.                                 values (char(@count))
  17317.                         select @count = @count + 1
  17318.                 end
  17319.  
  17320.                 /* Remove unwanted values */
  17321.  
  17322.                 delete #helpsort1 where ascii(char_val) in (128, 129, 141, 142, 143, 144, 157, 158)
  17323.  
  17324.         end
  17325.  
  17326.     if @charid = 8
  17327.         begin
  17328.                 select @count =32
  17329.                 while @count <= 255
  17330.                 begin
  17331.                         insert #helpsort1 (char_val)
  17332.                                 values (char(@count))
  17333.                         select @count = @count + 1
  17334.                 end
  17335.  
  17336.                 /* Remove unwanted values */
  17337.  
  17338.                 delete #helpsort1 where ascii(char_val) in (128, 129, 138, 140, 141, 142, 143, 144, 154, 156, 157, 158, 159)
  17339.  
  17340.         end
  17341.  
  17342.     if @charid = 9
  17343.         begin
  17344.                 select @count =32
  17345.                 while @count <= 255
  17346.                 begin
  17347.                         insert #helpsort1 (char_val)
  17348.                                 values (char(@count))
  17349.                         select @count = @count + 1
  17350.                 end
  17351.  
  17352.                 /* Remove unwanted values */
  17353.  
  17354.                 delete #helpsort1 where ascii(char_val) in (128, 138, 143, 152, 154, 159)
  17355.  
  17356.         end
  17357.  
  17358.     if @charid = 10
  17359.         begin
  17360.                 select @count =32
  17361.                 while @count <= 255
  17362.                 begin
  17363.                         insert #helpsort1 (char_val)
  17364.                                 values (char(@count))
  17365.                         select @count = @count + 1
  17366.                 end
  17367.  
  17368.                 /* Remove unwanted values */
  17369.  
  17370.                 delete #helpsort1 where ascii(char_val) in (128, 129, 131, 136, 138, 140, 143, 144, 156, 159)
  17371.  
  17372.         end
  17373.  
  17374.  
  17375.     if @charid > 10     /* User Character Set Not recognised by sp_helpsort */
  17376.     begin
  17377.            select 'Unknown Character Set : ' + name from syscharsets
  17378.                     where id = @sortid and type = 2001
  17379.         return (0)
  17380.     end
  17381.  
  17382.     select (char_val) into #helpsort2
  17383.         from #helpsort1
  17384.         order by char_val
  17385.  
  17386.     declare @char char(1)
  17387.     declare @char_str varchar(20)
  17388.     declare @incr int
  17389.     declare @seq_num int
  17390.     declare @rel char(1)
  17391.     declare @old_char char(1)
  17392.  
  17393.     select @char = char(0), @seq_num = 0, @count = 0, @incr = 8, @end_flag = 1
  17394.     select @rel = ' ', @old_char = NULL
  17395.  
  17396.     set rowcount 1
  17397.  
  17398.     while @end_flag <> 0
  17399.     begin
  17400.         select @char_str = ''
  17401.  
  17402.         /* If PST_NOTUNIQ is set, then possibly caseless */
  17403.         if (@status & 8 = 8)
  17404.             while (@count < @incr  and  @end_flag <> 0)
  17405.             begin
  17406.                 select @char = char_val
  17407.                     from #helpsort2
  17408.                     where char_val >= @char
  17409.                 select @end_flag = @@rowcount
  17410.  
  17411.         if (@end_flag <> 0)
  17412.         begin
  17413.             if (@char = @old_char)
  17414.             select @rel = '='
  17415.             else
  17416.             select @rel = ' '
  17417.  
  17418.             select @old_char = @char
  17419.             select @char_str = @char_str + @rel + @char
  17420.             delete from #helpsort2 where ascii(@char) = ascii(char_val)
  17421.  
  17422.             select @count = @count + 1
  17423.         end
  17424.     end
  17425.     else
  17426.         while (@count < @incr  and  @end_flag <> 0)
  17427.             begin
  17428.                 select @char = char_val
  17429.                     from #helpsort2
  17430.                     where char_val > @char
  17431.                 select @end_flag = @@rowcount
  17432.                 if (@end_flag <> 0)
  17433.                     begin
  17434.                         select @char_str = @char_str + @rel + @char
  17435.                         delete from #helpsort2 where ascii(@char) = ascii(char_val)
  17436.                         select @count = @count + 1
  17437.                     end
  17438.             end
  17439.  
  17440.         select @incr = @incr + 8, @seq_num = @seq_num + 1
  17441.         insert master.dbo.spt_values (name, number, type, low, high)
  17442.         values (@char_str, @seq_num, 'Z', @charid, @sortid)
  17443.     end
  17444.  
  17445.     set rowcount 0
  17446.  
  17447. END
  17448.  
  17449. /*
  17450. ** Display the sorted list of characters.
  17451. */
  17452. select @count = 1
  17453. select @end_flag = 1
  17454. select @incr = 5
  17455.  
  17456. truncate table #helpsort3
  17457.  
  17458. while @end_flag <> 0
  17459. BEGIN
  17460.     select @string = ''
  17461.  
  17462.     while @count < @incr
  17463.     begin
  17464.         select @string = @string + substring(name, 2, 19)
  17465.             from master.dbo.spt_values
  17466.             where type = 'Z'
  17467.                 and number = @count
  17468.                 and high = @sortid
  17469.         select @end_flag = @@rowcount
  17470.         select @count = @count + 1
  17471.     end
  17472.  
  17473.     select @incr = @incr + 4
  17474.  
  17475.     insert into #helpsort3 values (@string)
  17476. END
  17477.  
  17478. select 'Characters, in Order' = string
  17479.     from #helpsort3
  17480. set nocount off
  17481. return(0)
  17482. go
  17483.  
  17484. print ''
  17485. print 'Creating procedure sp_helpstartup.'
  17486. go
  17487. create procedure sp_helpstartup
  17488. as
  17489.  
  17490. /*
  17491. **  Only the SA can do this.
  17492. */
  17493. if suser_id() <> 1
  17494. begin
  17495.     raiserror(15003,-1,-1)
  17496.     return (1)
  17497. end
  17498.  
  17499. select 'Startup stored procedures:' = name from sysobjects
  17500.     where category & 16 = 16
  17501.  
  17502. return(0)
  17503. go
  17504.  
  17505. print ''
  17506. print 'Creating procedure sp_helpserver.'
  17507. go
  17508. create procedure sp_helpserver
  17509. @server varchar(30) = NULL,        /* server name */
  17510. @optname varchar(20) = NULL,
  17511. @show_topology varchar(1) = NULL
  17512. as
  17513.  
  17514. declare @optbit int
  17515.  
  17516. set nocount on
  17517.  
  17518. /*
  17519. **  If no server name given, get 'em all.
  17520. */
  17521. if @server = null
  17522.     select @server = '%'
  17523.  
  17524. /*
  17525. **  Does the server exist?
  17526. */
  17527. if not exists (select *
  17528.         from sysservers
  17529.             where srvname like @server
  17530.                 or srvnetname like @server)
  17531.     begin
  17532.         if @server = '%'
  17533.             raiserror(15205,-1,-1)
  17534.         else
  17535.             raiserror(15015,-1,-1,@server)
  17536.  
  17537.         return (1)
  17538.     end
  17539.  
  17540. /*
  17541. **  Display server information.
  17542. **  First put it into a temp table so we can blot inappropriate status
  17543. **  for the local server.  It's ugly but I couldn't think of another way.
  17544. */
  17545. declare @cursrvid smallint    /* the one we're currently working on */
  17546. declare @srvdesc varchar(11)    /* the total description for the server */
  17547. declare @bitdesc varchar(30)    /* the bit description for the server  */
  17548. create table #spt_server
  17549. (
  17550.     name    varchar(30)    NOT NULL,
  17551.     network    varchar(30)    NOT NULL,
  17552.     status    varchar(11)    NOT NULL,
  17553.     id    smallint        NOT NULL,
  17554.     topx    int        NULL,
  17555.     topy    int        NULL
  17556. )
  17557.  
  17558. /*
  17559. **  Allow option specification.
  17560. */
  17561. select @optbit = -1     /* 0xffffffff */
  17562. if @optname is not null
  17563.     begin
  17564.         select @optbit = null
  17565.         select @optbit = number
  17566.             from master.dbo.spt_values
  17567.             where type = 'A'
  17568.                 and name = @optname
  17569.         if @optbit is null or @optbit <= 0
  17570.             begin
  17571.                 raiserror(15206,-1,-1,@optname)
  17572.                 return(1)
  17573.             end
  17574.     end
  17575.  
  17576. /*
  17577. **  Set @cursrvid to the first or only srvid.
  17578. **  Mask out 'rpc' for the local server.
  17579. */
  17580. if @server = '%'
  17581.     select @cursrvid = min(srvid) from sysservers
  17582.         where (@optname is null or srvstatus & @optbit <> 0)
  17583.         and not (@optbit = 1 and srvid = 0)
  17584. else
  17585.     select @cursrvid = srvid from sysservers
  17586.         where srvname =    @server
  17587.         and (@optname is null or srvstatus & @optbit <> 0)
  17588.         and not (@optbit = 1 and srvid = 0)
  17589.  
  17590. while @cursrvid <> NULL
  17591. begin
  17592.     /*
  17593.     **  Initialize @srvdesc.
  17594.     */
  17595.     select @srvdesc = ''
  17596.  
  17597.     /*
  17598.     ** Check rpc bit (1)
  17599.     */
  17600.     if @cursrvid <> 0
  17601.         begin
  17602.             select @bitdesc = null
  17603.             select @bitdesc = v.name
  17604.                 from master.dbo.spt_values v, sysservers s
  17605.                 where s.srvid = @cursrvid
  17606.                     and v.type = 'A'
  17607.                     and v.name = 'rpc'
  17608.                     and s.srvstatus & v.number = 1
  17609.  
  17610.             if @bitdesc <> null
  17611.                 begin
  17612.                     if @srvdesc <> ''
  17613.                         select @srvdesc = @srvdesc + ',' +  @bitdesc
  17614.                     else
  17615.                         select @srvdesc = @bitdesc
  17616.                 end
  17617.          end
  17618.  
  17619.     /*
  17620.     ** Check publisher bit (2)
  17621.     */
  17622.     select @bitdesc = null
  17623.     select @bitdesc = v.name
  17624.         from master.dbo.spt_values v, sysservers s
  17625.         where s.srvid = @cursrvid
  17626.             and v.type = 'A'
  17627.             and v.name = 'pub'
  17628.             and s.srvstatus & v.number = 2
  17629.     
  17630.     if @bitdesc <> null
  17631.         begin
  17632.             if @srvdesc <> ''
  17633.                 select @srvdesc = @srvdesc + ',' +  @bitdesc
  17634.             else
  17635.                 select @srvdesc = @bitdesc
  17636.         end
  17637.  
  17638.     /*
  17639.     ** Check subscriber bit (4)
  17640.     */
  17641.     select @bitdesc = null
  17642.     select @bitdesc = v.name
  17643.         from master.dbo.spt_values v, sysservers s
  17644.         where s.srvid = @cursrvid
  17645.             and v.type = 'A'
  17646.             and v.name = 'sub'
  17647.             and s.srvstatus & v.number = 4
  17648.  
  17649.     if @bitdesc <> null
  17650.         begin
  17651.             if @srvdesc <> ''
  17652.                 select @srvdesc = @srvdesc + ',' +  @bitdesc
  17653.             else
  17654.                 select @srvdesc = @bitdesc
  17655.         end
  17656.  
  17657.     /*
  17658.     ** Check distribution bit (8)
  17659.     */
  17660.     select @bitdesc = null
  17661.     select @bitdesc = v.name
  17662.         from master.dbo.spt_values v, sysservers s
  17663.         where s.srvid = @cursrvid
  17664.             and v.type = 'A'
  17665.             and v.name = 'dist'
  17666.             and s.srvstatus & v.number = 8
  17667.  
  17668.     if @bitdesc <> null
  17669.         begin
  17670.             if @srvdesc <> ''
  17671.                 select @srvdesc = @srvdesc + ',' +  @bitdesc
  17672.             else
  17673.                 select @srvdesc = @bitdesc
  17674.         end
  17675.  
  17676.     /*
  17677.     ** Check distribution publisher bit (16)
  17678.     */
  17679.     select @bitdesc = null
  17680.     select @bitdesc = v.name
  17681.         from master.dbo.spt_values v, sysservers s
  17682.         where s.srvid = @cursrvid
  17683.             and v.type = 'A'
  17684.             and v.name = 'dpub'
  17685.             and s.srvstatus & v.number = 16
  17686.  
  17687.     if @bitdesc <> null
  17688.         begin
  17689.             if @srvdesc <> ''
  17690.                 select @srvdesc = @srvdesc + ',' +  @bitdesc
  17691.             else
  17692.                 select @srvdesc = @bitdesc
  17693.         end
  17694.  
  17695.     /*
  17696.     ** Check ODBC DSN bit (32)
  17697.     */
  17698.     select @bitdesc = null
  17699.     select @bitdesc = v.name
  17700.         from master.dbo.spt_values v, sysservers s
  17701.         where s.srvid = @cursrvid
  17702.             and v.type = 'A'
  17703.             and v.name = 'dsn'
  17704.             and s.srvstatus & v.number = 32
  17705.  
  17706.     if @bitdesc <> null
  17707.         begin
  17708.             if @srvdesc <> ''
  17709.                 select @srvdesc = @srvdesc + ',' +  @bitdesc
  17710.             else
  17711.                 select @srvdesc = @bitdesc
  17712.         end
  17713.  
  17714.     insert into #spt_server
  17715.         select s.srvname, s.srvnetname, @srvdesc, id = s.srvid,
  17716.             s.topologyx,s.topologyy
  17717.         from sysservers s
  17718.             where s.srvid = @cursrvid
  17719.  
  17720.     /*
  17721.     ** Quit if server specified or increment to next server.
  17722.     */
  17723.     if @server = '%'
  17724.         select @cursrvid = min(srvid) from sysservers
  17725.             where srvid > @cursrvid
  17726.             and (@optname is null or srvstatus & @optbit <> 0)
  17727.             and not (@optbit = 1 and srvid = 0)
  17728.     else
  17729.         select @cursrvid = NULL
  17730. end
  17731.  
  17732. if lower(@show_topology) <> 't' or @show_topology is null
  17733.     select name, network_name = substring(network, 1, 28),
  17734.         status = status, id = convert(char(4), id)
  17735.     from #spt_server
  17736.     order by name
  17737. else
  17738.     select name, network_name = substring(network, 1, 28),
  17739.         status = status, id = convert(char(4), id),
  17740.         topx,topy
  17741.     from #spt_server
  17742.     order by name
  17743.  
  17744. return(0)
  17745. go
  17746.  
  17747. print ''
  17748. print 'Creating procedure sp_makestartup.'
  17749. go
  17750. create procedure sp_makestartup
  17751. @procname varchar(30) = null
  17752. as
  17753. declare @objid    int
  17754. declare @dbname varchar(30)
  17755.  
  17756. /*
  17757. **    Check to see if a proc. name was specified.
  17758. */
  17759. if @procname is null
  17760.     begin
  17761.         raiserror(15207,-1,-1)
  17762.         return (1)
  17763.     end
  17764.  
  17765. /*
  17766. **  Only the SA can do this.
  17767. */
  17768. if suser_id() <> 1
  17769. begin
  17770.     raiserror(15003,-1,-1)
  17771.     return (1)
  17772. end
  17773.  
  17774. /*
  17775. **  Make sure the @procname is in the master database.
  17776. */
  17777. if @procname like '%.%.%' and    -- Explicit db name supplied
  17778.     substring(@procname, 1, charindex('.', @procname) - 1) <> 'master'
  17779.     begin
  17780.         raiserror(15272,-1,-1,@procname)
  17781.         return (1)
  17782.     end
  17783. else    -- No explicit name supplied so we need to be in the 'master' db
  17784.     if db_name() <> 'master'
  17785.         begin
  17786.             select @dbname = db_name()
  17787.             raiserror(15273,-1,-1,@procname,@dbname)
  17788.             return(1)
  17789.         end
  17790. /*
  17791. **  Make sure the procedure exists and get its id so we can use
  17792. **    a simpler where clause.
  17793. */
  17794. select @objid = id from master..sysobjects
  17795.     where sysstat & 0xf = 4
  17796.     and name = @procname
  17797.  
  17798. if @objid is null
  17799.     begin
  17800.         raiserror(15020,-1,-1,@procname)
  17801.         return (1)
  17802.     end
  17803.  
  17804. /*
  17805. **  Make sure that the procedure is owned by the SA.  We're looking
  17806. **    in master so if the uid indicates dbo it has to be the SA.
  17807. */
  17808. if (select uid from master..sysobjects
  17809.         where id = @objid) <> 1
  17810.     begin
  17811.         raiserror(15208,-1,-1)
  17812.         return (1)
  17813.     end
  17814.  
  17815. /*
  17816. **  Check to see that the procedure doesn't expect any parameters.
  17817. */
  17818. if exists (select * from master..syscolumns
  17819.             where id = @objid)
  17820.     begin
  17821.         raiserror(15209,-1,-1)
  17822.         return (1)
  17823.     end
  17824.  
  17825. /*
  17826. **    If we made it to here, make it autoexec.
  17827. */
  17828. if (select category & 16 from master..sysobjects where id = @objid) <> 16
  17829.     begin
  17830.         update master..sysobjects set category = category | 16
  17831.             where id = @objid
  17832.         print 'Procedure has been marked as ''startup''.'
  17833.     end
  17834. else
  17835.     print 'Procedure is already designated as ''startup''.'
  17836.  
  17837. return (0)
  17838. go
  17839.  
  17840. print ''
  17841. print 'Creating procedure sp_markreport.'
  17842. go
  17843. create procedure sp_markreport
  17844. @reportname varchar(92)        /* proc name we want to mark as report */
  17845. as
  17846.  
  17847. /*
  17848. **  Make sure the @reportname is local to the current database.
  17849. */
  17850. if @reportname like '%.%.%' and
  17851.     substring(@reportname, 1, charindex('.', @reportname) - 1) <> db_name()
  17852.     begin
  17853.         raiserror(15083,-1,-1)
  17854.         return (1)    
  17855.     end
  17856.  
  17857. /*
  17858. **  Make sure that it actually exists as a sproc.
  17859. */
  17860. if not exists (select * from sysobjects
  17861.         where id = object_id(@reportname)
  17862.         and sysstat & 0xf = 4    /* stored procedure */
  17863.         and uid = user_id())
  17864.     begin
  17865.         raiserror(15021,-1,-1,@reportname)
  17866.         return (1)
  17867.     end
  17868.  
  17869. update sysobjects
  17870.     set userstat = userstat | -32768    /* high bit means report */
  17871.         from sysobjects
  17872.             where id = object_id(@reportname)
  17873.             and sysstat & 0xf = 4        /* stored procedure */
  17874.             and uid = user_id()
  17875.  
  17876. return (0)
  17877. go
  17878.  
  17879. print ''
  17880. print 'Creating procedure sp_monitor.'
  17881. go
  17882. create procedure sp_monitor
  17883. as
  17884.  
  17885. /*
  17886. **  Declare variables to be used to hold current monitor values.
  17887. */
  17888. declare @now         datetime
  17889. declare @cpu_busy     int
  17890. declare @io_busy    int
  17891. declare @idle        int
  17892. declare @pack_received    int
  17893. declare @pack_sent    int
  17894. declare @pack_errors    int
  17895. declare @connections    int
  17896. declare @total_read    int
  17897. declare @total_write    int
  17898. declare @total_errors    int
  17899.  
  17900. declare @oldcpu_busy     int    /* used to see if DataServer has been rebooted */
  17901. declare @interval    int
  17902. declare @mspertick    int    /* milliseconds per tick */
  17903.  
  17904. /*
  17905. **  If we're in a transaction, disallow this since it might make recovery
  17906. **  impossible.
  17907. */
  17908. if @@trancount > 0
  17909.     begin
  17910.         raiserror(15002,-1,-1,'sp_monitor')
  17911.         return (1)
  17912.     end
  17913.  
  17914. /*
  17915. **  Set @mspertick.  This is just used to make the numbers easier to handle
  17916. **  and avoid overflow.
  17917. */
  17918. select @mspertick = convert(int, @@timeticks / 1000.0)
  17919.  
  17920. /*
  17921. **  Get current monitor values.
  17922. */
  17923. select
  17924.     @now = getdate(),
  17925.     @cpu_busy = @@cpu_busy,
  17926.     @io_busy = @@io_busy,
  17927.     @idle = @@idle,
  17928.     @pack_received = @@pack_received,
  17929.     @pack_sent = @@pack_sent,
  17930.     @connections = @@connections,
  17931.     @pack_errors = @@packet_errors,
  17932.     @total_read = @@total_read,
  17933.     @total_write = @@total_write,
  17934.     @total_errors = @@total_errors
  17935.  
  17936. /*
  17937. **  Check to see if DataServer has been rebooted.  If it has then the
  17938. **  value of @@cpu_busy will be less than the value of spt_monitor.cpu_busy.
  17939. **  If it has update spt_monitor.
  17940. */
  17941. select @oldcpu_busy = cpu_busy
  17942.     from spt_monitor
  17943. if @oldcpu_busy > @cpu_busy
  17944. begin
  17945.     update spt_monitor
  17946.         set
  17947.             lastrun = @now,
  17948.             cpu_busy = @cpu_busy,
  17949.             io_busy = @io_busy,
  17950.             idle = @idle,
  17951.             pack_received = @pack_received,
  17952.             pack_sent = @pack_sent,
  17953.             connections = @connections,
  17954.             pack_errors = @pack_errors,
  17955.             total_read = @total_read,
  17956.             total_write = @total_write,
  17957.             total_errors = @total_errors
  17958. end
  17959.  
  17960. /*
  17961. **  Now print out old and new monitor values.
  17962. */
  17963. set nocount on
  17964. select @interval = datediff(ss, lastrun, @now)
  17965.     from spt_monitor
  17966. /* To prevent a divide by zero error when run for the first
  17967. ** time after boot up
  17968. */
  17969. if @interval = 0
  17970.     select @interval = 1
  17971. select last_run = lastrun, current_run = @now, seconds = @interval
  17972.     from spt_monitor
  17973.  
  17974. select
  17975.     cpu_busy = substring(convert(varchar(11),
  17976.         convert(int, ((@cpu_busy * @mspertick) / 1000)))
  17977.         + '('
  17978.         + convert(varchar(11), convert(int, (((@cpu_busy - cpu_busy)
  17979.         * @mspertick) / 1000)))
  17980.         + ')'
  17981.         + '-'
  17982.         + convert(varchar(11), convert(int, ((((@cpu_busy - cpu_busy)
  17983.         * @mspertick) / 1000) * 100) / @interval))
  17984.         + '%',
  17985.         1, 25),
  17986.     io_busy = substring(convert(varchar(11),
  17987.         convert(int, ((@io_busy * @mspertick) / 1000)))
  17988.         + '('
  17989.         + convert(varchar(11), convert(int, (((@io_busy - io_busy)
  17990.         * @mspertick) / 1000)))
  17991.         + ')'
  17992.         + '-'
  17993.         + convert(varchar(11), convert(int, ((((@io_busy - io_busy)
  17994.         * @mspertick) / 1000) * 100) / @interval))
  17995.         + '%',
  17996.         1, 25),
  17997.     idle = substring(convert(varchar(11),
  17998.         convert(int, ((@idle * @mspertick) / 1000)))
  17999.         + '('
  18000.         + convert(varchar(11), convert(int, (((@idle - idle)
  18001.         * @mspertick) / 1000)))
  18002.         + ')'
  18003.         + '-'
  18004.         + convert(varchar(11), convert(int, ((((@idle - idle)
  18005.         * @mspertick) / 1000) * 100) / @interval))
  18006.         + '%',
  18007.         1, 25)
  18008. from spt_monitor
  18009.  
  18010. select
  18011.     packets_received = substring(convert(varchar(11), @pack_received) + '(' +
  18012.         convert(varchar(11), @pack_received - pack_received) + ')', 1, 25),
  18013.     packets_sent = substring(convert(varchar(11), @pack_sent) + '(' +
  18014.         convert(varchar(11), @pack_sent - pack_sent) + ')', 1, 25),
  18015.     packet_errors = substring(convert(varchar(11), @pack_errors) + '(' +
  18016.         convert(varchar(11), @pack_errors - pack_errors) + ')', 1, 25)
  18017. from spt_monitor
  18018.  
  18019. select
  18020.     total_read = substring(convert(varchar(11), @total_read) + '(' +
  18021.         convert(varchar(11), @total_read - total_read) + ')', 1, 19),
  18022.     total_write = substring(convert(varchar(11), @total_write) + '(' +
  18023.         convert(varchar(11), @total_write - total_write) + ')', 1, 19),
  18024.     total_errors = substring(convert(varchar(11), @total_errors) + '(' +
  18025.         convert(varchar(11), @total_errors - total_errors) + ')', 1, 19),
  18026.     connections = substring(convert(varchar(11), @connections) + '(' +
  18027.         convert(varchar(11), @connections - connections) + ')', 1, 18)
  18028. from spt_monitor
  18029.  
  18030. /*
  18031. **  Now update spt_monitor
  18032. */
  18033. update spt_monitor
  18034.     set
  18035.         lastrun = @now,
  18036.         cpu_busy = @cpu_busy,
  18037.         io_busy = @io_busy,
  18038.         idle = @idle,
  18039.         pack_received = @pack_received,
  18040.         pack_sent = @pack_sent,
  18041.         connections = @connections,
  18042.         pack_errors = @pack_errors,
  18043.         total_read = @total_read,
  18044.         total_write = @total_write,
  18045.         total_errors = @total_errors
  18046.  
  18047. return (0)
  18048. go
  18049.  
  18050. print ''
  18051. print 'Creating procedure sp_password.'
  18052. go
  18053. create procedure sp_password
  18054. @old varchar(30) = NULL,    /* the old (current) password */
  18055. @new varchar(30),        /* the new password */
  18056. @loginame varchar(30) = NULL    /* user to change password on */
  18057. as
  18058.  
  18059. declare @suid int        /* suid of person to change pw on */
  18060.  
  18061. /*
  18062. **  If we're in a transaction, disallow this since it might make recovery
  18063. **  impossible.
  18064. */
  18065. if @@trancount > 0
  18066.     begin
  18067.         raiserror(15002,-1,-1,'sp_password')
  18068.         return (1)
  18069.     end
  18070.  
  18071. /*
  18072. **  If the system administrator (sa) is running this command, the sa can
  18073. **  change anyone's password and doesn't have to know the old password.
  18074. **  We have this case is suser_id() = 1 and @loginame is NOT NULL.
  18075. **  In this case, we'll fill in the old password and set the suid.
  18076. */
  18077. if suser_id() <> 1 and @loginame IS NOT NULL
  18078.     begin
  18079.         /*
  18080.         **  Only the sa can use the @loginame.
  18081.         */
  18082.         raiserror(15210,-1,-1)
  18083.         return (1)
  18084.     end
  18085.  
  18086. /*
  18087. **  Does the SA want to change someone's password?
  18088. */
  18089. if suser_id() = 1 and @loginame IS NOT NULL
  18090. begin
  18091.     /*  Check to see if the user exists. */
  18092.  
  18093.     select @suid = suid from syslogins where name = @loginame
  18094.  
  18095.     if @suid is null
  18096.         begin
  18097.             raiserror(15007,-1,-1,@loginame)
  18098.             return (1)
  18099.         end
  18100.  
  18101.     /*
  18102.     **  Get the old password for the user.  If @old not given, don't
  18103.     **  bother checking against the old password.
  18104.     */
  18105.     if @old IS NOT NULL
  18106.     begin
  18107.         /*
  18108.         ** Reinitialize @suid since previous assignment
  18109.         ** set it.
  18110.         */
  18111.         select @suid = NULL
  18112.  
  18113.         select @suid = suid
  18114.             from syslogins
  18115.             where name = @loginame
  18116.                 and password = @old
  18117.                 or pwdcompare(@old, password) = 1
  18118.  
  18119.         if @suid is null
  18120.             begin
  18121.                 raiserror(15211,-1,-1)
  18122.                 return (1)
  18123.             end
  18124.     end
  18125. end
  18126.  
  18127. /*
  18128. **  This is just the normal case when someone wants to change their own
  18129. **  password.  Set the @suid.
  18130. */
  18131. else
  18132.     if @loginame is null
  18133.         select @suid = suid
  18134.             from syslogins
  18135.             where (password = @old or pwdcompare(@old, password) = 1)
  18136.                 and suid = suser_id()
  18137.  
  18138.  
  18139. if @suid is null
  18140.     begin
  18141.         raiserror(15211,-1,-1)
  18142.         return (1)
  18143.     end
  18144.  
  18145. /*
  18146. **  This is the final case.  The sa is running the command to change
  18147. **  someone else's password and is supplying the old password.  Confirm
  18148. **  that the old password is correct.
  18149. */
  18150. if suser_id() = 1
  18151.     begin
  18152.         select @suid = suid
  18153.             from syslogins
  18154.             where (password = @old or pwdcompare(@old, password) = 1)
  18155.                 and suid = suser_id(@loginame)
  18156.  
  18157.         if @suid is null                          
  18158.             begin
  18159.                 raiserror(15211,-1,-1)
  18160.                 return (1)
  18161.             end
  18162.     end
  18163.  
  18164. /*
  18165. **  If @suid still hasn't been set then the user running the procedure
  18166. **  doesn't have the right current password.
  18167. */
  18168. if @suid is null
  18169.     begin
  18170.         raiserror(15211,-1,-1)
  18171.         return (1)
  18172.     end
  18173.  
  18174. /*
  18175. **  Everything is consistent so change the password and set encrypt flag.
  18176. */
  18177. update syslogins set password = pwdencrypt(@new),status = status | 8
  18178.     where suid = @suid
  18179.  
  18180. print 'Password changed.'
  18181.  
  18182. return (0)
  18183. go
  18184.  
  18185. print ''
  18186. print 'Creating procedure sp_placeobject.'
  18187. go
  18188. create procedure sp_placeobject
  18189. @segname    varchar(30),    /* segment name */
  18190. @objname    varchar(62)    /* object name */
  18191. as
  18192.  
  18193. declare    @msg        char(100)
  18194. declare @objid        int
  18195. declare @tabname    varchar(30)
  18196. declare @indexname    varchar(30)
  18197. declare    @indexid    smallint
  18198. declare    @segment    smallint
  18199. declare @dbname        varchar(30)
  18200.  
  18201. /*
  18202. **  Check to see if the segment exists.
  18203. */
  18204. select @segment = segment from syssegments where name = @segname
  18205. if @segment is null
  18206.     begin
  18207.         raiserror(15018,-1,-1,@segname)
  18208.         return (1)
  18209.     end
  18210.  
  18211. select @dbname = db_name()
  18212.  
  18213. /*
  18214. **  Are we dealing with a table or its index?
  18215. */
  18216. if @objname like '%.%'
  18217.     begin
  18218.  
  18219.         /*
  18220.         **  Get the table name out.
  18221.         */
  18222.         select @tabname = substring(@objname, 1, charindex('.', @objname) - 1)
  18223.         select @indexname = substring(@objname, charindex('.', @objname) + 1, 61)
  18224.     end
  18225. else
  18226.         select @tabname = @objname, @indexname = null
  18227.  
  18228. /*
  18229. **  Can't use placeobject to move syslogs.
  18230. */
  18231. if (object_id(@tabname) = 8)
  18232.     begin
  18233.         raiserror(15212,-1,-1)
  18234.         return (1)
  18235.     end
  18236.  
  18237. /*
  18238. **  Can't move system tables.
  18239. */
  18240. if object_id(@tabname) < 100
  18241.     begin
  18242.         raiserror(15213,-1,-1)
  18243.         return (1)
  18244.     end
  18245.  
  18246. /*
  18247. **  If the user is not the dbo or the SA, make sure he/she owns it.
  18248. */
  18249. if suser_id() <> 1 and user_id() <> 1
  18250.     begin
  18251.         if not exists (select *
  18252.             from sysobjects
  18253.                 where name = @tabname
  18254.                     and uid = user_id())
  18255.             begin
  18256.                 raiserror(15214,-1,-1,@tabname)
  18257.                 return (1)
  18258.             end
  18259.     end
  18260. else
  18261.     begin
  18262.         /*
  18263.         **  If dbo or SA, make sure the table exists.
  18264.         */
  18265.         if not exists (select * from sysobjects where name = @tabname)
  18266.             begin
  18267.                 raiserror(15009,-1,-1,@tabname,@dbname)
  18268.                 return (1)
  18269.             end
  18270.     end
  18271.  
  18272. /*
  18273. **  If we are dealing with an index, make sure it exists.
  18274. */
  18275. if @indexname IS NOT NULL and not exists (select *
  18276.                     from sysindexes
  18277.                         where id = object_id(@tabname)
  18278.                             and name = @indexname)
  18279. begin
  18280.     raiserror(15215,-1,-1,@indexname,@tabname)
  18281.     return (1)
  18282.  
  18283. end
  18284.  
  18285. /*
  18286. **  Everything's ok so change the segment for the object.
  18287. */
  18288. if @indexname is null
  18289. begin
  18290.     select @indexid = indid
  18291.         from sysindexes
  18292.             where id = object_id(@tabname)
  18293.                 and indid < 2
  18294. end
  18295. else
  18296. begin
  18297.     select @indexid = indid
  18298.         from sysindexes
  18299.             where id = object_id(@tabname)
  18300.                 and name = @indexname
  18301. end
  18302.  
  18303. update sysindexes
  18304. set segment = @segment
  18305.     from sysindexes
  18306.         where id = object_id(@tabname)
  18307.             and indid = @indexid
  18308.  
  18309. dbcc dbrepair (@dbname, remap)
  18310. select @msg = '''' + @objname + ''' is now on segment ''' + @segname + '''.'
  18311. print @msg
  18312.  
  18313. return (0)
  18314. go
  18315.  
  18316. print ''
  18317. print 'Creating procedure sp_primarykey.'
  18318. go
  18319. create procedure sp_primarykey
  18320. @tabname  varchar(92),            /* table name that has the key */
  18321. @col1     varchar(30),             /* columns that make up the key */
  18322. @col2     varchar(30) = NULL,
  18323. @col3     varchar(30) = NULL,
  18324. @col4     varchar(30) = NULL,
  18325. @col5     varchar(30) = NULL,
  18326. @col6     varchar(30) = NULL,
  18327. @col7     varchar(30) = NULL,
  18328. @col8     varchar(30) = NULL
  18329. as
  18330.  
  18331. declare @objid int            /* object id of the table */
  18332. declare @uid smallint            /* owner id of the object */
  18333. declare @cnt smallint            /* howmany columns in key */
  18334. declare @key1 tinyint            /* colids of the columns in the key */
  18335. declare @key2 tinyint
  18336. declare @key3 tinyint
  18337. declare @key4 tinyint
  18338. declare @key5 tinyint
  18339. declare @key6 tinyint
  18340. declare @key7 tinyint
  18341. declare @key8 tinyint
  18342. declare @dbname    varchar(30)
  18343.  
  18344. /*
  18345. **  Check to see that the tabname is local.
  18346. */
  18347. if @tabname like '%.%.%' and
  18348.     substring(@tabname, 1, charindex('.', @tabname) - 1) <> db_name()
  18349.     begin
  18350.         raiserror(15078,-1,-1)
  18351.         return (1)
  18352.     end
  18353.  
  18354. /*
  18355. **  See if we can find the object.  It must be a system table, user table,
  18356. **  or view.  The low 4 bits of sysobjects.sysstat indicate what the
  18357. **  object type is -- it's more reliable than using sysobjects.type which
  18358. **  could change.
  18359. */
  18360. select @objid = id, @uid = uid
  18361.     from sysobjects
  18362.         where id = object_id(@tabname)
  18363.             and (sysstat & 0xf = 1        /* system table */
  18364.                 or sysstat & 0xf = 2    /* view */
  18365.                 or sysstat & 0xf = 3)    /* user table */
  18366.  
  18367. if @objid is NULL
  18368.     begin
  18369.         select @dbname=db_name()
  18370.         raiserror(15009,-1,-1,@tabname,@dbname)
  18371.         return (1)
  18372.     end
  18373.  
  18374. /*
  18375. **  Check to see that object owner is adding the key.
  18376. */
  18377. if @uid <> user_id()
  18378.     begin
  18379.         raiserror(15172,-1,-1)
  18380.         return (1)
  18381.     end
  18382.  
  18383. /*
  18384. **  See if the primary key exists already.  Syskeys.type = 1 indicates
  18385. **  a primary key.
  18386. */
  18387. if exists (select * from syskeys where id = @objid and type = 1)
  18388.     begin
  18389.         raiserror(15173,-1,-1)
  18390.         return (1)
  18391.     end
  18392.  
  18393. /*
  18394. **  Now check out each column argument to verify its existence.
  18395. */
  18396. select @cnt = 1, @key1 = colid
  18397.     from syscolumns
  18398.         where name = @col1
  18399.             and id = @objid
  18400. if @key1 is NULL
  18401.     begin
  18402.         raiserror(15154,-1,-1)
  18403.         return (1)
  18404.     end
  18405.  
  18406. if @col2 IS NOT NULL
  18407.     begin
  18408.         select @cnt = @cnt + 1, @key2 = colid
  18409.             from syscolumns
  18410.             where name = @col2
  18411.             and id = @objid
  18412.  
  18413.         if @key2 is NULL
  18414.             begin
  18415.                 raiserror(15155,-1,-1)
  18416.                 return (1)
  18417.             end
  18418.     end
  18419. else goto doinsert
  18420.  
  18421. if @col3 IS NOT NULL
  18422.     begin
  18423.         select @cnt = @cnt + 1, @key3 = colid
  18424.             from syscolumns
  18425.             where name = @col3
  18426.             and id = @objid
  18427.  
  18428.         if @key3 is NULL
  18429.             begin
  18430.                 raiserror(15156,-1,-1)
  18431.                 return (1)
  18432.             end
  18433.     end
  18434. else goto doinsert
  18435.  
  18436. if @col4 IS NOT NULL
  18437.     begin
  18438.         select @cnt = @cnt + 1, @key4 = colid
  18439.             from syscolumns
  18440.             where name = @col4
  18441.             and id = @objid
  18442.  
  18443.         if @key4 is NULL
  18444.             begin
  18445.                 raiserror(15157,-1,-1)
  18446.                 return (1)
  18447.             end
  18448.     end
  18449. else goto doinsert
  18450.  
  18451. if @col5 IS NOT NULL
  18452.     begin
  18453.         select @cnt = @cnt + 1, @key5 = colid
  18454.             from syscolumns
  18455.             where name = @col5
  18456.             and id = @objid
  18457.  
  18458.         if @key5 is NULL
  18459.             begin
  18460.                 raiserror(15158,-1,-1)
  18461.                 return (1)
  18462.             end
  18463.     end
  18464. else goto doinsert
  18465.  
  18466. if @col6 IS NOT NULL
  18467.     begin
  18468.         select @cnt = @cnt + 1, @key6 = colid
  18469.             from syscolumns
  18470.             where name = @col6
  18471.             and id = @objid
  18472.  
  18473.         if @key6 is NULL
  18474.             begin
  18475.                 raiserror(15159,-1,-1)
  18476.                 return (1)
  18477.             end
  18478.     end
  18479. else goto doinsert
  18480.  
  18481. if @col7 IS NOT NULL
  18482.     begin
  18483.         select @cnt = @cnt + 1, @key7 = colid
  18484.             from syscolumns
  18485.             where name = @col7
  18486.             and id = @objid
  18487.  
  18488.         if @key7 is NULL
  18489.             begin
  18490.                 raiserror(15160,-1,-1)
  18491.                 return (1)
  18492.             end
  18493.     end
  18494. else goto doinsert
  18495.  
  18496. if @col8 IS NOT NULL
  18497.     begin
  18498.         select @cnt = @cnt + 1, @key8 = colid
  18499.             from syscolumns
  18500.             where name = @col8
  18501.             and id = @objid
  18502.  
  18503.         if @key8 is NULL
  18504.             begin
  18505.                 raiserror(15161,-1,-1)
  18506.                 return (1)
  18507.             end
  18508.     end
  18509.  
  18510. /*
  18511. **  Type 1 is a primary key, 2 is a foreignkey, and 3 is a commonjoin.
  18512. */
  18513. doinsert:
  18514.  
  18515. insert into syskeys
  18516.     (id, type, depid, keycnt, size, key1, key2, key3, key4, key5,
  18517.         key6, key7, key8)
  18518. values (@objid, 1, NULL, @cnt, 0, @key1, @key2, @key3, @key4, @key5,
  18519.         @key6, @key7, @key8)
  18520.  
  18521. print 'New primary key added.'
  18522. return (0)
  18523. go
  18524.  
  18525. print ''
  18526. print 'Creating procedure sp_processmail.'
  18527. go
  18528. create procedure sp_processmail @subject varchar(255)=NULL,
  18529.                 @filetype varchar(3)='txt',
  18530.                 @separator varchar(3)='tab',
  18531.                 @set_user varchar(30)='guest',
  18532.                 @dbuse varchar(30)='master'
  18533. as
  18534.  
  18535. declare @status int
  18536. declare @msg_id varchar(64)
  18537. declare @originator varchar(255)
  18538. declare @cc_list varchar(255)
  18539. declare @msgsubject varchar(255)
  18540. declare @query varchar(255)
  18541. declare @messages int
  18542. declare @mapifailure int
  18543. declare @resultmsg varchar(80)
  18544. declare @filename varchar(12)
  18545.  
  18546. select @messages=0
  18547. select @mapifailure=0
  18548.  
  18549. if @separator='tab' select @separator=CHAR(9)
  18550.  
  18551. while (1=1)
  18552.   begin
  18553.     exec @status = xp_findnextmsg
  18554.         @msg_id=@msg_id output,
  18555.         @unread_only='true'
  18556.  
  18557.     if @status <> 0
  18558.     begin
  18559.         select @mapifailure=1
  18560.         break
  18561.     end
  18562.  
  18563.     if @msg_id is null break
  18564.  
  18565.     exec @status = xp_readmail
  18566.         @msg_id=@msg_id,
  18567.         @originator=@originator output,
  18568.         @cc_list=@cc_list output,
  18569.         @subject=@msgsubject output,
  18570.         @message=@query output,
  18571.         @peek='true',
  18572.         @suppress_attach='true'
  18573.  
  18574.     if @status <> 0
  18575.     begin
  18576.         select @mapifailure=1
  18577.         break
  18578.     end
  18579.  
  18580.     if ((@subject IS NULL) OR (@subject=@msgsubject))
  18581.     begin
  18582.     /* generate random filename */
  18583.     select @filename='SQL' + convert(varchar,ROUND(RAND()*100000,0)) + '.' + @filetype
  18584.  
  18585.     exec @status = xp_sendmail
  18586.             @recipients=@originator,
  18587.             @copy_recipients=@cc_list,
  18588.             @message=@query,
  18589.             @query=@query,
  18590.             @subject='Query Results',
  18591.             @separator=@separator,
  18592.             @width=256,
  18593.             @attachments=@filename,
  18594.             @attach_results='true',
  18595.             @no_output='true',
  18596.             @echo_error='true',
  18597.             @set_user=@set_user,
  18598.             @dbuse=@dbuse
  18599.  
  18600.     if @status <> 0
  18601.         begin
  18602.             select @mapifailure=1
  18603.             break        
  18604.         end
  18605.     
  18606.     select @messages=@messages+1
  18607.  
  18608.     exec xp_deletemail @msg_id
  18609.  
  18610.     end /* end of xp_sendmail block */
  18611.   end  /* end of xp_findnextmsg loop */
  18612.  
  18613.   /* finished examining the contents of inbox;  now send results */
  18614.   if @mapifailure=0
  18615.           begin
  18616.         raiserror(15079,-1,-1,@messages)
  18617.         return(1)
  18618.     end
  18619.   else    
  18620.     return(0)
  18621. go
  18622.  
  18623. print ''
  18624. print 'Creating procedure sp_recompile.'
  18625. go
  18626. create procedure sp_recompile
  18627. @objname    varchar(92)
  18628. as
  18629. declare @id    int
  18630. declare @type    smallint
  18631. declare @uid    smallint
  18632. declare @errmsg    varchar(250)
  18633. declare @dbname varchar(30)
  18634.  
  18635. if @objname like '%.%.%'
  18636.     begin
  18637.         select @dbname=substring(@objname, 1, charindex('.', @objname) - 1)
  18638.  
  18639.         if @dbname <> db_name()
  18640.             begin
  18641.                 raiserror(15250,-1,-1)
  18642.                 return(1)
  18643.             end
  18644.     end
  18645. else
  18646.     select @dbname=db_name()
  18647.  
  18648. select @id = id, @type = sysstat & 0xf, @uid = uid
  18649. from sysobjects
  18650. where id = object_id(@objname)
  18651.  
  18652. if @id is null
  18653.     begin
  18654.         raiserror(15009,-1,-1,@objname,@dbname)
  18655.         return(1)
  18656.     end
  18657.  
  18658. if @type = 1
  18659.     begin
  18660.         raiserror(15217,-1,-1,@objname)
  18661.         return(1)
  18662.     end
  18663. if @type <> 3
  18664.     begin
  18665.         raiserror(15218,-1,-1,@objname)
  18666.         return(1)
  18667. end
  18668.  
  18669. if user_id() <> 1 and @uid <> user_id()
  18670.     begin
  18671.         raiserror(15219,-1,-1,@objname)
  18672.         return(1)
  18673.     end
  18674.  
  18675. set nocount on
  18676.  
  18677. update sysobjects set schema_ver = schema_ver + 1 where id = @id
  18678.  
  18679. select @errmsg = 'Each stored procedure and trigger that uses table ' + @objname
  18680. print @errmsg
  18681. print 'will be recompiled the next time it is executed.'
  18682. go
  18683.  
  18684. print ''
  18685. print 'Creating procedure sp_remoteoption.'
  18686. go
  18687. create procedure sp_remoteoption
  18688. @remoteserver varchar(30) = NULL,    /* server name to change */
  18689. @loginame varchar(30) = NULL,        /* user's remote name */
  18690. @remotename varchar(30) = NULL,        /* user's local user name */
  18691. @optname varchar(20) = NULL,        /* option name to turn on/off */
  18692. @optvalue varchar(10) = NULL        /* true or false */
  18693. as
  18694.  
  18695. declare @statvalue smallint        /* number of option */
  18696. declare @optcount int            /* number of options like @optname */
  18697. declare    @msg    varchar(100)
  18698. declare @suid    smallint
  18699.  
  18700. /*
  18701. **  If no @server given, just list the possible remote login options.
  18702. **  Only certain status bits may be set or cleared.
  18703. **       settable                        not settable
  18704. **     ------------------------------  --------------------------
  18705. **     trusted (1)
  18706. */
  18707. if @remoteserver is null
  18708. begin
  18709.     print 'Settable remote login options.'
  18710.     select remotelogin_option = name
  18711.         from master.dbo.spt_values
  18712.         where type = 'F'
  18713.             and number in (1, 1)
  18714.             and number > 0
  18715.         order by name
  18716.     return (0)
  18717. end
  18718.  
  18719. /*
  18720. **  If @loginame is NULL then we want to set @suid = -1. Otherwise get
  18721. **  it real value.
  18722. */
  18723. if @loginame is null
  18724.     select @suid = -1
  18725. else select @suid = suser_id(@loginame)
  18726.  
  18727. /*
  18728. **  Verify the server name, local, and remote names.
  18729. */
  18730. if not exists (select *
  18731.         from sysremotelogins r, sysservers s
  18732.             where r.remoteserverid = s.srvid
  18733.                 and s.srvname = @remoteserver
  18734.                 and r.remoteusername = @remotename
  18735.                 and r.suid = @suid)
  18736.     begin
  18737.  
  18738.         raiserror(15185,-1,-1,@remotename,@loginame,@remoteserver)
  18739.         return (1)
  18740.     end
  18741.  
  18742. /*
  18743. **  Check remaining parameters.
  18744. */
  18745. if @optname is NULL or lower(@optvalue) not in ('true', 'false') or @optvalue = null
  18746.     begin
  18747.         raiserror(15220,-1,-1)
  18748.         return (1)
  18749.     end
  18750.  
  18751. /*
  18752. **  Use @optname and try to find the right option.
  18753. **  If there isn't just one, print appropriate diagnostics and return.
  18754. */
  18755. select @optcount = count(*)
  18756.     from master.dbo.spt_values
  18757.     where name like '%' + @optname + '%'
  18758.         and type = 'F'
  18759.         and number in (1, 1)
  18760.         and number > 0
  18761.  
  18762. /*
  18763. **  If no option, show the user what the options are.
  18764. */
  18765. if @optcount = 0
  18766.     begin
  18767.         raiserror(15221,-1,-1)
  18768.         return (1)
  18769.     end
  18770.  
  18771. /*
  18772. **  If more than one option like @optname, show the duplicates and return.
  18773. */
  18774. if @optcount > 1
  18775.     begin
  18776.         raiserror(15222,-1,-1,@optname)
  18777.         print ''
  18778.  
  18779.         select duplicate_option = name
  18780.         from master.dbo.spt_values
  18781.         where name like '%' + @optname + '%'
  18782.             and type = 'F'
  18783.             and number in (1, 1)
  18784.             and number > 0
  18785.  
  18786.         return (1)
  18787.     end
  18788.  
  18789. /*
  18790. **  Only the SA or the dbo of @dbnbame can execute the update part
  18791. **  of this procedure so check.  Also the sproc must be executed in the master
  18792. **  database.
  18793. */
  18794. if suser_id() <> 1
  18795. begin
  18796.     print 'Only the System Administrator (SA) may set remote login options.'
  18797.     return (1)
  18798. end
  18799.  
  18800. /*
  18801. **  If we're in a transaction, disallow this since it might make recovery
  18802. **  impossible.
  18803. */
  18804. if @@trancount > 0
  18805.     begin
  18806.         raiserror(15002,-1,-1,'sp_remoteoption')
  18807.         return (1)
  18808.     end
  18809.  
  18810. /*
  18811. **  Get the number which is the bit value to set
  18812. */
  18813. select @statvalue = number
  18814.     from master.dbo.spt_values
  18815.     where name like '%' + @optname + '%'
  18816.         and type = 'F'
  18817.         and number in (1, 1)
  18818.         and number > 0
  18819.  
  18820.  
  18821. /*
  18822. **  Now update sysremotelogins.
  18823. */
  18824. if lower(@optvalue) = 'true'
  18825.     begin
  18826.         update sysremotelogins
  18827.         set status = status | @statvalue
  18828.             from sysremotelogins r, sysservers s
  18829.             where r.remoteserverid = s.srvid
  18830.                 and s.srvname = @remoteserver
  18831.                 and r.remoteusername = @remotename
  18832.                 and r.suid = @suid
  18833.         select @msg = 'Option ''' + @optname + ''' turned on.'
  18834.         print @msg
  18835.         return (0)
  18836.     end
  18837.  
  18838. /*
  18839. **  We want to turn it off.
  18840. */
  18841. else
  18842.     begin
  18843.         update sysremotelogins
  18844.         set status = status & ~@statvalue
  18845.             from sysremotelogins r, sysservers s
  18846.             where r.remoteserverid = s.srvid
  18847.                 and s.srvname = @remoteserver
  18848.                 and r.remoteusername = @remotename
  18849.                 and r.suid = @suid
  18850.         select @msg = 'Option ''' + @optname + ''' turned off.'
  18851.         print @msg
  18852.         return (0)
  18853.     end
  18854.  
  18855. return (0)
  18856. go
  18857.  
  18858. print ''
  18859. print 'Creating procedure sp_rename.'
  18860. go
  18861. create procedure sp_rename
  18862. @objname varchar(61),        -- old (current) object name
  18863. @newname sysname,        -- new name we want to call it
  18864. @objtype varchar(6) = null
  18865. as
  18866.  
  18867. declare @objid        int    -- object id of the thing to rename
  18868. declare @returncode    int
  18869. declare @objcount    int
  18870. declare @dbname        varchar(30)
  18871. declare @indid        smallint
  18872. declare @pktableid    int
  18873.  
  18874. if @objname like '%.%.%'
  18875.     and substring(@objname, 1, charindex('.', @objname) - 1) <> db_name()
  18876.     begin
  18877.         raiserror(15250,-1,-1)
  18878.         return (1)
  18879.     end
  18880. else
  18881.     select @dbname = db_name()
  18882.  
  18883. /*
  18884. **  Check to see that the @newname is valid.
  18885. */
  18886. exec @returncode = sp_validname @newname
  18887. if @returncode <> 0
  18888.     return(1)
  18889.  
  18890. select @objtype = lower(@objtype)
  18891. if @objtype not in ('column','index') and @objtype is not null
  18892.     begin
  18893.         raiserror(15249,-1,-1,@objtype)
  18894.         return(1)
  18895.     end
  18896.  
  18897. /*
  18898. ** If @objname is of the form x.y we can interpret it as either
  18899. ** table.column or table.index.
  18900. */
  18901. if @objname like '%.%'
  18902. begin
  18903.     declare @tabname varchar(30)        -- name of table
  18904.     declare @colname varchar(30)        -- name of column
  18905.     declare @colid tinyint            -- colid of the column
  18906.  
  18907.     /*
  18908.     **  Parse the names out.
  18909.     */
  18910.     select @tabname = substring(@objname, 1, charindex('.', @objname) - 1)
  18911.     select @colname = substring(@objname, charindex('.', @objname) + 1, 61)
  18912.  
  18913.     /*
  18914.     **  Now check to see if the table has both a column and an
  18915.     **  index with the specified name.  If so, verify that the
  18916.     **  user explicitly specified which one be renamed.
  18917.     */
  18918.     if exists (select * from sysobjects o, syscolumns c, sysindexes i
  18919.             where c.id = o.id
  18920.                 and i.id = o.id
  18921.                 and o.name = @tabname
  18922.                 and c.name = @colname
  18923.                 and i.name = @colname
  18924.                 and (o.sysstat & 0xf = 2    -- user table
  18925.                     or o.sysstat & 0xf = 3)    -- view
  18926.                 and o.uid = user_id())
  18927.             and @objtype is null
  18928.         begin
  18929.             raiserror(15247,-1,-1,@objname,@tabname,@colname)
  18930.             return(1)
  18931.         end
  18932.  
  18933.     if @objtype = 'column' or @objtype is null
  18934.         begin
  18935.             /*
  18936.             **  Check to see if the column exists in a table owned
  18937.             **  by the user.
  18938.             */
  18939.             select @objid = c.id, @colid = c.colid
  18940.             from sysobjects o, syscolumns c
  18941.             where c.id = o.id
  18942.                 and o.name = @tabname
  18943.                 and c.name = @colname
  18944.                 and (o.sysstat & 0xf = 2    -- user table
  18945.                     or o.sysstat & 0xf = 3)    -- view
  18946.                 and o.uid = user_id()
  18947.  
  18948.             /*
  18949.             **  Did we find it?  If so, try and rename it.  Else, check to
  18950.             **  see if it is an index on the table and rename that.
  18951.             */
  18952.             if @objid IS NOT NULL
  18953.                 begin
  18954.                     /*
  18955.                     **  Check to make sure that there is not already a column
  18956.                     **  that has the new name.
  18957.                     */
  18958.                     if exists
  18959.                         (select * from syscolumns
  18960.                             where id = @objid
  18961.                             and name = @newname)
  18962.                     begin
  18963.                         raiserror(15223,-1,-1,@newname,@tabname)
  18964.                         return (1)
  18965.                     end
  18966.  
  18967.                     /*
  18968.                     **  Go ahead and change the column name.
  18969.                     */
  18970.                     update syscolumns set name = @newname
  18971.                     where id = @objid
  18972.                         and colid = @colid
  18973.  
  18974.                     print 'Column name has been changed.'
  18975.                     return (0)
  18976.                 end
  18977.  
  18978.             if @objid is null and @objtype = 'column'
  18979.                 begin
  18980.                     raiserror(15253,-1,-1,@colname,@tabname)
  18981.                     return (1)
  18982.                 end
  18983.         end
  18984.  
  18985.     /*
  18986.     **  Might be an index name.
  18987.     */
  18988.     select @objid = i.id, @colid = i.indid
  18989.     from sysobjects o, sysindexes i
  18990.     where i.id = o.id
  18991.         and o.name = @tabname
  18992.         and i.name = @colname
  18993.         and i.indid <> 0
  18994.         and o.sysstat & 0xf = 3        -- user table
  18995.         and o.uid = user_id()
  18996.  
  18997.     /*
  18998.     **  If @objid is still NULL then that means it isn't an
  18999.     **  index name.  We checked above to see if it was a column
  19000.     **  name so now it's time to give up.
  19001.     */
  19002.     if @objid is null
  19003.         begin
  19004.             select @dbname=db_name()
  19005.             raiserror(15009,-1,-1,@objname,@dbname)
  19006.             return (1)
  19007.         end
  19008.  
  19009.     /*
  19010.     **  Check to make sure that there is not already an index
  19011.     **  that has the new name.
  19012.     */
  19013.     if exists (select * from sysindexes where id = @objid
  19014.             and name = @newname)
  19015.         begin
  19016.             raiserror(15224,-1,-1,@newname,@tabname)
  19017.             return (1)
  19018.         end
  19019.  
  19020.     /*
  19021.     **  Go ahead and change the index name.
  19022.     */
  19023.     update sysindexes set name = @newname
  19024.     where id = @objid
  19025.         and indid = @colid
  19026.  
  19027.     /*
  19028.     ** It may be a Primary Key or a Unique
  19029.     ** constraint which requires that
  19030.     ** the sysobjects row be updated.
  19031.     */
  19032.     select @pktableid = constid
  19033.     from sysconstraints c, sysobjects o
  19034.     where c.id = @objid
  19035.         and o.id = c.constid
  19036.         and o.name = @colname
  19037.  
  19038.     if @@rowcount = 1
  19039.         begin
  19040.             update sysobjects set name = @newname
  19041.                 where id = @pktableid
  19042.  
  19043.             update sysobjects set schema_ver = schema_ver + 1
  19044.                 where name = @tabname
  19045.         end
  19046.  
  19047.     print 'Index name has been changed.'
  19048.     return (0)
  19049. end
  19050.  
  19051. if @objtype is not null        -- Error if object type was specified
  19052.                 -- for something that is neither a
  19053.                 -- column nor an index.
  19054.     begin
  19055.         raiserror(15248,-1,-1,@objtype)
  19056.         return(1)
  19057.     end
  19058.  
  19059. /*
  19060. **  Check to see if the object exists and is owned by the user.
  19061. **  It will either be in the sysobjects table or the systypes table.
  19062. **  Check sysobjects first.
  19063. **  System objects have ids < 100 and we don't allow their names to change.
  19064. */
  19065. select @objid = (select id from sysobjects
  19066.             where id = object_id(@objname)
  19067.                 and uid = user_id()
  19068.                 and id > 99)
  19069.  
  19070. /*
  19071. **  Don't allow the newname to begin with #.
  19072. */
  19073. if substring(@newname, 1, 1) = '#'
  19074.     begin
  19075.         raiserror(15225,-1,-1)
  19076.         return (1)
  19077.     end
  19078.  
  19079. /*
  19080. **  It's not in sysobjects so check systypes.
  19081. */
  19082. if @objid is NULL
  19083. begin
  19084.     select @objid = (select usertype from systypes
  19085.                 where name = @objname
  19086.                     and uid = user_id()
  19087.                     and usertype > 99)
  19088.  
  19089.     /*
  19090.     **  It's nowhere to be found so quit.
  19091.     */
  19092.     if @objid is NULL
  19093.         begin
  19094.             raiserror(15009,-1,-1,@objname,@dbname)
  19095.             return (1)
  19096.         end
  19097.  
  19098.     /*
  19099.     ** Check that newname doesn't already exist.
  19100.     */
  19101.     if exists (select * from systypes where name = @newname)
  19102.         begin
  19103.             raiserror(15029,-1,-1,@newname)
  19104.             return (1)
  19105.         end
  19106.  
  19107.     /*
  19108.     ** Change the name of a datatype
  19109.     */
  19110.     update systypes set name = @newname
  19111.         where usertype = @objid
  19112.  
  19113.     print 'User datatype name has been changed.'
  19114.     return (0)
  19115. end
  19116.  
  19117. begin transaction
  19118.  
  19119.     /*
  19120.     ** Check that newname doesn't already exist.
  19121.     */
  19122.     if exists (select * from sysobjects where name = @newname
  19123.             and uid = user_id())
  19124.         begin
  19125.             raiserror(15031,-1,-1,@newname)
  19126.             rollback transaction
  19127.             return (1)
  19128.         end
  19129.  
  19130.     /*
  19131.     ** If it is not a Primary Key.
  19132.     */
  19133.     if (select sysstat & 0xf from sysobjects where id = @objid) <> 9
  19134.         begin
  19135.             update sysobjects
  19136.                 set name = @newname,schema_ver=schema_ver+1
  19137.                 where id = @objid
  19138.  
  19139.             if exists (select * from sysdepends
  19140.                 where depid = @objid)
  19141.                     print 'Warning - Procedures, views or triggers reference this object and will become invalid.'
  19142.  
  19143.             /*
  19144.             ** If it is a table, update its sysindexes
  19145.             ** entry if it has no clustered index.
  19146.             */
  19147.             if exists (select * from sysindexes
  19148.                 where id = @objid and indid = 0)
  19149.  
  19150.             update sysindexes set name = @newname
  19151.                 where id = @objid
  19152.                     and indid = 0
  19153.  
  19154.             /*
  19155.             ** Update the entries for text columns in
  19156.             ** sysindexes.
  19157.             */
  19158.             update sysindexes set name = 't' + @newname
  19159.                 where id = @objid
  19160.                     and indid = 255
  19161.         end
  19162.     else    -- It is a Primary Key
  19163.         begin
  19164.  
  19165.             select @indid = indid, @pktableid =id
  19166.                 from sysindexes
  19167.                 where id = (select id from sysconstraints
  19168.                         where constid = @objid)
  19169.                     and name = @objname
  19170.  
  19171.             update sysindexes set name = @newname
  19172.                 where id = @pktableid
  19173.                     and indid = @indid
  19174.  
  19175.             update sysobjects
  19176.                 set name = @newname where id = @objid
  19177.  
  19178.             update sysobjects set schema_ver = schema_ver + 1
  19179.                 where id = (select id from sysconstraints
  19180.                         where constid = @objid)
  19181.  
  19182.         end
  19183.  
  19184. commit transaction
  19185.  
  19186. print 'Object name has been changed.'
  19187.  
  19188. return (0)
  19189. go
  19190.  
  19191. print ''
  19192. print 'Creating procedure sp_renamedb.'
  19193. go
  19194. create procedure sp_renamedb
  19195. @dbname sysname,            /* old (current) db name */
  19196. @newname sysname            /* new name we want to call it */
  19197. as
  19198.  
  19199. declare @objid int            /* object id of the thing to rename */
  19200. declare @bitdesc varchar(30)        /* bit description for the db */
  19201. declare @curdbid int            /* id of database to be changed */
  19202.  
  19203. /*
  19204. **  If we're in a transaction, disallow this since it might make recovery
  19205. **  impossible.
  19206. */
  19207. if @@trancount > 0
  19208.     begin
  19209.         raiserror(15002,-1,-1,'sp_renamedb')
  19210.         return (1)
  19211.     end
  19212.  
  19213. /*
  19214. **  Only the SA can do this.
  19215. */
  19216. if suser_id() <> 1
  19217.     begin
  19218.         raiserror(15226,-1,-1)
  19219.         return (1)
  19220.     end
  19221.  
  19222. /*
  19223. **  Make sure the database exists.
  19224. */
  19225. if not exists (select * from sysdatabases where name = @dbname)
  19226.     begin
  19227.         raiserror(15010,-1,-1,@dbname)
  19228.         return (1)
  19229.     end
  19230.  
  19231. /*
  19232. **  Make sure that the @newname db doesn't already exist.
  19233. */
  19234. if exists (select * from sysdatabases where name = @newname)
  19235.     begin
  19236.         raiserror(15032,-1,-1,@newname)
  19237.         return (1)
  19238.     end
  19239.  
  19240. /*
  19241. **  Check to see that the @newname is valid.
  19242. */
  19243. declare @returncode int
  19244. exec @returncode = sp_validname @newname
  19245. if @returncode <> 0
  19246.     return(1)
  19247.  
  19248. /*
  19249. **  Don't allow the names of master, tempdb, and model to be changed.
  19250. */
  19251. if @dbname in ('master', 'model', 'tempdb')
  19252.     begin
  19253.         raiserror(15227,-1,-1,@dbname)
  19254.         return (1)
  19255.     end
  19256.  
  19257. /* Get current database id */
  19258. select @curdbid = db_id(@dbname)
  19259.  
  19260. /*
  19261. ** Check single user bit (4096)
  19262. ** Database must be in single user mode to necessitate the rid update in the
  19263. ** database's DBTABLE
  19264. */
  19265. select @bitdesc = null
  19266. select @bitdesc = v.name
  19267.     from master.dbo.spt_values v, sysdatabases d
  19268.     where d.dbid = @curdbid
  19269.         and v.type = 'D'
  19270.         and d.status & v.number = 4096
  19271.  
  19272. if @bitdesc is null
  19273.     begin
  19274.         raiserror(15228,-1,-1,@dbname)
  19275.         return(1)
  19276.     end
  19277.  
  19278. /*
  19279. **  Everything is ok so do it.
  19280. */
  19281. update sysdatabases set name = @newname
  19282.     where name = @dbname
  19283.  
  19284. /*
  19285. ** Mark dbtable status dirty to update to the new name in Resources.
  19286. **
  19287. */
  19288. dbcc dbrepair (@newname,markdirty)
  19289.  
  19290. print 'Database is renamed and in single-user mode.'
  19291. print 'System Administrator (SA) must reset it to multi-user mode with sp_dboption.'
  19292.  
  19293. return (0)
  19294. go
  19295.  
  19296. print ''
  19297. print 'Creating procedure sp_serveroption.'
  19298. go
  19299. create procedure sp_serveroption
  19300. @server varchar(30) = NULL,    /* server name to change */
  19301. @optname varchar(20) = NULL,    /* option name to turn on/off */
  19302. @optvalue varchar(10) = NULL    /* true or false */
  19303. as
  19304.  
  19305. declare @srvid int            /* id of the server */
  19306. declare @statvalue smallint        /* number of option */
  19307. declare @optcount int            /* number of options like @optname */
  19308.  
  19309. /*
  19310. **  If no @server given, just list the possible server options.
  19311. **  Only certain status bits may be set or cleared.
  19312. **    settable                        not settable
  19313. **    ------------------------------  --------------------------
  19314. **      rpc (1)
  19315. **      pub (2)
  19316. **      sub (4)
  19317. **      dist (8)
  19318. **      dpub (16)
  19319. **      dsn (32)
  19320. */
  19321. if @server is null
  19322.     begin
  19323.         print 'Settable server options.'
  19324.         select server_option = name
  19325.             from master.dbo.spt_values
  19326.             where type = 'A'
  19327.                 and number not in (-1)
  19328.             order by name
  19329.         return (0)
  19330.     end
  19331.  
  19332. /*
  19333. **  Verify the server name and get the @srvid
  19334. */
  19335. select @srvid = srvid
  19336.     from sysservers
  19337.         where srvname = @server
  19338.  
  19339. /*
  19340. **  If @server not found, say so.
  19341. */
  19342. if @srvid is NULL
  19343.     begin
  19344.         raiserror(15015,-1,-1,@server)
  19345.         return (1)
  19346.     end
  19347.  
  19348. /*
  19349. **  Check remaining parameters.
  19350. */
  19351. if @optname is NULL or lower(@optvalue) not in ('true', 'false')
  19352.     begin
  19353.         raiserror(15229,-1,-1)
  19354.         return (1)
  19355.     end
  19356.  
  19357. /*
  19358. **  Use @optname and try to find the right option.
  19359. **  If there isn't just one, print appropriate diagnostics and return.
  19360. */
  19361. select @optcount = count(*) from master.dbo.spt_values
  19362.     where name like @optname
  19363.         and type = 'A'
  19364.         and number not in (-1)
  19365.  
  19366. /*
  19367. **  If no option, show the user what the options are.
  19368. */
  19369. if @optcount = 0
  19370.     begin
  19371.         raiserror(15230,-1,-1)
  19372.         return (1)
  19373.     end
  19374.  
  19375. /*
  19376. **  If more than one option like @optname, show the duplicates and return.
  19377. */
  19378. if @optcount > 1
  19379.     begin
  19380.         raiserror(15231,-1,-1,@optname)
  19381.         print ''
  19382.  
  19383.         select duplicate_option = name
  19384.             from master.dbo.spt_values
  19385.             where name like @optname
  19386.                 and type = 'A'
  19387.                 and number not in (-1)
  19388.         return (1)
  19389.     end
  19390.  
  19391. /*
  19392. **  Only the SA or the dbo of @dbnbame can execute the update part
  19393. **  of this procedure so check.  Also the sproc must be executed in the master
  19394. **  database.
  19395. */
  19396. if suser_id() <> 1
  19397.     begin
  19398.         raiserror(15232,-1,-1)
  19399.         return (1)
  19400.     end
  19401.  
  19402. /*
  19403. **  Get the number which is the bit value to set
  19404. */
  19405. select @statvalue = number
  19406.     from master.dbo.spt_values
  19407.     where name like @optname
  19408.         and type = 'A'
  19409.         and number > 0
  19410.  
  19411. /*
  19412. ** Only one server may be a distribution server.
  19413. */
  19414. if @optname like 'dist'
  19415.   begin
  19416.      if lower(@optvalue) = 'true'
  19417.         begin
  19418.     if exists (select * from sysservers where (srvstatus & @statvalue) <>
  19419.        0)
  19420.        begin
  19421.           raiserror(14090,-1,-1)
  19422.           return (1)
  19423.        end
  19424.     /* Add remote mapping of sa, if the distributor is remote. */
  19425.     if @srvid <> 0
  19426.        begin
  19427.               execute sp_addremotelogin @server, sa, sa
  19428.               execute sp_remoteoption @server, sa, sa, trusted, true
  19429.        end
  19430.     end
  19431.      else /* @optvalue = 'false' */
  19432.     /* Drop remote mapping of sa, if the distributor is remote. */
  19433.         if @srvid <> 0
  19434.            execute sp_dropremotelogin @server, sa, sa
  19435.   end
  19436.  
  19437. /*
  19438. **  If we're in a transaction, disallow this since it might make recovery
  19439. **  impossible.
  19440. */
  19441. if @@trancount > 0
  19442.     begin
  19443.         raiserror(15002,-1,-1,'sp_serveroption')
  19444.         return (1)
  19445.     end
  19446.  
  19447. /*
  19448. **  Now update sysservers.
  19449. */
  19450. if lower(@optvalue) = 'true'
  19451.     begin
  19452.         update sysservers
  19453.             set srvstatus = srvstatus | @statvalue
  19454.             where srvid = @srvid
  19455.     end
  19456.  
  19457. /*
  19458. **  We want to turn it off.
  19459. */
  19460. else
  19461.     update sysservers set srvstatus = srvstatus & ~@statvalue
  19462.         where srvid = @srvid
  19463.  
  19464. return (0)
  19465. go
  19466.  
  19467. print ''
  19468. print 'Creating procedure sp_setnetname.'
  19469. go
  19470. create procedure sp_setnetname
  19471. @server    varchar(30),        /* server name */
  19472. @netname varchar(30)        /* new net name */
  19473. as
  19474.  
  19475. /*
  19476. **  The server must exist, so check.
  19477. */
  19478. if not exists (select * from sysservers where srvname = @server)
  19479.     begin
  19480.         raiserror(15015,-1,-1,@server)
  19481.         return (1)
  19482.     end
  19483.  
  19484. /*
  19485. **  Server network names must be unique so check.
  19486. */
  19487. if exists (select *
  19488.         from sysservers
  19489.             where srvnetname = @netname)
  19490.     begin
  19491.         raiserror(15233,-1,-1,@netname)
  19492.         return (1)
  19493.     end
  19494.  
  19495.  
  19496. -- We will NOT validate this name here (1995/11/28).     execute @returncode = sp_validname @server
  19497.  
  19498. /*
  19499. **  Network name checks out, so update sysservers.
  19500. */
  19501.  
  19502. update sysservers set srvnetname = @netname where srvname = @server
  19503.  
  19504. print 'Server network name set.'
  19505. return (0)
  19506. go
  19507.  
  19508. dump tran master with no_log
  19509. go
  19510.  
  19511. print ''
  19512. print 'Creating procedure sp_spaceused.'
  19513. go
  19514. create procedure sp_spaceused
  19515. @objname varchar(92) = null,        -- The object we want size on.
  19516. @updateusage varchar(5) = false        -- Param. for specifying that
  19517.                     -- usage info. should be updated.
  19518. as
  19519.  
  19520. declare @id    int            -- The object id of @objname.
  19521. declare @type    smallint        -- The object type.
  19522. declare    @pages    int            -- Working variable for size calc.
  19523. declare @dbname varchar(30)
  19524. declare @dbsize dec(15,0)
  19525.  
  19526. /*
  19527. **  Check to see if user wants usages updated.
  19528. */
  19529.  
  19530. if @updateusage is not null
  19531.     begin
  19532.         select @updateusage=lower(@updateusage)
  19533.  
  19534.         if @updateusage not in ('true','false')
  19535.             begin
  19536.                 raiserror(15143,-1,-1,@updateusage)
  19537.                 return(1)
  19538.             end
  19539.     end
  19540. /*
  19541. **  Check to see that the objname is local.
  19542. */
  19543. if @objname IS NOT NULL
  19544. begin
  19545.     if @objname like '%.%.%'
  19546.         begin
  19547.             select @dbname =
  19548.                 substring(@objname, 1, charindex('.', @objname) - 1)
  19549.  
  19550.             if @dbname <> db_name()
  19551.                 begin
  19552.                     raiserror(15250,-1,-1)
  19553.                     return (1)
  19554.                 end
  19555.         end
  19556.     else
  19557.         select @dbname = db_name()
  19558.  
  19559.     /*
  19560.     **  Try to find the object.
  19561.     */
  19562.     select @id = null
  19563.     select @id = id, @type = sysstat & 0xf
  19564.         from sysobjects
  19565.             where id = object_id(@objname)
  19566.  
  19567.     /*
  19568.     **  Does the object exist?
  19569.     */
  19570.     if @id is null
  19571.         begin
  19572.             raiserror(15009,-1,-1,@objname,@dbname)
  19573.             return (1)
  19574.         end
  19575.  
  19576.     /*
  19577.     **  See if it's a space object.
  19578.     **  types are:
  19579.     **    1 - system table
  19580.     **    2 - view
  19581.     **    3 - user table
  19582.     **    4 - sproc
  19583.     **    6 - default
  19584.     **    7 - rule
  19585.     **    8 - trigger
  19586.     **    9 - primary key
  19587.     **    10 - check constraint
  19588.     **    11 - foreign key
  19589.     **    12 - replication filter stored proc
  19590.     */
  19591.  
  19592.     if not exists (select * from sysindexes
  19593.                 where @id = id and indid < 2)
  19594.  
  19595.         if @type in (4, 6, 7, 8, 10, 12)    -- data stored
  19596.                 begin            -- in sysprocedures
  19597.                     raiserror(15234,-1,-1)
  19598.                     return (1)
  19599.                 end
  19600.         else if @type = 2    -- View => no physical data storage.
  19601.                 begin
  19602.                     raiserror(15235,-1,-1)
  19603.                     return (1)
  19604.                 end
  19605.         else if @type = 9    -- PK => no physical data storage.
  19606.                 begin
  19607.                     raiserror(15064,-1,-1)
  19608.                     return (1)
  19609.                 end
  19610.         else if @type = 11    -- FK => no physical data storage.
  19611.                 begin
  19612.                     raiserror(15275,-1,-1)
  19613.                     return (1)
  19614.                 end
  19615. end
  19616.  
  19617. /*
  19618. **  Update usages if user specified to do so.
  19619. */
  19620.  
  19621. if @updateusage = 'true'
  19622.     begin
  19623.         if @objname is null
  19624.             dbcc updateusage(0) with no_infomsgs
  19625.         else
  19626.             dbcc updateusage(0,@objname) with no_infomsgs
  19627.         print ''
  19628.     end
  19629.  
  19630. /*
  19631. **  We need to create a temp table to do the calculation.
  19632. **  reserved: sum(reserved) where indid in (0, 1, 255)
  19633. **  data: sum(dpages) where indid < 2 + sum(used) where indid = 255 (text)
  19634. **  indexp: sum(used) where indid in (0, 1, 255) - data
  19635. **  unused: sum(reserved) - sum(used) where indid in (0, 1, 255)
  19636. */
  19637. create table #spt_space
  19638. (
  19639.     rows        int null,
  19640.     reserved    dec(15) null,
  19641.     data        dec(15) null,
  19642.     indexp        dec(15) null,
  19643.     unused        dec(15) null
  19644. )
  19645. set nocount on
  19646.  
  19647. /*
  19648. **  If @id is null, then we want summary data.
  19649. */
  19650. if @id is null
  19651. begin
  19652.     select @dbsize = sum(convert(dec(15),size))
  19653.         from sysusages
  19654.         where dbid = db_id()
  19655.  
  19656.     select  database_name = db_name(),
  19657.         database_size =
  19658.             ltrim(str(@dbsize / 512,15,2) + ' MB'),
  19659.         'unallocated space' =
  19660.             ltrim(str((@dbsize -
  19661.                 (select sum(convert(dec(15),reserved))
  19662.                     from sysindexes
  19663.                         where indid in (0, 1, 255)
  19664.                 ))/512,15,2)+ ' MB')
  19665.  
  19666.     print ''
  19667.     /*
  19668.     **  Now calculate the summary data.
  19669.     **  reserved: sum(reserved) where indid in (0, 1, 255)
  19670.     */
  19671.     insert into #spt_space (reserved)
  19672.         select sum(convert(dec(15),reserved))
  19673.             from sysindexes
  19674.                 where indid in (0, 1, 255)
  19675.  
  19676.     /*
  19677.     ** data: sum(dpages) where indid < 2
  19678.     **    + sum(used) where indid = 255 (text)
  19679.     */
  19680.     select @pages = sum(convert(dec(15),dpages))
  19681.             from sysindexes
  19682.                 where indid < 2
  19683.     select @pages = @pages + isnull(sum(convert(dec(15),used)), 0)
  19684.         from sysindexes
  19685.             where indid = 255
  19686.     update #spt_space
  19687.         set data = @pages
  19688.  
  19689.  
  19690.     /* index: sum(used) where indid in (0, 1, 255) - data */
  19691.     update #spt_space
  19692.         set indexp = (select sum(convert(dec(15),used))
  19693.                 from sysindexes
  19694.                     where indid in (0, 1, 255))
  19695.                 - data
  19696.  
  19697.     /* unused: sum(reserved) - sum(used) where indid in (0, 1, 255) */
  19698.     update #spt_space
  19699.         set unused = reserved
  19700.                 - (select sum(convert(dec(15),used))
  19701.                     from sysindexes
  19702.                         where indid in (0, 1, 255))
  19703.  
  19704.     select reserved = ltrim(str(reserved * d.low / 1024.,15,0) +
  19705.                 ' ' + 'KB'),
  19706.         data = ltrim(str(data * d.low / 1024.,15,0) +
  19707.                 ' ' + 'KB'),
  19708.         index_size = ltrim(str(indexp * d.low / 1024.,15,0) +
  19709.                 ' ' + 'KB'),
  19710.         unused = ltrim(str(unused * d.low / 1024.,15,0) +
  19711.                 ' ' + 'KB')
  19712.         from #spt_space, master.dbo.spt_values d
  19713.         where d.number = 1
  19714.             and d.type = 'E'
  19715. end
  19716.  
  19717. /*
  19718. **  We want a particular object.
  19719. */
  19720. else
  19721. begin
  19722.     /*
  19723.     **  Now calculate the summary data.
  19724.     **  reserved: sum(reserved) where indid in (0, 1, 255)
  19725.     */
  19726.     insert into #spt_space (reserved)
  19727.         select sum(reserved)
  19728.             from sysindexes
  19729.                 where indid in (0, 1, 255)
  19730.                     and id = @id
  19731.  
  19732.     /*
  19733.     ** data: sum(dpages) where indid < 2
  19734.     **    + sum(used) where indid = 255 (text)
  19735.     */
  19736.     select @pages = sum(dpages)
  19737.             from sysindexes
  19738.                 where indid < 2
  19739.                     and id = @id
  19740.     select @pages = @pages + isnull(sum(used), 0)
  19741.         from sysindexes
  19742.             where indid = 255
  19743.                 and id = @id
  19744.     update #spt_space
  19745.         set data = @pages
  19746.  
  19747.  
  19748.     /* index: sum(used) where indid in (0, 1, 255) - data */
  19749.     update #spt_space
  19750.         set indexp = (select sum(used)
  19751.                 from sysindexes
  19752.                     where indid in (0, 1, 255)
  19753.                         and id = @id)
  19754.                 - data
  19755.  
  19756.     /* unused: sum(reserved) - sum(used) where indid in (0, 1, 255) */
  19757.     update #spt_space
  19758.         set unused = reserved
  19759.                 - (select sum(used)
  19760.                     from sysindexes
  19761.                         where indid in (0, 1, 255)
  19762.                             and id = @id)
  19763.     update #spt_space
  19764.         set rows = i.rows
  19765.             from sysindexes i
  19766.                 where i.indid < 2
  19767.                     and i.id = @id
  19768.  
  19769.     select name = substring(object_name(@id), 1, 20),
  19770.         rows = convert(char(11), rows),
  19771.         reserved = ltrim(str(reserved * d.low / 1024.,15,0) +
  19772.                 ' ' + 'KB'),
  19773.         data = ltrim(str(data * d.low / 1024.,15,0) +
  19774.                 ' ' + 'KB'),
  19775.         index_size = ltrim(str(indexp * d.low / 1024.,15,0) +
  19776.                 ' ' + 'KB'),
  19777.         unused = ltrim(str(unused * d.low / 1024.,15,0) +
  19778.                 ' ' + 'KB')
  19779.     from #spt_space, master.dbo.spt_values d
  19780.         where d.number = 1
  19781.             and d.type = 'E'
  19782. end
  19783.  
  19784. return (0)
  19785. go
  19786.  
  19787. print ''
  19788. print 'Creating procedure sp_sqlexec.'
  19789. go
  19790. create procedure sp_sqlexec @p1 text as exec(@p1)
  19791. go
  19792.  
  19793.  
  19794. print ''
  19795. print 'Creating procedure sp_unbindefault.'
  19796. go
  19797. create procedure sp_unbindefault
  19798. --1995/09/14 15:06
  19799. @objname varchar(61),         /* table/column or datatype name */
  19800. @futureonly varchar(15) = NULL   /* flag to indicate extent of binding */
  19801. as
  19802.  
  19803. declare @olddefault int  --current default for type
  19804. declare @tabname varchar(92)  --possible name of table
  19805.        ,@colname varchar(92)  --possible name of column
  19806.  
  19807. declare @futurevalue varchar(15) /* the value of @futureonly that causes
  19808.                ** the binding to be limited */
  19809.  
  19810. select @futurevalue = 'futureonly'  /* initialize @futurevalue */
  19811.  
  19812. /*
  19813. **  When a default or rule is bound to a user-defined datatype, it is also
  19814. **  bound, by default, to any columns of the user datatype that are currently
  19815. **  using the existing default or rule as their default or rule.  This default
  19816. **  action may be overridden by setting @futureonly = @futurevalue when the
  19817. **  procedure is invoked.  In this case existing columns with the user
  19818. **  datatype won't have their existing default or rule changed.
  19819. */
  19820.  
  19821. /*
  19822. **  Check to see that the object names are local to the current database.
  19823. */
  19824. if @objname like '%.%.%'  --61?
  19825.    and substring(@objname, 1, charindex('.', @objname) - 1) <> db_name()
  19826.    begin
  19827.       raiserror(15084,-1,-1)
  19828.       return (1)
  19829.    end
  19830.  
  19831. /*
  19832. **  If @objname is of the form tab.col then we are unbinding a column.
  19833. **  Otherwise its a datatype.  In the column case, we need to extract
  19834. **  and verify the table and column names and make sure the user owns
  19835. **  the table that is getting the default unbound.
  19836. */
  19837. if @objname like '%.%'
  19838. begin
  19839.    /*
  19840.    **  Get the table name out.
  19841.    */
  19842.    select @tabname = substring(@objname, 1, charindex('.', @objname) - 1)
  19843.    select @colname = substring(@objname, charindex('.', @objname) + 1, 61)
  19844.  
  19845.    if (     datalength(@tabname) > 30
  19846.       or    datalength(@colname) > 30
  19847.       )
  19848.       begin
  19849.       raiserror(15299,-1,-1,@objname)
  19850.       return (1)
  19851.       end
  19852.  
  19853.    /*
  19854.    **  Find it and unbind it.
  19855.    */
  19856.    if exists (select *
  19857.          from syscolumns, sysobjects
  19858.       where syscolumns.id = object_id(@tabname)
  19859.          and syscolumns.name = @colname
  19860.          and sysobjects.id = object_id(@tabname)
  19861.          and uid = user_id()
  19862.          and sysobjects.sysstat & 0xf = 3)      /* user table */
  19863.    begin
  19864.       /*
  19865.       **  Is there something bound to it?
  19866.       */
  19867.       if exists (select *
  19868.          from syscolumns, sysobjects
  19869.       where syscolumns.id = object_id(@tabname)
  19870.          and syscolumns.name = @colname
  19871.          and sysobjects.id = object_id(@tabname)
  19872.          and uid = user_id()
  19873.          and sysobjects.sysstat & 0xf = 3      /* user table */
  19874.          and cdefault <> 0)
  19875.       begin
  19876.          update syscolumns
  19877.             set cdefault = 0
  19878.                from syscolumns, sysobjects
  19879.             where syscolumns.id = object_id(@tabname)
  19880.                and syscolumns.name = @colname
  19881.                and sysobjects.id = object_id(@tabname)
  19882.                and uid = user_id()
  19883.                and sysobjects.sysstat & 0xf = 3
  19884.  
  19885.          /*
  19886.          **  Since binding a default is a schema change,
  19887.          **  update schema count
  19888.          **  for the object in the sysobjects table.
  19889.          */
  19890.          update sysobjects set schema_ver = schema_ver + 1
  19891.             from sysobjects
  19892.             where id = object_id(@tabname)
  19893.                and uid = user_id()
  19894.  
  19895.          print 'Default unbound from table column.'
  19896.          return (0)
  19897.       end
  19898.  
  19899.       else
  19900.          begin
  19901.             raiserror(15236,-1,-1,@objname)
  19902.             return (1)
  19903.          end
  19904.    end
  19905.  
  19906.    /*
  19907.    **  If we got here, there was no such object.
  19908.    */
  19909.    raiserror(15104,-1,-1,@tabname,@colname)
  19910.    return (1)
  19911.  
  19912. end
  19913.  
  19914. else
  19915.  
  19916. begin
  19917.    /*
  19918.    **  We're unbinding to a user type.  In this case, the @objname
  19919.    **  is really the name of the user datatype.
  19920.    **  When we unbind to a user type, any existing columns get changed
  19921.    **  to the new binding unless their current binding is not equal
  19922.    **  to the current binding for the usertype or if they set the
  19923.    **  @futureonly parameter to @futurevalue.
  19924.    */
  19925.  
  19926.    if (     datalength(@objname) > 30)
  19927.       begin
  19928.       raiserror(15299,-1,-1,@objname)
  19929.       return (1)
  19930.       end
  19931.  
  19932.    /*
  19933.    **  Get the current default for the datatype.
  19934.    */
  19935.    select @olddefault = tdefault
  19936.       from systypes
  19937.          where name = @objname
  19938.             and uid = user_id()
  19939.             and usertype > 100
  19940.  
  19941.    if @olddefault is null
  19942.       begin
  19943.          raiserror(15036,-1,-1,@objname)
  19944.          return (1)
  19945.       end
  19946.  
  19947.    if @olddefault = 0
  19948.       begin
  19949.          raiserror(15237,-1,-1,@objname)
  19950.          return (1)
  19951.       end
  19952.  
  19953.    update systypes set tdefault = 0
  19954.       from systypes
  19955.       where name = @objname
  19956.          and uid = user_id()
  19957.          and usertype > 100
  19958.  
  19959.    print 'Default unbound from datatype.'
  19960.  
  19961.    /*
  19962.    **  Now see if there are any columns with the usertype that
  19963.    **  need the new binding.
  19964.    */
  19965.    if isnull(@futureonly, '') <> @futurevalue
  19966.       and exists (select *
  19967.          from syscolumns, systypes
  19968.             where syscolumns.usertype = systypes.usertype
  19969.                and systypes.name = @objname
  19970.                and systypes.usertype > 100
  19971.                and systypes.uid = user_id()
  19972.                and syscolumns.cdefault = @olddefault)
  19973.    begin
  19974.       /*
  19975.       **  Update syscolumns with new binding.
  19976.       */
  19977.       update syscolumns set cdefault = systypes.tdefault
  19978.          from syscolumns, systypes
  19979.          where syscolumns.usertype = systypes.usertype
  19980.             and systypes.name = @objname
  19981.             and systypes.usertype > 100
  19982.             and systypes.uid = user_id()
  19983.             and syscolumns.cdefault = @olddefault
  19984.  
  19985.       /*
  19986.       **  Update the table schema to indicate that something
  19987.       **  has changed in the table's schema.
  19988.       */
  19989.       update sysobjects set schema_ver = schema_ver + 1
  19990.          from sysobjects, syscolumns, systypes
  19991.          where sysobjects.id = syscolumns.id
  19992.             and syscolumns.usertype = systypes.usertype
  19993.             and systypes.name = @objname
  19994.             and systypes.usertype > 100
  19995.             and systypes.uid = user_id()
  19996.             and syscolumns.cdefault = systypes.tdefault
  19997.  
  19998.       print 'Columns of the user datatype specified had their defaults unbound.'
  19999.    end
  20000. end
  20001.  
  20002. return (0)
  20003. go
  20004.  
  20005.  
  20006. print ''
  20007. print 'Creating procedure sp_unbindrule.'
  20008. go
  20009. create procedure sp_unbindrule
  20010. --1995/09/14 15:24
  20011. @objname varchar(61),         /* table/column or datatype name */
  20012. @futureonly varchar(15) = NULL      /* flag to indicate extent of binding */
  20013. as
  20014.  
  20015. declare @oldrule int /* current rule for type */
  20016. declare @tabname varchar(30)     /* name of table */
  20017. declare @colname varchar(30)     /* name of column */
  20018. declare @futurevalue varchar(15) /* the value of @futureonly that causes
  20019.                            ** the binding to be limited */
  20020.  
  20021. select @futurevalue = 'futureonly'  /* initialize @futurevalue */
  20022.  
  20023. /*
  20024. **  When a default or rule is bound to a user-defined datatype, it is also
  20025. **  bound, by default, to any columns of the user datatype that are currently
  20026. **  using the existing default or rule as their default or rule.  This default
  20027. **  action may be overridden by setting @futureonly = @futurevalue when the
  20028. **  procedure is invoked.  In this case existing columns with the user
  20029. **  datatype won't have their existing default or rule changed.
  20030. */
  20031.  
  20032. /*
  20033. **  Check to see that the object names are local to the current database.
  20034. */
  20035. if @objname like '%.%.%'
  20036.    begin
  20037.       raiserror(15084,-1,-1)
  20038.       return (1)
  20039.    end
  20040.  
  20041. /*
  20042. **  If @objname is of the form tab.col then we are unbinding a column.
  20043. **  Otherwise its a datatype.  In the column case, we need to extract
  20044. **  and verify the table and column names and make sure the user owns
  20045. **  the table that is getting the default unbound.
  20046. */
  20047. if @objname like '%.%'
  20048. begin
  20049.    /*
  20050.    **  Get the table name out.
  20051.    */
  20052.    select @tabname = substring(@objname, 1, charindex('.', @objname) - 1)
  20053.    select @colname = substring(@objname, charindex('.', @objname) + 1, 61)
  20054.  
  20055.    if (     datalength(@tabname) > 30
  20056.       or    datalength(@colname) > 30
  20057.       )
  20058.       begin
  20059.       raiserror(15299,-1,-1,@objname)
  20060.       return (1)
  20061.       end
  20062.  
  20063.    /*
  20064.    **  Find it and unbind it.
  20065.    */
  20066.    if exists (select * from syscolumns, sysobjects
  20067.       where syscolumns.id = object_id(@tabname)
  20068.          and syscolumns.name = @colname
  20069.          and sysobjects.id = object_id(@tabname)
  20070.          and uid = user_id()
  20071.          and sysobjects.sysstat & 0xf = 3)      /* user table */
  20072.    begin
  20073.       /*
  20074.       **  Is there something bound to it?
  20075.       */
  20076.       if exists (select * from syscolumns, sysobjects
  20077.       where syscolumns.id = object_id(@tabname)
  20078.          and syscolumns.name = @colname
  20079.          and sysobjects.id = object_id(@tabname)
  20080.          and uid = user_id()
  20081.          and sysobjects.sysstat & 0xf = 3      /* user table */
  20082.          and domain <> 0)
  20083.       begin
  20084.          update syscolumns set domain = 0
  20085.             from syscolumns, sysobjects
  20086.             where syscolumns.id = object_id(@tabname)
  20087.                and syscolumns.name = @colname
  20088.                and sysobjects.id = object_id(@tabname)
  20089.                and uid = user_id()
  20090.                and sysobjects.sysstat & 0xf = 3
  20091.  
  20092.          /*
  20093.          **  Since binding a rule is a schema change,
  20094.          **  update schema count
  20095.          **  for the object in the sysobjects table.
  20096.          */
  20097.          update sysobjects set schema_ver = schema_ver + 1
  20098.             from sysobjects
  20099.             where id = object_id(@tabname)
  20100.                and uid = user_id()
  20101.  
  20102.          print 'Rule unbound from table column.'
  20103.          return (0)
  20104.       end
  20105.  
  20106.       else
  20107.          begin
  20108.             raiserror(15238,-1,-1,@colname)
  20109.             return (1)
  20110.          end
  20111.    end
  20112.  
  20113.    /*
  20114.    **  If we got here, there was no such object.
  20115.    */
  20116.    raiserror(15104,-1,-1,@tabname,@colname)
  20117.    return (1)
  20118.  
  20119. end
  20120.  
  20121. else
  20122.  
  20123. begin
  20124.    /*
  20125.    **  We're unbinding to a user type.  In this case, the @objname
  20126.    **  is really the name of the user datatype.
  20127.    **  When we unbind to a user type, any existing columns get changed
  20128.    **  to the new binding unless their current binding is not equal
  20129.    **  to the current binding for the usertype or if they set the
  20130.    **  @futureonly parameter to @futurevalue.
  20131.    */
  20132.  
  20133.    if (     datalength(@objname) > 30)
  20134.       begin
  20135.       raiserror(15299,-1,-1,@objname)
  20136.       return (1)
  20137.       end
  20138.  
  20139.    /*
  20140.    **  Get the current rule for the datatype.
  20141.    */
  20142.    select @oldrule = domain
  20143.    from systypes
  20144.    where name = @objname
  20145.       and uid = user_id()
  20146.       and usertype > 100
  20147.  
  20148.    if @oldrule is null
  20149.       begin
  20150.          raiserror(15036,-1,-1,@objname)
  20151.          return (1)
  20152.       end
  20153.  
  20154.    if @oldrule = 0
  20155.       begin
  20156.          raiserror(15239,-1,-1,@objname)
  20157.          return (1)
  20158.       end
  20159.  
  20160.    update systypes set domain = 0
  20161.       from systypes
  20162.       where name = @objname
  20163.          and uid = user_id()
  20164.          and usertype > 100
  20165.  
  20166.    print 'Rule unbound from datatype.'
  20167.  
  20168.    /*
  20169.    **  Now see if there are any columns with the usertype that
  20170.    **  need the new binding.
  20171.    */
  20172.    if isnull(@futureonly, '') <> @futurevalue
  20173.       and exists (select * from syscolumns, systypes
  20174.             where syscolumns.usertype = systypes.usertype
  20175.                and systypes.name = @objname
  20176.                and systypes.usertype > 100
  20177.                and systypes.uid = user_id()
  20178.                and syscolumns.domain = @oldrule)
  20179.    begin
  20180.       /*
  20181.       **  Update syscolumns with new binding.
  20182.       */
  20183.       update syscolumns set domain = systypes.domain
  20184.          from syscolumns, systypes
  20185.          where syscolumns.usertype = systypes.usertype
  20186.             and systypes.name = @objname
  20187.             and systypes.usertype > 100
  20188.             and systypes.uid = user_id()
  20189.             and syscolumns.domain = @oldrule
  20190.  
  20191.       /*
  20192.       **  Update the table schema to indicate that something
  20193.       **  has changed in the table's schema.
  20194.       */
  20195.       update sysobjects set schema_ver = schema_ver + 1
  20196.          from sysobjects, syscolumns, systypes
  20197.          where sysobjects.id = syscolumns.id
  20198.             and syscolumns.usertype = systypes.usertype
  20199.             and systypes.name = @objname
  20200.             and systypes.usertype > 100
  20201.             and systypes.uid = user_id()
  20202.             and syscolumns.domain = systypes.domain
  20203.  
  20204.       print 'Columns of the user datatype specified had their rules unbound.'
  20205.    end
  20206. end
  20207.  
  20208. return (0)
  20209. go
  20210.  
  20211.  
  20212. print ''
  20213. print 'Creating procedure sp_unmakestartup.'
  20214. go
  20215. create procedure sp_unmakestartup
  20216. @procname varchar(30) = null
  20217. as
  20218. declare @objid    int
  20219. declare @dbname varchar(30)
  20220.  
  20221. /*
  20222. **    Check to see if a proc. name was specified.
  20223. */
  20224. if @procname is null
  20225.     begin
  20226.         raiserror(15240,-1,-1)
  20227.         return (1)
  20228.     end
  20229.  
  20230. /*
  20231. **  Only the SA can do this.
  20232. */
  20233. if suser_id() <> 1
  20234.     begin
  20235.         raiserror(15003,-1,-1)
  20236.         return (1)
  20237.     end
  20238.  
  20239. /*
  20240. **  Make sure the @procname is in the master database.
  20241. */
  20242. if @procname like '%.%.%' and    -- Explicit db name supplied
  20243.     substring(@procname, 1, charindex('.', @procname) - 1) <> 'master'
  20244.     begin
  20245.         raiserror(15272,-1,-1,@procname)
  20246.         return (1)
  20247.     end
  20248. else    -- No explicit name supplied so we need to be in the 'master' db
  20249.     if db_name() <> 'master'
  20250.         begin
  20251.             select @dbname = db_name()
  20252.             raiserror(15274,-1,-1,@procname,@dbname)
  20253.             return(1)
  20254.         end
  20255.  
  20256. /*
  20257. **  Make sure the procedure exists and get its id so we can use
  20258. **    a simpler where clause.
  20259. */
  20260. select @objid = id from master..sysobjects
  20261.     where sysstat & 0xf = 4
  20262.     and name = @procname
  20263.  
  20264. if @objid is null
  20265.     begin
  20266.         raiserror(15020,-1,-1,@procname)
  20267.         return (1)
  20268.     end
  20269.  
  20270. /*
  20271. **    If we made it to here, set it to no longer be 'startup'.
  20272. */
  20273. if (select category & 16 from master..sysobjects where id = @objid) = 16
  20274.     begin
  20275.         update master..sysobjects set category = category & ~16
  20276.             where id = @objid
  20277.         print 'Procedure is no longer marked as ''startup''.'
  20278.     end
  20279. else
  20280.     print 'Procedure was not designated as ''startup''.'
  20281.  
  20282. return (0)
  20283. go
  20284.  
  20285.  
  20286. print ''
  20287. print 'Creating procedure sp_who.'
  20288. go
  20289. create procedure sp_who  --1995/11/28 15:47
  20290.        @loginame varchar(30) = NULL
  20291. as
  20292.  
  20293. declare     @low        int
  20294.     ,@high        int
  20295.     ,@spidlow    int
  20296.     ,@spidhigh    int
  20297.  
  20298. select     @low        =     0
  20299.     ,@high        = 32767
  20300.  
  20301. select     @spidlow    =     0
  20302.     ,@spidhigh    = 32767
  20303.  
  20304.  
  20305. if (    @loginame is not NULL
  20306.    AND    upper(@loginame) <> 'ACTIVE'
  20307.    )
  20308. begin
  20309.     select @low = suser_id(@loginame), @high = suser_id(@loginame)
  20310.     if @low is NULL
  20311.     begin
  20312.         if @loginame like '[0-9]%'
  20313.         begin
  20314.             select    @spidlow  = convert(int, @loginame),
  20315.                 @spidhigh = convert(int, @loginame),
  20316.                 @low = 0, @high = 32767
  20317.         end
  20318.         else
  20319.         begin
  20320.             raiserror(15007,-1,-1,@loginame)
  20321.             return (1)
  20322.         end
  20323.     end
  20324. end
  20325.  
  20326.  
  20327. if (    @loginame is not NULL
  20328.    AND    upper(@loginame) = 'ACTIVE'
  20329.    )
  20330.     begin
  20331.  
  20332.     select spid ,status
  20333.               ,loginame=substring(suser_name(suid),1,12)
  20334.           ,hostname ,blk=convert(char(5),blocked)
  20335.           ,dbname=substring(db_name(dbid),1,10),cmd
  20336.     from  sysprocesses
  20337.     where suid >= @low     and suid <= @high
  20338.     and   spid >= @spidlow and spid <= @spidhigh
  20339.     AND   upper(cmd) <> 'AWAITING COMMAND'
  20340.  
  20341.     end
  20342. else
  20343.     begin
  20344.  
  20345.     select spid ,status
  20346.               ,loginame=substring(suser_name(suid),1,12)
  20347.           ,hostname ,blk=convert(char(5),blocked)
  20348.           ,dbname=substring(db_name(dbid),1,10),cmd
  20349.     from  sysprocesses
  20350.     where suid >= @low     and suid <= @high
  20351.     and   spid >= @spidlow and spid <= @spidhigh
  20352.  
  20353.     end
  20354.  
  20355. return (0)
  20356. go
  20357.  
  20358.  
  20359. print ''
  20360. print 'Creating procedure sp_who2.'
  20361. go
  20362. CREATE PROCEDURE sp_who2  --1995/11/03 10:16
  20363.  
  20364.     @pMultiPurpose1     varchar(30) = NULL
  20365. as
  20366.  
  20367. set nocount on
  20368.  
  20369. declare
  20370.     @retcode         int
  20371.    ,@max_suid_spid   int
  20372.    ,@int1            int
  20373.  
  20374. declare
  20375.     @suidlow         int
  20376.    ,@suidhigh        int
  20377.    ,@spidlow         int
  20378.    ,@spidhigh        int
  20379.  
  20380. declare
  20381.     @charMaxLenLoginName      varchar(6)
  20382.    ,@charMaxLenDBName         varchar(6)
  20383.    ,@charMaxLenCPUTime        varchar(10)
  20384.    ,@charMaxLenDiskIO         varchar(10)
  20385.    ,@charMaxLenHostName       varchar(10)
  20386.    ,@charMaxLenProgramName    varchar(10)
  20387.    ,@charMaxLenLastBatch      varchar(10)
  20388.    ,@charMaxLenCommand        varchar(10)
  20389.  
  20390. declare
  20391.     @charsuidlow              varchar(11)
  20392.    ,@charsuidhigh             varchar(11)
  20393.  
  20394.    ,@charspidlow              varchar(11)
  20395.    ,@charspidhigh             varchar(11)
  20396.  
  20397. --------
  20398.  
  20399. select
  20400.     @retcode         = 0      -- 0=good ,1=bad.
  20401.    ,@max_suid_spid   = 32767
  20402.  
  20403. --------defaults
  20404. select
  20405.     @suidlow         = 0
  20406.    ,@suidhigh        = @max_suid_spid
  20407.  
  20408.    ,@spidlow         = 0
  20409.    ,@spidhigh        = @max_suid_spid
  20410.  
  20411. --------------------------------------------------------------
  20412.  
  20413.  
  20414. IF (@pMultiPurpose1 IS     NULL)  --Simple default to all LoginNames.
  20415.       GOTO LABEL_17PARM1EDITED
  20416.  
  20417. --------
  20418.  
  20419. select @int1 = suser_id(@pMultiPurpose1)
  20420.  
  20421. IF (@int1 IS NOT NULL)  --Parm is a recognized login name.
  20422.    begin
  20423.    select @suidlow  = suser_id(@pMultiPurpose1)
  20424.          ,@suidhigh = suser_id(@pMultiPurpose1)
  20425.    GOTO LABEL_17PARM1EDITED
  20426.    end
  20427.  
  20428. --------
  20429.  
  20430. IF (lower(@pMultiPurpose1) IN ('active'))  --Special action, not sleeping.
  20431.    begin
  20432.    select @pMultiPurpose1 = lower(@pMultiPurpose1)
  20433.    GOTO LABEL_17PARM1EDITED
  20434.    end
  20435.  
  20436. --------
  20437.  
  20438. IF (patindex ('%[^0-9]%' , isnull(@pMultiPurpose1,'z')) = 0)  --Is a number.
  20439.    begin
  20440.    select
  20441.              @spidlow   = convert(int, @pMultiPurpose1)
  20442.             ,@spidhigh  = convert(int, @pMultiPurpose1)
  20443.    GOTO LABEL_17PARM1EDITED
  20444.    end
  20445.  
  20446. --------
  20447.  
  20448. RaisError(15007,-1,-1,@pMultiPurpose1)
  20449. select @retcode = 1
  20450. GOTO LABEL_86RETURN
  20451.  
  20452.  
  20453. LABEL_17PARM1EDITED:
  20454.  
  20455.  
  20456. --------------------  Capture consistent sysprocesses.  -------------------
  20457.  
  20458. SELECT
  20459.  
  20460.   spid
  20461.  ,kpid
  20462.  ,status
  20463.  ,suid
  20464.  ,hostname
  20465.  ,program_name
  20466.  ,hostprocess
  20467.  ,cmd
  20468.  ,cpu
  20469.  ,physical_io
  20470.  ,memusage
  20471.  ,blocked
  20472.  ,waittype
  20473.  ,dbid
  20474.  ,uid
  20475.  ,gid
  20476.  ,login_time
  20477.  ,last_batch
  20478.  ,nt_domain
  20479.  ,nt_username
  20480.  ,net_address
  20481.  ,net_library
  20482.  
  20483.  ,spid as 'spid_sort'
  20484.  
  20485.  ,  substring( convert(varchar,last_batch,111) ,6  ,5 ) + ' '
  20486.   + substring( convert(varchar,last_batch,113) ,13 ,8 )
  20487.        as 'last_batch_char'
  20488.  
  20489.       INTO    #tb1_sysprocesses
  20490.       from master..sysprocesses
  20491.  
  20492.  
  20493.  
  20494. --------Screen out any rows?
  20495.  
  20496. IF (@pMultiPurpose1 IN ('active'))
  20497.    DELETE #tb1_sysprocesses
  20498.          where   lower(status)  = 'sleeping'
  20499.          and     upper(cmd)    IN (
  20500.                      'AWAITING COMMAND'
  20501.                     ,'MIRROR HANDLER'
  20502.                     ,'LAZY WRITER'
  20503.                     ,'CHECKPOINT SLEEP'
  20504.                     ,'RA MANAGER'
  20505.                                   )
  20506.  
  20507.          and     blocked       = 0
  20508.  
  20509.  
  20510.  
  20511. --------Prepare to dynamically optimize column widths.
  20512.  
  20513.  
  20514. Select
  20515.     @charsuidlow     = convert(varchar,@suidlow)
  20516.    ,@charsuidhigh    = convert(varchar,@suidhigh)
  20517.    ,@charspidlow     = convert(varchar,@spidlow)
  20518.    ,@charspidhigh    = convert(varchar,@spidhigh)
  20519.  
  20520.  
  20521.  
  20522. SELECT
  20523.              @charMaxLenLoginName =
  20524.                   convert( varchar
  20525.                           ,isnull( max( datalength( convert(varchar,suser_name(suid)))) ,5)
  20526.                          )
  20527.  
  20528.             ,@charMaxLenDBName    =
  20529.                   convert( varchar
  20530.                           ,isnull( max( datalength( convert(varchar,db_name(dbid)))) ,6)
  20531.                          )
  20532.  
  20533.             ,@charMaxLenCPUTime   =
  20534.                   convert( varchar
  20535.                           ,isnull( max( datalength( convert(varchar,cpu))) ,7)
  20536.                          )
  20537.  
  20538.             ,@charMaxLenDiskIO    =
  20539.                   convert( varchar
  20540.                           ,isnull( max( datalength( convert(varchar,physical_io))) ,6)
  20541.                          )
  20542.  
  20543.             ,@charMaxLenCommand  =
  20544.                   convert( varchar
  20545.                           ,isnull( max( datalength( convert(varchar,cmd))) ,7)
  20546.                          )
  20547.  
  20548.             ,@charMaxLenHostName  =
  20549.                   convert( varchar
  20550.                           ,isnull( max( datalength( convert(varchar,hostname))) ,8)
  20551.                          )
  20552.  
  20553.             ,@charMaxLenProgramName =
  20554.                   convert( varchar
  20555.                           ,isnull( max( datalength( convert(varchar,program_name))) ,11)
  20556.                          )
  20557.  
  20558.             ,@charMaxLenLastBatch =
  20559.                   convert( varchar
  20560.                           ,isnull( max( datalength( convert(varchar,last_batch_char))) ,9)
  20561.                          )
  20562.       from
  20563.              #tb1_sysprocesses
  20564.       where
  20565.              suid >= @suidlow
  20566.       and    suid <= @suidhigh
  20567.       and
  20568.              spid >= @spidlow
  20569.       and    spid <= @spidhigh
  20570.  
  20571.  
  20572.  
  20573. --------Output the report.
  20574.  
  20575.  
  20576. EXECUTE(
  20577. '
  20578. SET nocount off
  20579.  
  20580. SELECT
  20581.              SPID          = convert(char(5),spid)
  20582.  
  20583.             ,Status        =
  20584.                   CASE lower(status)
  20585.                      When ''sleeping'' Then lower(status)
  20586.                      Else                   upper(status)
  20587.                   END
  20588.  
  20589.             ,Login         = substring(suser_name(suid),1,' + @charMaxLenLoginName + ')
  20590.  
  20591.             ,HostName      =
  20592.                   CASE hostname
  20593.                      When Null  Then ''  .''
  20594.                      When '' '' Then ''  .''
  20595.                      Else    substring(hostname,1,' + @charMaxLenHostName + ')
  20596.                   END
  20597.  
  20598.             ,BlkBy         =
  20599.                   CASE               isnull(convert(char(5),blocked),''0'')
  20600.                      When ''0'' Then ''  .''
  20601.                      Else            isnull(convert(char(5),blocked),''0'')
  20602.                   END
  20603.  
  20604.             ,DBName        = substring(db_name(dbid),1,' + @charMaxLenDBName + ')
  20605.             ,Command       = substring(cmd,1,' + @charMaxLenCommand + ')
  20606.  
  20607.             ,CPUTime       = substring(convert(varchar,cpu),1,' + @charMaxLenCPUTime + ')
  20608.             ,DiskIO        = substring(convert(varchar,physical_io),1,' + @charMaxLenDiskIO + ')
  20609.  
  20610.             ,LastBatch     = substring(last_batch_char,1,' + @charMaxLenLastBatch + ')
  20611.  
  20612.             ,ProgramName   = substring(program_name,1,' + @charMaxLenProgramName + ')
  20613.             ,SPID          = convert(char(5),spid)  --Handy extra for right-scrolling users.
  20614.       from
  20615.              #tb1_sysprocesses  --Usually DB qualification is needed in exec().
  20616.       where
  20617.              suid >= ' + @charsuidlow  + '
  20618.       and    suid <= ' + @charsuidhigh + '
  20619.       and
  20620.              spid >= ' + @charspidlow  + '
  20621.       and    spid <= ' + @charspidhigh + '
  20622.  
  20623.       -- (Seems always auto sorted.)   order by spid_sort
  20624.  
  20625. SET nocount on
  20626. '
  20627. )
  20628.  
  20629.  
  20630.  
  20631. LABEL_86RETURN:
  20632.  
  20633.  
  20634. if (object_id('tempdb..#tb1_sysprocesses') is not null)
  20635.             drop table #tb1_sysprocesses
  20636.  
  20637. return @retcode
  20638. go
  20639.  
  20640.  
  20641. ---------------------------------------------------------------------------------------------
  20642. ---------------------------------------------------------------------------------------------
  20643. ---------------------------------------------------------------------------------------------
  20644.  
  20645.  
  20646. /*
  20647. ** Create following procs last, since they reference other procedures.
  20648. */
  20649.  
  20650. print ''
  20651. print 'Creating procedure sp_dboption.'
  20652. go
  20653. create procedure sp_dboption -- 1995/11/17 09:32
  20654. @dbname varchar(30) = NULL,     /* database name to change */
  20655. @optname varchar(20) = NULL,  /* option name to turn on/off */
  20656. @optvalue varchar(10) = NULL  /* true or false */
  20657. as
  20658.  
  20659. set nocount on
  20660.  
  20661. declare @dbid int         /* dbid of the database */
  20662. declare @dbuid int           /* id of the owner of the database */
  20663. declare @statvalue int     /* number of option */
  20664. declare @optcount int      /* number of options like @optname */
  20665. declare @allopts int    /* bit map off all options that can be
  20666.             ** set by sp_dboption. */
  20667. declare @devname varchar(30)
  20668. declare @cur_dbname varchar(30)
  20669. declare @pmsg varchar(255)
  20670. declare @ret_code int
  20671. declare @int1 int
  20672.  
  20673. /*
  20674. **  If no @dbname given, just list the possible dboptions.
  20675. **  Only certain status bits may be set or cleared by sp_dboption.
  20676. */
  20677.  
  20678. /*
  20679. ** Get bitmap of all options that can be set by sp_dboption.
  20680. */
  20681. select @allopts=number from master.dbo.spt_values where type = 'D'
  20682.    and name = 'ALL SETTABLE OPTIONS'
  20683.  
  20684. if @dbname is null
  20685. begin
  20686.    select 'Settable database options:' = name
  20687.       from master.dbo.spt_values
  20688.       where type = 'D'
  20689.          and number & @allopts <> 0
  20690.          and number not in (-1,@allopts)  /* Eliminate non-option entries */
  20691.       order by name
  20692.    return (0)
  20693. end
  20694.  
  20695. /*
  20696. **  Verify the database name and get the @dbid and @dbuid
  20697. */
  20698. select @dbid = dbid, @dbuid = suid
  20699.    from sysdatabases
  20700.       where name = @dbname
  20701.  
  20702. /*
  20703. **  If @dbname not found, say so and list the databases.
  20704. */
  20705. if @dbid is null
  20706.    begin
  20707.       raiserror(15010,-1,-1,@dbname)
  20708.       print ''
  20709.       select 'Available databases:' = name
  20710.          from sysdatabases
  20711.       return (1)
  20712.    end
  20713.  
  20714. /*
  20715. ** If no option was supplied, display current settings.
  20716. */
  20717. if @optname is null
  20718.    begin
  20719.       select 'The following options are set:' = v.name
  20720.          from master.dbo.spt_values v, sysdatabases d
  20721.             where d.name=@dbname
  20722.                and number & @allopts <> 0
  20723.                and number not in (-1,@allopts)  /* Eliminate non-option entries */
  20724.                and v.type = 'D'
  20725.                and ((v.number & d.status)=v.number
  20726.                   or d.category & (v.number/0x10000) <> 0)
  20727.  
  20728.       return(0)
  20729.    end
  20730.  
  20731. if lower(@optvalue) not in ('true', 'false') and @optvalue is not null
  20732.    begin
  20733.       raiserror(15241,-1,-1)
  20734.       return (1)
  20735.    end
  20736.  
  20737. /*
  20738. **  Use @optname and try to find the right option.
  20739. **  If there isn't just one, print appropriate diagnostics and return.
  20740. */
  20741. select @statvalue = min(number), @optcount = count(*)
  20742.       from master.dbo.spt_values
  20743.       where lower(name) like '%' + lower(@optname) + '%'
  20744.          and type = 'D'
  20745.          and number & @allopts <> 0
  20746.          and number not in (-1,@allopts)  /* Eliminate non-option entries */
  20747.  
  20748. /*
  20749. **  If no option, show the user what the options are.
  20750. */
  20751. if @optcount = 0
  20752.    begin
  20753.       raiserror(15011,-1,-1,@optname)
  20754.       print ''
  20755.  
  20756.       select 'Settable database options:' = name
  20757.          from master.dbo.spt_values
  20758.          where type = 'D'
  20759.             and number & @allopts <> 0
  20760.             and number not in (-1,@allopts)  /* Eliminate non-option entries */
  20761.          order by name
  20762.  
  20763.       return (1)
  20764.    end
  20765.  
  20766. /*
  20767. **  If more than one option like @optname, show the duplicates and return.
  20768. */
  20769. if @optcount > 1
  20770.    begin
  20771.       raiserror(15242,-1,-1,@optname)
  20772.       print ''
  20773.  
  20774.       select duplicate_options = name
  20775.          from master.dbo.spt_values
  20776.          where name like '%' + @optname + '%'
  20777.             and type = 'D'
  20778.             and number & @allopts <> 0
  20779.             and number not in (-1,@allopts)  /* Eliminate non-option entries */
  20780.       return (1)
  20781.    end
  20782.  
  20783. /*
  20784. **  You can not change any of the options in master, except the 'trunc log on
  20785. **  checkpoint' option (8).  If the user tries to do so tell them they can't.
  20786. */
  20787. if (@dbid = 1 and @statvalue <> 8 and @optvalue is not null)
  20788.    begin
  20789.       raiserror(15243,-1,-1,@optname)
  20790.       return (1)
  20791.    end
  20792.  
  20793. /*
  20794. **  Only the SA or the dbo of @dbname can execute the update part
  20795. **  of this procedure so check.
  20796. */
  20797. if suser_id() <> 1 and suser_id() <> @dbuid and @optvalue is not null
  20798.    begin
  20799.       raiserror(15244,-1,-1)
  20800.       return (1)
  20801.    end
  20802.  
  20803. /*
  20804. **  If we're in a transaction, disallow this since it might make recovery
  20805. **  impossible.
  20806. */
  20807. if @@trancount > 0 and @optvalue is not null
  20808.    begin
  20809.       raiserror(15002,-1,-1,'sp_dboption')
  20810.       return (1)
  20811.    end
  20812.  
  20813. select @cur_dbname=db_name()  /* Keep track of where we are. */
  20814.  
  20815.  
  20816. /*
  20817. **  Just want to see current setting of specified option.
  20818. */
  20819. if @optvalue is null
  20820. begin
  20821.       select       @int1   = min(number)
  20822.          from      master.dbo.spt_values
  20823.          where     name LIKE '%' + @optname + '%'
  20824.  
  20825.  
  20826.       select OptionName = v.name
  20827.  
  20828.             ,CurrentSetting =
  20829.                CASE
  20830.                   When ( (v.number & d.status) = v.number
  20831.                        or d.category & (v.number/0x10000) <> 0
  20832.                        )
  20833.                      Then 'ON'
  20834.                   When NOT
  20835.                        ( (v.number & d.status) = v.number
  20836.                        or d.category & (v.number/0x10000) <> 0
  20837.                        )
  20838.                      Then 'off'
  20839.                END
  20840.  
  20841.          from master.dbo.spt_values v, sysdatabases d
  20842.             where d.name=@dbname
  20843.                and v.number & @allopts <> 0
  20844.                and v.number not in (-1,@allopts)   /* Eliminate non-option entries */
  20845.                and v.type = 'D'
  20846.                and v.number = @int1 and @int1 is not null
  20847.  
  20848.    return (0)
  20849. end
  20850.  
  20851.  
  20852. /*
  20853. **  Now update sysdatabases.
  20854. */
  20855. if lower(@optvalue) = 'true'
  20856. begin
  20857.    /*
  20858.    **  If this is the option to make the database read only
  20859.    **  or to take it offline, we need to do some checking first.
  20860.    **  Unless it's the master db, no one can be using it.
  20861.    **  If it's the master db, only the SA may be using it.
  20862.    */
  20863.    if @statvalue in (512,1024)
  20864.       and (select count(*) from sysprocesses
  20865.          where dbid = @dbid
  20866.          and suid <> 1) > 0
  20867.       begin
  20868.          raiserror(15069,-1,-1)
  20869.          return (1)
  20870.       end
  20871.  
  20872.    /*
  20873.    ** If we're setting the database 'offline' - use 'dbcc dbcontrol'
  20874.    ** rather than setting the status bit directly.
  20875.    */
  20876.    if @statvalue = 512
  20877.    begin
  20878.       dbcc dbcontrol(@dbname,offline)
  20879.       if @@error>0
  20880.          begin
  20881.             raiserror(15245,-1,-1)
  20882.             return (1)
  20883.          end
  20884.       else
  20885.          print 'Database is now offline'
  20886.  
  20887.                 /*
  20888.       ** Now close all devices that belong solely to this database
  20889.       ** or are shared only by other offline databases.
  20890.       */
  20891.       exec('declare c1 cursor for
  20892.          select distinct v.name
  20893.          from master.dbo.sysdevices v, master.dbo.sysusages u, master.dbo.sysdatabases d
  20894.          where d.name = '''+
  20895.          @dbname+
  20896.          ''' and d.dbid = u.dbid
  20897.          and u.vstart between v.low and v.high
  20898.          and v.status & 2 = 2
  20899.          and not exists '+
  20900.          '(select * from master.dbo.sysdevices v2,
  20901.                master.dbo.sysusages u2,
  20902.                master.dbo.sysdatabases d2
  20903.             where v2.name = v.name
  20904.             and d2.dbid = u2.dbid
  20905.             and vstart between v2.low and v2.high
  20906.             and d2.dbid <> d.dbid
  20907.             and d2.status & 512 <> 512)')
  20908.  
  20909.       open c1
  20910.       fetch c1 into @devname
  20911.  
  20912.       while @@fetch_status >= 0
  20913.       begin
  20914.          select @pmsg='Closing device '''+@devname+''' and marking it ''deferred''.'
  20915.          print @pmsg
  20916.          dbcc devcontrol(@devname,offline)
  20917.          exec sp_devoption @devname,deferred,true
  20918.          fetch c1 into @devname
  20919.       end
  20920.       deallocate c1
  20921.       /*
  20922.       ** Don't need to continue and set status bit or 'checkpoint'
  20923.       ** the database if option was 'offline' since the dbcc
  20924.       ** command does.
  20925.       */
  20926.       return(0)   /* Don't need to continue and 'checkpoint' db for this
  20927.             ** option. */
  20928.    end
  20929.  
  20930.    if @statvalue = 65536   /* We're publishing the database. */
  20931.       begin
  20932.          exec ('use ' + @dbname + ' exec sp_publishdb ' + @dbname
  20933.         + ', ''true''')
  20934.          update sysdatabases
  20935.              set category = category | 1
  20936.              where name = @dbname
  20937.              print 'Database successfully published.'
  20938.              return(0)
  20939.       end
  20940.  
  20941.    if @statvalue = 131072  /* Allowing subscriptions in the database. */
  20942.       begin
  20943.          /* Add repl_publisher, dbo alias */
  20944.  
  20945.          exec ('use ' + @dbname + '
  20946.                 if not exists (select * from sysalternates where
  20947.             suid = 16382) '+ /* repl_publisher id */
  20948.             'insert into sysalternates (suid, altsuid)
  20949.                values (16382, 1)'
  20950.               )
  20951.  
  20952.          update sysdatabases set category = category | 2
  20953.             where name = @dbname
  20954.          print 'Database successfully enabled for subscriptions.'
  20955.          return (0)
  20956.       end
  20957.  
  20958.    /* All other options get handled identically. */
  20959.    update sysdatabases set status = status | @statvalue
  20960.       where dbid = @dbid
  20961.  
  20962. end
  20963.  
  20964. /*
  20965. **  We want to set the requested option off.
  20966. */
  20967.  
  20968. else
  20969.  
  20970. begin
  20971.    if @statvalue = 512     /* We're bringing it online. */
  20972.    begin
  20973.         /*
  20974.       ** Open all devices that this database uses.
  20975.       */
  20976.       exec('declare c1 cursor for
  20977.          select distinct v.name
  20978.          from master.dbo.sysdevices v, master.dbo.sysusages u, master.dbo.sysdatabases d
  20979.          where d.name = '''+
  20980.          @dbname+
  20981.          ''' and d.dbid = u.dbid
  20982.          and u.vstart between v.low and v.high
  20983.          and v.status & 2 = 2')
  20984.  
  20985.       open c1
  20986.       fetch c1 into @devname
  20987.  
  20988.       while @@fetch_status >= 0
  20989.       begin
  20990.          select @pmsg='Opening device '''+@devname+''' and marking it as non-deferred.'
  20991.          print @pmsg
  20992.          dbcc devcontrol(@devname,online)
  20993.          if @@error not in (0,5151,5155)
  20994.             begin
  20995.                                         deallocate c1
  20996.                raiserror(15246,-1,-1,@devname)
  20997.                return (1)
  20998.             end
  20999.          exec sp_devoption @devname,deferred,false
  21000.          fetch c1 into @devname
  21001.       end
  21002.       deallocate c1
  21003.  
  21004.       dbcc dbcontrol(@dbname,online)
  21005.       print 'Database is now online.'
  21006.       return(0)
  21007.    end
  21008.  
  21009.    if @statvalue = 65536   /* We're disabling publishing for the database. */
  21010.       begin
  21011.          exec ('use ' + @dbname + ' exec sp_publishdb ' + @dbname
  21012.         + ', ''false''')
  21013.          update sysdatabases
  21014.         set category = category & ~1
  21015.                 where name = @dbname
  21016.      print 'Database no longer published.'
  21017.       end
  21018.  
  21019.    if @statvalue = 131072  /* We're disabling subscriptions to database. */
  21020.       begin
  21021.          /* Drop repl_publisher, dbo alias */
  21022.  
  21023.          exec ('use ' + @dbname + '
  21024.                 if     exists (select * from sysalternates where
  21025.             suid = 16382) '+ /* repl_publisher id */
  21026.             'delete sysalternates where suid = 16382'
  21027.               )
  21028.  
  21029.          update sysdatabases set category = category & ~2
  21030.             where name = @dbname
  21031.          print 'Database no longer enabled for subscriptions.'
  21032.          return (0)
  21033.       end
  21034.  
  21035.    /* All other options get handled identically. */
  21036.    update sysdatabases set status = status & ~@statvalue
  21037.       where dbid = @dbid
  21038. end
  21039.  
  21040. /*
  21041. **  CHECKPOINT the database that was changed.
  21042. */
  21043. print 'CHECKPOINTing database that was changed.'
  21044.  
  21045. exec('use ' + @dbname + ' checkpoint')
  21046.  
  21047. return (0)
  21048. go
  21049.  
  21050.  
  21051.  
  21052. print ''
  21053. print 'Creating procedure sp_check_removable.'
  21054. go
  21055. create procedure sp_check_removable @autofix varchar(4)
  21056. as
  21057.  
  21058. declare @dbouid int
  21059. declare @dbname varchar(30)
  21060. declare @logdev varchar(30)
  21061.  
  21062. select @dbname=db_name()
  21063.     
  21064. /* Verify that SA owns the database. */
  21065.  
  21066. select @dbouid = suid from sysdatabases where name = @dbname
  21067. if @dbouid <> 1
  21068.     if @autofix='auto'
  21069.         begin
  21070.             print 'Setting db owner to SA.'
  21071.             update sysdatabases set suid = 1
  21072.                 where name = @dbname
  21073.             update sysusers set suid = 1
  21074.                 where uid = 1
  21075.         end
  21076.     else
  21077.         begin
  21078.             raiserror(15258,-1,-1)
  21079.             return(1)
  21080.         end
  21081.  
  21082. /* Check for any objects not owned by dbo. */
  21083. if exists (select * from sysobjects where uid <> 1)
  21084.  
  21085.     if @autofix='auto'
  21086.         begin
  21087.             print 'Giving ownership of all objects to dbo.'
  21088.             update sysobjects set uid = 1
  21089.         end
  21090.     else
  21091.         begin
  21092.             raiserror(15053,-1,-1)
  21093.             return(1)
  21094.         end
  21095.  
  21096. /* See if any non-dbo/guest users exist in db */
  21097. if exists (select * from sysusers where uid between 3 and 16382)
  21098.     if @autofix='auto'
  21099.         begin
  21100.             print 'Deleting non guest/dbo users from ''sysusers''.'
  21101.             delete from sysusers where uid between 3 and 16382
  21102.             delete from sysprotects where uid not in
  21103.                 (select uid from sysusers)
  21104.             delete from sysalternates where altsuid not in
  21105.                 (select suid from sysusers)
  21106.         end
  21107.     else
  21108.         begin
  21109.             raiserror(15254,-1,-1)
  21110.             return(1)
  21111.         end
  21112.  
  21113. /* If we made it to here, move the log segment to the system segment. */
  21114. update sysusages set segmap = 5 where dbid = db_id(@dbname) and segmap = 1
  21115. dbcc dbrepair (@dbname,remap) with no_infomsgs
  21116.  
  21117. /* Save the old log device's name and unmap the log segment from it. */
  21118. select @logdev = v.name from sysusages u,sysdevices v
  21119.     where u.dbid = db_id(@dbname)
  21120.         and u.segmap = 4
  21121.         and u.vstart = low
  21122.  
  21123. update sysusages set segmap = 0
  21124.     where dbid = db_id(@dbname) and segmap = 4
  21125. dbcc dbrepair (@dbname,remap) with no_infomsgs
  21126.  
  21127. /* Force first log page onto new device. */
  21128. while exists
  21129.     (select * from sysindexes where name = 'syslogs' and root not between
  21130.         (select lstart from sysusages
  21131.             where dbid = db_id(@dbname) and segmap = 5)
  21132.         and
  21133.         (select lstart+size-1 from sysusages
  21134.          where dbid = db_id(@dbname) and segmap = 5))
  21135. or exists
  21136.     (select * from sysindexes where name = 'syslogs' and first not between
  21137.         (select lstart from sysusages
  21138.             where dbid = db_id(@dbname) and segmap = 5)
  21139.         and
  21140.         (select lstart+size-1 from sysusages
  21141.             where dbid = db_id(@dbname) and segmap = 5))
  21142.  
  21143.     begin
  21144.         update sysobjects set name = name    -- no_op to generate
  21145.                             -- log activity
  21146.  
  21147.         exec('dump tran '+@dbname+' with no_log')
  21148.     end
  21149.  
  21150. /* Delete the old log segment and drop its device. */
  21151.  
  21152. delete from sysusages where dbid = db_id(@dbname) and segmap = 0
  21153. dbcc dbrepair (@dbname,remap) with no_infomsgs
  21154.  
  21155. exec sp_dropdevice @logdev
  21156. return(0)
  21157. go
  21158.  
  21159.  
  21160. print ''
  21161. print 'Creating procedure sp_certify_removable.'
  21162. go
  21163. CREATE PROCEDURE sp_certify_removable  --1995/11/20 13:20
  21164.  
  21165.         @dbname varchar(30) = null,
  21166.         @autofix varchar(4) = null
  21167. as
  21168.  
  21169. declare @ret_value int,
  21170.         @vc1 varchar(255),
  21171.         @SQLPath varchar(255),
  21172.         @OneMb int,
  21173.         @countloop1 int,
  21174.     @char_autofix varchar(25)
  21175.  
  21176. declare
  21177.        @cu1PKSequence      int
  21178.       ,@cu1DeviceName      varchar( 30)
  21179.       ,@cu1SegmentType     varchar( 12)
  21180.       ,@cu1FragmentSizeMb  int
  21181.       ,@cu1DeviceFileName  varchar(127)
  21182.  
  21183.  
  21184. select  @OneMb = 1048576
  21185.  
  21186.  
  21187. if suser_id() <> 1      -- Make sure that it is the SA executing this.
  21188.         begin
  21189.                 raiserror(15003,-1,-1)
  21190.                 return(1)
  21191.         end
  21192.  
  21193.  
  21194. select @autofix = lower(@autofix)
  21195.  
  21196. if @autofix <> 'auto' and @autofix is not null
  21197.         begin
  21198.                 raiserror(15255,-1,-1,@autofix)
  21199.                 return(1)
  21200.         end
  21201.  
  21202.  
  21203. if @dbname is null      -- Show usage diagram if no dbname supplied.
  21204.         begin
  21205.                 raiserror(15256,-1,-1)
  21206.                 return(1)
  21207.         end
  21208.  
  21209.  
  21210. --See if DB exists.
  21211. if not exists (select * from sysdatabases where name = @dbname)
  21212.         begin
  21213.                 raiserror(15010,-1,-1,@dbname)
  21214.                 return(1)
  21215.         end
  21216.  
  21217.  
  21218. --Cannot take master, tempdb or model databases offline.
  21219. if lower(@dbname) in ('master','tempdb','model')
  21220.         begin
  21221.                 raiserror(15266,-1,-1,@dbname)
  21222.                 return(1)
  21223.         end
  21224.  
  21225.  
  21226. -- Will not be able to take db offline if user is in it.
  21227. if @dbname = db_name()
  21228.         begin
  21229.                 raiserror(15257,-1,-1)
  21230.                 return(1)
  21231.         end
  21232.  
  21233.  
  21234. ------------------  validate fragment continuity  -----------------
  21235.  
  21236.  
  21237. --Coalesce any contiguous device fragments for this database.
  21238. exec sp_coalesce_fragments @dbname
  21239.  
  21240.  
  21241. --Verify that two or more noncontiguous fragments do not exist on any
  21242. --   device for the database.
  21243. if exists (select * from sysusages u1,sysdevices v
  21244.                 where u1.dbid = db_id(@dbname)
  21245.                 and u1.vstart between v.low and v.high
  21246.                 and exists (
  21247.                             select * from sysusages u2
  21248.                                 where u2.dbid=u1.dbid
  21249.                                 and u2.vstart between v.low and v.high
  21250.                                 and u2.vstart <> u1.vstart
  21251.                            )
  21252.           )
  21253.         begin
  21254.                 raiserror(15260,-1,-1)
  21255.                 return(1)
  21256.         end
  21257.  
  21258.  
  21259. --Verify that the database spans at least 3 devices (system, data and
  21260. --   log) and that segment mappings are proper.
  21261. if
  21262.         (select count(*) from sysusages where dbid = db_id(@dbname)
  21263.                 and segmap = 1) <> 1    -- dedicated system device
  21264.         or (select count(*) from sysusages where dbid = db_id(@dbname)
  21265.                 and segmap = 4) <> 1    -- dedicated log device
  21266.         or (select count(*) from sysusages where dbid = db_id(@dbname)
  21267.                 and segmap = 2) < 1     -- dedicated data device
  21268.  
  21269.                 begin
  21270.                         raiserror(15259,-1,-1)
  21271.                         return(1)
  21272.                 end
  21273.  
  21274.  
  21275. -------------  Check things that exist only in the db.  -------------------
  21276.  
  21277.  
  21278. --set quoted_identifiers off  --maybe a good idea
  21279.  
  21280. select @char_autofix =
  21281.     CASE
  21282.        When @autofix IS NOT Null Then '''Auto'''
  21283.        Else                           'Null'
  21284.     END
  21285.  
  21286.  
  21287. execute(
  21288. '
  21289. use ' + @dbname + '
  21290.  
  21291. declare @inx_ret_value int ,@int1 int
  21292. select  @inx_ret_value = 1
  21293.  
  21294. exec @inx_ret_value = sp_check_removable ' + @char_autofix + '
  21295.  
  21296. --Kludge @@rowcount for a user_assignable global variable for communication.
  21297. if @inx_ret_value <> 0    --bad
  21298.     begin
  21299.     select @int1 = suid from master.dbo.syslogins where suid=1 --SA
  21300.     return
  21301.     end
  21302. else
  21303.     begin
  21304.     select @int1 = suid from master.dbo.syslogins where suid=1 and 1=2
  21305.     return
  21306.     end
  21307. '
  21308. )
  21309.  
  21310. if @@rowcount > 0
  21311.         return (1)  --Error was returned by other proc, so exit
  21312.  
  21313.  
  21314. -------------------  report on the db devices  ----------------------
  21315.  
  21316.  
  21317. raiserror('',1,1)
  21318. raiserror(15309,-1,-1)  --"Please write down this crucial info."
  21319. raiserror('' ,1,1)
  21320.  
  21321.  
  21322. create table #tb1_ForDBInstall
  21323.    (
  21324.     PKSequence          int            not null    identity(1,1)
  21325.    ,UG_LStart           int            not null
  21326.    ,DeviceName          varchar(30)        null
  21327.    ,SegmentType         varchar(12)        null
  21328.    ,FragmentSizeMb      int                null
  21329.    ,DeviceFileName      varchar(127)       null
  21330.    )
  21331.  
  21332.  
  21333.  
  21334. insert
  21335.       into #tb1_ForDBInstall
  21336.          (
  21337.           -- PKSequence,
  21338.           UG_LStart
  21339.          ,DeviceName
  21340.          ,SegmentType
  21341.          ,FragmentSizeMb
  21342.          ,DeviceFileName
  21343.          )
  21344.    select
  21345.              -- identitycol,
  21346.              u.lstart
  21347.             ,v.name
  21348.  
  21349.             ,case u.segmap
  21350.                 when 5 then 'System + Log'
  21351.                 when 2 then 'Data'
  21352.              end
  21353.  
  21354.             ,convert( int
  21355.                      ,round( (
  21356.                 (select low
  21357.                    from master.dbo.spt_values
  21358.                    where type = 'E' and number = 1
  21359.                 )
  21360.                      * convert(float, u.size)
  21361.                              ) / @OneMb
  21362.                           ,0
  21363.                            )
  21364.                     )
  21365.  
  21366.             ,phyname
  21367.    from
  21368.              sysdevices    v
  21369.             ,sysusages     u
  21370.    where
  21371.              u.dbid   = db_id(@dbname)
  21372.    and       u.vstart = v.low
  21373.    order by
  21374.              lstart
  21375.  
  21376.  
  21377.  
  21378. select
  21379.              'Sequence'    = convert(char(8),PKSequence)
  21380.             ,DeviceName
  21381.             ,SegmentType
  21382.             ,FragmentSizeMb
  21383.             ,DeviceFileName
  21384.       from
  21385.              #tb1_ForDBInstall
  21386.       order by
  21387.              UG_LStart ,PKSequence  --Should match plain PKSequence.
  21388.  
  21389. raiserror('',1,1) with nowait
  21390.  
  21391.  
  21392. ------------  Make a ReadMe style file named Log\CertifyR_<dbname>.TXT  ------
  21393.  
  21394.  
  21395. if (0 < (select  count(*)
  21396.            from  master.dbo.sysobjects
  21397.            where type='X ' and name in (
  21398.                     'xp_cmdshell' ,'xp_regread'
  21399.                                        )
  21400.            and   category & 8192 > 0     --See sp_xpoption.
  21401.         )
  21402.    )
  21403.    begin
  21404.    raiserror(15328,-1,-1)
  21405.    goto LABEL_58AFTERWRITECERTIFYR
  21406.    end
  21407.  
  21408.  
  21409. exec master..xp_regread
  21410.        'HKEY_LOCAL_MACHINE'
  21411.       ,'SOFTWARE\Microsoft\MSSQLServer\Setup'
  21412.       ,'SQLPath'
  21413.             ,@SQLPath   OUTPUT  --example:  C:\SQL60  (missing trailing \ )
  21414.  
  21415. select @SQLPath = rtrim(@SQLPath) + '\Log\CertifyR_' + rtrim(@dbname) + '.TXT'
  21416.  
  21417.  
  21418.  
  21419. --Prime the TXT file.
  21420. select @vc1 = 'echo --sp_certify_removable, db='
  21421.             + rtrim(@dbname) + ',  ' + convert(varchar,getdate(),113)
  21422.                + '  >' + rtrim(@SQLPath)
  21423. exec master..xp_cmdshell @vc1 , 'no_output'
  21424.  
  21425.  
  21426. select @vc1 =
  21427.     'echo --Sequence,DeviceName,SegmentType,FragmentSizeMb,DeviceFileName'
  21428.                + ' >>' + rtrim(@SQLPath)
  21429. exec master..xp_cmdshell @vc1 , 'no_output'
  21430.  
  21431.  
  21432.  
  21433. --Loop thru temp #table rows.
  21434. declare cursor1_tb1
  21435.    insensitive
  21436.    cursor for
  21437. select
  21438.        PKSequence
  21439.       ,DeviceName
  21440.       ,SegmentType
  21441.       ,FragmentSizeMb
  21442.       ,DeviceFileName
  21443.    from
  21444.        #tb1_ForDBInstall
  21445.    order by
  21446.        PKSequence
  21447.  
  21448.  
  21449. open cursor1_tb1
  21450.  
  21451. select @countloop1 = 0
  21452.  
  21453.  
  21454. -----------------------
  21455. while (     1=1
  21456.       and   @@error = 0
  21457.       )
  21458.    begin
  21459.  
  21460.    fetch     next
  21461.       from   cursor1_tb1
  21462.       into
  21463.              @cu1PKSequence
  21464.             ,@cu1DeviceName
  21465.             ,@cu1SegmentType
  21466.             ,@cu1FragmentSizeMb
  21467.             ,@cu1DeviceFileName
  21468.  
  21469.    if (@@fetch_status <> 0)
  21470.       begin
  21471.       deallocate cursor1_tb1
  21472.       break
  21473.       end
  21474.  
  21475.    select @countloop1 = @countloop1 + 1
  21476.  
  21477.  
  21478.    select @vc1 = 'echo '
  21479.  
  21480.                + convert(varchar ,@cu1PKSequence)
  21481.          + ',' +                  @cu1DeviceName
  21482.          + ',' +                  @cu1SegmentType
  21483.          + ',' + convert(varchar ,@cu1FragmentSizeMb)
  21484.          + ',' +                  @cu1DeviceFileName
  21485.  
  21486.                + ' >>' + rtrim(@SQLPath)
  21487.  
  21488.  
  21489.    exec master..xp_cmdshell @vc1 ,'no_output'
  21490.  
  21491.    end --loop 1
  21492.  
  21493.  
  21494.  
  21495. select @vc1 = convert(varchar,@countloop1)
  21496.             + ' noncomment records were written to LOG\CertifyR*.TXT file.'
  21497.  
  21498. raiserror(15310,-1,-1 ,@countloop1)
  21499.  
  21500. -- - - -
  21501.  
  21502. select @vc1 = 'echo --' + @vc1
  21503.                + ' >>' + rtrim(@SQLPath)
  21504. exec master..xp_cmdshell @vc1 , 'no_output'
  21505.  
  21506.  
  21507. LABEL_58AFTERWRITECERTIFYR:
  21508.  
  21509.  
  21510. if object_id('tempdb..#tb1_ForDBInstall') is null
  21511.            drop table #tb1_ForDBInstall
  21512.  
  21513.  
  21514. raiserror('' ,1,1)
  21515. exec sp_dboption @dbname,'offline','true'
  21516.  
  21517. return(0)
  21518. go
  21519.  
  21520.  
  21521. ---------------------------------------------------------------
  21522. raiserror('
  21523. Now done creating the general system stored procs.
  21524. Start with miscellaneous tasks like xp_ and grants.
  21525. ',1,1)
  21526. ---------------------------------------------------------------
  21527. go
  21528.  
  21529. /*
  21530. ** Drop extended procs. if they already exist now that sp_dropextendedproc
  21531. ** has been created.
  21532. */
  21533.  
  21534. print ''
  21535. print 'Dropping any existing extended stored procedures.'
  21536. go
  21537.  
  21538. if exists (select * from sysobjects
  21539.         where sysstat & 0xf = 4
  21540.             and name = 'xp_addattach')
  21541.     exec sp_dropextendedproc 'xp_addattach'
  21542.  
  21543. if exists (select * from sysobjects
  21544.         where sysstat & 0xf = 4
  21545.             and name = 'xp_addmsgline')
  21546.     exec sp_dropextendedproc 'xp_addmsgline'
  21547.  
  21548. if exists (select * from sysobjects
  21549.         where sysstat & 0xf = 4
  21550.             and name = 'xp_cmdshell')
  21551.     exec sp_dropextendedproc 'xp_cmdshell'
  21552.  
  21553. if exists (select * from sysobjects
  21554.         where sysstat & 0xf = 4
  21555.             and name = 'sp_cursor')
  21556.     exec sp_dropextendedproc 'sp_cursor'
  21557.  
  21558. if exists (select * from sysobjects
  21559.         where sysstat & 0xf = 4
  21560.             and name = 'sp_cursorclose')
  21561.     exec sp_dropextendedproc 'sp_cursorclose'
  21562.  
  21563. if exists (select * from sysobjects
  21564.         where sysstat & 0xf = 4
  21565.             and name = 'sp_cursorfetch')
  21566.     exec sp_dropextendedproc 'sp_cursorfetch'
  21567.  
  21568. if exists (select * from sysobjects
  21569.         where sysstat & 0xf = 4
  21570.             and name = 'sp_cursoropen')
  21571.     exec sp_dropextendedproc 'sp_cursoropen'
  21572.  
  21573. if exists (select * from sysobjects
  21574.         where sysstat & 0xf = 4
  21575.             and name = 'sp_cursoroption')
  21576.     exec sp_dropextendedproc 'sp_cursoroption'
  21577.  
  21578. if exists (select * from sysobjects
  21579.         where sysstat & 0xf = 4
  21580.             and name = 'xp_deletemail')
  21581.     exec sp_dropextendedproc 'xp_deletemail'
  21582.  
  21583. if exists (select * from sysobjects
  21584.         where sysstat & 0xf = 4
  21585.             and name = 'xp_enumgroups')
  21586.     exec sp_dropextendedproc 'xp_enumgroups'
  21587.  
  21588. if exists (select * from sysobjects
  21589.         where sysstat & 0xf = 4
  21590.             and name = 'xp_findnextmsg')
  21591.     exec sp_dropextendedproc 'xp_findnextmsg'
  21592.  
  21593. if exists (select * from sysobjects
  21594.         where sysstat & 0xf = 4
  21595.             and name = 'xp_grantlogin')
  21596.     exec sp_dropextendedproc 'xp_grantlogin'
  21597.  
  21598. if exists (select * from sysobjects
  21599.         where sysstat & 0xf = 4
  21600.             and name = 'xp_logevent')
  21601.     exec sp_dropextendedproc 'xp_logevent'
  21602.  
  21603. if exists (select * from sysobjects
  21604.         where sysstat & 0xf = 4
  21605.             and name = 'xp_loginconfig')
  21606.     exec sp_dropextendedproc 'xp_loginconfig'
  21607.  
  21608. if exists (select * from sysobjects
  21609.         where sysstat & 0xf = 4
  21610.             and name = 'xp_logininfo')
  21611.     exec sp_dropextendedproc 'xp_logininfo'
  21612.  
  21613. if exists (select * from sysobjects
  21614.         where sysstat & 0xf = 4
  21615.             and name = 'xp_loginmail')
  21616.     exec sp_dropextendedproc 'xp_loginmail'
  21617.  
  21618. if exists (select * from sysobjects
  21619.         where sysstat & 0xf = 4
  21620.             and name = 'xp_logoffmail')
  21621.     exec sp_dropextendedproc 'xp_logoffmail'
  21622.  
  21623. if exists (select * from sysobjects
  21624.         where sysstat & 0xf = 4
  21625.             and name = 'xp_mailproclist')
  21626.     exec sp_dropextendedproc 'xp_mailproclist'
  21627.  
  21628. if exists (select * from sysobjects
  21629.         where sysstat & 0xf = 4
  21630.             and name = 'xp_msver')
  21631.     exec sp_dropextendedproc 'xp_msver'
  21632.  
  21633. if exists (select * from sysobjects
  21634.         where sysstat & 0xf = 4
  21635.             and name = 'xp_prepmsg')
  21636.     exec sp_dropextendedproc 'xp_prepmsg'
  21637.  
  21638. if exists (select * from sysobjects
  21639.         where sysstat & 0xf = 4
  21640.             and name = 'xp_readmail')
  21641.     exec sp_dropextendedproc 'xp_readmail'
  21642.  
  21643. if exists (select * from sysobjects
  21644.         where sysstat & 0xf = 4
  21645.             and name = 'xp_revokelogin')
  21646.     exec sp_dropextendedproc 'xp_revokelogin'
  21647.  
  21648. if exists (select * from sysobjects
  21649.         where sysstat & 0xf = 4
  21650.             and name = 'xp_sendmail')
  21651.     exec sp_dropextendedproc 'xp_sendmail'
  21652.  
  21653. if exists (select * from sysobjects
  21654.         where sysstat & 0xf = 4
  21655.             and name = 'xp_sendmsg')
  21656.     exec sp_dropextendedproc 'xp_sendmsg'
  21657.  
  21658. if exists (select * from sysobjects
  21659.         where sysstat & 0xf = 4
  21660.             and name = 'xp_sprintf')
  21661.     exec sp_dropextendedproc 'xp_sprintf'
  21662.  
  21663. if exists (select * from sysobjects
  21664.         where sysstat & 0xf = 4
  21665.             and name = 'xp_sscanf')
  21666.     exec sp_dropextendedproc 'xp_sscanf'
  21667.  
  21668. if exists (select * from sysobjects
  21669.         where sysstat & 0xf = 4
  21670.             and name = 'xp_startmail')
  21671.     exec sp_dropextendedproc 'xp_startmail'
  21672.  
  21673. if exists (select * from sysobjects
  21674.         where sysstat & 0xf = 4
  21675.             and name = 'xp_stopmail')
  21676.     exec sp_dropextendedproc 'xp_stopmail'
  21677. go
  21678.  
  21679. if exists (select * from sysobjects
  21680.         where sysstat & 0xf = 4
  21681.             and name = 'xp_unc_to_drive')
  21682.     exec sp_dropextendedproc 'xp_unc_to_drive'
  21683.  
  21684. if exists (select * from sysobjects
  21685.         where sysstat & 0xf = 4
  21686.             and name = 'sp_bindsession')
  21687.     exec sp_dropextendedproc 'sp_bindsession'
  21688.  
  21689. if exists (select * from sysobjects
  21690.         where sysstat & 0xf = 4
  21691.             and name = 'sp_getbindtoken')
  21692.     exec sp_dropextendedproc 'sp_getbindtoken'
  21693.  
  21694. /* Add extended stored procedures. */
  21695.  
  21696. print ''
  21697. print 'Adding extended stored procedures.'
  21698. go
  21699. /*
  21700. ** Add xp_cmdshell extended procedure
  21701. */
  21702. sp_addextendedproc 'xp_cmdshell','xpsql60.dll'
  21703. go
  21704.  
  21705. /*
  21706. ** Add xp_logevent extended procedure
  21707. */
  21708. sp_addextendedproc 'xp_logevent','xpsql60.dll'
  21709. go
  21710.  
  21711. /*
  21712. ** Add xp_sprintf extended procedure
  21713. */
  21714. sp_addextendedproc 'xp_sprintf','xpsql60.dll'
  21715. go
  21716.  
  21717. /*
  21718. ** Add xp_sscanf extended procedure
  21719. */
  21720. sp_addextendedproc 'xp_sscanf','xpsql60.dll'
  21721. go
  21722.  
  21723. /*
  21724. ** Add xp_unc_to_drive extended procedure
  21725. */
  21726. sp_addextendedproc 'xp_unc_to_drive','xpsql60.dll'
  21727. go
  21728.  
  21729. /*
  21730. ** Add xp_logevent extended procedure
  21731. */
  21732. sp_addextendedproc 'xp_msver','xpsql60.dll'
  21733. go
  21734.  
  21735. /*
  21736. ** Add xp_enumgroups extended procedure
  21737. */
  21738. sp_addextendedproc 'xp_enumgroups','xplog60.dll'
  21739. go
  21740.  
  21741. /* Add mail enabling extended procedures */
  21742. sp_addextendedproc 'xp_startmail', 'sqlmap60.dll'
  21743. go
  21744. sp_addextendedproc 'xp_stopmail', 'sqlmap60.dll'
  21745. go
  21746. sp_addextendedproc 'xp_sendmail', 'sqlmap60.dll'
  21747. go
  21748. sp_addextendedproc 'xp_deletemail', 'sqlmap60.dll'
  21749. go
  21750. sp_addextendedproc 'xp_findnextmsg', 'sqlmap60.dll'
  21751. go
  21752. sp_addextendedproc 'xp_readmail', 'sqlmap60.dll'
  21753. go
  21754.  
  21755. /* Add extended stored procedures for NT integrated login security. */
  21756.  
  21757. sp_addextendedproc 'xp_loginconfig', 'xplog60.dll'
  21758. go
  21759. sp_addextendedproc 'xp_logininfo', 'xplog60.dll'
  21760. go
  21761. sp_addextendedproc 'xp_revokelogin', 'xplog60.dll'
  21762. go
  21763. sp_addextendedproc 'xp_grantlogin', 'xplog60.dll'
  21764. go
  21765.  
  21766. /*
  21767. ** Add extended stored procedures for cursor support.
  21768. */
  21769. sp_addextendedproc  'sp_cursor', '(server internal)'
  21770. go
  21771. sp_addextendedproc  'sp_cursorclose', '(server internal)'
  21772. go
  21773. sp_addextendedproc  'sp_cursorfetch', '(server internal)'
  21774. go
  21775. sp_addextendedproc  'sp_cursoropen', '(server internal)'
  21776. go
  21777. sp_addextendedproc  'sp_cursoroption', '(server internal)'
  21778. go
  21779.  
  21780. /*
  21781. ** Add extended stored procedures for bound session support.
  21782. */
  21783. sp_addextendedproc  'sp_bindsession', '(server internal)'
  21784. go
  21785. sp_addextendedproc  'sp_getbindtoken', '(server internal)'
  21786. go
  21787.  
  21788.  
  21789. print ''
  21790. print 'Creating procedure MS_sqlctrs_users.'
  21791. go
  21792. create proc MS_sqlctrs_users
  21793. as
  21794. select syslogins.name+' - '+convert(varchar(30),
  21795.         sysprocesses.spid), memusage 'Memory (2K Pages)',
  21796.         cpu 'CPU time', physical_io,
  21797.         count(syslocks.spid) 'Locks held',sysprocesses.spid
  21798. from sysprocesses, syslocks, syslogins where sysprocesses.spid *= syslocks.spid and sysprocesses.suid=syslogins.suid
  21799. group by syslogins.name,sysprocesses.spid,memusage,cpu,physical_io
  21800. go
  21801.  
  21802. /*
  21803. **  Add the login and user named 'probe'.  These are used for the
  21804. **  2-phased commit service.
  21805. */
  21806. if not exists (select * from syslogins where name = 'probe')
  21807.     exec sp_addlogin 'probe'
  21808. go
  21809.  
  21810. if not exists (select * from sysusers where name = 'probe')
  21811.     exec sp_adduser 'probe'
  21812. go
  21813.  
  21814. print ''
  21815. print 'Dropping keys'
  21816. print ''
  21817. go
  21818.  
  21819. /*
  21820. ** Drop 'old-style' common keys.
  21821. */
  21822. if exists (select * from syskeys where type = 3 and id = object_id('syscolumns')
  21823.         and depid = object_id('syscomments'))
  21824.     execute sp_dropkey common, syscolumns, syscomments
  21825. go
  21826. if exists (select * from syskeys where type = 3 and id = object_id('syscolumns')
  21827.         and depid = object_id('syskeys'))
  21828.     execute sp_dropkey common, syscolumns, syskeys
  21829. go
  21830. if exists (select * from syskeys where type = 3 and id = object_id('syscolumns')
  21831.         and depid = object_id('sysobjects'))
  21832.     execute sp_dropkey common, syscolumns, sysobjects
  21833. go
  21834. if exists (select * from syskeys where type = 3 and id = object_id('syscolumns')
  21835.         and depid = object_id('systypes'))
  21836.     execute sp_dropkey common, syscolumns, systypes
  21837. go
  21838. if exists (select * from syskeys where type = 3 and id = object_id('syscomments')
  21839.         and depid = object_id('sysobjects'))
  21840.     execute sp_dropkey common, syscomments, sysobjects
  21841. go
  21842. if exists (select * from syskeys where type = 3 and id = object_id('sysdepends')
  21843.         and depid = object_id('sysobjects'))
  21844.     execute sp_dropkey common, sysdepends, sysobjects
  21845. go
  21846. if exists (select * from syskeys where type = 3 and id = object_id('sysindexes')
  21847.         and depid = object_id('sysobjects'))
  21848.     execute sp_dropkey common, sysindexes, sysobjects
  21849. go
  21850. if exists (select * from syskeys where type = 3 and id = object_id('sysindexes')
  21851.         and depid = object_id('syssegments'))
  21852.     execute sp_dropkey common, sysindexes, syssegments
  21853. go
  21854. if exists (select * from syskeys where type = 3 and id = object_id('syskeys')
  21855.         and depid = object_id('sysobjects'))
  21856.     execute sp_dropkey common, syskeys, sysobjects
  21857. go
  21858. if exists (select * from syskeys where type = 3 and id = object_id('sysobjects')
  21859.         and depid = object_id('sysprocedures'))
  21860.     execute sp_dropkey common, sysobjects, sysprocedures
  21861. go
  21862. if exists (select * from syskeys where type = 3 and id = object_id('sysobjects')
  21863.         and depid = object_id('sysprotects'))
  21864.     execute sp_dropkey common, sysobjects, sysprotects
  21865. go
  21866. if exists (select * from syskeys where type = 3 and id = object_id('sysobjects')
  21867.         and depid = object_id('sysusers'))
  21868.     execute sp_dropkey common, sysobjects, sysusers
  21869. go
  21870. if exists (select * from syskeys where type = 3 and id = object_id('sysprotects')
  21871.         and depid = object_id('sysusers'))
  21872.     execute sp_dropkey common, sysprotects, sysusers
  21873. go
  21874. if exists (select * from syskeys where type = 3 and id = object_id('systypes')
  21875.         and depid = object_id('sysusers'))
  21876.     execute sp_dropkey common, systypes, sysusers
  21877. go
  21878. if exists (select * from syskeys where type = 3 and id = object_id('syscurconfigs')
  21879.         and depid = object_id('sysconfigures'))
  21880.     execute sp_dropkey common, syscurconfigs, sysconfigures
  21881. go
  21882. if exists (select * from syskeys where type = 3 and id = object_id('sysdatabases')
  21883.         and depid = object_id('syslocks'))
  21884.     execute sp_dropkey common, sysdatabases, syslocks
  21885. go
  21886. if exists (select * from syskeys where type = 3 and id = object_id('sysdatabases')
  21887.         and depid = object_id('syslogins'))
  21888.     execute sp_dropkey common, sysdatabases, syslogins
  21889. go
  21890. if exists (select * from syskeys where type = 3 and id = object_id('sysdatabases')
  21891.         and depid = object_id('sysprocesses'))
  21892.       execute sp_dropkey common, sysdatabases, sysprocesses
  21893. go
  21894. if exists (select * from syskeys where type = 3 and id = object_id('sysdatabases')
  21895.         and depid = object_id('sysusages'))
  21896.     execute sp_dropkey common, sysdatabases, sysusages
  21897. go
  21898. if exists (select * from syskeys where type = 3 and id = object_id('syslocks')
  21899.         and depid = object_id('sysprocesses'))
  21900.     execute sp_dropkey common, syslocks, sysprocesses
  21901. go
  21902. if exists (select * from syskeys where type = 3 and id = object_id('syslogins')
  21903.         and depid = object_id('sysprocesses'))
  21904.     execute sp_dropkey common, syslogins, sysprocesses
  21905. go
  21906. if exists (select * from syskeys where type = 3 and id = object_id('sysservers')
  21907.         and depid = object_id('sysremotelogins'))
  21908.     execute sp_dropkey common, sysservers, sysremotelogins
  21909. go
  21910. if exists (select * from syskeys where type = 3 and id = object_id('sysremotelogins')
  21911.         and depid = object_id('sysusers'))
  21912.     execute sp_dropkey common, sysremotelogins, sysusers
  21913. go
  21914.  
  21915. /*
  21916. ** Drop 'old-style' foreign keys.
  21917. */
  21918. if exists (select * from syskeys where type = 2 and id = object_id('sysalternates')
  21919.         and depid = object_id('sysusers'))
  21920.     execute sp_dropkey 'foreign', sysalternates, sysusers
  21921. go
  21922. if exists (select * from syskeys where type = 2 and id = object_id('syskeys')
  21923.         and depid = object_id('sysobjects'))
  21924.     execute sp_dropkey 'foreign', syskeys, sysobjects
  21925. go
  21926.  
  21927. /*
  21928. ** Drop 'old-style' primary keys.
  21929. */
  21930. if exists (select * from syskeys where type = 1 and id = object_id('sysalternates'))
  21931.     execute sp_dropkey 'primary', sysalternates
  21932. go
  21933. if exists (select * from syskeys where type = 1 and id = object_id('syscolumns'))
  21934.     execute sp_dropkey 'primary', syscolumns
  21935. go
  21936. if exists (select * from syskeys where type = 1 and id = object_id('syscomments'))
  21937.     execute sp_dropkey 'primary', syscomments
  21938. go
  21939. if exists (select * from syskeys where type = 1 and id = object_id('sysconfigures'))
  21940.     execute sp_dropkey 'primary', sysconfigures
  21941. go
  21942. if exists (select * from syskeys where type = 1 and id = object_id('sysdatabases'))
  21943.     execute sp_dropkey 'primary', sysdatabases
  21944. go
  21945. if exists (select * from syskeys where type = 1 and id = object_id('sysdepends'))
  21946.     execute sp_dropkey 'primary', sysdepends
  21947. go
  21948. if exists (select * from syskeys where type = 1 and id = object_id('sysdevices'))
  21949.     execute sp_dropkey 'primary', sysdevices
  21950. go
  21951. if exists (select * from syskeys where type = 1 and id = object_id('sysindexes'))
  21952.     execute sp_dropkey 'primary', sysindexes
  21953. go
  21954. if exists (select * from syskeys where type = 1 and id = object_id('syskeys'))
  21955.     execute sp_dropkey 'primary', syskeys
  21956. go
  21957. if exists (select * from syskeys where type = 1 and id = object_id('syslogins'))
  21958.     execute sp_dropkey 'primary', syslogins
  21959. go
  21960. if exists (select * from syskeys where type = 1 and id = object_id('sysmessages'))
  21961.     execute sp_dropkey 'primary', sysmessages
  21962. go
  21963. if exists (select * from syskeys where type = 1 and id = object_id('sysobjects'))
  21964.     execute sp_dropkey 'primary', sysobjects
  21965. go
  21966. if exists (select * from syskeys where type = 1 and id = object_id('sysprocedures'))
  21967.     execute sp_dropkey 'primary', sysprocedures
  21968. go
  21969. if exists (select * from syskeys where type = 1 and id = object_id('sysremotelogins'))
  21970.     execute sp_dropkey 'primary', sysremotelogins
  21971. go
  21972. if exists (select * from syskeys where type = 1 and id = object_id('sysprotects'))
  21973.     execute sp_dropkey 'primary', sysprotects
  21974. go
  21975. if exists (select * from syskeys where type = 1 and id = object_id('syssegments'))
  21976.     execute sp_dropkey 'primary', syssegments
  21977. go
  21978. if exists (select * from syskeys where type = 1 and id = object_id('sysservers'))
  21979.     execute sp_dropkey 'primary', sysservers
  21980. go
  21981. if exists (select * from syskeys where type = 1 and id = object_id('systypes'))
  21982.     execute sp_dropkey 'primary', systypes
  21983. go
  21984. if exists (select * from syskeys where type = 1 and id = object_id('sysusers'))
  21985.     execute sp_dropkey 'primary', sysusers
  21986. go
  21987. if exists (select * from syskeys where type = 1 and id = object_id('sysusages'))
  21988.     execute sp_dropkey 'primary', sysusages
  21989. go
  21990.  
  21991. print ''
  21992. print 'Granting privileges on system tables.'
  21993. go
  21994.  
  21995. grant select on spt_monitor to public --Created where ?!
  21996. go
  21997.  
  21998. grant select on sysalternates to public
  21999. grant select on syscharsets to public
  22000. grant select on syscolumns to public
  22001. grant select on syscomments to public
  22002. grant select on sysconfigures to public
  22003. grant select on syscurconfigs to public
  22004. grant select on sysdatabases to public
  22005. grant select on sysdepends to public
  22006. grant select on sysdevices to public
  22007. grant select on sysindexes to public
  22008. grant select on syskeys to public
  22009. grant select on syslanguages to public
  22010. grant select on syslocks to public
  22011. go
  22012. grant select on syslogins to public
  22013. revoke select (password) on syslogins from public
  22014. go
  22015. grant select on syslogs to public
  22016. grant select on sysmessages to public
  22017. grant select on sysobjects to public
  22018. grant select on sysprocedures to public
  22019. grant select on sysprocesses to public
  22020. grant select on sysprotects to public
  22021. grant select on sysremotelogins to public
  22022. grant select on syssegments to public
  22023. grant select on sysservers to public
  22024. grant select on systypes to public
  22025. grant select on sysusages to public
  22026. grant select on sysusers to public
  22027. go
  22028.  
  22029. print ''
  22030. print 'Granting privileges on system stored procedures'
  22031. go
  22032.  
  22033. grant execute on MS_sqlctrs_users to public
  22034. go
  22035.  
  22036. grant execute on sp_user_counter1   to probe
  22037. grant execute on sp_user_counter2   to probe
  22038. grant execute on sp_user_counter3   to probe
  22039. grant execute on sp_user_counter4   to probe
  22040. grant execute on sp_user_counter5   to probe
  22041. grant execute on sp_user_counter6   to probe
  22042. grant execute on sp_user_counter7   to probe
  22043. grant execute on sp_user_counter8   to probe
  22044. grant execute on sp_user_counter9   to probe
  22045. grant execute on sp_user_counter10  to probe
  22046. grant execute on sp_userdefcounters to probe
  22047. go
  22048.  
  22049. grant execute on sp_a_count_bits_on to public
  22050. grant execute on sp_abort_xact to public
  22051. grant execute on sp_addalias to public
  22052. grant execute on sp_addgroup to public
  22053. grant execute on sp_addmessage to public
  22054. grant execute on sp_addsegment to public
  22055. grant execute on sp_addtype to public
  22056. grant execute on sp_adduser to public
  22057. grant execute on sp_altermessage to public
  22058. grant execute on sp_bindefault to public
  22059. grant execute on sp_bindrule to public
  22060. grant execute on sp_change_configstatus to public
  22061. grant execute on sp_change_users_login to public
  22062. grant execute on sp_changegroup to public
  22063. grant execute on sp_checknames to public
  22064. grant execute on sp_coalesce_fragments to public
  22065. grant execute on sp_commit_xact to public
  22066. grant execute on sp_commonkey to public
  22067. grant execute on sp_configure to public
  22068. grant execute on sp_cursor to public
  22069. grant execute on sp_cursorclose to public
  22070. grant execute on sp_cursorfetch to public
  22071. grant execute on sp_cursoropen to public
  22072. grant execute on sp_cursoroption to public
  22073. grant execute on sp_dboption to public
  22074. grant execute on sp_bindsession to public
  22075. grant execute on sp_getbindtoken to public
  22076. go
  22077. grant execute on sp_defaultdb to public
  22078. grant execute on sp_defaultlanguage to public
  22079. grant execute on sp_depends to public
  22080. grant execute on sp_devoption to public
  22081. grant execute on sp_dropalias to public
  22082. grant execute on sp_dropgroup to public
  22083. grant execute on sp_dropkey to public
  22084. grant execute on sp_dropmessage to public
  22085. grant execute on sp_dropsegment to public
  22086. grant execute on sp_droptype to public
  22087. grant execute on sp_dropuser to public
  22088. grant execute on sp_extendsegment to public
  22089. go
  22090. grant execute on sp_help to public
  22091. grant execute on sp_help_setopts to public
  22092. grant execute on sp_help_revdatabase to public
  22093. grant execute on sp_helpconstraint to public
  22094. grant execute on sp_helpdb to public
  22095. grant execute on sp_helpdevice to public
  22096. grant execute on sp_helpextendedproc to public
  22097. grant execute on sp_foreignkey to public
  22098. grant execute on sp_helpgroup to public
  22099. grant execute on sp_helpindex to public
  22100. grant execute on sp_helpjoins to public
  22101. grant execute on sp_helpkey to public
  22102. grant execute on sp_helplanguage to public
  22103. grant execute on sp_helplog to public
  22104. grant execute on sp_helplogins to public
  22105. grant execute on sp_helpremotelogin to public
  22106. grant execute on sp_helprotect to public
  22107. grant execute on sp_helpsegment to public
  22108. grant execute on sp_helpserver to public
  22109. grant execute on sp_helpsort to public
  22110. grant execute on sp_helptext to public
  22111. grant execute on sp_helpuser to public
  22112. grant execute on sp_lock to public
  22113. grant execute on sp_lock2 to public
  22114. grant execute on sp_lockinfo to public
  22115. grant execute on sp_logdevice to public
  22116. grant execute on sp_lookup to public
  22117. grant execute on sp_markreport to public
  22118. grant execute on sp_namecrack to public
  22119. go
  22120. grant execute on sp_objectsegment to public
  22121. grant execute on sp_password to public
  22122. grant execute on sp_placeobject to public
  22123. grant execute on sp_primarykey to public
  22124. grant execute on sp_processinfo to public
  22125. grant execute on sp_probe_xact to public
  22126. grant execute on sp_recompile to public
  22127. grant execute on sp_remoteoption to public
  22128. grant execute on sp_remove_xact to public
  22129. grant execute on sp_rename to public
  22130. grant execute on sp_scan_xact to public
  22131. grant execute on sp_serveroption to public
  22132. grant execute on sp_spaceused to public
  22133. grant execute on sp_sqlexec to public
  22134. grant execute on sp_start_xact to public
  22135. grant execute on sp_stat_xact to public
  22136. go
  22137.  
  22138. grant execute on sp_blockcnt to probe
  22139. grant execute on sp_tempdbspace to probe  --Not designed for public use.
  22140. go
  22141.  
  22142. grant execute on sp_unbindefault to public
  22143. grant execute on sp_unbindrule to public
  22144. grant execute on sp_validname to public
  22145. grant execute on sp_validlang to public
  22146. grant execute on sp_who to public
  22147. grant execute on sp_who2 to public
  22148. grant execute on sp_xpoption to public
  22149. go
  22150.  
  22151. print ''
  22152. print 'Granting privileges on extended stored procedures'
  22153. go
  22154.  
  22155. grant execute on xp_regread to probe  --Not documented, so not to public.
  22156. go
  22157.  
  22158. grant execute on xp_sprintf to public
  22159. grant execute on xp_sscanf to public
  22160. grant execute on xp_unc_to_drive to public
  22161. grant execute on xp_msver to public
  22162. go
  22163.  
  22164. print ''
  22165. print 'Granting privileges on objects in model database.'
  22166. go
  22167. use model
  22168. go
  22169. grant select on sysalternates to public
  22170. grant select on syscolumns to public
  22171. grant select on syscomments to public
  22172. grant select on sysconstraints to public
  22173. grant select on sysdepends to public
  22174. grant select on sysindexes to public
  22175. grant select on syskeys to public
  22176. grant select on sysobjects to public
  22177. grant select on sysprocedures to public
  22178. grant select on sysprotects to public
  22179. grant select on syssegments to public
  22180. grant select on systypes to public
  22181. grant select on sysusers to public
  22182. grant select on syslogs to public
  22183. go
  22184.  
  22185. use master
  22186. go
  22187.  
  22188. /*
  22189. ** Grant privileges on SQL 6.0 system tables that exist in all databases.
  22190. */
  22191.  
  22192. declare @dbname sysname
  22193. declare db_name_cursor cursor for select name from sysdatabases
  22194. open db_name_cursor
  22195. fetch db_name_cursor into @dbname
  22196.  
  22197. while @@fetch_status >= 0
  22198.     begin
  22199.  
  22200.     exec ('use ' + @dbname
  22201.         + ' grant select on sysarticles      to public'
  22202.         + ' grant select on sysconstraints   to public'
  22203.         + ' grant select on syspublications  to public'
  22204.         + ' grant select on sysreferences    to public'
  22205.         + ' grant select on syssubscriptions to public'
  22206.          )
  22207.  
  22208.     fetch db_name_cursor into @dbname
  22209.  
  22210.     end
  22211.  
  22212. deallocate db_name_cursor
  22213. go
  22214.  
  22215.  
  22216. use master
  22217. go
  22218.  
  22219. /*
  22220. ** Set some things now that sp_configure has been created.
  22221. */
  22222. go
  22223. print ''
  22224. print 'Making final database configuration settings.'
  22225. go
  22226.  
  22227. /********  sdf
  22228.  
  22229. raiserror('
  22230. If this is a new install, shrink size of model db (helps floppy RemovableMedia).
  22231. ',1,1)
  22232. --go
  22233.  
  22234. ********/
  22235.  
  22236. declare @i varchar(255)
  22237.  
  22238. exec master..xp_regread 'HKEY_LOCAL_MACHINE',
  22239.      'SOFTWARE\Microsoft\MSSQLServer\Setup', 'SetupStatus',
  22240.       @i out
  22241.  
  22242. print ''
  22243.  
  22244. if isnull(lower(@i),'null') not in ('upgrade','installed')    -- That key will only exist during an upgrade.
  22245.     begin -- NewInstall
  22246.         select 'Will leave database size config=111 alone at',value from sysconfigures where config=111
  22247.  
  22248. --        print 'Setting default database size to 1 Meg.'
  22249. --        exec sp_configure 'database size',1
  22250.     end
  22251. else
  22252.         begin
  22253.             select 'Re-Initializing free buffer setting, from....',value from sysconfigures where config=1515
  22254.             update sysconfigures set value =
  22255.                 (select value/20 from sysconfigures
  22256.                     where config = 104)
  22257.                 where config = 1515
  22258.         end
  22259. go
  22260. print 'Forcing config for remote access to 1'
  22261. exec sp_configure 'remote access',1
  22262. go
  22263.  
  22264. sp_configure 'allow updates',0
  22265. go
  22266. sp_dboption 'master','trunc. log on chkpt.','true'
  22267. go
  22268. reconfigure with override
  22269. go
  22270.  
  22271. print ''
  22272. print 'Checking objects created by ProcSyst.SQL ....'
  22273. go
  22274.  
  22275. exec sp_check_objects 'general' --Perhaps rename ?!
  22276. go
  22277.  
  22278. declare @vdt varchar(99)
  22279. select  @vdt = convert(varchar,getdate(),113)
  22280. raiserror('
  22281. Finishing Install\ProcSyst.SQL at  %s',1,1,@vdt)
  22282. go
  22283.  
  22284. dump tran master with no_log
  22285. go
  22286. checkpoint
  22287. go
  22288. -- -
  22289.