home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / databases / sybase-faq / part18 < prev    next >
Encoding:
Text File  |  2004-04-21  |  134.3 KB  |  3,944 lines

  1. Path: senator-bedfellow.mit.edu!dreaderd!not-for-mail
  2. Message-ID: <databases/sybase-faq/part18_1082468590@rtfm.mit.edu>
  3. Supersedes: <databases/sybase-faq/part18_1074677126@rtfm.mit.edu>
  4. Expires: 2 Aug 2004 13:43:10 GMT
  5. References: <databases/sybase-faq/part1_1082468590@rtfm.mit.edu>
  6. X-Last-Updated: 2003/03/02
  7. From: dowen@midsomer.org (David Owen)
  8. Newsgroups: comp.databases.sybase,comp.answers,news.answers
  9. Subject: Sybase FAQ: 18/19 - ASE Section 9 (3 of 3)
  10. Reply-To: dowen@midsomer.org (David Owen)
  11. Followup-To: comp.databases.sybase
  12. Distribution: world
  13. Organization: Midsomer Consultants Inc.
  14. Approved: news-answers-request@MIT.EDU
  15. Keywords: FAQ, DATABASES, SYBASE, ASA, ASE, REP
  16. Originator: faqserv@penguin-lust.MIT.EDU
  17. Date: 20 Apr 2004 13:45:17 GMT
  18. Lines: 3921
  19. NNTP-Posting-Host: penguin-lust.mit.edu
  20. X-Trace: 1082468717 senator-bedfellow.mit.edu 559 18.181.0.29
  21. Xref: senator-bedfellow.mit.edu comp.databases.sybase:106216 comp.answers:56962 news.answers:270302
  22.  
  23. Archive-name: databases/sybase-faq/part18
  24. URL: http://www.isug.com/Sybase_FAQ
  25. Version: 1.7
  26. Maintainer: David Owen
  27. Last-modified: 2003/03/02
  28. Posting-Frequency: posted every 3rd month
  29.    A how-to-find-the-FAQ article is posted on the intervening months.
  30.  
  31. #!/usr/bin/perl
  32.  
  33. # Author:  Vincent Yin  (umyin@mctrf.mb.ca)   Aug 1994    Last Modified: May 1996
  34.  
  35. chomp($basename = `basename $0`);
  36.  
  37. $usage = <<EOF;
  38. USAGE
  39.     $basename database userid passwd pattern [ pattern... ]
  40.  
  41. DESCRIPTION
  42.     Prints isql scripts that would insert records into the
  43.     tables whose names match any of the patterns in command line.  In
  44.     other words, this program reverse engineers the data in a given
  45.     table(s).  Roughly, it `select * from <table>', analyses the data
  46.     and table structure, then prints out a bunch of
  47.             insert <table> values ( ... )
  48.     statements that would re-populate the table.  It's an alternative
  49.     to `bcp'.  `bcp' has its limitations (e.g. one often needs to turn on
  50.     "select into/bulk copy" option in the database before running bcp.)
  51.  
  52.     Table names are matched to <pattern> with Transact-SQL's LIKE clause.
  53.     When more than one pattern is specified on command line, the LIKE
  54.     clauses are OR'ed.  In any case, the LIKE clause(s) is logged to
  55.     the beginning of the output as a comment, so that you'll see how this
  56.     program interprets the command line.
  57.  
  58.     The SQL script is printed to stdout.  Since it only prints out the SQL
  59.     but doesn't submit it to the SQL server, this procedure is safe to run.
  60.     It doesn't modify database in any way.
  61.  
  62. EXAMPLES
  63.     To print this usage page:
  64.             % $basename
  65.     To print SQL that populates the table master..sysobjects and systypes:
  66.             % $basename master userid passwd "sysobjects" "systypes"
  67.     To print SQL that populates all system tables in master db:
  68.             % $basename master userid passwd "sys%"
  69.  
  70. BUGS
  71.     Embedded line breaks in strings are allowed in Sybase's isql, but not
  72.     allowed in SQLAnywhere's isql.  So this script converts embedded line
  73.     breaks (both DOS styled and UNIX styled) to blank characters.
  74.  
  75. EOF
  76.  
  77. $batchsize = 10;        # The number of INSERTs before a `go' is issued.
  78.                         # This is to make the output compact.
  79.  
  80. # .................... No change needed below this line ........................
  81.  
  82. use Sybase::DBlib;
  83.  
  84. die $usage unless $#ARGV >= 3;
  85. ($db, $user, $passwd, @pattern) = @ARGV;
  86.  
  87. $likeclause = &sql_pattern_to_like_clause("name", @pattern);
  88.  
  89. print <<EOF;
  90. -- This script is created by $0.
  91. -- It would generate INSERT statements for tables whose names match the
  92. -- following pattern:
  93. /* $likeclause
  94. */
  95.  
  96. set nocount on
  97. go
  98. EOF
  99.  
  100. $dbh = new Sybase::DBlib $user, $passwd;
  101. $dbh->{dbNullIsUndef} = 1;
  102. $dbh->dbuse($db);
  103.  
  104.     # Get the list of tables.
  105. $tablelist = $dbh->sql("select name
  106.                           from sysobjects
  107.                          where type in (\'S\',\'U\')
  108.                            and $likeclause
  109.                          order by name
  110.                   ");
  111.  
  112. foreach $tableref (@$tablelist) {
  113.   $table = @$tableref[0];
  114.   print "\n\n/*.............. $table ...............*/\n";
  115.   print "-- ", `date`, "\n";
  116.   print "declare \@d datetime\n";
  117.   print "select \@d = getdate()\n";
  118.   print "print        '       %1!    $table', \@d\ngo\n\n";
  119.   print "truncate table $table  -- Lookout !!!!!!\ngo\n\n";
  120.  
  121.   $dbh->dbcmd("select * from $table");
  122.   $dbh->dbsqlexec;
  123.   $dbh->dbresults;
  124.  
  125.   while (@row = $dbh->dbnextrow()) {
  126.     print "insert $table values(";
  127.  
  128.     for ($i=0; $i <= $#row; $i++) { # build the INSERT statement
  129.       # Analyse datatype to decide if this column needs to be quoted.
  130.       $coltype = $dbh->dbcoltype($i+1);
  131.  
  132.       if (!defined($row[$i])) {
  133.         print "NULL";    # Never quote NULL regardless of datatype
  134.       }
  135.       elsif ($coltype==35 or $coltype==39 or $coltype==47 or
  136.              $coltype==58 or $coltype==61 or $coltype==111 ){
  137.         # See systypes.type/name for explanation of $coltype.
  138.         $row[$i] =~ s/\r|\n/ /g; # Handles both DOS and UNIX line breaks
  139.         $row[$i] =~ s/\'/\'\'/g;    # Stuff double quotes
  140.         print '\'' . $row[$i] . '\'';
  141.       } else {
  142.         print $row[$i];
  143.       }
  144.       print ", " unless $i == $#row;
  145.     }
  146.  
  147.     print ")\n";            # wrap up the INSERT statement.
  148.                               # print `go' at every $batchsize interval.
  149.     print "go\n" unless $dbh->DBCURROW % $batchsize;
  150.   }
  151.   print "\ngo\n\n";           # print a `go' after the entire table is done.
  152.   print "-- ### End for $table:  rowcount = ", $dbh->DBCURROW, "\n";
  153. }
  154.  
  155. # ................................. sub ........................................
  156. sub sql_pattern_to_like_clause {
  157.   local($field_name, @pattern) = @_;
  158.   $like_clause = "\t(  1 = 0 ";
  159.   foreach (@pattern) {
  160.     $like_clause .= "\n     or $field_name like '" . $_ . "' ";
  161.   }
  162.   $like_clause .= "\n\t) \n";
  163. }
  164. #!/bin/sh
  165. #-*-sh-*-
  166. # Code for question 9.3: Generating dump/load database command.
  167. #
  168. # This script calls the function gen_dumpload_command to generate
  169. # either a dump or a load command.
  170. #
  171. # This function works for both System 10 and Sybase 4.x
  172. # installations.  You simply need to change your method of thinking.
  173. # In Sybase 4.x, we only had a single stripe.  In System 10, most
  174. # of the time we define a single stripe but in our bigger databases
  175. # we define more stripes.
  176. #
  177. # Therefore, everything is a stripe.  Whether we use one stripe or
  178. # many... cool?  Right on!
  179. #
  180. #
  181. # The function gen_dumpload_command assumes that all dump devices
  182. # adhere to the following naming convention:
  183. #
  184. #     stripe_NN_database
  185. #
  186. # NOTE:  If your shop is different search for "stripe" and replace
  187. #        with your shop's value.
  188. #
  189. #
  190.  
  191.  
  192. # gen_dumpload_command():
  193. #
  194. #        purpose:  to generate a dump/load to/from command based on
  195. #                  what is defined in sysdevices.  The environment
  196. #                  variable D_DEV is set.
  197. #
  198. #        return:   zero on success, non-zero on failure.
  199. #
  200. #        sets var: D_DEV is set with the actual dump/load command;
  201. #                  stripe devices are also handled.
  202. #
  203. #        calls:    *none*
  204. #
  205. #        parms:    1 = DSQUERY
  206. #                  2 = PASSWD
  207. #                  3 = DB
  208. #                  4 = CMD -> "dump" or "load"
  209. #
  210.  
  211.  
  212. gen_dumpload_command()
  213. {
  214.    LOCAL_DSQUERY=$1
  215.    LOCAL_PASSWD=$2
  216.    DB_TO_AFFECT=$3
  217.    CMD=$4 # dump/load
  218.  
  219.    if [ "$CMD" = "dump" ] ; then
  220.       VIA="to"
  221.    else
  222.       VIA="from"
  223.    fi
  224.  
  225.    # Check for a dump device
  226.  
  227.    echo "Checking for standard $CMD device"
  228.     #   D_DEV=`echo "$LOCAL_PASSWD
  229. $SYBIN/isql -U sa -S $LOCAL_DSQUERY -w1000 | sed -n -e '/stripe/p' | \
  230. select name from sysdevices where name like \"stripe%_$DB_TO_AFFECT\"
  231. go"
  232. EOSQL
  233.       gawk '{ if (NR == 1) print "'$CMD' database '$DB_TO_AFFECT' '$VIA'", $0
  234.                          else print "stripe on", $0
  235.                          }'`
  236.  
  237.    if [ -z "$D_DEV" ] ; then # nothing defined... :(
  238.       return 1
  239.    fi
  240.  
  241.    return 0
  242. }
  243.  
  244. SYBIN=$SYBASE/bin
  245.  
  246. gen_dumpload_command $1 $2 $3 $4
  247.  
  248. if [ $? -eq 1 ] ; then
  249.    echo "Error..."
  250.    exit 1
  251. fi
  252.  
  253. # so what does this generate?  :-)
  254. echo $D_DEV
  255.  
  256. # ... and it can be used as follows:
  257.  
  258. echo "$PASSWD
  259. $D_DEV
  260. go" | isql ...
  261.  
  262. exit 0
  263. #!/usr/bin/perl
  264.  
  265. # $Id: int.pl,v 1.4 1995/11/04 03:16:38 mm Exp mm $
  266.  
  267. # convert a sun4 interfaces file to a different format (see @modelist)
  268. # limitations:
  269. # - does not handle tli/spx entries (yet)
  270. # - drivers for desktop platform hard coded
  271. # - no sanity checks (duplicate names, incomplete entries)
  272. # - ignores extraneous tokens silently (e.g. a 6th field)
  273. # - don't know whether/how to convert decnet to tli format
  274. # - ???
  275.  
  276. require 'getopts.pl';
  277.  
  278. sub usage
  279. {
  280.         local(@token) = @_;
  281.  
  282.         if (!($token[0] eq 'short' || $token[0] eq 'long'))
  283.         {
  284.                 printf STDERR "Environment variable(s) @token not defined.\n";
  285.                 exit (1);
  286.         }
  287.  
  288.         print STDERR <<EOM;
  289. Usage:  $progname  -f <sun4 interfaces file>
  290.                 -o { $modetext1 }
  291.                 [-V] [-v] [-h]
  292. EOM
  293.  
  294.         if ($token[0] eq 'long')
  295.         {
  296.                 print STDERR <<EOM;
  297. where
  298.         -f <file> input file to process
  299.         -o <mode> specify output mode
  300.                   (e.g. $modetext2)
  301.         -V        turn on verbose mode
  302.         -v        print version string
  303.         -h        print this message
  304. EOM
  305.         }
  306.         else
  307.         {
  308.                 print STDERR "For more details run $progname -h\n";
  309.         }
  310.         exit(1);
  311. } # end of usage
  312.  
  313.  
  314. # FUNCTION NAME:     parse_command_line
  315. # DESCRIPTION:       call getopts and assign command line arguments or
  316. #                    default values to global variables
  317. # FORMAL PARAMETERS: none
  318. # IMPLICIT INPUTS:   command line arguments
  319. # IMPLICIT OUTPUTS:  $inputfile, $mode, $verbose
  320. # RETURN VALUE:      none, exits (in usage) if -h was specified
  321. #                    (help option).
  322. # SIDE EFFECTS:      none
  323. #
  324. sub parse_command_line {
  325.         &Getopts('f:o:hvV') || &usage('short');
  326.         $inputfile = $opt_f;
  327.         $mode = $opt_o;
  328.         $verbose = $opt_V ? 1 : 0;
  329.  
  330.         print("$progname version is: $version\n"), exit 0 if $opt_v;
  331.         &usage('long') if $opt_h;
  332.         &usage('short') if ! $inputfile || ! $mode;
  333.         &usage('short') if ! grep($mode eq $_, @modelist);
  334. } # end of parse_command_line
  335.  
  336. # FUNCTION NAME:     process_file
  337. # DESCRIPTION:       parse file, try to convert it line by line.
  338. # FORMAL PARAMETERS: $file - file to process
  339. # IMPLICIT INPUTS:   none
  340. # IMPLICIT OUTPUTS:  none
  341. # RETURN VALUE:      none
  342. # SIDE EFFECTS:      none
  343.  
  344. sub process_file {
  345.         local($file) = @_;
  346.         open(INPUT, "<$file") ||
  347.                 die "can't open file $file: $!\nExit.";
  348.         local($line) = 0;
  349.         local($type, $prot, $stuff, $host, $port, $tmp);
  350.         print $os2_header if $mode eq 'os2';
  351.         while (<INPUT>)
  352.         {
  353.                 $line++;
  354.                 # handle empty lines (actually lines with spaces and tabs only)
  355.                 #print('\n'), next if /^\s*$/;
  356.                 next if /^\s*$/;
  357.                 chop;
  358.                 # comments, strip leading spaces and tabs
  359.                 s/^\s*//, print("$_$lf{$mode}\n"), next if /^\s*#/;
  360.                 #s/^\s*//, next if /^\s*#/;
  361.  
  362.                 # server names
  363.                 if (/^\w+/)
  364.                 {
  365.                         if ($mode eq 'sol' || $mode eq 'ncr'
  366.                                 || $mode eq 'vms' || $mode eq 'nw386')
  367.                         {
  368.                                 print "$_$lf{$mode}\n";
  369.                                 next;
  370.                         }
  371.                         elsif ($mode eq 'os2')
  372.                         {
  373.                                 $server = $_;
  374.                                 next;
  375.                         }
  376.                         else {
  377.                                 print "[$_]$lf{$mode}\n" if !(/SPX$/);
  378.                                 next;
  379.                         }
  380.                 }
  381.  
  382.                 if (/^\tmaster|^\tquery|\tconsole/)
  383.                 {
  384.                         # descriptions
  385.                         # parse first whitespace delimited word and
  386.                         # following space(s)
  387.                         # quietly ignore any extraerraneous characters
  388.                         # I actually tried to catch them, but - believe
  389.                         # it or not - perl would chop off the last digit of
  390.                         # $port.                                   vvvv
  391.                         # /^\t(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)(.+)$/;
  392.                         if (!(($type, $prot, $stuff, $host, $port) =
  393.                                 /^\t(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/))
  394.                         {
  395.                                 print STDERR "line $line: unknown format: $_";
  396.                                 next;
  397.                         }
  398.                         #print ("line $line: more than 5 tokens >$etc<, \n"),
  399.                         #       next if $etc;
  400.                         if (!($type eq 'master' || $type eq 'query'
  401.                                 || $type eq 'console'))
  402.                         {
  403.                                 # unknown type
  404.                                 print STDERR "line $line: unknown type $type\n";
  405.                                 next;
  406.                         }
  407.                         if ($prot eq 'tli')
  408.                         {
  409.                                 #print STDERR "line $line: can't handle tli",
  410.                                 #       " entries (yet)\n";
  411.                                 # adjust to tli format
  412.                                 ($layer, $prot, $device, $entry) =
  413.                                         ($prot, $stuff, $host, $port);
  414.                                 print "\t$type tli $prot $device ",
  415.                                         "$entry$lf{$mode}\n" if $mode ne 'win3';
  416.                                 next;
  417.                         }
  418.                         if (!($prot eq 'tcp' || $prot eq 'decnet'))
  419.                         {
  420.                                 # unknown protocol
  421.                                 print STDERR
  422.                                         "line $line: unknown protocol $prot\n";
  423.                                 next;
  424.                         }
  425.                         if ($mode eq 'sol' || $mode eq 'ncr' || $mode eq 'nw386')
  426.                         {
  427.                                 $ip = &get_ip_address($host, 'hex');
  428.                                 $hexport = sprintf("%4.4x", $port);
  429.                                 print "\t$type tli $prot $device{$prot} \\x",
  430.                                 "$prefix{$mode}$hexport$ip$nulls{$mode}\n";
  431.                                 next;
  432.                         }
  433.                         if ($mode eq 'vms')
  434.                         {
  435.                                 $ip = &get_ip_address($host, 'dot');
  436.                                 print "\t$type $prot $stuff $ip $port\n";
  437.                                 next;
  438.                         }
  439.                         if ($mode eq 'nt386')
  440.                         {
  441.                                 $type =~ tr/a-z/A-Z/;
  442.                                 print "\t$type=$sock{$mode},$host,",
  443.                                         "$port$lf{$mode}\n";
  444.                                 next;
  445.                         }
  446.                         if ($mode eq 'dos' || $mode eq 'win3')
  447.                         {
  448.                                 next if $type ne 'query';
  449.                                 print "\t${mode}_$type=$sock{$mode},",
  450.                                         "$host,$port$lf{$mode}\n";
  451.                                 next;
  452.                         }
  453.                         if ($mode eq 'ntdoswin3')
  454.                         {
  455.                                 ($tmp = $type) =~ tr/a-z/A-Z/;
  456.                                 # watch out for this local($mode) !!
  457.                                 # its scope is this BLOCK only and
  458.                                 # (within this block) overrides the
  459.                                 # other $mode!!! But we can still access
  460.                                 # the array %sock.
  461.                                 local($mode) = 'nt386';
  462.                                 print "\t$tmp=$sock{$mode},$host,$port",
  463.                                         "$lf{$mode}\n";
  464.                                 next if $type ne 'query';
  465.                                 $mode = 'dos';
  466.                                 print "\t${mode}_$type=$sock{$mode},",
  467.                                         "$host,$port$lf{$mode}\n";
  468.                                 $mode = 'win3';
  469.                                 print "\t${mode}_$type=$sock{$mode},",
  470.                                         "$host,$port$lf{$mode}\n";
  471.                                 next;
  472.                         }
  473.                         if ($mode eq 'os2')
  474.                         {
  475.                           print "  \'$server\' \'$type\' \'$sock{'os2'}",",$host,$port\'\n";
  476.                           next;
  477.                         }
  478.                 }
  479.                 printf STDERR "line $line is ->%s<-\n", chop($_);
  480.         }
  481.         close(INPUT);
  482.         print $os2_tail if $mode eq 'os2';
  483.  
  484. } # end of process_file
  485.  
  486. # FUNCTION NAME:     print_array
  487. # DESCRIPTION:       print the array
  488. # FORMAL PARAMETERS: *array - array to be printed, passed by reference
  489. # IMPLICIT INPUTS:   none
  490. # IMPLICIT OUTPUTS:  none
  491. # RETURN VALUE:      none
  492. # SIDE EFFECTS:      none
  493. #
  494. sub print_array {
  495.         local(*array) = @_;
  496.         foreach (sort keys %array)
  497.         {
  498.                 printf STDERR "%-16s %s\n", $_, $array{$_};
  499.         }
  500.  
  501. } # end of print_array
  502.  
  503. # FUNCTION NAME:     get_ip_address
  504. # DESCRIPTION:       get the ip address of a host specified by name, return
  505. #                    it as a string in the requested format, e.g.
  506. #                    requested format == 'dot' --> return 130.214.140.2
  507. #                    requested format == 'hex' --> return 82d68c02
  508. #                    In order to avoid repeated calls of gethostbyname with
  509. #                    the same host, store (formatted) results of gethostbyname
  510. #                    in array %map.
  511. # FORMAL PARAMETERS: name of host, requested return type: hex or dot format
  512. # IMPLICIT INPUTS:   %map
  513. # IMPLICIT OUTPUTS:  none
  514. # RETURN VALUE:      ip address
  515. # SIDE EFFECTS:      maintains %map, key is host name, value is ip address.
  516. #
  517. sub get_ip_address {
  518.         local($host, $mode) = @_;
  519.         if (!$map{$host})
  520.         {
  521.                 #print "calling gethostbyname for $host";
  522.                 ($name, $aliases, $addrtype, $length, @addrs) =
  523.                         gethostbyname($host);
  524.                 $map{$host} = join('.', unpack('C4', $addrs[0]));
  525.                 if ($mode eq 'hex')
  526.                 {
  527.                         $map{$host} = sprintf("%2.2x%2.2x%2.2x%2.2x",
  528.                                         split(/\./, $map{$host}));
  529.                 }
  530.                 #print " - $map{$host}\n";
  531.         }
  532.         return $map{$host};
  533. } # end of get_ip_address
  534.  
  535.  
  536. $version = "\$Id: int.pl,v 1.4 1995/11/04 03:16:38 mm Exp mm \$";
  537. $| = 1;
  538. ($progname = $0) =~ s#.*/##g;
  539. @modelist = ('sol', 'ncr', 'vms', 'nw386', 'os2',
  540.                  'nt386', 'win3', 'dos', 'ntdoswin3');
  541. $modetext1 = join('|', @modelist);
  542. $modetext2 = join(', ', @modelist);
  543.  
  544. # tli on solaris needs more zeroes
  545. $nulls{'sol'} = "0000000000000000";
  546. $nulls{'nw386'} = "0000000000000000";
  547. $nulls{'ncr'} = "";
  548. $nulls{'nt386'} = "";
  549.  
  550. # prefix for tli entries
  551. $prefix{'sol'} = "0002";
  552. $prefix{'nw386'} = "0200";
  553. $prefix{'ncr'} = "0002";
  554. $prefix{'nt386'} = "0200";
  555.  
  556. # protocol devices
  557. $device{'tcp'} = "/dev/tcp";
  558. $device{'spx'} = "/dev/nspx";
  559. $device{'decnet'} = "/dev/tcp";
  560.  
  561. # socket driver names
  562. $sock{'nt386'}="NLWNSCK";
  563. $sock{'dos'}="NLFTPTCP";
  564. $sock{'win3'}="WNLWNSCK";
  565. $sock{'os2'}="nlibmtcp";
  566.  
  567. # linefeed's (^M) for the MS world
  568. $lf{'nt386'}="
  569. ";
  570. $lf{'dos'}="
  571. ";
  572. $lf{'win3'}="
  573. ";
  574. $lf{'ntdoswin3'}="
  575. ";
  576. $lf{'os2'}="";
  577. $lf{'vms'}="";
  578. $lf{'sol'}="";
  579. $lf{'ncr'}="";
  580. $lf{'nw386'}="";
  581.  
  582. $os2_header = sprintf("STRINGTABLE\nBEGIN\n%s", "  \'\'\n" x 10);
  583. $os2_tail = "END\n";
  584.  
  585. &parse_command_line;
  586. &process_file($inputfile);
  587. &print_array(*map) if $verbose;
  588. #!/usr/bin/perl -w
  589.  
  590. use Getopt::Std;
  591. use strict;
  592. use English;
  593.  
  594. my($fullRow, @processStats, $owner, $pid, $parentPid);
  595. my($started, $engineNum, %engine);
  596. my($cpuTime, $servType, $param, $servParam, @dirComps);
  597. my(@engineParts, %stypes, @procParts);
  598. my($serverName, %server, $srvType, $engine);
  599. my($cmd);
  600.  
  601. # (Empirically) I have found with large numbers of engines, that not
  602. # all of the child parent relationships are as you imagine, ie engine
  603. # 0 does not start off all other engines.  "-l" indents to show this
  604. # heirarchy.
  605.  
  606. getopts('l');
  607.  
  608. # Script to show, in a nice fashion, all of the Sybase servers on a
  609. # system.
  610.  
  611. $cmd = "ps -ef -o user,pid,ppid,start,comm";
  612.  
  613. SWITCH:
  614.     for ($OSNAME) {
  615.  
  616.         /AIX|OSF1/  && do {
  617.             $cmd = "ps auwwx";
  618.             last SWITCH;
  619.         };
  620.  
  621.         /freebsd/   && do {
  622.             $cmd = "ps ps awwxo user,pid,ppid,start,command";
  623.             last SWITCH;
  624.         };
  625.  
  626.         /linux/     && do {
  627.             $cmd = "ps -awxo user,pid,ppid,stime,command";
  628.             last SWITCH;
  629.         };
  630.  
  631.         /solaris/   && do {
  632.             $cmd = "ps -ef -o user,pid,ppid,stime,args";
  633.             last SWITCH;
  634.         };
  635.     }
  636.  
  637.  
  638. open(PSCMD, "$cmd |") or die("Cannot fork: $!");
  639.  
  640. while (<PSCMD>) {
  641.     next if !/dataserver|backupserver|repserver|rsmsrvr|monserver/;
  642.  
  643.     # Remove any white space after the -[sS] command.
  644.  
  645.     s/(-[sS])[\s\s*]/$1/;
  646.  
  647.     # Remove leading space.
  648.  
  649.     s/^  *//;
  650.  
  651.     $fullRow      = $_;
  652.     @processStats = split(/\s+/);
  653.  
  654.     $owner     = shift(@processStats);
  655.     $pid       = shift(@processStats);
  656.     $parentPid = shift(@processStats);
  657.     $started   = shift(@processStats);
  658.  
  659. #    $cpuTime     = shift(@processStats);
  660.  
  661.     $cpuTime = 999;
  662.  
  663.     # Is it a parent or a child?
  664.  
  665.     if ($fullRow =~ /-ONLINE:/) {
  666.         # Child!
  667.         @procParts = split(/[:]/, $processStats[1]);
  668.         @engineParts = split(/[,]/, $procParts[1]);
  669.         $engineNum   = $engineParts[0];
  670.         push(@{ $engine{$parentPid} }, [ $pid, $engineNum, $cpuTime ]);
  671.     } else {
  672.  
  673.         $servParam = shift(@processStats);
  674.         @dirComps = split(/\//, $servParam);
  675.         $servType = pop(@dirComps);
  676.  
  677.       PROCSTAT:
  678.         foreach $param (@processStats) {
  679.             if ($param =~ /^-[sS]/) {
  680.                 $serverName = substr($param, 2);
  681.                 last PROCSTAT;
  682.             }
  683.         }
  684.         $server{$pid} = [ $serverName, $owner, $started ];
  685.         push(@{ $stypes{$servType} }, $pid);
  686.         push(@{ $engine{$pid} }, [ $pid, 0, $cpuTime ]);
  687.     }
  688. }
  689.  
  690. close(PSCMD);
  691.  
  692. foreach $srvType (keys(%stypes)) {
  693.     print "\n$srvType\'s\n";
  694.     print "-" x (length($srvType) + 2);
  695.  
  696.  
  697.     foreach $pid (@{ $stypes{$srvType} }) {
  698.         print "\n  $server{$pid}[0] Owner: $server{$pid}[1], Started: $server{$pid}[2]";
  699.  
  700.         printEngines($pid, 0);
  701.     }
  702.     print "\n";
  703. }
  704.  
  705. print "\n";
  706. $Getopt::Std::opt_l = 0;
  707.  
  708. sub printEngines {
  709.  
  710.     my($pid)   = shift;
  711.     my($level) = shift;
  712.  
  713.     if (defined($engine{$pid})) {
  714.         foreach $engine (@{ $engine{$pid} }) {
  715.             print  "\n      ";
  716.  
  717.             print "  " x $level if defined($Getopt::Std::opt_l);
  718.  
  719.             printf "Engine: %2.2s (PID: %s)", @$engine[1], @$engine[0];
  720.  
  721.             if (@$engine[0] ne $pid) {
  722.                 printEngines(@$engine[0], $level + 1);
  723.             }
  724.         }
  725.     }
  726. }
  727.  
  728.  
  729. use sybsystemprocs
  730. go
  731.  
  732. CREATE PROCEDURE sp__create_crosstab
  733.         ,@code_table    varchar(30)     -- table containing code lookup rows
  734.         ,@code_key_col  varchar(30)     -- name of code/lookup ID column
  735.         ,@code_desc_col varchar(30)     -- name of code/lookup descriptive text column
  736.         ,@value_table   varchar(30)     -- name of table containing detail rows
  737.         ,@value_col     varchar(30)     -- name of value column in detail table
  738.         ,@value_group_by varchar(30)    -- value table column to group by.
  739.         ,@value_aggregate varchar(5)    -- operator to apply to value being aggregated
  740.  
  741. AS
  742. /*
  743. Copyright (c) 1997, Clayton Groom. All rights reserved.
  744. Procedure to generate a cross tab query script
  745. Reqires:
  746.         1. A lookup table with a code/id column and/or descriptive text column
  747.         2. A data table with a foreign key from the lookup table & a data value to aggregate
  748.         3. column(s) name from data table to group by
  749.         4. Name of an aggregate function to perform on the data value column.
  750. */
  751.  
  752. set nocount on
  753.  
  754. if sign(charindex(upper(@value_aggregate), 'MAX MIN AVG SUM COUNT')) = 0
  755. BEGIN
  756.         print "@value_aggregate value is not a valid aggregate function"
  757.         -- return -1
  758. END
  759.  
  760. declare @value_col_type         varchar(12)     -- find out data type for aggregated column.
  761.         ,@value_col_len         int             -- get length of the value column
  762.         ,@str_eval_char         varchar(255)
  763.         ,@str_eval_int          varchar(255)
  764. -- constants
  765.         ,@IS_CHAR               varchar(100)    -- character data types
  766.         ,@IS_NOT_ALLOWED        varchar(100)    -- data types not allowed
  767.         ,@IS_NUMERIC            varchar(255)    -- numeric data type names
  768.         ,@NL                    char(2)         -- new line
  769.         ,@QUOTE                 char(1)         -- ascii character 34 '"'
  770. --test variables
  771.         ,@value_col_is_char     tinyint         -- 1 = string data type, 0 = numeric or not allowed
  772.         ,@value_col_is_ok       tinyint         -- 1 = string or numeric type, 0 = type cannot be used.
  773.         ,@value_col_is_num      tinyint         -- 1 = numeric data type, 0 = string or not allowed
  774.  
  775. select   @IS_CHAR       = 'varchar char nchar nvarchar text sysname'
  776.         ,@IS_NOT_ALLOWED= 'binary bit varbinary smalldatetime datetime datetimn image timestamp'
  777.         ,@IS_NUMERIC    = 'decimal decimaln float floatn int intn money moneyn numeric numericn real smallint smallmoney tinyint'
  778.         ,@NL            = char(13) + char(10)
  779.         ,@QUOTE         = '"'   -- ascii 34
  780.  
  781. -- get the base data type & length of the value column. Is it a numeric type or a string type?
  782. -- need to know this to use string or numeric functions in the generated select statement.
  783. select  @value_col_type = st.name
  784.         ,@value_col_len = sc.length
  785.                         from syscolumns sc
  786.                                 ,systypes st
  787.                         where   sc.id = object_id(@value_table)
  788.                         and     sc.name = @value_col
  789.                         and     sc.type = st.type
  790.                         and     st.usertype = (select min(usertype)
  791.                                                 from systypes st2
  792.                                                 where st2.type = sc.type)
  793. --select @value_col_type, @value_col_len
  794.  
  795. select @value_col_is_char = sign(charindex( @value_col_type, @IS_CHAR))
  796.         ,@value_col_is_ok = 1 - sign(charindex( @value_col_type, @IS_NOT_ALLOWED))
  797.         ,@value_col_is_num = sign(charindex( @value_col_type, @IS_NUMERIC))
  798.  
  799. IF @value_col_is_ok = 1
  800. BEGIN
  801.         if @value_col_is_char = 1
  802.         begin
  803.                 select @str_eval_char = ''
  804.         end
  805.         else
  806.         if @value_col_is_num = 1
  807.         begin
  808.                 select @str_eval_char = ''
  809.         end
  810.         else
  811.         begin
  812.                 print " @value_col data type unnown. must be string or numeric"
  813.                 -- return -1
  814.         end
  815. END
  816. ELSE    --ERROR
  817. BEGIN
  818.         print " @value_col data type not allowed. must be string or numeric"
  819.         -- return -1
  820. END
  821.  
  822. -- template. first level expansion query.
  823. -- result must be executed to generate final output query.
  824.  
  825. SELECT "select 'select " + @value_group_by + "'"
  826. IF @value_col_is_char = 1
  827. BEGIN
  828.         SELECT "select '," + @QUOTE + "' + convert(varchar(40), " + @code_desc_col+ " ) + '" + @QUOTE + @NL
  829.         + " = "
  830.         + @value_aggregate
  831.         + "(isnull( substring("
  832.         + @value_col
  833.         + ", 1, ( "
  834.         + convert(varchar(3), @value_col_len )
  835.         + " * charindex( "
  836.         + @QUOTE
  837.         + "'+"
  838.         + @code_key_col
  839.         + "+'"
  840.         + @QUOTE
  841.         + ", "
  842.         + @code_key_col
  843.         + " ))), "
  844.         + @QUOTE + @QUOTE
  845.         + "))'"
  846. END
  847. ELSE IF @value_col_is_num = 1
  848. BEGIN
  849.         SELECT "select '," + @QUOTE + "' + convert(varchar(40), " + @code_desc_col+ " ) + '" + @QUOTE + @NL
  850.         + " = "
  851.         + @value_aggregate
  852.         + "("
  853.         + @value_col
  854.         + " * charindex( "
  855.         + @QUOTE
  856.         + "'+"
  857.         + @code_key_col
  858.         + "+'"
  859.         + @QUOTE
  860.         + ", "
  861.         + @code_key_col
  862.         + "))'"
  863. END
  864. SELECT "from " + @code_table + @NL
  865.         + "select  'from " + @value_table + "'" + @NL
  866.         + "select 'group by " + @value_group_by + "'"
  867.  
  868. -- end
  869. go
  870. use sybsystemprocs
  871. go
  872.  
  873. if object_id('sp__indexreport') is not null
  874.     drop procedure sp__indexreport
  875. go
  876.  
  877. /*
  878. ** A system sproc to report on user indexes.
  879. **
  880. ** Written by Anthony Mandic - July 2000.
  881. */
  882. create procedure sp__indexreport
  883. as
  884.  
  885. if @@trancount = 0
  886.     set chained off
  887.  
  888. set transaction isolation level 1
  889.  
  890. set nocount on
  891.  
  892. /*
  893. ** Check for user tables first.
  894. */
  895. if (select count(*) from sysobjects where type = "U") = 0
  896. begin
  897.     print "No user tables found in current database"
  898.     return 1
  899. end
  900.  
  901. /*
  902. ** Check for tables without any indexes.
  903. */
  904. select    name
  905. into    #tablelist
  906. from    sysindexes
  907. group by id
  908. having    count(id) = 1
  909. and    indid      = 0
  910. and    id      > 99
  911. and    name not like "#tablelist%"   /* Avoid finding it if run in tempdb */
  912.  
  913. if @@rowcount > 0
  914.     select    "Tables without indexes" = name
  915.     from    #tablelist
  916.     order by name
  917.  
  918. drop table #tablelist
  919.  
  920. /*
  921. ** Select all user indexes where there are multiple indexes on a table.
  922. */
  923. select    tid        = id,
  924.     tname        = object_name(id),
  925.     iname        = name,
  926.     iid        = indid,
  927.     indexcolumns    = convert(varchar(254), "")
  928. into    #indexlist
  929. from    sysindexes
  930. where    id        > 99
  931. and    indid    between 1 and 254
  932. group by id
  933. having    count(id)    > 1
  934. and    indid    between 1 and 254
  935.  
  936. if @@rowcount = 0
  937. begin
  938.     print "No duplicate indexes found in current database"
  939.     return 1
  940. end
  941.  
  942. declare    @count        int,
  943.     @tid        int,
  944.     @size        int,
  945.     @icolumns    varchar(254)
  946.  
  947. select    @count    = 1
  948.  
  949. while    @count < 17    /* 16 appears to be the max number of indexes */
  950. begin
  951.     update    #indexlist
  952.     set    indexcolumns    =
  953.                 case
  954.                     when @count > 1 then indexcolumns + ', '
  955.                 end
  956.                 + index_col(tname, iid, @count)
  957.     where    index_col(tname, iid, @count) is not null
  958.  
  959.         if @@rowcount = 0
  960.         break
  961.  
  962.         select    @count    = @count + 1
  963. end
  964.  
  965. create    table    #finallist
  966. (
  967.     table_name    varchar(30),
  968.     index_name    varchar(30),
  969.     tid        int,
  970.     index_columns    varchar(254)
  971. )
  972.  
  973. insert    #finallist
  974. select    b.tname,
  975.     b.iname,
  976.     b.tid,
  977.     b.indexcolumns
  978. from    #indexlist a,
  979.     #indexlist b
  980. where    a.tid        = b.tid
  981. and    a.indexcolumns    like b.indexcolumns + '%'
  982. group by a.tid,
  983.     a.iname
  984. having    count(*)    > 1
  985. and    a.tid        = b.tid
  986. and    a.indexcolumns    like b.indexcolumns + '%'
  987.  
  988. if (select count(*) from #finallist) = 0
  989. begin
  990.     print "No duplicate indexes found in current database"
  991.     return 1
  992. end
  993.  
  994. select    @size    = low / 1024
  995. from    master..spt_values
  996. where    number    = 1
  997. and    type    = "E"
  998.  
  999. print "Duplicate leading index columns"
  1000. print "-------------------------------"
  1001. print ""
  1002.  
  1003. /*
  1004. ** The distinct is needed to eliminate duplicated identical indexes on tables.
  1005. ** The order by is to get the resultant distinct list sorted.
  1006. */
  1007. select    distinct
  1008.     "table name"    = table_name,
  1009.     "index name"    = index_name,
  1010.     "size"        = str(
  1011.               (data_pgs(id, doampg) + data_pgs(id, ioampg)) * @size)
  1012.             + " KB",
  1013.     "index columns"    = index_columns
  1014. from    #finallist,
  1015.     sysindexes
  1016. where    id    = tid
  1017. and    name    = index_name
  1018. order by table_name, index_columns
  1019.  
  1020. return 0
  1021. go
  1022.  
  1023. exec sp_procxmode 'sp__indexreport', 'anymode'
  1024. go
  1025.  
  1026. grant execute on sp__indexreport to public
  1027. go
  1028. set flushmessage on
  1029. go
  1030.  
  1031. use sybsystemprocs
  1032. go
  1033.  
  1034. if exists (select 1
  1035.         from sysobjects
  1036.                 where sysstat & 7 = 4
  1037.                         and name = 'sp__optdiag')
  1038. begin
  1039.         print "Dropping sp__optdiag"
  1040.         drop procedure sp__optdiag
  1041. end
  1042. go
  1043.  
  1044. print "Installing sp__optdiag"
  1045. go
  1046.  
  1047. create procedure sp__optdiag
  1048.     @tabname    varchar(62) = null,  /* user table name */
  1049.     @colname    varchar(30) = null,    /* column name */
  1050.     @option        varchar(60) = null        /* output format */
  1051.  , @proc_version varchar(78) = "sp__optdiag/0.4/0/P/KJS/AnyPlat/AnyOS/G/Fri Jan  5 14:56:32 2001"
  1052. as
  1053. /*************************************************************************************************
  1054. **
  1055. **    Description: Format opdiag info from stored procedure
  1056. **
  1057. **    Options:  NULL - default
  1058. **
  1059. **                "V/?/HELP/H" - will print the current version string of this proc
  1060. **                "CR" - will approximate cluster ratio calculations.  Note that these are simply
  1061. **                       simply approximations since cluster ratio calculations are not published.
  1062. **                       (future change, not supported yet)
  1063. **
  1064. **    Future Info:  Other options can be added in the future
  1065. **                    using the @option parameter.
  1066. **
  1067. **    Dependencies:  This proc relies on the object_id built-in
  1068. **                    and sp_namecrack
  1069. **
  1070. **    Errors:
  1071. **
  1072. **    Version:  This proc is for ASE 11.9.x and beyond
  1073. **
  1074. **    Usage:  exec <dbname>..sp__optdiag <tabname>, <colname>, <opt>
  1075. **
  1076. **    History: 10/31/2000 (ksherlock) 0.1
  1077. **                  Original
  1078. **               11/14/2000 (ksherlock) 0.2
  1079. **                  Fixed bug to handle binary histograms and handle user defined types
  1080. **               12/20/2000 (ksherlock) 0.3
  1081. **                  Fixed bug with column groups not being retrieved in col_cursor
  1082. **               01/05/2001 (ksherlock) 0.4
  1083. **                  Final version which handles numeric decimals correctly
  1084. **
  1085. *************************************************************************************************/
  1086.  
  1087. declare
  1088.         @colid int  /* Variable to hold colid from syscolumns */
  1089.       , @tabid int  /* Variable to hold object_id from sysobjects */
  1090.       , @tabtype char(2)  /* Variable to hold type from sysobjects */
  1091.       , @s_dbname varchar(30)
  1092.       , @s_tabowner varchar(30)
  1093.       , @s_tabname varchar(30)
  1094.       , @u_tabname varchar(30)
  1095.       , @u_tabowner varchar(30)
  1096.       , @colgroup_name varchar(255)
  1097.       , @u_dbname varchar(30)
  1098.       , @u_dbid int
  1099.       , @colidarray varbinary(100)
  1100.       , @colidarray_len smallint
  1101.       , @indid int
  1102.       , @index_cols varchar(254)
  1103.       , @index_name varchar(30)
  1104.       , @keycnt int
  1105.       , @dol_clustered int
  1106.       , @clustered int
  1107.       , @last_updt varchar(28)
  1108.       , @c1stat int
  1109.       , @statid smallint
  1110.       , @used_count int
  1111.       , @rownum int
  1112.       , @coltype int
  1113.       , @typename varchar(30)
  1114.       , @collength varchar(5)
  1115.       , @precision varchar(3)
  1116.       , @scale varchar(3)
  1117.       , @rc_density varchar(24)
  1118.       , @tot_density varchar(24)
  1119.       , @r_sel varchar(24)
  1120.       , @between_sel varchar(24)
  1121.       , @freq_cell smallint
  1122.       , @steps_act int
  1123.       , @steps_req int
  1124.       , @step char(9)
  1125.       , @weight char(10)
  1126.       , @prev_step char(9)
  1127.       , @prev_weight char(10)
  1128.       , @value_raw varbinary(255)
  1129.       , @value_c varchar(255)
  1130.       , @leafcnt varchar(32) -- int
  1131.       , @pagecnt varchar(32) -- int
  1132.       , @emptypgcnt varchar(32) -- int
  1133.       , @rowcnt varchar(32)
  1134.       , @forwrowcnt varchar(32)
  1135.       , @delrowcnt varchar(32)
  1136.       , @dpagecrcnt varchar(32)
  1137.       , @dpagecr varchar(32)
  1138.       , @ipagecrcnt varchar(32)
  1139.       , @ipagecr varchar(32)
  1140.       , @drowcrcnt varchar(32)
  1141.       , @drowcr varchar(32)
  1142.       , @oamapgcnt varchar(32) -- int
  1143.       , @extent0pgcnt varchar(32)
  1144.       , @datarowsize varchar(32)
  1145.       , @leafrowsize varchar(32)
  1146.       , @indexheight varchar(32) -- int
  1147.       , @spare1 varchar(32) -- int
  1148.       , @spare2 varchar(32)
  1149.       , @ptn_data_pgs int
  1150.       , @seq int
  1151.  
  1152.  
  1153. if @@trancount = 0
  1154. begin
  1155.     set chained off
  1156. end
  1157.  
  1158. set transaction isolation level 1
  1159. set nocount on
  1160. set flushmessage on
  1161.  
  1162. if ( (select lower(@option)) in ("v","version","?","h","help") )
  1163. begin
  1164.    print "%1!",@proc_version
  1165.    return 0
  1166. end
  1167.  
  1168. exec sp_namecrack @tabname, " ", @s_dbname out, @s_tabowner out, @s_tabname out
  1169. select @s_dbname = isnull(@s_dbname,db_name())
  1170.  
  1171. declare object_cursor cursor for
  1172. select  id,
  1173.         db_name(),
  1174.         db_id(),
  1175.         user_name(uid),
  1176.         name
  1177. from sysobjects
  1178. where user_name(uid) like isnull(@s_tabowner,"%")
  1179. and   name like isnull(@s_tabname,"%")
  1180. and type = "U" and id > 100
  1181. order by user_name(uid), name
  1182. for read only
  1183.  
  1184. declare index_cursor cursor for
  1185. select  st.indid
  1186.       , si.name
  1187.       , abs(sign(si.status2 & 512)) /* DOL clustered index */
  1188.       , abs(sign(si.status & 16)) /* clustered bit */
  1189.       , si.keycnt
  1190. from systabstats st, sysindexes si
  1191. where st.id = @tabid
  1192.   and si.id = @tabid
  1193.   and st.id = si.id
  1194.   and st.indid = si.indid
  1195. order by st.indid
  1196. for read only
  1197.  
  1198. declare col_cursor cursor for
  1199. select  sc.colid,
  1200.         ss.colidarray,
  1201.         datalength(ss.colidarray),
  1202.         sc.name,
  1203.         ss.statid,
  1204.         convert(int,ss.c1),
  1205.         convert(varchar,ss.moddate,109),
  1206.         ltrim(str(round(convert(double precision,ss.c2),16),24,16)),
  1207.         ltrim(str(round(convert(double precision,ss.c3),16),24,16)),
  1208.         convert(int,ss.c4),
  1209.         convert(int,ss.c5),
  1210.         st.name,
  1211.         ltrim(str(convert(int,ss.c7),5)),
  1212.         ltrim(str(convert(int,ss.c8),3)),
  1213.         ltrim(str(convert(int,ss.c9),3)),
  1214.         ltrim(str(round(convert(double precision,ss.c10),16),24,16)),
  1215.         ltrim(str(round(convert(double precision,ss.c11),16),24,16))
  1216. from syscolumns sc, sysstatistics ss, systypes st
  1217. where sc.id = @tabid
  1218. and   sc.name like isnull(@colname,"%")
  1219. and   ss.id = sc.id
  1220. and   convert(int,ss.c6) *= st.type
  1221. and   st.name not in ("timestamp","sysname", "nchar", "nvarchar")
  1222. and   st.usertype < 100
  1223. and   convert(tinyint,substring(ss.colidarray,1,1)) = sc.colid
  1224. and   ss.formatid = 100
  1225. order by sc.id, sc.name, ss.colidarray
  1226. for read only
  1227.  
  1228. declare nostats_cursor cursor for
  1229. select sc.name
  1230. from syscolumns sc,
  1231.  sysstatistics ss
  1232. where ss.id =* sc.id
  1233. and  sc.id = @tabid
  1234. and  ss.formatid = 100
  1235. and  ss.statid = 0
  1236. and  ss.sequence = 1
  1237. and  sc.colid *= convert(tinyint,substring(ss.colidarray,1,1))
  1238. and  datalength(ss.colidarray) = 1
  1239. group by sc.name
  1240. having count(ss.id) = 0
  1241. order by sc.name
  1242. for read only
  1243.  
  1244. create table #cells(seq int,colnum int)
  1245.  
  1246. /** DO NOT FOLD, SPINDAL, OR MUTILATE (unless its sysstatistics) **/
  1247. /** OK, bear with me, here we go... **/
  1248.  
  1249. declare histogram_cursor cursor for
  1250. select
  1251.       /** Here is the step number **/
  1252.       str(
  1253.       ((c.seq-1)*80 + 1 )*(1-abs(sign(c.colnum-1 ))) + ((c.seq-1)*80 + 2 )*(1-abs(sign(c.colnum-2 ))) +
  1254.       ((c.seq-1)*80 + 3 )*(1-abs(sign(c.colnum-3 ))) + ((c.seq-1)*80 + 4 )*(1-abs(sign(c.colnum-4 ))) +
  1255.       ((c.seq-1)*80 + 5 )*(1-abs(sign(c.colnum-5 ))) + ((c.seq-1)*80 + 6 )*(1-abs(sign(c.colnum-6 ))) +
  1256.       ((c.seq-1)*80 + 7 )*(1-abs(sign(c.colnum-7 ))) + ((c.seq-1)*80 + 8 )*(1-abs(sign(c.colnum-8 ))) +
  1257.       ((c.seq-1)*80 + 9 )*(1-abs(sign(c.colnum-9 ))) + ((c.seq-1)*80 + 10)*(1-abs(sign(c.colnum-10))) +
  1258.       ((c.seq-1)*80 + 11)*(1-abs(sign(c.colnum-11))) + ((c.seq-1)*80 + 12)*(1-abs(sign(c.colnum-12))) +
  1259.       ((c.seq-1)*80 + 13)*(1-abs(sign(c.colnum-13))) + ((c.seq-1)*80 + 14)*(1-abs(sign(c.colnum-14))) +
  1260.       ((c.seq-1)*80 + 15)*(1-abs(sign(c.colnum-15))) + ((c.seq-1)*80 + 16)*(1-abs(sign(c.colnum-16))) +
  1261.       ((c.seq-1)*80 + 17)*(1-abs(sign(c.colnum-17))) + ((c.seq-1)*80 + 18)*(1-abs(sign(c.colnum-18))) +
  1262.       ((c.seq-1)*80 + 19)*(1-abs(sign(c.colnum-19))) + ((c.seq-1)*80 + 20)*(1-abs(sign(c.colnum-20))) +
  1263.       ((c.seq-1)*80 + 21)*(1-abs(sign(c.colnum-21))) + ((c.seq-1)*80 + 22)*(1-abs(sign(c.colnum-22))) +
  1264.       ((c.seq-1)*80 + 23)*(1-abs(sign(c.colnum-23))) + ((c.seq-1)*80 + 24)*(1-abs(sign(c.colnum-24))) +
  1265.       ((c.seq-1)*80 + 25)*(1-abs(sign(c.colnum-25))) + ((c.seq-1)*80 + 26)*(1-abs(sign(c.colnum-26))) +
  1266.       ((c.seq-1)*80 + 27)*(1-abs(sign(c.colnum-27))) + ((c.seq-1)*80 + 28)*(1-abs(sign(c.colnum-28))) +
  1267.       ((c.seq-1)*80 + 29)*(1-abs(sign(c.colnum-29))) + ((c.seq-1)*80 + 30)*(1-abs(sign(c.colnum-30))) +
  1268.       ((c.seq-1)*80 + 31)*(1-abs(sign(c.colnum-31))) + ((c.seq-1)*80 + 32)*(1-abs(sign(c.colnum-32))) +
  1269.       ((c.seq-1)*80 + 33)*(1-abs(sign(c.colnum-33))) + ((c.seq-1)*80 + 34)*(1-abs(sign(c.colnum-34))) +
  1270.       ((c.seq-1)*80 + 35)*(1-abs(sign(c.colnum-35))) + ((c.seq-1)*80 + 36)*(1-abs(sign(c.colnum-36))) +
  1271.       ((c.seq-1)*80 + 37)*(1-abs(sign(c.colnum-37))) + ((c.seq-1)*80 + 38)*(1-abs(sign(c.colnum-38))) +
  1272.       ((c.seq-1)*80 + 39)*(1-abs(sign(c.colnum-39))) + ((c.seq-1)*80 + 40)*(1-abs(sign(c.colnum-40))) +
  1273.       ((c.seq-1)*80 + 41)*(1-abs(sign(c.colnum-41))) + ((c.seq-1)*80 + 42)*(1-abs(sign(c.colnum-42))) +
  1274.       ((c.seq-1)*80 + 43)*(1-abs(sign(c.colnum-43))) + ((c.seq-1)*80 + 44)*(1-abs(sign(c.colnum-44))) +
  1275.       ((c.seq-1)*80 + 45)*(1-abs(sign(c.colnum-45))) + ((c.seq-1)*80 + 46)*(1-abs(sign(c.colnum-46))) +
  1276.       ((c.seq-1)*80 + 47)*(1-abs(sign(c.colnum-47))) + ((c.seq-1)*80 + 48)*(1-abs(sign(c.colnum-48))) +
  1277.       ((c.seq-1)*80 + 49)*(1-abs(sign(c.colnum-49))) + ((c.seq-1)*80 + 50)*(1-abs(sign(c.colnum-50))) +
  1278.       ((c.seq-1)*80 + 51)*(1-abs(sign(c.colnum-51))) + ((c.seq-1)*80 + 52)*(1-abs(sign(c.colnum-52))) +
  1279.       ((c.seq-1)*80 + 53)*(1-abs(sign(c.colnum-53))) + ((c.seq-1)*80 + 54)*(1-abs(sign(c.colnum-54))) +
  1280.       ((c.seq-1)*80 + 55)*(1-abs(sign(c.colnum-55))) + ((c.seq-1)*80 + 56)*(1-abs(sign(c.colnum-56))) +
  1281.       ((c.seq-1)*80 + 57)*(1-abs(sign(c.colnum-57))) + ((c.seq-1)*80 + 58)*(1-abs(sign(c.colnum-58))) +
  1282.       ((c.seq-1)*80 + 59)*(1-abs(sign(c.colnum-59))) + ((c.seq-1)*80 + 60)*(1-abs(sign(c.colnum-60))) +
  1283.       ((c.seq-1)*80 + 61)*(1-abs(sign(c.colnum-61))) + ((c.seq-1)*80 + 62)*(1-abs(sign(c.colnum-62))) +
  1284.       ((c.seq-1)*80 + 63)*(1-abs(sign(c.colnum-63))) + ((c.seq-1)*80 + 64)*(1-abs(sign(c.colnum-64))) +
  1285.       ((c.seq-1)*80 + 65)*(1-abs(sign(c.colnum-65))) + ((c.seq-1)*80 + 66)*(1-abs(sign(c.colnum-66))) +
  1286.       ((c.seq-1)*80 + 67)*(1-abs(sign(c.colnum-67))) + ((c.seq-1)*80 + 68)*(1-abs(sign(c.colnum-68))) +
  1287.       ((c.seq-1)*80 + 69)*(1-abs(sign(c.colnum-69))) + ((c.seq-1)*80 + 70)*(1-abs(sign(c.colnum-70))) +
  1288.       ((c.seq-1)*80 + 71)*(1-abs(sign(c.colnum-71))) + ((c.seq-1)*80 + 72)*(1-abs(sign(c.colnum-72))) +
  1289.       ((c.seq-1)*80 + 73)*(1-abs(sign(c.colnum-73))) + ((c.seq-1)*80 + 74)*(1-abs(sign(c.colnum-74))) +
  1290.       ((c.seq-1)*80 + 75)*(1-abs(sign(c.colnum-75))) + ((c.seq-1)*80 + 76)*(1-abs(sign(c.colnum-76))) +
  1291.       ((c.seq-1)*80 + 77)*(1-abs(sign(c.colnum-77))) + ((c.seq-1)*80 + 78)*(1-abs(sign(c.colnum-78))) +
  1292.       ((c.seq-1)*80 + 79)*(1-abs(sign(c.colnum-79))) + ((c.seq-1)*80 + 80)*(1-abs(sign(c.colnum-80)))
  1293.        ,9),
  1294.  
  1295.       /** And here is the Weight of the cell **/
  1296.  
  1297.       str(
  1298.       isnull(convert(real,s.c0)*(1-abs(sign(c.colnum-1 ))) ,0) + isnull(convert(real,s.c1)*(1-abs(sign(c.colnum-2 ))) ,0) +
  1299.       isnull(convert(real,s.c2)*(1-abs(sign(c.colnum-3 ))) ,0) + isnull(convert(real,s.c3)*(1-abs(sign(c.colnum-4 ))) ,0) +
  1300.       isnull(convert(real,s.c4)*(1-abs(sign(c.colnum-5 ))) ,0) + isnull(convert(real,s.c5)*(1-abs(sign(c.colnum-6 ))) ,0) +
  1301.       isnull(convert(real,s.c6)*(1-abs(sign(c.colnum-7 ))) ,0) + isnull(convert(real,s.c7)*(1-abs(sign(c.colnum-8 ))) ,0) +
  1302.       isnull(convert(real,s.c8)*(1-abs(sign(c.colnum-9 ))) ,0) + isnull(convert(real,s.c9)*(1-abs(sign(c.colnum-10))) ,0) +
  1303.       isnull(convert(real,s.c10)*(1-abs(sign(c.colnum-11))) ,0) + isnull(convert(real,s.c11)*(1-abs(sign(c.colnum-12))) ,0) +
  1304.       isnull(convert(real,s.c12)*(1-abs(sign(c.colnum-13))) ,0) + isnull(convert(real,s.c13)*(1-abs(sign(c.colnum-14))) ,0) +
  1305.       isnull(convert(real,s.c14)*(1-abs(sign(c.colnum-15))) ,0) + isnull(convert(real,s.c15)*(1-abs(sign(c.colnum-16))) ,0) +
  1306.       isnull(convert(real,s.c16)*(1-abs(sign(c.colnum-17))) ,0) + isnull(convert(real,s.c17)*(1-abs(sign(c.colnum-18))) ,0) +
  1307.       isnull(convert(real,s.c18)*(1-abs(sign(c.colnum-19))) ,0) + isnull(convert(real,s.c19)*(1-abs(sign(c.colnum-20))) ,0) +
  1308.       isnull(convert(real,s.c20)*(1-abs(sign(c.colnum-21))) ,0) + isnull(convert(real,s.c21)*(1-abs(sign(c.colnum-22))) ,0) +
  1309.       isnull(convert(real,s.c22)*(1-abs(sign(c.colnum-23))) ,0) + isnull(convert(real,s.c23)*(1-abs(sign(c.colnum-24))) ,0) +
  1310.       isnull(convert(real,s.c24)*(1-abs(sign(c.colnum-25))) ,0) + isnull(convert(real,s.c25)*(1-abs(sign(c.colnum-26))) ,0) +
  1311.       isnull(convert(real,s.c26)*(1-abs(sign(c.colnum-27))) ,0) + isnull(convert(real,s.c27)*(1-abs(sign(c.colnum-28))) ,0) +
  1312.       isnull(convert(real,s.c28)*(1-abs(sign(c.colnum-29))) ,0) + isnull(convert(real,s.c29)*(1-abs(sign(c.colnum-30))) ,0) +
  1313.       isnull(convert(real,s.c30)*(1-abs(sign(c.colnum-31))) ,0) + isnull(convert(real,s.c31)*(1-abs(sign(c.colnum-32))) ,0) +
  1314.       isnull(convert(real,s.c32)*(1-abs(sign(c.colnum-33))) ,0) + isnull(convert(real,s.c33)*(1-abs(sign(c.colnum-34))) ,0) +
  1315.       isnull(convert(real,s.c34)*(1-abs(sign(c.colnum-35))) ,0) + isnull(convert(real,s.c35)*(1-abs(sign(c.colnum-36))) ,0) +
  1316.       isnull(convert(real,s.c36)*(1-abs(sign(c.colnum-37))) ,0) + isnull(convert(real,s.c37)*(1-abs(sign(c.colnum-38))) ,0) +
  1317.       isnull(convert(real,s.c38)*(1-abs(sign(c.colnum-39))) ,0) + isnull(convert(real,s.c39)*(1-abs(sign(c.colnum-40))) ,0) +
  1318.       isnull(convert(real,s.c40)*(1-abs(sign(c.colnum-41))) ,0) + isnull(convert(real,s.c41)*(1-abs(sign(c.colnum-42))) ,0) +
  1319.       isnull(convert(real,s.c42)*(1-abs(sign(c.colnum-43))) ,0) + isnull(convert(real,s.c43)*(1-abs(sign(c.colnum-44))) ,0) +
  1320.       isnull(convert(real,s.c44)*(1-abs(sign(c.colnum-45))) ,0) + isnull(convert(real,s.c45)*(1-abs(sign(c.colnum-46))) ,0) +
  1321.       isnull(convert(real,s.c46)*(1-abs(sign(c.colnum-47))) ,0) + isnull(convert(real,s.c47)*(1-abs(sign(c.colnum-48))) ,0) +
  1322.       isnull(convert(real,s.c48)*(1-abs(sign(c.colnum-49))) ,0) + isnull(convert(real,s.c49)*(1-abs(sign(c.colnum-50))) ,0) +
  1323.       isnull(convert(real,s.c50)*(1-abs(sign(c.colnum-51))) ,0) + isnull(convert(real,s.c51)*(1-abs(sign(c.colnum-52))) ,0) +
  1324.       isnull(convert(real,s.c52)*(1-abs(sign(c.colnum-53))) ,0) + isnull(convert(real,s.c53)*(1-abs(sign(c.colnum-54))) ,0) +
  1325.       isnull(convert(real,s.c54)*(1-abs(sign(c.colnum-55))) ,0) + isnull(convert(real,s.c55)*(1-abs(sign(c.colnum-56))) ,0) +
  1326.       isnull(convert(real,s.c56)*(1-abs(sign(c.colnum-57))) ,0) + isnull(convert(real,s.c57)*(1-abs(sign(c.colnum-58))) ,0) +
  1327.       isnull(convert(real,s.c58)*(1-abs(sign(c.colnum-59))) ,0) + isnull(convert(real,s.c59)*(1-abs(sign(c.colnum-60))) ,0) +
  1328.       isnull(convert(real,s.c60)*(1-abs(sign(c.colnum-61))) ,0) + isnull(convert(real,s.c61)*(1-abs(sign(c.colnum-62))) ,0) +
  1329.       isnull(convert(real,s.c62)*(1-abs(sign(c.colnum-63))) ,0) + isnull(convert(real,s.c63)*(1-abs(sign(c.colnum-64))) ,0) +
  1330.       isnull(convert(real,s.c64)*(1-abs(sign(c.colnum-65))) ,0) + isnull(convert(real,s.c65)*(1-abs(sign(c.colnum-66))) ,0) +
  1331.       isnull(convert(real,s.c66)*(1-abs(sign(c.colnum-67))) ,0) + isnull(convert(real,s.c67)*(1-abs(sign(c.colnum-68))) ,0) +
  1332.       isnull(convert(real,s.c68)*(1-abs(sign(c.colnum-69))) ,0) + isnull(convert(real,s.c69)*(1-abs(sign(c.colnum-70))) ,0) +
  1333.       isnull(convert(real,s.c70)*(1-abs(sign(c.colnum-71))) ,0) + isnull(convert(real,s.c71)*(1-abs(sign(c.colnum-72))) ,0) +
  1334.       isnull(convert(real,s.c72)*(1-abs(sign(c.colnum-73))) ,0) + isnull(convert(real,s.c73)*(1-abs(sign(c.colnum-74))) ,0) +
  1335.       isnull(convert(real,s.c74)*(1-abs(sign(c.colnum-75))) ,0) + isnull(convert(real,s.c75)*(1-abs(sign(c.colnum-76))) ,0) +
  1336.       isnull(convert(real,s.c76)*(1-abs(sign(c.colnum-77))) ,0) + isnull(convert(real,s.c77)*(1-abs(sign(c.colnum-78))) ,0) +
  1337.       isnull(convert(real,s.c78)*(1-abs(sign(c.colnum-79))) ,0) + isnull(convert(real,s.c79)*(1-abs(sign(c.colnum-80))) ,0)
  1338.       ,10,8),
  1339.  
  1340.       /** And finally, here is the Value of the cell **/
  1341.  
  1342.       substring(convert(varbinary(255),v.c0),(1-abs(sign(c.colnum-1 ))) ,255) + substring(convert(varbinary(255),v.c1),(1-abs(sign(c.colnum-2 ))) ,255) +
  1343.       substring(convert(varbinary(255),v.c2),(1-abs(sign(c.colnum-3 ))) ,255) + substring(convert(varbinary(255),v.c3),(1-abs(sign(c.colnum-4 ))) ,255) +
  1344.       substring(convert(varbinary(255),v.c4),(1-abs(sign(c.colnum-5 ))) ,255) + substring(convert(varbinary(255),v.c5),(1-abs(sign(c.colnum-6 ))) ,255) +
  1345.       substring(convert(varbinary(255),v.c6),(1-abs(sign(c.colnum-7 ))) ,255) + substring(convert(varbinary(255),v.c7),(1-abs(sign(c.colnum-8 ))) ,255) +
  1346.       substring(convert(varbinary(255),v.c8),(1-abs(sign(c.colnum-9 ))) ,255) + substring(convert(varbinary(255),v.c9),(1-abs(sign(c.colnum-10))) ,255) +
  1347.       substring(convert(varbinary(255),v.c10),(1-abs(sign(c.colnum-11))) ,255) + substring(convert(varbinary(255),v.c11),(1-abs(sign(c.colnum-12))) ,255) +
  1348.       substring(convert(varbinary(255),v.c12),(1-abs(sign(c.colnum-13))) ,255) + substring(convert(varbinary(255),v.c13),(1-abs(sign(c.colnum-14))) ,255) +
  1349.       substring(convert(varbinary(255),v.c14),(1-abs(sign(c.colnum-15))) ,255) + substring(convert(varbinary(255),v.c15),(1-abs(sign(c.colnum-16))) ,255) +
  1350.       substring(convert(varbinary(255),v.c16),(1-abs(sign(c.colnum-17))) ,255) + substring(convert(varbinary(255),v.c17),(1-abs(sign(c.colnum-18))) ,255) +
  1351.       substring(convert(varbinary(255),v.c18),(1-abs(sign(c.colnum-19))) ,255) + substring(convert(varbinary(255),v.c19),(1-abs(sign(c.colnum-20))) ,255) +
  1352.       substring(convert(varbinary(255),v.c20),(1-abs(sign(c.colnum-21))) ,255) + substring(convert(varbinary(255),v.c21),(1-abs(sign(c.colnum-22))) ,255) +
  1353.       substring(convert(varbinary(255),v.c22),(1-abs(sign(c.colnum-23))) ,255) + substring(convert(varbinary(255),v.c23),(1-abs(sign(c.colnum-24))) ,255) +
  1354.       substring(convert(varbinary(255),v.c24),(1-abs(sign(c.colnum-25))) ,255) + substring(convert(varbinary(255),v.c25),(1-abs(sign(c.colnum-26))) ,255) +
  1355.       substring(convert(varbinary(255),v.c26),(1-abs(sign(c.colnum-27))) ,255) + substring(convert(varbinary(255),v.c27),(1-abs(sign(c.colnum-28))) ,255) +
  1356.       substring(convert(varbinary(255),v.c28),(1-abs(sign(c.colnum-29))) ,255) + substring(convert(varbinary(255),v.c29),(1-abs(sign(c.colnum-30))) ,255) +
  1357.       substring(convert(varbinary(255),v.c30),(1-abs(sign(c.colnum-31))) ,255) + substring(convert(varbinary(255),v.c31),(1-abs(sign(c.colnum-32))) ,255) +
  1358.       substring(convert(varbinary(255),v.c32),(1-abs(sign(c.colnum-33))) ,255) + substring(convert(varbinary(255),v.c33),(1-abs(sign(c.colnum-34))) ,255) +
  1359.       substring(convert(varbinary(255),v.c34),(1-abs(sign(c.colnum-35))) ,255) + substring(convert(varbinary(255),v.c35),(1-abs(sign(c.colnum-36))) ,255) +
  1360.       substring(convert(varbinary(255),v.c36),(1-abs(sign(c.colnum-37))) ,255) + substring(convert(varbinary(255),v.c37),(1-abs(sign(c.colnum-38))) ,255) +
  1361.       substring(convert(varbinary(255),v.c38),(1-abs(sign(c.colnum-39))) ,255) + substring(convert(varbinary(255),v.c39),(1-abs(sign(c.colnum-40))) ,255) +
  1362.       substring(convert(varbinary(255),v.c40),(1-abs(sign(c.colnum-41))) ,255) + substring(convert(varbinary(255),v.c41),(1-abs(sign(c.colnum-42))) ,255) +
  1363.       substring(convert(varbinary(255),v.c42),(1-abs(sign(c.colnum-43))) ,255) + substring(convert(varbinary(255),v.c43),(1-abs(sign(c.colnum-44))) ,255) +
  1364.       substring(convert(varbinary(255),v.c44),(1-abs(sign(c.colnum-45))) ,255) + substring(convert(varbinary(255),v.c45),(1-abs(sign(c.colnum-46))) ,255) +
  1365.       substring(convert(varbinary(255),v.c46),(1-abs(sign(c.colnum-47))) ,255) + substring(convert(varbinary(255),v.c47),(1-abs(sign(c.colnum-48))) ,255) +
  1366.       substring(convert(varbinary(255),v.c48),(1-abs(sign(c.colnum-49))) ,255) + substring(convert(varbinary(255),v.c49),(1-abs(sign(c.colnum-50))) ,255) +
  1367.       substring(convert(varbinary(255),v.c50),(1-abs(sign(c.colnum-51))) ,255) + substring(convert(varbinary(255),v.c51),(1-abs(sign(c.colnum-52))) ,255) +
  1368.       substring(convert(varbinary(255),v.c52),(1-abs(sign(c.colnum-53))) ,255) + substring(convert(varbinary(255),v.c53),(1-abs(sign(c.colnum-54))) ,255) +
  1369.       substring(convert(varbinary(255),v.c54),(1-abs(sign(c.colnum-55))) ,255) + substring(convert(varbinary(255),v.c55),(1-abs(sign(c.colnum-56))) ,255) +
  1370.       substring(convert(varbinary(255),v.c56),(1-abs(sign(c.colnum-57))) ,255) + substring(convert(varbinary(255),v.c57),(1-abs(sign(c.colnum-58))) ,255) +
  1371.       substring(convert(varbinary(255),v.c58),(1-abs(sign(c.colnum-59))) ,255) + substring(convert(varbinary(255),v.c59),(1-abs(sign(c.colnum-60))) ,255) +
  1372.       substring(convert(varbinary(255),v.c60),(1-abs(sign(c.colnum-61))) ,255) + substring(convert(varbinary(255),v.c61),(1-abs(sign(c.colnum-62))) ,255) +
  1373.       substring(convert(varbinary(255),v.c62),(1-abs(sign(c.colnum-63))) ,255) + substring(convert(varbinary(255),v.c63),(1-abs(sign(c.colnum-64))) ,255) +
  1374.       substring(convert(varbinary(255),v.c64),(1-abs(sign(c.colnum-65))) ,255) + substring(convert(varbinary(255),v.c65),(1-abs(sign(c.colnum-66))) ,255) +
  1375.       substring(convert(varbinary(255),v.c66),(1-abs(sign(c.colnum-67))) ,255) + substring(convert(varbinary(255),v.c67),(1-abs(sign(c.colnum-68))) ,255) +
  1376.       substring(convert(varbinary(255),v.c68),(1-abs(sign(c.colnum-69))) ,255) + substring(convert(varbinary(255),v.c69),(1-abs(sign(c.colnum-70))) ,255) +
  1377.       substring(convert(varbinary(255),v.c70),(1-abs(sign(c.colnum-71))) ,255) + substring(convert(varbinary(255),v.c71),(1-abs(sign(c.colnum-72))) ,255) +
  1378.       substring(convert(varbinary(255),v.c72),(1-abs(sign(c.colnum-73))) ,255) + substring(convert(varbinary(255),v.c73),(1-abs(sign(c.colnum-74))) ,255) +
  1379.       substring(convert(varbinary(255),v.c74),(1-abs(sign(c.colnum-75))) ,255) + substring(convert(varbinary(255),v.c75),(1-abs(sign(c.colnum-76))) ,255) +
  1380.       substring(convert(varbinary(255),v.c76),(1-abs(sign(c.colnum-77))) ,255) + substring(convert(varbinary(255),v.c77),(1-abs(sign(c.colnum-78))) ,255) +
  1381.       substring(convert(varbinary(255),v.c78),(1-abs(sign(c.colnum-79))) ,255) + substring(convert(varbinary(255),v.c79),(1-abs(sign(c.colnum-80))) ,255)
  1382. from #cells c, sysstatistics s, sysstatistics v
  1383. where s.id = @tabid
  1384. and s.colidarray = convert(varbinary(1),convert(tinyint,@colid))
  1385. and s.formatid = 104
  1386. and v.id =* s.id
  1387. and v.colidarray =* s.colidarray
  1388. and v.statid =* s.statid
  1389. and v.sequence =* s.sequence
  1390. and v.formatid = 102
  1391. and c.seq = s.sequence
  1392. for read only
  1393.  
  1394. /** Wow, I'm glad that's over **/
  1395. /** Let's get on with the business at hand **/
  1396.  
  1397. print "%1!",@proc_version
  1398. print "%1!",@@version
  1399. print ''
  1400.  
  1401. /** Standard optdiag output **/
  1402. begin
  1403.    print 'Server name:                            "%1!"',@@servername
  1404.    print ''
  1405.    print 'Specified database:                     "%1!"',@s_dbname
  1406.    if (@s_tabowner is null)
  1407.      print 'Specified table owner:                  not specified'
  1408.    else
  1409.      print 'Specified table owner:                  "%1!"',@s_tabowner
  1410.    if (@s_tabname is null)
  1411.      print 'Specified table:                        not specified'
  1412.    else
  1413.      print 'Specified table:                        "%1!"',@s_tabname
  1414.    if (@colname is null)
  1415.      print 'Specified column:                       not specified'
  1416.    else
  1417.      print 'Specified column:                       "%1!"',@colname
  1418.    print ''
  1419.  
  1420. /*
  1421. ** Check to see if the @tabname is in sysobjects.
  1422. */
  1423.  
  1424.    open object_cursor
  1425.  
  1426.    fetch object_cursor into
  1427.       @tabid, @u_dbname, @u_dbid,
  1428.       @u_tabowner, @u_tabname
  1429.  
  1430. while (@@sqlstatus = 0)
  1431. begin
  1432.    print 'Table owner:                            "%1!"',@u_tabowner
  1433.    print 'Table name:                             "%1!"',@u_tabname
  1434.    print ''
  1435.  
  1436.    dbcc flushstats(@u_dbid, @tabid)
  1437.  
  1438.    select @ptn_data_pgs = convert(int, max(ptn_data_pgs(@tabid, partitionid)))
  1439.    from syspartitions
  1440.    where id = @tabid
  1441.  
  1442.    ---------------------
  1443.    -- Work on Indexes --
  1444.    ---------------------
  1445.    open index_cursor
  1446.    fetch index_cursor into
  1447.               @indid ,@index_name ,@dol_clustered, @clustered, @keycnt
  1448.  
  1449.    while (@@sqlstatus = 0)
  1450.    begin
  1451.       select @keycnt = @keycnt - isnull(abs(sign(@clustered - 1)),0)
  1452.             ,@index_cols = null
  1453.       while (@keycnt > 0)
  1454.       begin
  1455.          select @index_cols = substring(', ' ,abs(sign(@keycnt - 1)),2)
  1456.                             + '"' + index_col(@u_tabname, @indid, @keycnt, user_id(@u_tabowner)) + '"'
  1457.                             + @index_cols
  1458.          select @keycnt = @keycnt - 1
  1459.       end
  1460.       select @leafcnt = ltrim(convert(varchar(32),convert(int,leafcnt))),
  1461.              @pagecnt = ltrim(convert(varchar(32),convert(int,pagecnt))),
  1462.              @emptypgcnt = ltrim(convert(varchar(32),convert(int,emptypgcnt))),
  1463.              @rowcnt = ltrim(convert(varchar(32),str(round(convert(double precision,rowcnt),16),32,16))),
  1464.              @forwrowcnt = ltrim(convert(varchar(32),str(round(convert(double precision,forwrowcnt),16),32,16))),
  1465.              @delrowcnt = ltrim(convert(varchar(32),str(round(convert(double precision,delrowcnt),16),32,16))),
  1466.              @dpagecrcnt = ltrim(convert(varchar(32),str(round(convert(double precision,dpagecrcnt),16),32,16))),
  1467.              @dpagecr = ltrim(convert(varchar(32),str(round(convert(double precision,dpagecrcnt),16),32,16))),
  1468.              @ipagecrcnt = ltrim(convert(varchar(32),str(round(convert(double precision,ipagecrcnt),16),32,16))),
  1469.              @ipagecr = ltrim(convert(varchar(32),str(round(convert(double precision,ipagecrcnt),16),32,16))),
  1470.              @drowcrcnt = ltrim(convert(varchar(32),str(round(convert(double precision,drowcrcnt),16),32,16))),
  1471.              @drowcr = ltrim(convert(varchar(32),str(round(convert(double precision,drowcrcnt),16),32,16))),
  1472.              @oamapgcnt = ltrim(convert(varchar(32),convert(int,oamapgcnt))),
  1473.              @extent0pgcnt = ltrim(convert(varchar(32),convert(int,extent0pgcnt))),
  1474.              @datarowsize = ltrim(convert(varchar(32),str(round(convert(double precision,datarowsize),16),32,16))),
  1475.              @leafrowsize = ltrim(convert(varchar(32),str(round(convert(double precision,leafrowsize),16),32,16))),
  1476.              @indexheight = ltrim(convert(varchar(32),convert(smallint,indexheight))),
  1477.              @spare1 = ltrim(convert(varchar(32),convert(int,spare1))),
  1478.              @spare2 = ltrim(convert(varchar(32),str(round(convert(double precision,spare2),16),32,16)))
  1479.       from systabstats
  1480.       where id = @tabid and indid = @indid
  1481.  
  1482.       ----------------------
  1483.       -- print index info --
  1484.       ----------------------
  1485.  
  1486.       if (@indid = 0)
  1487.          print 'Statistics for table:                   "%1!"',@index_name
  1488.       else if (1 in (@clustered,@dol_clustered))
  1489.          print 'Statistics for index:                   "%1!" (clustered)',@index_name
  1490.       else
  1491.          print 'Statistics for index:                   "%1!" (nonclustered)',@index_name
  1492.       if (@indid > 0)
  1493.          print 'Index column list:                      %1!',@index_cols
  1494.       else
  1495.          print ''
  1496.       if (@clustered = 1 or @indid = 0)
  1497.          print '     Data page count:                   %1!',@pagecnt
  1498.       else
  1499.          print '     Leaf count:                        %1!',@leafcnt
  1500.  
  1501.       if (1 in (@clustered,@dol_clustered) or @indid = 0)
  1502.          print '     Empty data page count:             %1!',@emptypgcnt
  1503.       else
  1504.          print '     Empty leaf page count:             %1!',@emptypgcnt
  1505.  
  1506.       if (@clustered = 1 or @indid = 0)
  1507.       begin
  1508.          print '     Data row count:                    %1!',@rowcnt
  1509.          print '     Forwarded row count:               %1!',@forwrowcnt
  1510.          print '     Deleted row count:                 %1!',@delrowcnt
  1511.       end
  1512.  
  1513.       print '     Data page CR count:                %1!',@dpagecrcnt
  1514.       if ((@clustered = 0 or @dol_clustered = 1) and @indid > 0)
  1515.       begin
  1516.          print '     Index page CR count:               %1!',@ipagecrcnt
  1517.          print '     Data row CR count:                 %1!',@drowcrcnt
  1518.       end
  1519.  
  1520.       if (@clustered = 1 or @indid = 0)
  1521.          print '     OAM + allocation page count:       %1!',@oamapgcnt
  1522.  
  1523.       if (@indid = 0)
  1524.          print '     First extent data pages:           %1!',@extent0pgcnt
  1525.       else
  1526.          print '     First extent leaf pages:           %1!',@extent0pgcnt
  1527.       if (@clustered = 1 or @indid = 0)
  1528.          print '     Data row size:                     %1!',@datarowsize
  1529.       else
  1530.          print '     Leaf row size:                     %1!',@leafrowsize
  1531.       if (@indid > 0)
  1532.          print '     Index height:                      %1!',@indexheight
  1533.       if ((@clustered = 1 or @indid = 0) and @ptn_data_pgs is not null)
  1534.          print '     Pages in largest partition:        %1!',@ptn_data_pgs
  1535.  
  1536.       print ''
  1537.       print '  Derived statistics:'
  1538.  
  1539.       if ( (select lower(@option)) in ("cr","cluster ratio") )
  1540.       begin
  1541.          print '     Data page cluster ratio:           proprietary'
  1542.       end
  1543.       else
  1544.          print '     Data page cluster ratio:           proprietary'
  1545.       if ((@clustered = 0 or @dol_clustered = 1) and @indid > 0)
  1546.       begin
  1547.          print '     Index page cluster ratio:          proprietary'
  1548.          print '     Data row cluster ratio:            proprietary'
  1549.       end
  1550.       print ''
  1551.  
  1552.       fetch index_cursor into
  1553.                  @indid ,@index_name ,@dol_clustered ,@clustered, @keycnt
  1554.    end
  1555.    close index_cursor
  1556.  
  1557.    ---------------------
  1558.    -- Work on Columns --
  1559.    ---------------------
  1560.       open col_cursor
  1561.       fetch col_cursor into
  1562.          @colid, @colidarray, @colidarray_len, @colname, @statid, @c1stat, @last_updt, @rc_density, @tot_density
  1563.         ,@steps_act, @steps_req, @typename, @collength, @precision, @scale, @r_sel, @between_sel
  1564.  
  1565.       while (@@sqlstatus = 0)
  1566.       begin
  1567.          if (@steps_act is not null)
  1568.             print 'Statistics for column:                  "%1!"',@colname
  1569.          else
  1570.          begin   -- BUILD A COLUMN GROUP NAME
  1571.             select @colgroup_name = null
  1572.             while (@colidarray_len > 0)
  1573.             begin
  1574.                select @colgroup_name =
  1575.                                 substring(', ' ,abs(sign(@colidarray_len - 1)),2)
  1576.                               + '"' + name + '"'
  1577.                               + @colgroup_name
  1578.                from syscolumns
  1579.                where id = @tabid
  1580.                  and colid = convert(tinyint,substring(@colidarray,@colidarray_len,1))
  1581.                select @colidarray_len = @colidarray_len - 1
  1582.             end
  1583.             print 'Statistics for column group:            %1!',@colgroup_name
  1584.          end
  1585.          print 'Last update of column statistics:       %1!',@last_updt
  1586.          if (@c1stat & 2 = 2)
  1587.             print 'Statistics loaded from Optdiag.'
  1588.          print ''
  1589.          print '     Range cell density:                %1!',@rc_density
  1590.          print '     Total density:                     %1!',@tot_density
  1591.          if (@r_sel is not null)
  1592.             print '     Range selectivity:                 %1!',@r_sel
  1593.          else
  1594.             print '     Range selectivity:                 default used (0.33)'
  1595.          if (@between_sel is not null)
  1596.             print '     In between selectivity:            %1!',@between_sel
  1597.          else
  1598.             print '     In between selectivity:            default used (0.25)'
  1599.          print ''
  1600.          if (@steps_act is not null) /** Print a Histogram **/
  1601.          begin
  1602.             truncate table #cells
  1603.             select @freq_cell = 0, @seq = 1
  1604.             select @used_count = isnull(sum(usedcount),0)
  1605.             from sysstatistics
  1606.             where id = @tabid
  1607.              and  statid = @statid
  1608.              and  colidarray = convert(varbinary(1),convert(tinyint,@colid))
  1609.              and  formatid = 104
  1610.              and  sequence = @seq
  1611.             while (@used_count > 0)
  1612.             begin
  1613.                select @rownum = 1
  1614.                while (@rownum <= @used_count)
  1615.                begin
  1616.                   insert into #cells(seq,colnum) values (@seq,@rownum)
  1617.                   select @rownum = @rownum + 1
  1618.                end
  1619.                select @seq = @seq + 1
  1620.                select @used_count = isnull(sum(usedcount),0)
  1621.                from sysstatistics
  1622.                where id = @tabid
  1623.                 and  statid = @statid
  1624.                 and  colidarray = convert(varbinary(1),convert(tinyint,@colid))
  1625.                 and  formatid = 104
  1626.                 and  sequence = @seq
  1627.             end
  1628.  
  1629.             print 'Histogram for column:                   "%1!"',@colname
  1630.             if (@typename in ("int","intn"))
  1631.                select @typename = "integer"
  1632.             if (@typename = "float" and @collength = "4")
  1633.                select @typename = "real"
  1634.             if (@typename = "float" and @collength = "8")
  1635.                select @typename = "double precision"
  1636.             if (@typename in ("varchar","nvarchar","char","nchar","binary","varbinary","float","floatn"))
  1637.                print 'Column datatype:                        %1!(%2!)',@typename,@collength
  1638.             else if (@typename in ("numeric","decimal","numericn","decimaln"))
  1639.                print 'Column datatype:                        %1!(%2!,%3!)',@typename,@precision,@scale
  1640.             else
  1641.                print 'Column datatype:                        %1!',@typename
  1642.             print 'Requested step count:                   %1!',@steps_req
  1643.             print 'Actual step count:                      %1!',@steps_act
  1644.             print ''
  1645.             print '     Step     Weight                    Value'
  1646.             print ''
  1647.  
  1648.             open histogram_cursor
  1649.             fetch histogram_cursor into
  1650.                @step, @weight, @value_raw
  1651.             while (@@sqlstatus = 0)
  1652.             begin
  1653.                select
  1654.                  @value_c =
  1655.                      CASE
  1656.                       WHEN @typename in ("varchar","nvarchar","char","nchar")
  1657.                        THEN '"' + convert(varchar(255),@value_raw) + '"'
  1658.  
  1659.                       WHEN @typename in ("int","intn","integer")
  1660.                        THEN str(convert(int,@value_raw),10)
  1661.  
  1662.                       WHEN @typename in ("smallint")
  1663.                        THEN str(convert(smallint,@value_raw),10)
  1664.  
  1665.                       WHEN @typename in ("tinyint")
  1666.                        THEN str(convert(tinyint,@value_raw),10)
  1667.  
  1668.                       /** Oh, oh, a scaled numeric, where does the decimal place go??? **/
  1669.                       WHEN (@typename in ("numeric","decimal","numericn","decimaln") and convert(smallint,@scale) > 0)
  1670.                        THEN str(convert(numeric(38),right(replicate(0x00,255-convert(smallint,@collength)) + @value_raw,17))
  1671.                               /* move over @scale decimal places please */
  1672.                                 /power(convert(numeric,10),convert(smallint,@scale))
  1673.                               /* make room for @precision, minus, and decimal signs */
  1674.                                , convert(smallint,@precision)+2,convert(smallint,@scale))
  1675.  
  1676.                       WHEN (@typename in ("numeric","decimal","numericn","decimaln") and @scale = "0")
  1677.                        THEN str(convert(numeric(38),right(replicate(0x00,255-convert(smallint,@collength)) + @value_raw,17))
  1678.                                 , convert(smallint,@precision))
  1679.  
  1680.                       WHEN (@typename in ("float","floatn","real") and @collength = "4")
  1681.                        THEN str(convert(real,@value_raw),40,8)
  1682.  
  1683.                       WHEN (@typename in ("float","floatn","double precision") and @collength = "8")
  1684.                        THEN str(convert(double precision,@value_raw),40,16)
  1685.  
  1686.                       WHEN @typename in ("money","moneyn","smallmoney")
  1687.                        THEN str(convert(money,@value_raw),22,2)
  1688.  
  1689.                       WHEN @typename in ("datetime","datetimn")
  1690.                        THEN '"' + convert(varchar(255),convert(datetime,@value_raw),109) + '"'
  1691.  
  1692.                       WHEN @typename in ("smalldatetime")
  1693.                        THEN '"' + convert(varchar(255),convert(smalldatetime,@value_raw),100) + '"'
  1694.  
  1695.                       ELSE @value_raw
  1696.                      END
  1697.  
  1698.                if (@value_raw is null)
  1699.                  select @freq_cell =1 , @prev_step = @step, @prev_weight = @weight, @value_c = "null"
  1700.                else
  1701.                begin
  1702.                  select @value_c = ltrim(@value_c)
  1703.                  if (@freq_cell = 1)
  1704.                  begin /* Printing a frequency cell */
  1705.                     if (@typename in ("binary","varbinary","timestamp"))
  1706.                     begin
  1707.                        print '%1!     %2!        <       %3!',@prev_step,@prev_weight,@value_raw
  1708.                        print '%1!     %2!        =       %3!',@step,@weight,@value_raw
  1709.                     end
  1710.                     else
  1711.                     begin
  1712.                        print '%1!     %2!        <       %3!',@prev_step,@prev_weight,@value_c
  1713.                        print '%1!     %2!        =       %3!',@step,@weight,@value_c
  1714.                     end
  1715.                  end
  1716.                  else /* NOT printing a frequency cell */
  1717.                  begin
  1718.                     if (@typename in ("binary","varbinary","timestamp"))
  1719.                        print '%1!     %2!       <=       %3!',@step,@weight,@value_raw
  1720.                     else
  1721.                        print '%1!     %2!       <=       %3!',@step,@weight,@value_c
  1722.                  end
  1723.                  select @freq_cell = 0
  1724.                end
  1725.  
  1726.                fetch histogram_cursor into
  1727.                   @step, @weight, @value_raw
  1728.             end
  1729.             close histogram_cursor
  1730.             /* Is there only one cell (a freqency cell) */
  1731.             if (@freq_cell = 1)
  1732.                     print '%1!     %2!        =       %3!',@prev_step,@prev_weight,@value_c
  1733.             print ''
  1734.          end /* histogram print */
  1735.  
  1736.       fetch col_cursor into
  1737.          @colid, @colidarray, @colidarray_len,  @colname, @statid, @c1stat, @last_updt, @rc_density, @tot_density
  1738.         ,@steps_act, @steps_req, @typename, @collength, @precision, @scale, @r_sel, @between_sel
  1739.       end
  1740.       close col_cursor
  1741.       -----------------------
  1742.       -- Done with columns --
  1743.       -----------------------
  1744.  
  1745.       ------------------------------
  1746.       -- print cols with no stats --
  1747.       ------------------------------
  1748.       select @keycnt = 0
  1749.       open nostats_cursor
  1750.       fetch nostats_cursor into @colname
  1751.       while (@@sqlstatus = 0)
  1752.       begin
  1753.          select @keycnt = @keycnt + 1
  1754.          if (@keycnt = 1)
  1755.             print 'No statistics for remaining columns:    "%1!"',@colname
  1756.          else if (@keycnt = 2)
  1757.             print '(default values used)                   "%1!"',@colname
  1758.          else
  1759.             print '                                        "%1!"',@colname
  1760.          fetch nostats_cursor into @colname
  1761.       end
  1762.       close nostats_cursor
  1763.       if (@keycnt = 1)
  1764.          print '(default values used)'
  1765.  
  1766.       print ''
  1767.  
  1768.       fetch object_cursor into
  1769.          @tabid, @u_dbname, @u_dbid,
  1770.          @u_tabowner, @u_tabname
  1771.    end
  1772.    close object_cursor
  1773. -----------------------
  1774. -- Done with Objects --
  1775. -----------------------
  1776. end
  1777.  
  1778. go
  1779.  
  1780. grant execute on sp__optdiag to public
  1781. go
  1782. use sybsystemprocs
  1783. go
  1784. drop procedure sp__rev_configure
  1785. go
  1786. create procedure sp__rev_configure
  1787. as
  1788. declare @sptlang        int             /* current sessions language */
  1789. declare @whichone       int             /* using english or default lang ? */
  1790.  
  1791. if @@trancount = 0
  1792. begin
  1793.         set transaction isolation level 1
  1794.         set chained off
  1795. end
  1796.  
  1797. select @whichone = 0
  1798.  
  1799. select @sptlang = @@langid
  1800.  
  1801. if @@langid != 0
  1802. begin
  1803.         if not exists (
  1804.                 select * from master.dbo.sysmessages where error
  1805.                 between 17015 and 17049
  1806.                 and langid = @@langid)
  1807.             select @sptlang = 0
  1808.         else
  1809.         if not exists (
  1810.                 select * from master.dbo.sysmessages where error
  1811.                 between 17100 and 17109
  1812.                 and langid = @@langid)
  1813.             select @sptlang = 0
  1814. end
  1815.  
  1816. if @sptlang = 0
  1817. begin
  1818.     select "-- sp_configure settings"
  1819.         = "sp_configure '" + name + "', "
  1820.         + convert( char(12), c.value)
  1821.         + char(13) + char(10) + "go"
  1822.     from master.dbo.spt_values a,
  1823.         master.dbo.syscurconfigs c
  1824.         where a.type = "C"
  1825.                 and a.number *= c.config
  1826.                 and a.number >= 0
  1827. end
  1828. else
  1829. begin
  1830.     select "-- sp_configure settings"
  1831.         = "sp_configure '" + name + "', "
  1832.         + convert(char(12), c.value)
  1833.         + char(13) + char(10) + "go"
  1834.     from master.dbo.spt_values a,
  1835.         master.dbo.syscurconfigs c,
  1836.         master.dbo.sysmessages d
  1837.         where  type = "C"
  1838.                 and a.number *= c.config
  1839.                 and a.number >= 0
  1840.                 and msgnum = error and isnull(langid, 0) = @sptlang
  1841. end
  1842. return (0)
  1843. go
  1844. --
  1845. -- You may or may not wish to do the following.
  1846. --
  1847. --grant execute on sp__rev_configure to public
  1848. --gouse sybsystemprocs
  1849. go
  1850.  
  1851. /*
  1852.  * DROP PROC sp__revroles
  1853.  */
  1854. IF OBJECT_ID('sp__revroles') IS NOT NULL
  1855. BEGIN
  1856.     DROP PROC sp__revroles
  1857.     PRINT '<<< Dropped proc sp__revroles >>>'
  1858. END
  1859. go
  1860. create procedure sp__revroles
  1861. as
  1862. /* Created 03/05/97 by Clayton Groom
  1863. creates a reverse engineered set of commands to restore user roles
  1864. */
  1865. select "exec sp_role grant, " + u.name + ", " + s.name + char(13) + char(10) + "go"
  1866. from    master..syssrvroles s,
  1867.         sysroles r,
  1868.         sysusers u
  1869. where   r.id    = s.srid
  1870. and     r.lrid  = u.uid
  1871. and     s.name <> u.name
  1872. go
  1873.  
  1874. IF OBJECT_ID('sp__revroles') IS NOT NULL
  1875.     PRINT '<<< Created proc sp__revroles >>>'
  1876. ELSE
  1877.     PRINT '<<< Failed to create proc sp__revroles >>>'
  1878. go
  1879. use sybsystemprocs
  1880. go
  1881.  
  1882. if object_id('sp_days') is not NULL
  1883.     drop proc sp_days
  1884. go
  1885.  
  1886. create proc sp_days @days tinyint OUTPUT, @month tinyint, @year smallint
  1887. as
  1888.   declare @date datetime
  1889.   select @date=convert(char,@month)+'/01/'+convert(char, @year)
  1890.   select @days=datediff(dd,@date, dateadd(mm,1,@date))
  1891.   select @days
  1892. go
  1893.  
  1894. grant exec on sp_days to public
  1895. gouse sybsystemprocs
  1896. go
  1897.  
  1898. if object_id('dbo.sp_ddl_create_table') is not null
  1899.     drop procedure sp_ddl_create_table
  1900.     print "Dropping sp_ddl_create_table"
  1901. go
  1902.  
  1903. create proc sp_ddl_create_table
  1904. as
  1905.  
  1906. -- Creates the DDL for all the user tables in the
  1907. -- current database
  1908.  
  1909. select  right('create table ' + so1.name + '(' + '
  1910. ', 255 * ( abs( sign(sc1.colid - 1) - 1 ) ) )+
  1911.         sc1.name + ' ' +
  1912.         st1.name + ' ' +
  1913.         substring( '(' + rtrim( convert( char, sc1.length ) ) + ') ', 1,
  1914.         patindex('%char', st1.name ) * 10 ) +
  1915.         substring( '(' + rtrim( convert( char, sc1.prec ) ) + ', ' + rtrim(
  1916.         convert( char, sc1.scale ) ) + ') ' , 1, patindex('numeric', st1.name ) * 10 ) +
  1917.         substring( 'NOT NULL', ( convert( int, convert( bit,( sc1.status & 8 ) ) ) * 4 ) + 1,
  1918.         8 * abs(convert(bit, (sc1.status & 0x80)) - 1 ) ) +
  1919.         right('identity ', 9 * convert(bit, (sc1.status & 0x80)) ) +
  1920.         right(',', 5 * ( convert(int,sc2.colid) - convert(int,sc1.colid) ) ) +
  1921.         right(' )
  1922. ' + 'go' + '
  1923. ' + '
  1924. ', 255 * abs( sign( ( convert(int,sc2.colid) - convert(int,sc1.colid) ) ) -
  1925. 1 ) )
  1926. from    sysobjects so1,
  1927.         syscolumns sc1,
  1928.         syscolumns sc2,
  1929.         systypes st1
  1930. where so1.type = 'U'
  1931. and sc1.id = so1.id
  1932. and st1.usertype = sc1.usertype
  1933. and sc2.id = sc1.id
  1934. and sc2.colid = (select max(colid)
  1935.                 from syscolumns
  1936.                 where id = sc1.id)
  1937. order by so1.name, sc1.colid
  1938. go
  1939.  
  1940. if object_id('dbo.sp_ddl_create_table') is not null
  1941. begin
  1942.     grant execute on sp_ddl_create_table to public
  1943.     print "Created sp_ddl_create_table"
  1944. end
  1945. else
  1946.     print "Failed to create sp_ddl_create_table"
  1947. go
  1948.  
  1949. goIF OBJECT_ID('sp_desc') IS NOT NULL
  1950. BEGIN
  1951.     DROP PROCEDURE sp_desc
  1952.     IF OBJECT_ID('sp_desc') IS NOT NULL
  1953.         PRINT '<<< FAILED DROPPING PROCEDURE sp_desc >>>'
  1954.     ELSE
  1955.         PRINT '<<< DROPPED PROCEDURE sp_desc >>>'
  1956. END
  1957. go
  1958.  
  1959. create procedure sp_desc @table_name char(30) = NULL
  1960. --
  1961. -- Snarfed from CDS, cannot remember who posted the original.
  1962. -- Update for dec and numeric data types, plus ensured that
  1963. -- varchars came out as that.
  1964. --
  1965. -- David Owen 2001 (dowen@midsomer.org)
  1966.  
  1967. as
  1968.   -- This stored procedure returns a description of a SQL Server table in
  1969.   -- a format more like the Oracle DESC command.
  1970.  
  1971.     if (@table_name IS NULL)
  1972.     begin
  1973.         raiserror 20001 "Must specify table name for sp_desc!"
  1974.         return
  1975.     end
  1976.  
  1977.     declare @min_id int
  1978.  
  1979.     select
  1980.         C.colid    'column_id',
  1981.         C.name     'column_name',
  1982.         T.name     'column_type',
  1983.         T.usertype 'user_type',
  1984.         T.type     'base_type',
  1985.         C.length   'column_length',
  1986.         C.scale    'column_scale',
  1987.         C.status   'column_is_null'
  1988.     into
  1989.         #tab_descr
  1990.     from
  1991.         syscolumns C,
  1992.         sysobjects O,
  1993.         systypes   T
  1994.     where
  1995.         C.id       = O.id
  1996.     and C.usertype = T.usertype
  1997.     and O.name     = @table_name
  1998.  
  1999.     if (@@rowcount = 0)
  2000.     begin
  2001.         raiserror 20001 "Table specified does not exist"
  2002.         return
  2003.     end
  2004.  
  2005.     update
  2006.         #tab_descr
  2007.     set
  2008.         user_type = systypes.usertype
  2009.     from
  2010.         systypes
  2011.     where
  2012.         systypes.type     = #tab_descr.base_type
  2013.     and systypes.usertype < 100
  2014.  
  2015. --    update
  2016. --        #tab_descr
  2017. --    set
  2018. --        column_type = name
  2019. --    from
  2020. --        systypes
  2021. --    where
  2022. --        #tab_descr.user_type = systypes.usertype
  2023.  
  2024.     update
  2025.         #tab_descr
  2026.     set
  2027.         column_type = name
  2028.     from
  2029.         systypes   st,
  2030.         #tab_descr td
  2031.     where td.base_type = st.type
  2032.       and td.user_type > 100
  2033.  
  2034.     update
  2035.         #tab_descr
  2036.     set
  2037.         column_type = column_type + "(" + LTRIM(RTRIM(str(column_length)))+")"
  2038.     where
  2039.         column_type in ("char", "varchar", "nchar", "nvarchar", "binary", "varbinary")
  2040.  
  2041.     update
  2042.         #tab_descr
  2043.     set
  2044.         column_type = column_type + "(" +
  2045.                                      LTRIM(RTRIM(str(column_length))) +
  2046.                                      "," +
  2047.                                      LTRIM(RTRIM(str(column_scale))) +
  2048.                                      ")"
  2049.     where
  2050.         column_type in ("dec", "numeric", "decimal")
  2051.  
  2052. --    update
  2053. --        #tab_descr
  2054. --    set
  2055. --        column_type = "varchar("+LTRIM(RTRIM(str(column_length)))+")"
  2056. --    where
  2057. --        column_type = "sysname"
  2058.  
  2059.     select
  2060.         @min_id = min(column_id)
  2061.     from
  2062.         #tab_descr
  2063.  
  2064.     update
  2065.         #tab_descr
  2066.     set
  2067.         column_id = column_id - @min_id + 1
  2068.  
  2069.     print @table_name
  2070.  
  2071.     select
  2072.         convert(char(5), "("+LTRIM(str(column_id))+")") 'No.',
  2073.         column_name                                     'Column Name',
  2074.         convert(char(20), column_type)                  'Datatype',
  2075.         case column_is_null
  2076.         when 0 then "NOT NULL"
  2077.         else ""
  2078.         end
  2079.     from
  2080.         #tab_descr
  2081.     order by column_id
  2082. go
  2083.  
  2084. IF OBJECT_ID('dbo.sp_desc') IS NOT NULL
  2085. BEGIN
  2086.     PRINT '<<< CREATED PROCEDURE dbo.sp_desc >>>'
  2087.     GRANT EXECUTE ON dbo.sp_desc TO public
  2088. END
  2089. ELSE
  2090.     PRINT '<<< FAILED CREATING PROCEDURE dbo.sp_desc >>>'
  2091. go
  2092. use sybsystemprocs
  2093. go
  2094. /*
  2095.  * DROP PROC dbo.sp_devusage
  2096.  */
  2097. IF OBJECT_ID('dbo.sp_devusage') IS NOT NULL
  2098. BEGIN
  2099.     DROP PROC dbo.sp_devusage
  2100.     PRINT '<<< DROPPED PROC dbo.sp_devusage >>>'
  2101. END
  2102. go
  2103. CREATE PROCEDURE sp_devusage (@device_name char(30) = NULL)
  2104. AS
  2105. IF  @device_name != NULL
  2106.  BEGIN
  2107.    SELECT  dev_name = substring(dv.name,1,20),db_name = substring(db.name,1,20),
  2108.    size_mb = u.size/512.0,
  2109.    u.segmap,
  2110.    vdevno = u.vstart/power(2,24)
  2111.    FROM master..sysusages u , master..sysdevices dv,
  2112.         master..sysdatabases db
  2113.    WHERE  u.vstart between dv.low and dv.high
  2114.    AND db.dbid = u.dbid
  2115.    AND cntrltype  = 0
  2116.   AND dv.name = @device_name
  2117.   ORDER BY dv.name
  2118.   COMPUTE sum(u.size/512.0) by dv.name
  2119.    END
  2120. ELSE
  2121.  BEGIN
  2122.  SELECT  dev_name = substring(dv.name,1,20),db_name = substring(db.name,1,20),
  2123.   size_mb = u.size/512.0, u.segmap,
  2124.   vdevno = u.vstart/power(2,24)
  2125.   FROM master..sysusages u , master..sysdevices dv,
  2126.         master..sysdatabases db
  2127.  WHERE  u.vstart between dv.low and dv.high
  2128.  AND db.dbid = u.dbid
  2129.  AND cntrltype  = 0
  2130.  ORDER BY dv.name
  2131.  COMPUTE sum(u.size/512.0) by dv.name
  2132. END
  2133. go
  2134.  
  2135. IF OBJECT_ID('dbo.sp_devusage') IS NOT NULL
  2136.     PRINT '<<< CREATED PROC dbo.sp_devusage >>>'
  2137. ELSE
  2138.     PRINT '<<< FAILED CREATING PROC dbo.sp_devusage >>>'
  2139. go
  2140. /*
  2141.  * Granting/Revoking Permissions on dbo.sp_devusage
  2142.  */
  2143. GRANT EXECUTE ON dbo.sp_devusage TO public
  2144. go
  2145.  
  2146. /*>>>>>>>>>>>>>>>>>>>>>>>>>>> sp_dos <<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
  2147. IF OBJECT_ID('dbo.sp_dos') IS NOT NULL
  2148.     DROP PROCEDURE sp_dos
  2149. go
  2150.  
  2151. CREATE PROCEDURE sp_dos
  2152.     @vcObjectName varchar(30) = NULL
  2153. AS
  2154. /***********************************************************************
  2155. * sp_dos - Display Object Scope
  2156. *       This procedure graphically displays the scope of a object in
  2157. *       the database.
  2158. *
  2159. * Copyright 1996, all rights reserved.
  2160. *
  2161. * Author:  David W. Pledger, Strategic Data Systems, Inc.
  2162. *
  2163. * Parameters
  2164. *       ----------------------------------------------------------------
  2165. *       Name            In/Out  Description
  2166. *       ----------------------------------------------------------------
  2167. *       @vcObjectName    In     Mandatory - The exact name of a single
  2168. *                               database object for which the call
  2169. *                               hierarchy is to be extracted.
  2170. *
  2171. * Selected Data
  2172. *       A sample report follows:
  2173. *       ----------------------------------------------------------------
  2174. *
  2175. *               SCOPE OF EFFECT FOR OBJECT:  ti_users
  2176. *       +------------------------------------------------------------------+
  2177. *       (T) ti_users (Trigger on table 'users')
  2178. *       |
  2179. *       +--(P) pUT_GetError
  2180. *       |  |
  2181. *       |  +--(U) ui_error
  2182. *       |
  2183. *       +--(U) BGRP
  2184. *       |
  2185. *       +--(U) user_information (See Triggers: tu_user_information)
  2186. *       |
  2187. *       +--(U) users (See Triggers: ti_users, tu_users, td_users)
  2188. *       |
  2189. *       +--(P) pUT_LUDVersion
  2190. *          |
  2191. *          +--(P) pUT_GetError
  2192. *          |  |
  2193. *          |  +--(U) ui_error
  2194. *          |
  2195. *          +--(U) BGRP_LUDVersion
  2196. *
  2197. *       <End of Sample>
  2198. *
  2199. * Return Values
  2200. *       ----------------------------------------------------------------
  2201. *       Value           Description
  2202. *       ----------------------------------------------------------------
  2203. *       < -99           Unexpected error - should never occur.
  2204. *
  2205. *       -99 to -1       Sybase **reserved** return status values.
  2206. *
  2207. *       0               Execution succeeded
  2208. *
  2209. *       1               Execution of this procedure failed.
  2210. *
  2211. *       > 1             Unexpected error - should never occur.
  2212. *
  2213. ***********************************************************************/
  2214. BEGIN
  2215.  
  2216.     /*------------------- Local Declarations -------------------------*/
  2217.     DECLARE @iObjectID    int           /* System ID of object        */
  2218.     DECLARE @cObjectType  char(1)       /* System Object Type code    */
  2219.     DECLARE @vcName       varchar(30)   /* System Object name         */
  2220.     DECLARE @vcMsg        varchar(255)  /* Error Message if needed    */
  2221.     DECLARE @iInsTrigID   int           /* Insert Trigger ID          */
  2222.     DECLARE @iUpdTrigID   int           /* Update Trigger ID          */
  2223.     DECLARE @iDelTrigID   int           /* Delete Trigger ID          */
  2224.     DECLARE @vcErrMsg     varchar(255)  /* Error Message              */
  2225.  
  2226.     /* Local variables to facilitate descending the parent-child
  2227.     ** object hierarchy.
  2228.     */
  2229.     DECLARE @iCurrent     int           /* Current node in the tree   */
  2230.     DECLARE @iRoot        int           /* The root node in the tree  */
  2231.     DECLARE @iLevel       int           /* The current level          */
  2232.  
  2233.     /* Local variables that contain the fragments of the text to
  2234.     ** be displayed while descending the hierarchy.
  2235.     */
  2236.     DECLARE @iDotIndex    int           /* Index for locating periods */
  2237.     DECLARE @cConnector   char(3)       /* '+--'                      */
  2238.     DECLARE @cSibSpacer   char(3)       /* '|  '                      */
  2239.     DECLARE @cBar         char(1)       /* '|'                        */
  2240.     DECLARE @cSpacer      char(3)       /* '   '                      */
  2241.     DECLARE @cPrntStrng1  char(255)     /* The first string to print  */
  2242.     DECLARE @cPrntStrng2  char(255)     /* The second string to print */
  2243.     DECLARE @iLoop        int           /* Temp var used for loop     */
  2244.     DECLARE @vcDepends    varchar(255)  /* Dependency String          */
  2245.     DECLARE @iDependsItem int           /* Index to a string item     */
  2246.  
  2247.     /* Create a temporary table to handle the hierarchical
  2248.     ** decomposition of the task parent-child relationship.  The Stack
  2249.     ** table keeps track of where we are while the leaf table keeps
  2250.     ** track of the leaf tasks which need to be performed.
  2251.     */
  2252.     CREATE TABLE #Stack
  2253.         (iItem int,
  2254.          iLevel int)
  2255.  
  2256.     /*------------------- Validate Input Parameters --------------------*/
  2257.     /* Make sure the table is local to the current database. */
  2258.     IF (@vcObjectName LIKE "%.%.%") AND (SUBSTRING(@vcObjectName, 1,
  2259.             CHARINDEX(".", @vcObjectName) - 1) != DB_NAME())
  2260.         GOTO ErrorNotLocal
  2261.  
  2262.     /* Now check to see that the object is in sysobjects. */
  2263.     IF OBJECT_ID(@vcObjectName) IS NULL
  2264.         GOTO ErrorNotFound
  2265.  
  2266.     /* ---------------------- Initialization -------------------------*/
  2267.  
  2268.     /* Do print any rowcounts while this is in progress. */
  2269.     SET NOCOUNT ON
  2270.  
  2271.     /* Retrieve the object ID out of sysobjects */
  2272.     SELECT @iObjectID = O.id,
  2273.            @cObjectType = O.type
  2274.     FROM   sysobjects O
  2275.     WHERE  O.name = @vcObjectName
  2276.  
  2277.     /* Make sure a job exists. */
  2278.     IF NOT (@@rowcount = 1 and @@error = 0 and @iObjectID > 0)
  2279.         GOTO ErrorNotFound
  2280.  
  2281.     /* Initialize the print string pieces. */
  2282.     SELECT @cConnector  = "+--",
  2283.            @cSibSpacer  = "|..",
  2284.            @cBar        = "|",
  2285.            @cSpacer     = "...",
  2286.            @cPrntStrng1 = "",
  2287.            @cPrntStrng2 = ""
  2288.  
  2289.     /* Print a separator line. */
  2290.     PRINT " "
  2291.     PRINT "** Utility by David Pledger, Strategic Data Systems, Inc.  **"
  2292.     PRINT "**         PO Box 498, Springboro, OH  45066               **"
  2293.     PRINT " "
  2294.     PRINT "         SCOPE OF EFFECT FOR OBJECT:  %1!",@vcObjectName
  2295.     PRINT "+------------------------------------------------------------------+"
  2296.  
  2297.     /* -------------------- Show the Hierarchy -----------------------*/
  2298.     /* Find the root task for this job.  The root task is the only task
  2299.     ** that has a parent task ID of null.
  2300.     */
  2301.     SELECT @iRoot = @iObjectID
  2302.  
  2303.     /* Since there is a root task, we can assign the first
  2304.     ** stack value and assign it a level of one.
  2305.     */
  2306.     SELECT @iCurrent = @iRoot,
  2307.            @iLevel = 1
  2308.  
  2309.     /* Prime the stack with the root level. */
  2310.     INSERT INTO #Stack values (@iCurrent, 1)
  2311.  
  2312.     /* As long as there are nodes which have not been visited
  2313.     ** within the tree, the level will be > 0.  Continue until all
  2314.     ** nodes are visited.  This outer loop descends the tree through
  2315.     ** the parent-child relationship of the nodes.
  2316.     */
  2317.     WHILE (@iLevel > 0)
  2318.     BEGIN
  2319.  
  2320.         /* Do any nodes exist at the current level?  If yes, process them.
  2321.         ** If no, then back out to the previous level.
  2322.         */
  2323.         IF EXISTS
  2324.             (SELECT *
  2325.              FROM   #Stack S
  2326.              WHERE  S.iLevel = @iLevel)
  2327.         BEGIN
  2328.  
  2329.             /* Get the smallest numbered node at the current level. */
  2330.             SELECT @iCurrent = min(S.iItem)
  2331.             FROM   #Stack S
  2332.             WHERE  S.iLevel = @iLevel
  2333.  
  2334.             /* Get the name and type of this node.  */
  2335.             SELECT @cObjectType = O.type,
  2336.                    @vcName = O.name,
  2337.                    @iInsTrigID = ISNULL(O.instrig, 0),
  2338.                    @iUpdTrigID = ISNULL(O.updtrig, 0),
  2339.                    @iDelTrigID = ISNULL(O.deltrig, 0)
  2340.             FROM   sysobjects O
  2341.             WHERE  O.id = @iCurrent
  2342.  
  2343.            /*
  2344.             *    *=================================================*    *
  2345.             *    * Print out data for this node.  (Consider        *    *
  2346.             *    * making this a separate procedure.)              *    *
  2347.             *    *=================================================*    *
  2348.             */
  2349.  
  2350.             /* Initialize the print strings to empty (different from NULL).
  2351.             ** @cPrntStrng1 is used to 'double space' the output and
  2352.             ** contains the necessary column connectors, but no data.
  2353.             ** @cPrntStrng2 contains the actual data at the end of the
  2354.             ** string.
  2355.             */
  2356.             SELECT @cPrntStrng1 = ""
  2357.             SELECT @cPrntStrng2 = ""
  2358.  
  2359.             /* Level 1 is the root node level.  All Jobs have a single
  2360.             ** root task.  All other tasks are subordinate to this task.
  2361.             ** No job may have more than one root task.
  2362.             */
  2363.             IF @iLevel = 1
  2364.             BEGIN
  2365.                 /* Print data for the root node. */
  2366.                 SELECT @cPrntStrng1 = "",
  2367.                        @cPrntStrng2 = "(" + @cObjectType + ") " + @vcName
  2368.             END
  2369.             ELSE /* Else part of (IF @iLevel = 1) */
  2370.             BEGIN
  2371.  
  2372.                 /* Initialize loop variable to 2 since level one has
  2373.                 ** already been processed for printing.
  2374.                 */
  2375.                 SELECT @iLoop = 2
  2376.  
  2377.                 /* Look at the values on the stack at each level to
  2378.                 ** determine which symbol should be inserted into the
  2379.                 ** print string.
  2380.                 */
  2381.                 WHILE @iLoop <= @iLevel
  2382.                 BEGIN
  2383.  
  2384.                    /* While the loop variable is less than the current
  2385.                    ** level, add the appropriate spacer to line up
  2386.                    ** the printed output.
  2387.                    */
  2388.                    IF @iLoop < @iLevel
  2389.                    BEGIN
  2390.  
  2391.                        /* Is there a sibling (another node which exists
  2392.                        ** at the same level) on the stack?  If so, use
  2393.                        ** one type of separator; otherwise, use another
  2394.                        ** type of separator.
  2395.                        */
  2396.                        IF EXISTS(SELECT * FROM #Stack WHERE iLevel = @iLoop)
  2397.                        BEGIN
  2398.                            SELECT @cPrntStrng1 = rtrim(@cPrntStrng1) +
  2399.                                    @cSibSpacer
  2400.                            SELECT @cPrntStrng2 = rtrim(@cPrntStrng2) +
  2401.                                    @cSibSpacer
  2402.                        END
  2403.                        ELSE
  2404.                        BEGIN
  2405.                            SELECT @cPrntStrng1 = rtrim(@cPrntStrng1) + @cSpacer
  2406.                            SELECT @cPrntStrng2 = rtrim(@cPrntStrng2) + @cSpacer
  2407.                        END
  2408.                    END
  2409.                    ELSE /* Else part of (IF @iLoop < @iLevel) */
  2410.                    BEGIN
  2411.                        SELECT @cPrntStrng1 = rtrim(@cPrntStrng1) + @cBar
  2412.                        SELECT @cPrntStrng2 = rtrim(@cPrntStrng2) +
  2413.                                @cConnector + "(" + @cObjectType + ") " +
  2414.                                @vcName
  2415.                    END
  2416.  
  2417.                    /* Increment the loop variable */
  2418.                    SELECT @iLoop = @iLoop + 1
  2419.  
  2420.                 END /* While @iLoop <= @iLevel */
  2421.             END /* IF @iLevel = 1 */
  2422.  
  2423.             /* Spaces are inserted into the string to separate the levels
  2424.             ** into columns in the printed output.  Spaces, however, caused
  2425.             ** a number of problems when attempting to concatenate the
  2426.             ** two strings together.  To perform the concatenation, the
  2427.             ** function rtrim was used to remove the end of the string.
  2428.             ** This also removed the spaces we just added.  To aleviate
  2429.             ** this problem, we used a period (.) wherever there was
  2430.             ** supposed to be a space.  Now that we are ready to print
  2431.             ** the line of text, we need to substitute real spaces
  2432.             ** wherever there is a period in the string.  To do this,
  2433.             ** we simply look for periods and substitute spaces.  This
  2434.             ** has to be done in a loop since there is no mechanism to
  2435.             ** make this substitution in the whole string at once.
  2436.             */
  2437.  
  2438.             /* Find the first period. */
  2439.             SELECT @iDotIndex = charindex (".", @cPrntStrng1)
  2440.  
  2441.             /* If a period exists, substitute a space for it and then
  2442.             ** find the next period.
  2443.             */
  2444.             WHILE @iDotIndex > 0
  2445.             BEGIN
  2446.                 /* Substitute the space */
  2447.                 SELECT @cPrntStrng1 = stuff(@cPrntStrng1, @iDotIndex, 1, " ")
  2448.  
  2449.                 /* Find the next. */
  2450.                 SELECT @iDotIndex = charindex (".", @cPrntStrng1)
  2451.             END
  2452.  
  2453.             /* Do the same thing for the second print string. */
  2454.             SELECT @iDotIndex = charindex (".", @cPrntStrng2)
  2455.             WHILE @iDotIndex > 0
  2456.             BEGIN
  2457.                 SELECT @cPrntStrng2 = stuff(@cPrntStrng2, @iDotIndex, 1, " ")
  2458.                 SELECT @iDotIndex = charindex (".", @cPrntStrng2)
  2459.             END
  2460.  
  2461.             SELECT @vcDepends = NULL
  2462.  
  2463.             IF @iInsTrigID > 0
  2464.                 SELECT @vcDepends = OBJECT_NAME(@iInsTrigID) + " (Insert)"
  2465.  
  2466.             IF @iUpdTrigID > 0
  2467.                 IF @vcDepends IS NULL
  2468.                     SELECT @vcDepends = OBJECT_NAME(@iUpdTrigID) + " (Update)"
  2469.                 ELSE
  2470.                     SELECT @vcDepends = @vcDepends + ", " +
  2471.                            OBJECT_NAME(@iUpdTrigID) + " (Update)"
  2472.  
  2473.             IF @iDelTrigID > 0
  2474.                 IF @vcDepends IS NULL
  2475.                     SELECT @vcDepends = OBJECT_NAME(@iDelTrigID) + " (Delete)"
  2476.                 ELSE
  2477.                     SELECT @vcDepends = @vcDepends + ", " +
  2478.                            OBJECT_NAME(@iDelTrigID) + " (Delete)"
  2479.  
  2480.              IF @vcDepends IS NOT NULL
  2481.                  IF @cObjectType = "T"
  2482.                      SELECT @cPrntStrng2 = @cPrntStrng2 +
  2483.                                " (Trigger on table '" + @vcDepends + "')"
  2484.                  ELSE
  2485.                      SELECT @cPrntStrng2 = @cPrntStrng2 +
  2486.                                        " (See Triggers: " + @vcDepends + ")"
  2487.  
  2488.             /* Remove trailing blanks from the first print string.  */
  2489.             SELECT @cPrntStrng1 = rtrim(@cPrntStrng1)
  2490.             SELECT @cPrntStrng2 = rtrim(@cPrntStrng2)
  2491.  
  2492.             /* Print the two strings. */
  2493.             PRINT @cPrntStrng1
  2494.             PRINT @cPrntStrng2
  2495.  
  2496.             /* Remove the current entry from the stack (Pop) */
  2497.             DELETE #Stack
  2498.             WHERE  #Stack.iLevel = @iLevel
  2499.             AND    #Stack.iItem = @iCurrent
  2500.  
  2501.             /* Add (push) to the stack all the children of the current
  2502.             ** node.
  2503.             */
  2504.             INSERT INTO #Stack
  2505.             SELECT D.depid,
  2506.                    @iLevel + 1
  2507.             FROM   sysdepends D
  2508.             WHERE  D.id = @iCurrent
  2509.  
  2510.             /* If any were added, then we must descend another level. */
  2511.             IF @@rowcount > 0
  2512.             BEGIN
  2513.                 SELECT @iLevel = @iLevel + 1
  2514.             END
  2515.  
  2516.         END
  2517.         ELSE
  2518.         BEGIN
  2519.             /* We have reached a leaf node.  Move back to the previous
  2520.             ** level and see what else is left to process.
  2521.             */
  2522.             SELECT @iLevel = @iLevel - 1
  2523.         END
  2524.  
  2525.     END /* While (@iLevel > 0) */
  2526.  
  2527.     PRINT " "
  2528.  
  2529.     RETURN (0)
  2530.  
  2531. /*------------------------ Error Handling --------------------------*/
  2532. ErrorNotLocal:
  2533.     /* 17460, Table must be in the current database. */
  2534.     EXEC sp_getmessage 17460, @vcErrMsg OUT
  2535.     PRINT @vcErrMsg
  2536.     RETURN (1)
  2537.  
  2538. ErrorNotFound:
  2539.     /* 17461, Table is not in this database. */
  2540.     EXEC sp_getmessage 17461, @vcErrMsg OUT
  2541.     PRINT @vcErrMsg
  2542.     PRINT " "
  2543.  
  2544.     PRINT "Local object types and objecs are:"
  2545.  
  2546.     SELECT "Object Type" = type,
  2547.            "Object Name" = name
  2548.     FROM   sysobjects
  2549.     WHERE  type IN ("U","TR","P","V")
  2550.     ORDER BY type, name
  2551.  
  2552.     RETURN (1)
  2553.  
  2554. END
  2555. go
  2556.  
  2557. grant execute on sp_dos to public
  2558. go
  2559.  
  2560. /* 
  2561.  * If sybsystemprocs exists, we wish to use it.  If it fails, then we
  2562.  * should be left in either master or the users defaultdb, both of which
  2563.  * are probably what we want.
  2564.  */
  2565.  
  2566. use sybsystemprocs
  2567. go
  2568.  
  2569. /* Procedure sp_freedevice, owner dbo */
  2570. IF OBJECT_ID('sp_freedevice') IS NOT NULL
  2571. BEGIN
  2572.  
  2573.     setuser 'dbo'
  2574.  
  2575.     DROP PROCEDURE sp_freedevice
  2576.     IF OBJECT_ID('sp_freedevice') IS NOT NULL
  2577.         PRINT '<<< FAILED TO DROP PROCEDURE sp_freedevice >>>'
  2578.     ELSE
  2579.         PRINT '<<< DROPPED PROCEDURE sp_freedevice >>>'
  2580. END
  2581. go
  2582.  
  2583. setuser 'dbo'
  2584. go
  2585.  
  2586. /*
  2587.  * Name:            sp_freedevice
  2588.  * Version:         1.1
  2589.  * Author:          Unknown (if you know who it is/was let me know and I will modify this).
  2590.  * Description:     Prints the current disk usage in a nice table for all of the devices on the system.
  2591.  *                  Part of the FAQ ASE code package.  Latest version available from URL below.
  2592.  * Source:          http://www.isug.com/Sybase_FAQ/ASE/section9.html
  2593.  * Maintainer:      David Owen (dowen@midsomer.org)
  2594.  */
  2595.  
  2596. create proc sp_freedevice
  2597. @devname char(30) = null
  2598. as
  2599.  
  2600.   declare @showdev bit
  2601.   declare @alloc   int
  2602.  
  2603.   if @devname = null
  2604.      select @devname = '%'
  2605.            ,@showdev = 0
  2606.   else
  2607.      select @showdev = 1
  2608.  
  2609.   select @alloc = low
  2610.     from master.dbo.spt_values
  2611.    where type   = 'E'
  2612.      and number = 1
  2613.  
  2614.   create table #freedev
  2615.      (
  2616.       name char(30)
  2617.      ,size numeric(14,2)
  2618.      ,used numeric(14,2)
  2619.      )
  2620.  
  2621.   insert #freedev
  2622.   select dev.name
  2623.         ,((dev.high - dev.low) * @alloc + 500000) / 1048576
  2624.         ,convert(numeric(14,2), sum((usg.size * @alloc + 500000) / 1048576))
  2625.     from master.dbo.sysdevices dev
  2626.         ,master.dbo.sysusages  usg
  2627.    where dev.low      <= usg.size + usg.vstart - 1
  2628.      and dev.high     >= usg.size + usg.vstart - 1
  2629.      and dev.cntrltype = 0
  2630.    group by dev.name
  2631.  
  2632.   insert #freedev
  2633.   select name
  2634.         ,convert(numeric(14,2), ((sd.high - sd.low) * @alloc + 500000) / 1048576)
  2635.         ,0
  2636.     from master.dbo.sysdevices sd
  2637.    where sd.cntrltype = 0
  2638.      and not exists (select 1
  2639.                        from #freedev fd
  2640.                       where fd.name = sd.name)
  2641.  
  2642.   if @showdev = 1
  2643.   begin
  2644.       select devname = dev.name
  2645.             ,size    = right(replicate(' ', 21) + convert(varchar(18),f.size)          + ' MB', 21)
  2646.             ,used    = right(replicate(' ', 21) + convert(varchar(18),f.used)          + ' MB', 21)
  2647.             ,free    = right(replicate(' ', 21) + convert(varchar(18),f.size - f.used) + ' MB', 21)
  2648.         from master.dbo.sysdevices dev
  2649.             ,#freedev f
  2650.        where dev.name = f.name
  2651.          and dev.name like @devname
  2652.  
  2653.       select dbase = db.name
  2654.             ,size  = right(replicate(' ', 21) + convert(varchar(18),
  2655.                              (usg.size * @alloc + 500000) / 1048576
  2656.                              ) + ' MB', 21)
  2657.             ,usage = vl.name
  2658.         from master.dbo.sysdatabases db
  2659.             ,master.dbo.sysusages usg
  2660.             ,master.dbo.sysdevices dev
  2661.             ,master.dbo.spt_values vl
  2662.        where db.dbid        = usg.dbid
  2663.          and usg.segmap     = vl.number
  2664.          and dev.low       <= usg.size + usg.vstart - 1
  2665.          and dev.high      >= usg.size + usg.vstart - 1
  2666.          and dev.status & 2 = 2
  2667.          and vl.type        = 'S'
  2668.          and dev.name       = @devname
  2669.   end
  2670.   else
  2671.   begin
  2672.  
  2673.       select total   = right(replicate(' ', 21) + convert(varchar(18), sum(size))             + ' MB', 21)
  2674.             ,used    = right(replicate(' ', 21) + convert(varchar(18), sum(used))             + ' MB', 21)
  2675.             ,free    = right(replicate(' ', 21) + convert(varchar(18), sum(size) - sum(used)) + ' MB', 21)
  2676.         from #freedev
  2677.  
  2678.       select devname = dev.name
  2679.             ,size    = right(replicate(' ', 21) + convert(varchar(18), f.size)          + ' MB', 21)
  2680.             ,used    = right(replicate(' ', 21) + convert(varchar(18), f.used)          + ' MB', 21)
  2681.             ,free    = right(replicate(' ', 21) + convert(varchar(18), f.size - f.used) + ' MB', 21)
  2682.         from master.dbo.sysdevices dev
  2683.             ,#freedev f
  2684.        where dev.name = f.name
  2685.   end
  2686. go
  2687.  
  2688. IF OBJECT_ID('sp_freedevice') IS NOT NULL
  2689.     PRINT '<<< CREATED PROCEDURE sp_freedevice >>>'
  2690. ELSE
  2691.     PRINT '<<< FAILED TO CREATE PROCEDURE sp_freedevice >>>'
  2692. go
  2693.  
  2694. IF OBJECT_ID('sp_freedevice') IS NOT NULL
  2695. BEGIN
  2696.     GRANT EXECUTE ON sp_freedevice TO public
  2697. END
  2698. go
  2699. use sybsystemprocs
  2700. go
  2701.  
  2702. if object_id('sp_helpoptions') is not null
  2703. begin
  2704.     drop procedure sp_helpoptions
  2705.     if object_id('sp_helpoptions') is not null
  2706.         print '<<< Failed to drop procedure sp_helpoptions >>>'
  2707.     else
  2708.         print '<<< Dropped procedure sp_helpoptions >>>'
  2709. end
  2710. go
  2711.  
  2712.  
  2713.  
  2714. create procedure sp_helpoptions as
  2715.  
  2716. -- initial design by Bret Halford (bret@sybase.com) 10 Jan 2000
  2717. -- with assistance from Kimberly Russell
  2718. -- relies only on @@options, developed on ASE 11.5.x Solaris
  2719.  
  2720. -- This stored procedure displays a list of SET options and indicates
  2721. -- for each option if the option is ON or OFF
  2722.  
  2723. -- The @@options global variable contains bits that indicate
  2724. -- whether certain of the SET command options are on or not.
  2725.  
  2726. -- By observing the difference (if any) in @@options value when an
  2727. -- option is on and off, a test can be derived for that condition
  2728.  
  2729. -- Note that @@options is not documented in the manuals and its details
  2730. -- are possibly subject to change without notice and may vary by platform.
  2731.  
  2732. -- This procedure can probably be expanded to test for other SET command
  2733. -- options as well.  If you come up with a test for any other SET option,
  2734. -- please send it to me and I will add it to the procedure.
  2735.  
  2736. declare @high_bits int
  2737. declare @low_bits int
  2738. select @high_bits = convert(int,substring(@@options,1,4))
  2739. select @low_bits = convert(int,substring(@@options,5,4))
  2740.  
  2741. if (@high_bits & 268435456 = 268435456 )    print "showplan is on"
  2742. else print "showplan is off"
  2743.  
  2744. if (@low_bits & 33554432 = 33554432) print "ansinull is on"
  2745. else print "ansinull is off"
  2746.  
  2747. if (@low_bits & 536870912 = 536870912) print "ansi_permissions is on"
  2748. else print "ansi_permissions is off"
  2749.  
  2750. if (@high_bits & -2147418112 = -2147418112) print "arithabort is on"
  2751. else print "arithabort is off"
  2752.  
  2753. if (@high_bits & 1073741824 = 1073741824) print "arithignore is on"
  2754. else print "arithignore is off"
  2755.  
  2756. if (@high_bits & 1073741824 = 1073741824) print "arithignore arith_overflow"
  2757. else print "arithignore arith_overflow off"
  2758.  
  2759. if (@high_bits & 32 = 32) print "close on endtran is on"
  2760. else print "close on endtran is off"
  2761.  
  2762. if (@high_bits & 32768 = 32768) print "nocount is on"
  2763. else print "nocount is off"
  2764.  
  2765. -- Note: if 'noexec' or 'parseonly' were on, this procedure could not run,
  2766. -- so no test is necessary.
  2767. print 'noexec is off'
  2768. print 'parseonly is off.'
  2769.  
  2770. go
  2771.  
  2772. if object_id('sp_helpoptions') is not null
  2773. begin
  2774.     print '<<< Created procedure sp_helpoptions >>>'
  2775.     grant execute on sp_helpoptions to public
  2776. end
  2777. else
  2778.     print '<<< Failed to create procedure sp_helpoptions >>>'
  2779. go
  2780.  
  2781. use sybsystemprocs
  2782. go
  2783.  
  2784. drop procedure sp_lockconfig
  2785. go
  2786.  
  2787. -- sp_lockconfig, 'Lists data for lock promotions and index locking schemes'
  2788. -- sp_lockconfig, '   if SYS_FLAG is non-null include system tables'
  2789.  
  2790.  
  2791. create procedure sp_lockconfig (@SYS_FLAG  char (1) = NULL) as
  2792.    set ansinull                      on
  2793.    set flushmessage                  on
  2794.    set nocount                       on
  2795.    set string_rtruncation            on
  2796.  
  2797.    print ' '
  2798.  
  2799.    if (@@trancount = 0)
  2800.       begin
  2801.          set chained off
  2802.  
  2803.          if (@@isolation > 1)
  2804.             begin
  2805.                set transaction isolation level 1
  2806.             end
  2807.       end
  2808.    else
  2809.       begin
  2810.          print '    sp_lockconfig CANNOT BE RUN FROM WITHIN A TRANSACTION.'
  2811.  
  2812.          print ' '
  2813.  
  2814.          return 1
  2815.       end
  2816.  
  2817.    declare @allcount  varchar (7),
  2818.            @dpcount   varchar (7),
  2819.            @drcount   varchar (7),
  2820.            @sysval    smallint,
  2821.            @tabtext   varchar (12)
  2822.  
  2823.    create table #lockcfg
  2824.      (sort      tinyint       not null,
  2825.       type      char (8)      not null,
  2826.       name      varchar (30)  not null,
  2827.       levelx    varchar ( 5)  not null,
  2828.       txt       varchar (33)  not null)
  2829.  
  2830.    insert into #lockcfg
  2831.       select 1,
  2832.              'Table',
  2833.              object_name (object),
  2834.              'page',
  2835.              substring (char_value, 1, 33)
  2836.       from sysattributes
  2837.       where class       = 5
  2838.         and attribute   = 0
  2839.         and object_type = 'T'
  2840.  
  2841.    insert into #lockcfg
  2842.       select 1,
  2843.              'Table',
  2844.              object_name (object),
  2845.              'row',
  2846.              substring (char_value, 1, 33)
  2847.       from sysattributes
  2848.       where class       = 5
  2849.         and attribute   = 1
  2850.         and object_type = 'T'
  2851.  
  2852.    insert into #lockcfg
  2853.       select 2,
  2854.              'Database',
  2855.              db_name (),
  2856.              'page',
  2857.              substring (char_value, 1, 33)
  2858.       from master.dbo.sysattributes
  2859.       where class       = 5
  2860.         and attribute   = 0
  2861.         and object_type = 'D'
  2862.         and object      = db_id ()
  2863.  
  2864.    insert into #lockcfg
  2865.       select 2,
  2866.              'Database',
  2867.              db_name (),
  2868.              'row',
  2869.              substring (char_value, 1, 33)
  2870.       from master.dbo.sysattributes
  2871.       where class       = 5
  2872.         and attribute   = 1
  2873.         and object_type = 'D'
  2874.         and object      = db_id ()
  2875.  
  2876.    insert into #lockcfg
  2877.       select 3,
  2878.              'Server',
  2879.              'default lock scheme',
  2880.              '-',
  2881.              substring (c.value2, 1, 10)
  2882.       from master.dbo.sysconfigures f,
  2883.            master.dbo.syscurconfigs c
  2884.       where f.name    = 'lock scheme'
  2885.         and f.parent <> 19
  2886.         and f.config <> 19
  2887.         and c.config  = f.config
  2888.  
  2889.    insert into #lockcfg
  2890.       select 3,
  2891.              'Server',
  2892.              '-',
  2893.              'page',
  2894.              'PCT = '
  2895.              +  convert (varchar (11), pc.value)
  2896.              +  ', LWM = '
  2897.              +  convert (varchar (11), lc.value)
  2898.              +  ', HWM = '
  2899.              +  convert (varchar (11), hc.value)
  2900.       from master.dbo.sysconfigures pf,
  2901.            master.dbo.sysconfigures lf,
  2902.            master.dbo.sysconfigures hf,
  2903.            master.dbo.syscurconfigs pc,
  2904.            master.dbo.syscurconfigs lc,
  2905.            master.dbo.syscurconfigs hc
  2906.       where pf.config  = pc.config
  2907.         and pf.name    = 'page lock promotion PCT'
  2908.         and pf.parent <> 19
  2909.         and pf.config <> 19
  2910.         and lf.config  = lc.config
  2911.         and lf.name    = 'page lock promotion LWM'
  2912.         and lf.parent <> 19
  2913.         and lf.config <> 19
  2914.         and hf.config  = hc.config
  2915.         and hf.name    = 'page lock promotion HWM'
  2916.         and hf.parent <> 19
  2917.         and hf.config <> 19
  2918.  
  2919.    insert into #lockcfg
  2920.       select 3,
  2921.              'Server',
  2922.              '-',
  2923.              'row',
  2924.              'PCT = '
  2925.              +  convert (varchar (11), pc.value)
  2926.              +  ', LWM = '
  2927.              +  convert (varchar (11), lc.value)
  2928.              +  ', HWM = '
  2929.              +  convert (varchar (11), hc.value)
  2930.       from master.dbo.sysconfigures pf,
  2931.            master.dbo.sysconfigures lf,
  2932.            master.dbo.sysconfigures hf,
  2933.            master.dbo.syscurconfigs pc,
  2934.            master.dbo.syscurconfigs lc,
  2935.            master.dbo.syscurconfigs hc
  2936.       where pf.config  = pc.config
  2937.         and pf.name    = 'row lock promotion PCT'
  2938.         and pf.parent <> 19
  2939.         and pf.config <> 19
  2940.         and lf.config  = lc.config
  2941.         and lf.name    = 'row lock promotion LWM'
  2942.         and lf.parent <> 19
  2943.         and lf.config <> 19
  2944.         and hf.config  = hc.config
  2945.         and hf.name    = 'row lock promotion HWM'
  2946.         and hf.parent <> 19
  2947.         and hf.config <> 19
  2948.  
  2949.    select TYPE        = type,
  2950.           OBJECT      = substring (name, 1, 28),
  2951.           'LEVEL'     = levelx,
  2952.           'LOCK DATA' = txt
  2953.    from #lockcfg
  2954.    order by sort, name, levelx
  2955.  
  2956.    print ' '
  2957.  
  2958.    if (@SYS_FLAG IS NULL)
  2959.       begin
  2960.          select @sysval  = 3,
  2961.                 @tabtext = 'USER'
  2962.       end
  2963.    else
  2964.       begin
  2965.          select @sysval  = 1,
  2966.                 @tabtext = 'USER/SYSTEM'
  2967.       end
  2968.  
  2969.    select @allcount = ltrim (substring (convert (char (10),
  2970.                                                  convert (money,
  2971.                                                           count (*)),
  2972.                                                  1),
  2973.                                         1,
  2974.                                         7))
  2975.    from sysobjects
  2976.    where (sysstat & 15)    in (@sysval, 3)
  2977.      and (sysstat2 & 8192)  = 8192
  2978.  
  2979.    select @dpcount = ltrim (substring (convert (char (10),
  2980.                                                 convert (money,
  2981.                                                          count (*)),
  2982.                                                 1),
  2983.                                        1,
  2984.                                        7))
  2985.    from sysobjects
  2986.    where (sysstat & 15)     in (@sysval, 3)
  2987.      and (sysstat2 & 16384)  = 16384
  2988.  
  2989.    select @drcount = ltrim (substring (convert (char (10),
  2990.                                                 convert (money,
  2991.                                                          count (*)),
  2992.                                                 1),
  2993.                                        1,
  2994.                                        7))
  2995.    from sysobjects
  2996.    where (sysstat & 15)     in (@sysval, 3)
  2997.      and (sysstat2 & 32768)  = 32768
  2998.  
  2999.    if ((@allcount <> '0')  and  (@dpcount = '0')  and  (@drcount = '0'))
  3000.       begin
  3001.          print '    ALL %1! TABLES USE ALLPAGES LOCKING.', @tabtext
  3002.       end
  3003.    else if ((@allcount = '0')  and  (@dpcount <> '0')  and  (@drcount = '0'))
  3004.       begin
  3005.          print '    ALL %1! TABLES USE DATAPAGES LOCKING.', @tabtext
  3006.       end
  3007.    else if ((@allcount = '0')  and  (@dpcount = '0')  and  (@drcount <> '0'))
  3008.       begin
  3009.          print '    ALL %1! TABLES USE DATAROWS LOCKING.', @tabtext
  3010.       end
  3011.    else
  3012.       begin
  3013.          if (@allcount = '0')
  3014.             begin
  3015.                print '    THERE ARE NO %1! TABLES WITH ALLPAGES LOCKING.', @tabtext
  3016.             end
  3017.          else
  3018.             begin
  3019.                print '    THERE ARE %1! %2! TABLES WITH ALLPAGES LOCKING.',
  3020.                      @allcount, @tabtext
  3021.  
  3022.                print ' '
  3023.  
  3024.                select 'TABLE' = name,
  3025.                       OWNER   = user_name (uid)
  3026.                from sysobjects
  3027.                where (sysstat & 15)    in (@sysval, 3)
  3028.                  and (sysstat2 & 8192)  = 8192
  3029.                order by 'TABLE', OWNER
  3030.             end
  3031.  
  3032.          print ' '
  3033.  
  3034.          if (@dpcount = '0')
  3035.             begin
  3036.                print '    THERE ARE NO %1! TABLES WITH DATAPAGES LOCKING.',
  3037.                      @tabtext
  3038.             end
  3039.          else
  3040.             begin
  3041.                print '    THERE ARE %1! %2! TABLES WITH DATAPAGES LOCKING.',
  3042.                      @dpcount, @tabtext
  3043.  
  3044.                print ' '
  3045.  
  3046.                   select 'TABLE' = space (30),
  3047.                          OWNER   = space (30)
  3048.                   where 1 = 2
  3049.                union
  3050.                   select substring (name  +  ' *',
  3051.                                     1,
  3052.                                     30),
  3053.                          user_name (uid)
  3054.                   from sysobjects
  3055.                   where (sysstat & 15)     in (@sysval, 3)
  3056.                     and (sysstat2 & 16384)  = 16384
  3057.                     and (sysstat2 & 131072) = 131072
  3058.                union
  3059.                   select name,
  3060.                          user_name (uid)
  3061.                   from sysobjects
  3062.                   where (sysstat & 15)      in (@sysval, 3)
  3063.                     and (sysstat2 & 16384)   = 16384
  3064.                     and (sysstat2 & 131072) <> 131072
  3065.                order by 'TABLE', OWNER
  3066.             end
  3067.  
  3068.          print ' '
  3069.  
  3070.          if (@drcount = '0')
  3071.             begin
  3072.                print '    THERE ARE NO %1! TABLES WITH DATAROWS LOCKING.',
  3073.                      @tabtext
  3074.             end
  3075.          else
  3076.             begin
  3077.                print '    THERE ARE %1! %2! TABLES WITH DATAROWS LOCKING.',
  3078.                      @drcount, @tabtext
  3079.  
  3080.                print ' '
  3081.  
  3082.                   select 'TABLE' = space (30),
  3083.                          OWNER   = space (30)
  3084.                   where 1 = 2
  3085.                union
  3086.                   select substring (name  +  ' *',
  3087.                                     1,
  3088.                                     30),
  3089.                          user_name (uid)
  3090.                   from sysobjects
  3091.                   where (sysstat & 15)      in (@sysval, 3)
  3092.                     and (sysstat2 & 32768)   = 32768
  3093.                     and (sysstat2 & 131072)  = 131072
  3094.                union
  3095.                   select name,
  3096.                          user_name (uid)
  3097.                   from sysobjects
  3098.                   where (sysstat & 15)      in (@sysval, 3)
  3099.                     and (sysstat2 & 32768)   = 32768
  3100.                     and (sysstat2 & 131072) <> 131072
  3101.                order by 'TABLE', OWNER
  3102.             end
  3103.       end
  3104.  
  3105.    print ' '
  3106. go
  3107. sp_procxmode sp_lockconfig, anymode
  3108. go
  3109. use sybsystemprocs
  3110. go
  3111. /*
  3112.  * DROP PROC dbo.sp_servermap
  3113.  */
  3114. IF OBJECT_ID('dbo.sp_servermap') IS NOT NULL
  3115. BEGIN
  3116.     DROP PROC dbo.sp_servermap
  3117.     PRINT '<<< DROPPED PROC dbo.sp_servermap >>>'
  3118. END
  3119. go
  3120.  
  3121. create proc sp_servermap (@selection varchar(10) = "ABCDEF")
  3122. as
  3123.  
  3124. /* produces 6 "reports" against all possible data in
  3125.    master..sysdatabases
  3126.    master..sysdevices
  3127.    master..sysusages
  3128.  
  3129.    sp_servermap help
  3130.    produces a list of the six reports.
  3131.    A subset of the complete set of reports can be requested by passing
  3132.    an argument that consists of a string containing the letters of the
  3133.    desired report.
  3134.  
  3135.    This procedure was developed on 4.9.1 server. It will run on 4.8
  3136.    and 10.0 servers, but it has not been verified that the results
  3137.    produced are correct.
  3138. */
  3139.  
  3140. declare @atitle varchar(40),
  3141.         @btitle varchar(40),
  3142.         @ctitle varchar(40),
  3143.         @dtitle varchar(40),
  3144.         @etitle varchar(40),
  3145.         @ftitle varchar(40),
  3146.         @stars varchar(40),
  3147.         @xstars varchar(40)
  3148.  
  3149. set nocount on
  3150.  
  3151. select @atitle = "A - DATABASE SEGMENT MAP",
  3152.        @btitle = "B - DATABASE INFORMATION",
  3153.        @ctitle = "C - DEVICE ALLOCATION MAP",
  3154.        @dtitle = "D - DEVICE NUMBER, DEFAULT & SPACE USAGE",
  3155.        @etitle = "E - DEVICE LOCATION",
  3156.        @ftitle = "F - MIRRORED DEVICES",
  3157.        @selection = upper(@selection),
  3158.        @stars = replicate("*",40)
  3159.  
  3160. if @selection = "HELP" begin
  3161.   print @atitle
  3162.   print @btitle
  3163.   print @ctitle
  3164.   print @dtitle
  3165.   print @etitle
  3166.   print @ftitle
  3167.   print ""
  3168.   print "select any combination of reports by entering a string of"
  3169.   print "report letters as the argument to sp_servermap:"
  3170.   print "      sp_servermap acd"
  3171.   print "will select reports A,C and D."
  3172.   print "calling sp_servermap with no argument will produce all reports"
  3173.  return
  3174.  end
  3175.  
  3176. select @@servername, "Current Date/Time" = getdate()
  3177. select "Version" = @@version
  3178.  
  3179. if charindex("A",@selection) > 0
  3180. begin
  3181. print ""
  3182. print @atitle
  3183. select @xstars = substring(@stars,1,datalength(@atitle))
  3184. print @xstars
  3185.  
  3186. select db=substring(db.name,1,15),db.dbid,
  3187.        usg.segmap,
  3188.        segs = substring(" U",sign(usg.segmap/8)+1,1) +
  3189.               substring(" L",(usg.segmap & 4)/4+1,1) +
  3190.       substring(" D",(usg.segmap & 2)/2+1,1) +
  3191.               substring(" S",(usg.segmap & 1)+1,1),
  3192.        "device fragment"=substring(dev.name,1,15),
  3193.        "start (pg)" = usg.vstart,"size (MB)" = str(usg.size/512.,7,2)
  3194. from master.dbo.sysusages usg,
  3195.      master.dbo.sysdevices dev,
  3196.      master.dbo.sysdatabases db
  3197. where vstart between low and high
  3198.   and cntrltype = 0
  3199.   and db.dbid = usg.dbid
  3200. order by db.dbid, usg.lstart
  3201.  
  3202. print ""
  3203. print"Segment Codes:"
  3204. print "U=User-defined segment on this device fragment"
  3205. print "L=Database Log may be placed on this device fragment"
  3206. print "D=Database objects may be placed on this device fragment by DEFAULT"
  3207. print "S=SYSTEM objects may be placed on this device fragment"
  3208. print ""
  3209. end
  3210.  
  3211. if charindex("B",@selection) > 0
  3212. begin
  3213. print ""
  3214. print @btitle
  3215. select @xstars = substring(@stars,1,datalength(@btitle))
  3216. print @xstars
  3217.  
  3218. select db=substring(db.name,1,15),
  3219.        db.dbid,
  3220.        "size (MB)" = str(sum(usg.size)/512.,7,2),
  3221.        "db status codes " = substring(" A",(status & 4)/4+1,1) +
  3222.                      substring(" B",(status & 8)/8+1,1) +
  3223.                      substring(" C",(status & 16)/16+1,1) +
  3224.                      substring(" D",(status & 32)/32+1,1) +
  3225.                      substring(" E",(status & 256)/256+1,1) +
  3226.                      substring(" F",(status & 512)/512+1,1) +
  3227.                      substring(" G",(status & 1024)/1024+1,1) +
  3228.                      substring(" H",(status & 2048)/2048+1,1) +
  3229.                      substring(" I",(status & 4096)/4096+1,1) +
  3230.                      substring(" J",(status & 16384)/16384+1,1) +
  3231.                      substring(" K",(status & 64)/64+1,1) +
  3232.                      substring(" L",(status & 128)/128+1,1) +
  3233.                      substring(" M",(status2 & 1)/1+1,1) +
  3234.                      substring(" N",(status2 & 2)/2+1,1) +
  3235.                      substring(" O",(status2 & 4)/4+1,1) +
  3236.                      substring(" P",(status2 & 8)/8+1,1) +
  3237.                      substring(" Q",(status2 & 16)/16+1,1) +
  3238.                      substring(" R",(status2 & 32)/32+1,1),
  3239.        "created" = convert(char(9),crdate,6) + " " +
  3240.                    convert(char(5),crdate,8),
  3241.        "dump tran" = convert(char(9),dumptrdate,6) + " " +
  3242.                  convert(char(5),dumptrdate,8)
  3243. from master.dbo.sysdatabases db,
  3244.      master.dbo.sysusages usg
  3245. where db.dbid =usg.dbid
  3246. group by db.dbid
  3247. order by db.dbid
  3248.  
  3249. print ""
  3250. print "Status Code Key"
  3251. print ""
  3252. print "Code       Status"
  3253. print "----       ----------------------------------"
  3254. print " A         select into/bulk copy allowed"
  3255. print " B         truncate log on checkpoint"
  3256. print " C         no checkpoint on recovery"
  3257. print " D         db in load-from-dump mode"
  3258. print " E         db is suspect"
  3259. print " F         ddl in tran"
  3260. print " G         db is read-only"
  3261. print " H         db is for dbo use only"
  3262. print " I         db in single-user mode"
  3263. print " J         db name has been changed"
  3264. print " K         db is in recovery"
  3265. print " L         db has bypass recovery set"
  3266. print " M         abort tran on log full"
  3267. print " N         no free space accounting"
  3268. print " O         auto identity"
  3269. print " P         identity in nonunique index"
  3270. print " Q         db is offline"
  3271. print " R         db is offline until recovery completes"
  3272. print ""
  3273. end
  3274.  
  3275. if charindex("C",@selection) > 0
  3276. begin
  3277. print ""
  3278. print @ctitle
  3279. select @xstars = substring(@stars,1,datalength(@ctitle))
  3280. print @xstars
  3281.  
  3282. select "device fragment"=substring(dev.name,1,15),
  3283.        "start (pg)" = usg.vstart,"size (MB)" = str(usg.size/512.,7,2),
  3284.        db=substring(db.name,1,15),
  3285.        lstart,
  3286.        segs = substring(" U",sign(usg.segmap/8)+1,1) +
  3287.               substring(" L",(usg.segmap & 4)/4+1,1) +
  3288.               substring(" D",(usg.segmap & 2)/2+1,1) +
  3289.               substring(" S",(usg.segmap & 1)+1,1)
  3290. from master.dbo.sysusages usg,
  3291.      master.dbo.sysdevices dev,
  3292.      master.dbo.sysdatabases db
  3293. where usg.vstart between dev.low and dev.high
  3294.   and dev.cntrltype = 0
  3295.   and db.dbid = usg.dbid
  3296. group by dev.name, usg.vstart, db.name
  3297. having db.dbid = usg.dbid
  3298. order by dev.name, usg.vstart
  3299.  
  3300.  
  3301. print ""
  3302. print "Segment Codes:"
  3303. print "U=USER-definedsegment on this device fragment"
  3304. print "L=Database LOG may be placed on this device fragment"
  3305. print "D=Database objects may be placed on this device fragment by DEFAULT"
  3306. print "S=SYSTEM objects may be placed on this device fragment"
  3307. print ""
  3308. end
  3309.  
  3310. if charindex("D",@selection) > 0
  3311. begin
  3312. print ""
  3313. print @dtitle
  3314. select @xstars = substring(@stars,1,datalength(@dtitle))
  3315. print @xstars
  3316.  
  3317. declare @vsize int
  3318. select @vsize = low
  3319. from master.dbo.spt_values
  3320. where type="E"
  3321.    and number = 3
  3322.  
  3323. select device = substring(name,1,15),
  3324.        vdevno = convert(tinyint,substring(convert(binary(4),low),@vsize,1)),
  3325.        "default disk?" = "    " + substring("NY",(status & 1)+1,1),
  3326.        "total (MB)" = str(round((high-low)/512.,2),7,2),
  3327.        used = str(round(isnull(sum(size),0)/512.,2),7,2),
  3328.        free = str(round(abs((high-low-isnull(sum(size),0))/512.),2),7,2)
  3329. from master.dbo.sysusages,
  3330.      master.dbo.sysdevices
  3331. where vstart between low and high
  3332.  and cntrltype=0
  3333.  group by all name
  3334.     having cntrltype=0
  3335. order by vdevno
  3336. end
  3337.  
  3338. if charindex("E",@selection) > 0
  3339. begin
  3340. print ""
  3341. print @etitle
  3342. select @xstars = substring(@stars,1,datalength(@etitle))
  3343. print @xstars
  3344.  
  3345. select device = substring(name,1,15),
  3346.        location = substring(phyname,1,60)
  3347. from master.dbo.sysdevices
  3348. where cntrltype=0
  3349. end
  3350.  
  3351. if charindex("F",@selection) > 0
  3352. begin
  3353. if exists (select 1
  3354.            from master.dbo.sysdevices
  3355.            where status & 64 = 64)
  3356. begin
  3357.  
  3358. print ""
  3359. print @ftitle
  3360. select @xstars = substring(@stars,1,datalength(@ftitle))
  3361. print @xstars
  3362.  
  3363. select device = substring(name,1,15),
  3364.        pri =" " + substring("* **",(status/256)+1,1),
  3365.        sec = " " + substring(" ***",(status/256)+1,1),
  3366.        serial = "   " + substring(" *",(status & 32)/32+1,1),
  3367.        "mirror" = substring(mirrorname,1,35),
  3368.        reads = "   " + substring(" *",(status & 128)/128+1,1)
  3369. from master.dbo.sysdevices
  3370. where cntrltype=0
  3371.  and status & 64 = 64
  3372. end
  3373. else
  3374. begin
  3375. print ""
  3376. print "NO DEVICES ARE MIRRORED"
  3377. end
  3378. end
  3379.  
  3380. set nocount off
  3381.  
  3382.  
  3383. go
  3384. IF OBJECT_ID('dbo.sp_servermap') IS NOT NULL
  3385. BEGIN
  3386.     PRINT '<<< CREATED PROC dbo.sp_servermap >>>'
  3387.     grant execute on dbo.sp_servermap to sa_role
  3388. END
  3389. ELSE
  3390.     PRINT '<<< FAILED CREATING PROC dbo.sp_servermap >>>'
  3391. gouse sybsystemprocs
  3392. go
  3393.  
  3394. IF OBJECT_ID('dbo.sp_spaceused_table') IS NOT NULL
  3395. BEGIN
  3396.     DROP PROCEDURE dbo.sp_spaceused_table
  3397.     IF OBJECT_ID('dbo.sp_spaceused_table') IS NOT NULL
  3398.         PRINT '<<< FAILED TO DROP dbo.sp_spaceused_table >>>'
  3399.     ELSE
  3400.         PRINT '<<< DROPPED PROC dbo.sp_spaceused_table >>>'
  3401. END
  3402. go
  3403.  
  3404. create procedure sp_spaceused_table
  3405. @list_indices  int = 0
  3406. as
  3407. declare @type         smallint,      -- the object type
  3408.         @msg          varchar(250),  -- message output
  3409.         @dbname       varchar(30),   -- database name
  3410.         @tabname      varchar(30),   -- table name
  3411.         @length       int,
  3412.         @object_id    int
  3413.  
  3414. set nocount on
  3415.  
  3416. if @@trancount = 0
  3417. begin
  3418.     set chained off
  3419. end
  3420.  
  3421. set transaction isolation level 1
  3422.  
  3423. create table #pagecounts
  3424.    (
  3425.     name        varchar(45)   null,
  3426.     iname       varchar(45)   null,
  3427.     low         int           null,
  3428.     rowtotal    int           null,
  3429.     reserved    numeric(20,9) null,
  3430.     data        numeric(20,9) null,
  3431.     index_size  numeric(20,9) null,
  3432.     unused      numeric(20,9) null
  3433.    )
  3434.  
  3435. select @object_id = min(id)
  3436.   from sysobjects
  3437.  where type = 'U'
  3438.    and name not like "%pagecount%"
  3439.  
  3440. while (@object_id is not null)
  3441. begin
  3442.     /*
  3443.     **  We want a particular object.
  3444.     */
  3445.     insert #pagecounts
  3446.     select  name       = o.name,
  3447.             iname      = i.name,
  3448.             low        = d.low,
  3449.             rowtotal   = rowcnt(i.doampg),
  3450.             reserved   = convert(numeric(20,9),
  3451.                                  (reserved_pgs(i.id, i.doampg) +
  3452.                                   reserved_pgs(i.id, i.ioampg))),
  3453.             data       = convert(numeric(20,9), data_pgs(i.id, i.doampg)),
  3454.             index_size = convert(numeric(20,9), data_pgs(i.id, i.ioampg)),
  3455.             unused = convert(numeric(20,9),
  3456.                              ((reserved_pgs(i.id, i.doampg) +
  3457.                                reserved_pgs(i.id, i.ioampg)) -
  3458.                                (data_pgs(i.id, i.doampg) +
  3459.                                 data_pgs(i.id, i.ioampg))))
  3460.       from sysobjects o
  3461.           ,sysindexes i
  3462.           ,master.dbo.spt_values d
  3463.      where i.id     = @object_id
  3464.        and o.id     = @object_id
  3465.        and i.id     = o.id
  3466.        and d.number = 1
  3467.        and d.type   = 'E'
  3468.  
  3469.     select @object_id = min(id)
  3470.       from sysobjects
  3471.      where type = 'U'
  3472.        and id   > @object_id
  3473.        and name not like "%pagecount%"
  3474.  
  3475. end
  3476.  
  3477. select @length = max(datalength(iname))
  3478.   from #pagecounts
  3479.  
  3480. if (@list_indices = 1)
  3481. begin
  3482.  
  3483.     if (@length > 20)
  3484.     begin
  3485.         select  index_name = iname,
  3486.                 size = convert(char(10), convert(varchar(11),
  3487.                        convert(numeric(11,0),
  3488.                                index_size / 1024 *
  3489.                                low)) + ' KB'),
  3490.                 reserved = convert(char(10),
  3491.                            convert(varchar(11),
  3492.                            convert(numeric(11,0),
  3493.                                    reserved / 1024 *
  3494.                                    low)) + ' KB'),
  3495.                 unused = convert(char(10), convert(varchar(11),
  3496.                          convert(numeric(11,0), unused / 1024 *
  3497.                                         low)) + ' KB')
  3498.         from #pagecounts
  3499.  
  3500.     end
  3501.     else
  3502.     begin
  3503.         select  index_name = convert(char(20), iname),
  3504.                 size = convert(char(10), convert(varchar(11),
  3505.                        convert(numeric(11,0),
  3506.                                         index_size / 1024 *
  3507.                                         low)) + ' KB'),
  3508.                 reserved = convert(char(10),
  3509.                                    convert(varchar(11),
  3510.                                            convert(numeric(11,0),
  3511.                                                    reserved / 1024 *
  3512.                                                    low)) + ' KB'),
  3513.                 unused = convert(char(10), convert(varchar(11),
  3514.                          convert(numeric(11,0), unused / 1024 *
  3515.                                         low)) + ' KB')
  3516.         from #pagecounts
  3517.     end
  3518. end
  3519.  
  3520. if (@length > 20)
  3521. begin
  3522.     select distinct name,
  3523.            rowtotal = convert(char(11), sum(rowtotal)),
  3524.            reserved = convert(char(15), convert(varchar(11),
  3525.                       convert(numeric(11,0), sum(reserved) *
  3526.                                              (low / 1024))) + ' KB'),
  3527.            data = convert(char(15), convert(varchar(11),
  3528.                   convert(numeric(11,0), sum(data) * (low / 1024)))
  3529.                    + ' KB'),
  3530.            index_size = convert(char(15), convert(varchar(11),
  3531.                     convert(numeric(11,0), sum(index_size) *
  3532.                     (low / 1024))) + ' KB'),
  3533.            unused = convert(char(15), convert(varchar(11),
  3534.                     convert(numeric(11,0), sum(unused) *
  3535.                     (low / 1024))) + ' KB')
  3536.       from #pagecounts
  3537.      group by name
  3538. end
  3539. else
  3540. begin
  3541.     select distinct name = convert(char(20), name),
  3542.            rowtotal = convert(char(11), sum(rowtotal)),
  3543.            reserved = convert(char(15), convert(varchar(11),
  3544.                    convert(numeric(11,0), sum(reserved) *
  3545.                    (low / 1024))) + ' KB'),
  3546.            data = convert(char(15), convert(varchar(11),
  3547.                    convert(numeric(11,0), sum(data) * (low / 1024)))
  3548.                    + ' KB'),
  3549.            index_size = convert(char(15), convert(varchar(11),
  3550.                     convert(numeric(11,0), sum(index_size) *
  3551.                     (low / 1024))) + ' KB'),
  3552.            unused = convert(char(15), convert(varchar(11),
  3553.                     convert(numeric(11,0), sum(unused) *
  3554.                     (low / 1024))) + ' KB')
  3555.       from #pagecounts
  3556.      group by name
  3557. end
  3558.  
  3559. return (0)
  3560. go
  3561.  
  3562. IF OBJECT_ID('dbo.sp_spaceused_table') IS NOT NULL
  3563.     PRINT '<<< CREATED PROC dbo.sp_spaceused_table >>>'
  3564. ELSE
  3565.     PRINT '<<< FAILED TO CREATE PROC dbo.sp_spaceused_table >>>'
  3566. go
  3567. use sybsystemprocs
  3568. go
  3569.  
  3570. if object_id('sp_whodo') is not null
  3571. begin
  3572.     drop procedure sp_whodo
  3573.     if object_id('sp_whodo') is not null
  3574.         print '<<< Failed to drop procedure sp_whodo >>>'
  3575.     else
  3576.         print '<<< Dropped procedure sp_whodo >>>'
  3577. end
  3578. go
  3579.  
  3580. create procedure sp_whodo @loginame varchar(30) = NULL
  3581. as
  3582.  
  3583.   declare @low     int
  3584.          ,@high    int
  3585.          ,@spidlow int
  3586.          ,@spidhigh int
  3587.  
  3588.   select @low      = 0
  3589.         ,@high     = 32767
  3590.         ,@spidlow  = 0
  3591.         ,@spidhigh = 32767
  3592.  
  3593.   if @loginame is not NULL
  3594.   begin
  3595.       select @low  = suser_id(@loginame)
  3596.             ,@high = suser_id(@loginame)
  3597.  
  3598.       if @low is NULL
  3599.       begin
  3600.           if @loginame like "[0-9]%"
  3601.           begin
  3602.               select @spidlow  = convert(int, @loginame)
  3603.                     ,@spidhigh = convert(int, @loginame)
  3604.                     ,@low      = 0
  3605.                     ,@high     = 32767
  3606.           end
  3607.           else
  3608.           begin
  3609.                print "Login %1! does not exist.", @loginame
  3610.                return (1)
  3611.           end
  3612.       end
  3613.   end
  3614.  
  3615.   select spid
  3616.         ,status
  3617.         ,substring(suser_name(suid),1,12)           loginame
  3618.         ,hostname
  3619.         ,convert(char(3),  blocked)                 blk
  3620.         ,convert(char(7),  isnull(time_blocked, 0)) blk_sec
  3621.         ,convert(char(16), program_name)            program
  3622.         ,convert(char(7),  db_name(dbid))           dbname
  3623.         ,convert(char(16), cmd)                     cmd
  3624.         ,convert(char(6),  cpu)                     cpu
  3625.         ,convert(char(7),  physical_io)             io
  3626.         ,convert(char(16), isnull(tran_name, ""))   tran_name
  3627.     from master..sysprocesses
  3628.    where suid >= @low
  3629.      and suid <= @high
  3630.      and spid>= @spidlow
  3631.      and spid <= @spidhigh
  3632.  
  3633.   return (0)
  3634.  
  3635. go
  3636.  
  3637. if object_id('sp_whodo') is not null
  3638. begin
  3639.     print '<<< Created procedure sp_whodo >>>'
  3640.     grant execute on sp_whodo to public
  3641. end
  3642. else
  3643.     print '<<< Failed to create procedure sp_whodo >>>'
  3644. go
  3645.  
  3646. use master
  3647. go
  3648.  
  3649. if object_id('sp_whodo') is not null
  3650. begin
  3651.     drop procedure sp_whodo
  3652.     if object_id('sp_whodo') is not null
  3653.         print '<<< Failed to drop procedure sp_whodo >>>'
  3654.     else
  3655.         print '<<< Dropped procedure sp_whodo >>>'
  3656. end
  3657. go
  3658.  
  3659. create procedure sp_whodo @loginame varchar(30) = NULL
  3660. as
  3661.  
  3662.   declare @low     int
  3663.          ,@high    int
  3664.          ,@spidlow int
  3665.          ,@spidhigh int
  3666.  
  3667.   select @low      = 0
  3668.         ,@high     = 32767
  3669.         ,@spidlow  = 0
  3670.         ,@spidhigh = 32767
  3671.  
  3672.   if @loginame is not NULL
  3673.   begin
  3674.  
  3675.       select @low = suser_id(@loginame)
  3676.             ,@high = suser_id(@loginame)
  3677.  
  3678.       if @low is NULL
  3679.       begin
  3680.           if @loginame like "[0-9]%"
  3681.           begin
  3682.               select @spidlow  = convert(int, @loginame)
  3683.                     ,@spidhigh = convert(int, @loginame)
  3684.                     ,@low      = 0
  3685.                     ,@high     = 32767
  3686.           end
  3687.           else
  3688.           begin
  3689.               print "No login exists with the supplied name."
  3690.               return (1)
  3691.           end
  3692.       end
  3693.   end
  3694.  
  3695.   select
  3696.          spid
  3697.         ,status
  3698.         ,substring(suser_name(suid),1,12) loginame
  3699.         ,hostname
  3700.         ,convert(char(3),  blocked)       blk
  3701.         ,convert(char(16), program_name)  program
  3702.         ,convert(char(7),  db_name(dbid)) dbname
  3703.         ,convert(char(16), cmd)           cmd
  3704.         ,convert(char(6),  cpu)           cpu
  3705.         ,convert(char(7),  physical_io)   io
  3706.     from master..sysprocesses
  3707.    where suid >= @low
  3708.      and suid <= @high
  3709.      and spid >= @spidlow
  3710.      and spid <= @spidhigh
  3711.  
  3712.   return (0)
  3713. go
  3714.  
  3715. if object_id('sp_whodo') is not null
  3716. begin
  3717.     print '<<< Created procedure sp_whodo >>>'
  3718.     grant execute on sp_whodo to public
  3719. else
  3720.     print '<<< Failed to create procedure sp_whodo >>>'
  3721. end
  3722. goCreate procedure sp_whodoneit
  3723. as
  3724. Create table #usr_locks(
  3725.    spid int, dbid smallint, id int)
  3726. Insert Into #usr_locks(spid,dbid,id)
  3727.    Select distinct spid,dbid,id
  3728.    From master..syslocks
  3729. Select
  3730.    str(procs.spid,4) as "Spid",
  3731.    substring(isnull(suser_name(procs.suid),"Sybase"),1,12) as "User",
  3732.    hostname as "Host",
  3733.    substring(cmd,1,6) as "Cmd",
  3734.    convert(varchar(5),procs.cpu) as "Cpu",
  3735.    convert(varchar(7),physical_io) as "I/O",
  3736.    convert(varchar(3),blocked) as "Blk",
  3737.    convert(varchar(10),db_name(ul.dbid)) as "DB Name",
  3738.    ul.id as "Object Id",
  3739.    getdate() as "Date"
  3740. From master..sysprocesses procs, #usr_locks ul
  3741. Where procs.spid *= ul.spid
  3742. #!/bin/csh -f
  3743.  
  3744. isql -U<dbusr> -P<dbpw> -S<dbsvr> -w265 $*
  3745. #!/bin/csh
  3746. # ########################################################################
  3747. # #
  3748. # #                         SCCS Keyword Header
  3749. # #                         -------------------
  3750. # #
  3751. # #           Module Name  :  update_stats.csh
  3752. # #           Version      :  1.8
  3753. # #           Last Modified:  2/16/98 at 17:19:38
  3754. # #           Extracted    :  2/16/98 at 17:19:39
  3755. # #           Archived as  :  <host>:/u/sybase/SCCS/s.update_stats.csh
  3756. # #
  3757. # ########################################################################
  3758.  
  3759.  
  3760.  
  3761.  
  3762.  
  3763. # upd_stats.csh
  3764. # ------------------
  3765. #
  3766. # Shell to update the distribution pages for each table in a database.
  3767. #
  3768. # Requires sqlsa (script w/ the proper isql login for dbo of a database)
  3769. # ex:
  3770. #     #!/bin/csh -f
  3771. #     isql -U<dbusr> -P<dbpw> -S<dbsvr> -w265 $*
  3772. #     exit($$status)
  3773. #
  3774. # Author:  FJ Lundy, 2/96
  3775.  
  3776.  
  3777.  
  3778. ARGS:
  3779.   set progname = `basename $0`
  3780.   if ($#argv != 2) then
  3781.         goto USAGE
  3782.   endif
  3783.   set dbdb          = $1
  3784.   set parallel_jobs = $2
  3785.  
  3786.  
  3787.  
  3788. INIT:
  3789.   # Declare intermediate files
  3790.   set filebase    = /tmp/$progname:r.-D$dbdb
  3791.   set cmdfile     = $filebase.sql
  3792.   set awkfile     = $filebase.awk
  3793.   set tblfile     = $filebase.tbl
  3794.   set workflag    = $filebase.working
  3795.   set logfile     = $filebase.log
  3796.   set runningflag = $filebase.running
  3797.  
  3798.   # Check for another running copy of this process
  3799.   if ( -f $runningflag ) goto ERROR
  3800.  
  3801.   # Set the running flag to prevent multiple copies of
  3802.   onintr DONE
  3803.  
  3804.   # Clean up from previous runs
  3805.   rm -f $filebase.* >& /dev/null
  3806.  
  3807.   # Set the 'running flag' (this step must FOLLOW the 'clean-up from previous
  3808.   #  runs' step!
  3809.   touch $runningflag
  3810.  
  3811.   # Which OS are we running on?
  3812.   set os = `uname`
  3813.   switch ($os)
  3814.         case  'IRIX':
  3815.         case  'IRIX64':
  3816.         case  'HP-UX':
  3817.                 set splitFlag = '-l'
  3818.                 breaksw
  3819.         case  'Linux':
  3820.         case  'SunOS':
  3821.                 set splitFlag = '-'
  3822.                 breaksw
  3823.         default:
  3824.                 echo 'ERROR:  $progname- Unsupported Os($os). Aborting'
  3825.                 exit(-1)
  3826.   endsw
  3827.  
  3828.  
  3829.  
  3830. MAIN:
  3831.   # Start the Log
  3832.   rm -f $logfile
  3833.   echo '$0 $*'                                       > $logfile
  3834.   echo 'NOTE:  $progname- (`date`) BEGIN $progname' >> $logfile
  3835.  
  3836.  
  3837.   # Create the awk command file.
  3838.   cat << EOJ > $awkfile
  3839.         \$0 !~ /^\$/    {
  3840.                 tblname = \$1
  3841.                 printf('declare @msg varchar(255), @dt_start datetime, @dt_end datetime\n')
  3842.                 printf('select @msg = \'Updating Statistics for: Db(%s)\'\n', '$dbdb')
  3843.                 printf('print  @msg\n')
  3844.                 printf('select @dt_start = getdate()\n')
  3845.                 printf('update statistics %s\n', tblname)
  3846.                 printf('exec sp_recompile '%s'\n', tblname)
  3847.                 printf('select @dt_end = getdate()\n')
  3848.                 printf('select @msg = \'Table(%s)\'\n', tblname)
  3849.                 printf('print  @msg\n')
  3850.                 printf('select @msg = \'\tstart(\' + convert(varchar, @dt_start) + \')\'\n')
  3851.                 printf('print  @msg\n')
  3852.                 printf('select @msg = \'\t  end(\' + convert(varchar, @dt_end) + \')\'\n')
  3853.                 printf('print  @msg\n')
  3854.                 printf('print \'\'\n')
  3855.                 printf('go\n\n')
  3856.         }
  3857. EOJ
  3858.  
  3859.  
  3860.   # Create a list of tables to update the stats for
  3861.   sqlsa << EOJ | tail +3 | sed 's/^[   ]*//g' | cut -f1 -d\   > $tblfile
  3862.         set nocount on
  3863.         use $dbdb
  3864. go
  3865.         select   u.name + '.' + o.name 'Table',
  3866.                  sum((reserved_pgs(i.id, i.doampg) + reserved_pgs(i.id, i.ioampg)) * 2) 'Kb'
  3867.         from     sysindexes i, sysobjects o, sysusers u
  3868.         where    (o.id = i.id) and (o.uid = u.uid) and (o.type = 'U' or o.type = 'S')
  3869.         group by u.name, o.name
  3870.         order by Kb desc
  3871. go
  3872. EOJ
  3873.  
  3874. exit(0)
  3875.   # Split the files into equal-sized chunks based on the passed
  3876.   # parameter for the number of parallelized jobs
  3877.   @ ct = 0
  3878.   foreach tbl (`cat $tblfile`)
  3879.         @ i = $ct % $parallel_jobs
  3880.         echo '$tbl' >> $tblfile.$i
  3881.         @ ct = $ct + 1
  3882.   end
  3883.  
  3884.  
  3885.   # For each of the created table lists:
  3886.   #     1) create TSQL, 2) set a work flag 3) background the job
  3887.   @ i = 0
  3888.   set all_work_flags = ''
  3889.   foreach file ( $tblfile.* )
  3890.         # Create the T-SQL command file
  3891.         @ i = $i + 1
  3892.         echo 'set nocount on'     > $cmdfile.$i
  3893.         echo 'use $dbdb'         >> $cmdfile.$i
  3894.         echo 'go'                >> $cmdfile.$i
  3895.         awk -f $awkfile $file    >> $cmdfile.$i
  3896.  
  3897.         # Spawn a subshell and remove the working flag when done
  3898.         # Log output to a log file commonto all threads.  This can possibly cause
  3899.         # lost information in the log file if all the threads come crashing in
  3900.         # at once.  Oh well...
  3901.         set all_work_flags = ( $all_work_flags $workflag.$i )
  3902.         touch $workflag.$i
  3903.         (sqlsa < $cmdfile.$i >>& $logfile ; rm -f $workflag.$i) &
  3904.   end
  3905.  
  3906.  
  3907.   # Loop until all of the spawned processes are finished (as indicated by the
  3908.   # absence of working flags
  3909.   while ( 1 )
  3910.         set num_working = `ls $workflag.* | wc -l`
  3911.         if ( $num_working == 0 ) break
  3912.         sleep 10
  3913.   end   # end-while: wait for work to finish
  3914.  
  3915.  
  3916.  
  3917. DONE:
  3918.   rm $awkfile $cmdfile.* $tblfile $tblfile.*
  3919.   rm $runningflag
  3920.   echo 'NOTE:  $progname- (`date`) END $progname' >> $logfile
  3921.   cat $logfile
  3922.   exit(0)
  3923.  
  3924.  
  3925.  
  3926. USAGE:
  3927.   echo ''
  3928.   echo 'USAGE   : $progname <db> <# of parallel jobs>'
  3929.   echo '          Updates the distribution pages for each user and system table in'
  3930.   echo '          the specified database.'
  3931.   echo 'REQUIRES: sqlsa'
  3932.   echo ''
  3933.   exit(-1)
  3934.  
  3935.  
  3936.  
  3937. ERROR:
  3938.   echo ''
  3939.   echo 'ERROR:  $progname- This process is already running for $dbdb. Aborting'
  3940.   echo ''
  3941.   exit(-2)
  3942.  
  3943. # EOJ
  3944.